[PATCH] D147326: [clang][dataflow][NFC] Share code between Environment ctor and pushCallInternal().

2023-04-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme updated this revision to Diff 510413.
mboehme marked 2 inline comments as done.
mboehme added a comment.

Rename function again to be consistent with `getFieldsAndGlobalVars()`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147326

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

Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -203,7 +203,33 @@
 
 // FIXME: Add support for resetting globals after function calls to enable
 // the implementation of sound analyses.
-void Environment::initVars(llvm::DenseSet Vars) {
+void Environment::initFieldsAndGlobals(const FunctionDecl *FuncDecl) {
+  assert(FuncDecl->getBody() != nullptr);
+
+  llvm::DenseSet Fields;
+  llvm::DenseSet Vars;
+
+  // Look for global variable and field references in the
+  // constructor-initializers.
+  if (const auto *CtorDecl = dyn_cast(FuncDecl)) {
+for (const auto *Init : CtorDecl->inits()) {
+  if (const auto *M = Init->getAnyMember())
+  Fields.insert(M);
+  const Expr *E = Init->getInit();
+  assert(E != nullptr);
+  getFieldsAndGlobalVars(*E, Fields, Vars);
+}
+// Add all fields mentioned in default member initializers.
+for (const FieldDecl *F : CtorDecl->getParent()->fields())
+  if (const auto *I = F->getInClassInitializer())
+  getFieldsAndGlobalVars(*I, Fields, Vars);
+  }
+  getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
+
+  // These have to be added before the lines that follow to ensure that
+  // `create*` work correctly for structs.
+  DACtx->addModeledFields(Fields);
+
   for (const VarDecl *D : Vars) {
 if (getStorageLocation(*D, SkipPast::None) != nullptr)
   continue;
@@ -239,31 +265,7 @@
   if (const auto *FuncDecl = dyn_cast(&DeclCtx)) {
 assert(FuncDecl->getBody() != nullptr);
 
-llvm::DenseSet Fields;
-llvm::DenseSet Vars;
-
-// Look for global variable and field references in the
-// constructor-initializers.
-if (const auto *CtorDecl = dyn_cast(&DeclCtx)) {
-  for (const auto *Init : CtorDecl->inits()) {
-if (const auto *M = Init->getAnyMember())
-  Fields.insert(M);
-const Expr *E = Init->getInit();
-assert(E != nullptr);
-getFieldsAndGlobalVars(*E, Fields, Vars);
-  }
-  // Add all fields mentioned in default member initializers.
-  for (const FieldDecl *F  : CtorDecl->getParent()->fields())
-if (const auto *I = F->getInClassInitializer())
-  getFieldsAndGlobalVars(*I, Fields, Vars);
-}
-getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
-
-// These have to be added before the lines that follow to ensure that
-// `create*` work correctly for structs.
-DACtx.addModeledFields(Fields);
-
-initVars(Vars);
+initFieldsAndGlobals(FuncDecl);
 
 for (const auto *ParamDecl : FuncDecl->parameters()) {
   assert(ParamDecl != nullptr);
@@ -337,26 +339,7 @@
ArrayRef Args) {
   CallStack.push_back(FuncDecl);
 
-  // FIXME: Share this code with the constructor, rather than duplicating it.
-  llvm::DenseSet Fields;
-  llvm::DenseSet Vars;
-  // Look for global variable references in the constructor-initializers.
-  if (const auto *CtorDecl = dyn_cast(FuncDecl)) {
-for (const auto *Init : CtorDecl->inits()) {
-  if (const auto *M = Init->getAnyMember())
-Fields.insert(M);
-  const Expr *E = Init->getInit();
-  assert(E != nullptr);
-  getFieldsAndGlobalVars(*E, Fields, Vars);
-}
-  }
-  getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
-
-  // These have to be added before the lines that follow to ensure that
-  // `create*` work correctly for structs.
-  DACtx->addModeledFields(Fields);
-
-  initVars(Vars);
+  initFieldsAndGlobals(FuncDecl);
 
   const auto *ParamIt = FuncDecl->param_begin();
 
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -460,8 +460,9 @@
   void pushCallInternal(const FunctionDecl *FuncDecl,
 ArrayRef Args);
 
-  /// Assigns storage locations and values to all variables in `Vars`.
-  void initVars(llvm::DenseSet Vars);
+  /// Assigns storage locations and values to all global variables and fields
+  /// referenced in `FuncDecl`. `FuncDecl` must have a body.
+  void initFieldsAndGlobals(const FunctionDecl *FuncDecl);
 
   // `DACtx` is not null and not owned by this object.
   Dataflow

[PATCH] D147326: [clang][dataflow][NFC] Share code between Environment ctor and pushCallInternal().

2023-04-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme added inline comments.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:465
+  /// referenced in `FuncDecl`. `FuncDecl` must have a body.
+  void initVars(const FunctionDecl *FuncDecl);
 

ymandel wrote:
> xazax.hun wrote:
> > I wonder if we should rename this to something like `initFieldAndGlobals`.
> +1
Done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147326

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


[PATCH] D147302: [clang][dataflow] Add `create()` methods to `Environment` and `DataflowAnalysisContext`.

2023-04-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme updated this revision to Diff 510416.
mboehme added a comment.

Changes in response to review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147302

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

Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -312,8 +312,7 @@
 
   if (Member->getType()->isReferenceType()) {
 auto &MemberLoc = ThisLoc.getChild(*Member);
-Env.setValue(MemberLoc, Env.takeOwnership(std::make_unique(
-*InitStmtLoc)));
+Env.setValue(MemberLoc, Env.create(*InitStmtLoc));
   } else {
 auto &MemberLoc = ThisLoc.getChild(*Member);
 Env.setValue(MemberLoc, *InitStmtVal);
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -237,7 +237,7 @@
   Env.setStorageLocation(*S, *DeclLoc);
 } else {
   auto &Loc = Env.createStorageLocation(*S);
-  auto &Val = Env.takeOwnership(std::make_unique(*DeclLoc));
+  auto &Val = Env.create(*DeclLoc);
   Env.setStorageLocation(*S, Loc);
   Env.setValue(Loc, Val);
 }
@@ -276,8 +276,7 @@
   // FIXME: reuse the ReferenceValue instead of creating a new one.
   if (auto *InitExprLoc =
   Env.getStorageLocation(*InitExpr, SkipPast::Reference)) {
-auto &Val =
-Env.takeOwnership(std::make_unique(*InitExprLoc));
+auto &Val = Env.create(*InitExprLoc);
 Env.setValue(Loc, Val);
   }
 } else if (auto *InitExprVal = Env.getValue(*InitExpr, SkipPast::None)) {
@@ -423,8 +422,8 @@
 
   auto &Loc = Env.createStorageLocation(*S);
   Env.setStorageLocation(*S, Loc);
-  Env.setValue(Loc, Env.takeOwnership(std::make_unique(
-SubExprVal->getPointeeLoc(;
+  Env.setValue(Loc,
+   Env.create(SubExprVal->getPointeeLoc()));
   break;
 }
 case UO_AddrOf: {
@@ -437,8 +436,7 @@
 break;
 
   auto &PointerLoc = Env.createStorageLocation(*S);
-  auto &PointerVal =
-  Env.takeOwnership(std::make_unique(*PointeeLoc));
+  auto &PointerVal = Env.create(*PointeeLoc);
   Env.setStorageLocation(*S, PointerLoc);
   Env.setValue(PointerLoc, PointerVal);
   break;
@@ -468,8 +466,7 @@
 
 auto &Loc = Env.createStorageLocation(*S);
 Env.setStorageLocation(*S, Loc);
-Env.setValue(Loc, Env.takeOwnership(
-  std::make_unique(*ThisPointeeLoc)));
+Env.setValue(Loc, Env.create(*ThisPointeeLoc));
   }
 
   void VisitReturnStmt(const ReturnStmt *S) {
@@ -523,8 +520,7 @@
 } else {
   auto &Loc = Env.createStorageLocation(*S);
   Env.setStorageLocation(*S, Loc);
-  Env.setValue(Loc, Env.takeOwnership(
-std::make_unique(*VarDeclLoc)));
+  Env.setValue(Loc, Env.create(*VarDeclLoc));
 }
 return;
   }
@@ -558,8 +554,7 @@
 } else {
   auto &Loc = Env.createStorageLocation(*S);
   Env.setStorageLocation(*S, Loc);
-  Env.setValue(
-  Loc, Env.takeOwnership(std::make_unique(MemberLoc)));
+  Env.setValue(Loc, Env.create(MemberLoc));
 }
   }
 
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -221,9 +221,9 @@
 /// Creates a symbolic value for an `optional` value using `HasValueVal` as the
 /// symbolic value of its "has_value" property.
 StructValue &createOptionalValue(Environment &Env, BoolValue &HasValueVal) {
-  auto OptionalVal = std::make_unique();
-  setHasValue(*OptionalVal, HasValueVal);
-  return Env.takeOwnership(std::move(OptionalVal));
+  auto &OptionalVal = Env.create();
+  setHasValue(OptionalVal, HasValueVal);
+  return OptionalVal;
 }
 
 /// Returns the symbolic value that represents the "has_value" property of the
@@ -312,8 +312,8 @@
 return nullptr;
   auto &ValueLoc = Env.createStorageLocation(Ty);
   Env.setValue(ValueLoc, *ValueVal);
-  auto 

[PATCH] D147302: [clang][dataflow] Add `create()` methods to `Environment` and `DataflowAnalysisContext`.

2023-04-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked an inline comment as done.
mboehme added inline comments.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:100
+// used `StorageLocation` subclasses and make them use a 
`BumpPtrAllocator`.
+Locs.push_back(std::make_unique(std::forward(args)...));
+return *cast(Locs.back().get());

xazax.hun wrote:
> Would emplace back work? That returns a reference to the just emplaced 
> element saving us the call to `back` making the code a bit more concise.
Nice -- thanks for the suggestion! Done.



Comment at: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h:328
+  template 
+  std::enable_if_t::value, T &>
+  create(Args &&...args) {

xazax.hun wrote:
> Just curious, what is the reason for repeating the `enable_if` here in 
> addition to the one in the called function? Do we get better error messages?
Yes, the idea is:

  - We get error messages from the interface of `create()` rather than the 
implementation
  - The `enable_if` documents intent. (The comment above states this intent 
too, but it's always nicer to have the code itself state the intent if 
possible.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147302

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


[PATCH] D147417: [clang-tidy] Do not emit bugprone-exception-escape warnings from coroutines

2023-04-03 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape-coro.cpp:115
+
+// CHECK-MESSAGES

add tests with c_yield and co_await


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147417

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


[PATCH] D146987: [Assignment Tracking] Enable by default

2023-04-03 Thread Orlando Cazalet-Hyams via Phabricator via cfe-commits
Orlando added a comment.

Hi @haowei, thanks for the report and revert.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[PATCH] D147417: [clang-tidy] Do not emit bugprone-exception-escape warnings from coroutines

2023-04-03 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape-coro.cpp:75-79
+  // CHECK-MESSAGES-NOT: :[[@LINE-1]]:11: warning: an exception may be thrown 
in function 'b_ShouldNotDiag' which should not throw exceptions
+  if (b == 0)
+throw b;
+
+  co_return a / b;

I don't understand why we shouldn't emit the warning here. Since the function 
is marked `noexcept` but it may throw actually in `unhandled_exception`. I 
think it is meaningful to warn for this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147417

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


[PATCH] D146941: [clangd] Use all inputs to SystemIncludeExtractor in cache key

2023-04-03 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/SystemIncludeExtractor.cpp:80
+  std::string Driver;
+  std::string Directory;
+  // Whether certain includes should be part of query.

It looks like the purpose of including `Directory` in the key is to use it in 
`make_absolute` in case where `Driver` is not an absolute path.

I wonder if it would make sense to perform that `make_absolute` operation 
eagerly and store its result in the key instead.

I'm thinking of a scenario where a project has say 10,000 source files in 500 
directories, and in the `compile_commands.json` entries the `directory` is the 
directory immediately containing the source file (or a corresponding directory 
in a `build/` directory hierarchy). In such cases, having the directory be in 
the key would mean executing the driver 500 times instead of just once 
(assuming no other properties are different) during indexing.



Comment at: clang-tools-extra/clangd/SystemIncludeExtractor.cpp:138
+  if (Type == driver::types::TY_INVALID) {
+elog("System include extraction: invalid file type for {0}", Ext);
+  } else {

The previous behaviour was to abort system include extraction in this case.

Assuming you're not looking to change that behaviour, one way to preserve it 
could be to have `render()` check for an empty `Lang` and return an empty 
vector in that case, and also have `extractSystemIncludesAndTarget()` check for 
`render()` returning an empty vector and return an empty optional in that case.



Comment at: clang-tools-extra/clangd/test/system-include-extractor.test:45
 # can match output lines like "ASTWorker building file"
-# RUN: clangd -lit-test -query-driver="**.test,**.sh" < %t.test 2>&1 | 
FileCheck -strict-whitespace %t.test
+# RUN: clangd -lit-test -query-driver="**.test,**.sh" < %t.test 2>&1 | 
FileCheck -strict-whitespace %t.test -dump-input=fail
 {"jsonrpc":"2.0","id":0,"method":"initialize","params":{}}

(did you mean to add `-dump-input=fail` here? according to FileCheck docs 
that's the default)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146941

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


[clang] ce0ab9d - [clang][dataflow][NFC] Share code between Environment ctor and pushCallInternal().

2023-04-03 Thread Martin Braenne via cfe-commits

Author: Martin Braenne
Date: 2023-04-03T08:25:10Z
New Revision: ce0ab9d11cec0a81c4e48645a23fa8eddea926ab

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

LOG: [clang][dataflow][NFC] Share code between Environment ctor and 
pushCallInternal().

The deduplicated code is moved into initVars().

As an added bonus, pushCallInternal() now also gets the "Add all fields
mentioned in default member initializers" behavior, which apparently had been
added to the Environment ctor but not pushCallInternal().

Reviewed By: xazax.hun, ymandel

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

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 678e5b871cc83..b4ae172e3fa2f 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -460,8 +460,9 @@ class Environment {
   void pushCallInternal(const FunctionDecl *FuncDecl,
 ArrayRef Args);
 
-  /// Assigns storage locations and values to all variables in `Vars`.
-  void initVars(llvm::DenseSet Vars);
+  /// Assigns storage locations and values to all global variables and fields
+  /// referenced in `FuncDecl`. `FuncDecl` must have a body.
+  void initFieldsAndGlobals(const FunctionDecl *FuncDecl);
 
   // `DACtx` is not null and not owned by this object.
   DataflowAnalysisContext *DACtx;

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index e3bde37ea68f7..fbb8d8ab7edda 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -203,7 +203,33 @@ static void getFieldsAndGlobalVars(const Stmt &S,
 
 // FIXME: Add support for resetting globals after function calls to enable
 // the implementation of sound analyses.
-void Environment::initVars(llvm::DenseSet Vars) {
+void Environment::initFieldsAndGlobals(const FunctionDecl *FuncDecl) {
+  assert(FuncDecl->getBody() != nullptr);
+
+  llvm::DenseSet Fields;
+  llvm::DenseSet Vars;
+
+  // Look for global variable and field references in the
+  // constructor-initializers.
+  if (const auto *CtorDecl = dyn_cast(FuncDecl)) {
+for (const auto *Init : CtorDecl->inits()) {
+  if (const auto *M = Init->getAnyMember())
+  Fields.insert(M);
+  const Expr *E = Init->getInit();
+  assert(E != nullptr);
+  getFieldsAndGlobalVars(*E, Fields, Vars);
+}
+// Add all fields mentioned in default member initializers.
+for (const FieldDecl *F : CtorDecl->getParent()->fields())
+  if (const auto *I = F->getInClassInitializer())
+  getFieldsAndGlobalVars(*I, Fields, Vars);
+  }
+  getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
+
+  // These have to be added before the lines that follow to ensure that
+  // `create*` work correctly for structs.
+  DACtx->addModeledFields(Fields);
+
   for (const VarDecl *D : Vars) {
 if (getStorageLocation(*D, SkipPast::None) != nullptr)
   continue;
@@ -239,31 +265,7 @@ Environment::Environment(DataflowAnalysisContext &DACtx,
   if (const auto *FuncDecl = dyn_cast(&DeclCtx)) {
 assert(FuncDecl->getBody() != nullptr);
 
-llvm::DenseSet Fields;
-llvm::DenseSet Vars;
-
-// Look for global variable and field references in the
-// constructor-initializers.
-if (const auto *CtorDecl = dyn_cast(&DeclCtx)) {
-  for (const auto *Init : CtorDecl->inits()) {
-if (const auto *M = Init->getAnyMember())
-  Fields.insert(M);
-const Expr *E = Init->getInit();
-assert(E != nullptr);
-getFieldsAndGlobalVars(*E, Fields, Vars);
-  }
-  // Add all fields mentioned in default member initializers.
-  for (const FieldDecl *F  : CtorDecl->getParent()->fields())
-if (const auto *I = F->getInClassInitializer())
-  getFieldsAndGlobalVars(*I, Fields, Vars);
-}
-getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
-
-// These have to be added before the lines that follow to ensure that
-// `create*` work correctly for structs.
-DACtx.addModeledFields(Fields);
-
-initVars(Vars);
+initFieldsAndGlobals(FuncDecl);
 
 for (const auto *ParamDecl : FuncDecl->parameters()) {
   assert(ParamDecl != nullptr);
@@ -337,26 +339,7 @@ void Environment::pushCallInternal(const FunctionDecl 
*FuncDecl,
ArrayRef Args) {
   CallStack.push_back(FuncDecl);

[PATCH] D147326: [clang][dataflow][NFC] Share code between Environment ctor and pushCallInternal().

2023-04-03 Thread Martin Böhme via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGce0ab9d11cec: [clang][dataflow][NFC] Share code between 
Environment ctor and pushCallInternal… (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147326

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

Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -203,7 +203,33 @@
 
 // FIXME: Add support for resetting globals after function calls to enable
 // the implementation of sound analyses.
-void Environment::initVars(llvm::DenseSet Vars) {
+void Environment::initFieldsAndGlobals(const FunctionDecl *FuncDecl) {
+  assert(FuncDecl->getBody() != nullptr);
+
+  llvm::DenseSet Fields;
+  llvm::DenseSet Vars;
+
+  // Look for global variable and field references in the
+  // constructor-initializers.
+  if (const auto *CtorDecl = dyn_cast(FuncDecl)) {
+for (const auto *Init : CtorDecl->inits()) {
+  if (const auto *M = Init->getAnyMember())
+  Fields.insert(M);
+  const Expr *E = Init->getInit();
+  assert(E != nullptr);
+  getFieldsAndGlobalVars(*E, Fields, Vars);
+}
+// Add all fields mentioned in default member initializers.
+for (const FieldDecl *F : CtorDecl->getParent()->fields())
+  if (const auto *I = F->getInClassInitializer())
+  getFieldsAndGlobalVars(*I, Fields, Vars);
+  }
+  getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
+
+  // These have to be added before the lines that follow to ensure that
+  // `create*` work correctly for structs.
+  DACtx->addModeledFields(Fields);
+
   for (const VarDecl *D : Vars) {
 if (getStorageLocation(*D, SkipPast::None) != nullptr)
   continue;
@@ -239,31 +265,7 @@
   if (const auto *FuncDecl = dyn_cast(&DeclCtx)) {
 assert(FuncDecl->getBody() != nullptr);
 
-llvm::DenseSet Fields;
-llvm::DenseSet Vars;
-
-// Look for global variable and field references in the
-// constructor-initializers.
-if (const auto *CtorDecl = dyn_cast(&DeclCtx)) {
-  for (const auto *Init : CtorDecl->inits()) {
-if (const auto *M = Init->getAnyMember())
-  Fields.insert(M);
-const Expr *E = Init->getInit();
-assert(E != nullptr);
-getFieldsAndGlobalVars(*E, Fields, Vars);
-  }
-  // Add all fields mentioned in default member initializers.
-  for (const FieldDecl *F  : CtorDecl->getParent()->fields())
-if (const auto *I = F->getInClassInitializer())
-  getFieldsAndGlobalVars(*I, Fields, Vars);
-}
-getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
-
-// These have to be added before the lines that follow to ensure that
-// `create*` work correctly for structs.
-DACtx.addModeledFields(Fields);
-
-initVars(Vars);
+initFieldsAndGlobals(FuncDecl);
 
 for (const auto *ParamDecl : FuncDecl->parameters()) {
   assert(ParamDecl != nullptr);
@@ -337,26 +339,7 @@
ArrayRef Args) {
   CallStack.push_back(FuncDecl);
 
-  // FIXME: Share this code with the constructor, rather than duplicating it.
-  llvm::DenseSet Fields;
-  llvm::DenseSet Vars;
-  // Look for global variable references in the constructor-initializers.
-  if (const auto *CtorDecl = dyn_cast(FuncDecl)) {
-for (const auto *Init : CtorDecl->inits()) {
-  if (const auto *M = Init->getAnyMember())
-Fields.insert(M);
-  const Expr *E = Init->getInit();
-  assert(E != nullptr);
-  getFieldsAndGlobalVars(*E, Fields, Vars);
-}
-  }
-  getFieldsAndGlobalVars(*FuncDecl->getBody(), Fields, Vars);
-
-  // These have to be added before the lines that follow to ensure that
-  // `create*` work correctly for structs.
-  DACtx->addModeledFields(Fields);
-
-  initVars(Vars);
+  initFieldsAndGlobals(FuncDecl);
 
   const auto *ParamIt = FuncDecl->param_begin();
 
Index: clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
===
--- clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -460,8 +460,9 @@
   void pushCallInternal(const FunctionDecl *FuncDecl,
 ArrayRef Args);
 
-  /// Assigns storage locations and values to all variables in `Vars`.
-  void initVars(llvm::DenseSet Vars);
+  /// Assigns storage locations and values to all global variables and fields
+  /// referenced in `FuncDecl`. `FuncDecl` must have a body.
+  void initFieldsAndGlobals(const FunctionDecl *FuncDecl);
 
   // `DACtx` is not null and not owned by

[PATCH] D145868: [clang][ASTImporter] Fix import of typedef with unnamed structures

2023-04-03 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

ping
This is a solution for a problem at least until a better fix is found.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145868

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


[PATCH] D146987: [Assignment Tracking] Enable by default

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

We've also seen  crashes with this patch, e.g.

  clang -cc1 -triple x86_64-unknown-linux -emit-obj 
-debug-info-kind=constructor -O1 bbi-80938.c

crashes with

  clang: ../include/llvm/ADT/IntervalMap.h:1187: bool 
llvm::IntervalMap >::overlaps(KeyT, KeyT) const [KeyT 
= unsigned int, ValT = unsigned int, N = 16, Traits = 
llvm::IntervalMapHalfOpenInfo]: Assertion `Traits::nonEmpty(a, 
b)' failed.
  PLEASE submit a bug report to 
https://developer.internal.ericsson.com/docs/bbi/languages/support/ and include 
the crash backtrace, preprocessed source, and associated run script.
  Stack dump:
  0.Program arguments: build-all/bin/clang -cc1 -triple 
x86_64-unknown-linux -emit-obj -debug-info-kind=constructor -O1 bbi-80938.c
  1. parser at end of file
  2.Code generation
  3.Running pass 'Function Pass Manager' on module 'bbi-80938.c'.
  4.Running pass 'Assignment Tracking Analysis' on function '@main'
   #0 0x03213388 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) 
(build-all/bin/clang+0x3213388)
   #1 0x03210f1e llvm::sys::RunSignalHandlers() 
(build-all/bin/clang+0x3210f1e)
   #2 0x03213a06 SignalHandler(int) Signals.cpp:0:0
   #3 0x7f483e5c8630 __restore_rt sigaction.c:0:0
   #4 0x7f483bd0f387 raise (/lib64/libc.so.6+0x36387)
   #5 0x7f483bd10a78 abort (/lib64/libc.so.6+0x37a78)
   #6 0x7f483bd081a6 __assert_fail_base (/lib64/libc.so.6+0x2f1a6)
   #7 0x7f483bd08252 (/lib64/libc.so.6+0x2f252)
   #8 0x02a749e9 llvm::IntervalMap>::overlaps(unsigned int, unsigned 
int) const crtstuff.c:0:0
   #9 0x02a5e420 (anonymous 
namespace)::MemLocFragmentFill::run(FunctionVarLocsBuilder*) 
AssignmentTrackingAnalysis.cpp:0:0
  #10 0x02a567b9 
llvm::AssignmentTrackingAnalysis::runOnFunction(llvm::Function&) 
(build-all/bin/clang+0x2a567b9)
  #11 0x02bd91bf llvm::FPPassManager::runOnFunction(llvm::Function&) 
(build-all/bin/clang+0x2bd91bf)
  #12 0x02be00c8 llvm::FPPassManager::runOnModule(llvm::Module&) 
(build-all/bin/clang+0x2be00c8)
  #13 0x02bd9787 llvm::legacy::PassManagerImpl::run(llvm::Module&) 
(build-all/bin/clang+0x2bd9787)
  #14 0x034187fe clang::EmitBackendOutput(clang::DiagnosticsEngine&, 
clang::HeaderSearchOptions const&, clang::CodeGenOptions const&, 
clang::TargetOptions const&, clang::LangOptions const&, llvm::StringRef, 
llvm::Module*, clang::BackendAction, 
llvm::IntrusiveRefCntPtr, 
std::unique_ptr>) (build-all/bin/clang+0x34187fe)
  #15 0x0432c062 
clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) crtstuff.c:0:0
  #16 0x04dfeb53 clang::ParseAST(clang::Sema&, bool, bool) 
(build-all/bin/clang+0x4dfeb53)
  #17 0x03c363e6 clang::FrontendAction::Execute() 
(build-all/bin/clang+0x3c363e6)
  #18 0x03ba1724 
clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) 
(build-all/bin/clang+0x3ba1724)
  #19 0x03cfbafb 
clang::ExecuteCompilerInvocation(clang::CompilerInstance*) 
(build-all/bin/clang+0x3cfbafb)
  #20 0x00a5b1fc cc1_main(llvm::ArrayRef, char const*, 
void*) (build-all/bin/clang+0xa5b1fc)
  #21 0x00a57050 ExecuteCC1Tool(llvm::SmallVectorImpl&, 
llvm::ToolContext const&) driver.cpp:0:0
  #22 0x00a55087 clang_main(int, char**, llvm::ToolContext const&) 
(build-all/bin/clang+0xa55087)
  #23 0x00a66c91 main (build-all/bin/clang+0xa66c91)
  #24 0x7f483bcfb555 __libc_start_main (/lib64/libc.so.6+0x22555)
  #25 0x00a5277b _start (build-all/bin/clang+0xa5277b)
  Abort (core dumped)

I've no idea if thiis is the same problem already reported above or not.
F26992749: bbi-80938.c 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[PATCH] D147073: [Coverage] Handle invalid end location of an expression/statement.

2023-04-03 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

I'm not familiar with this code. I suppose the question is whether it's 
reasonable for this code to expect that the source locations are always valid 
or not?




Comment at: clang/lib/CodeGen/CoverageMappingGen.cpp:605
 
+// If the either location is invalid, set it to std::nullopt to avoid
+// letting users of RegionStack think that region has a valid start/end

nit: the "the" is not needed



Comment at: clang/test/CoverageMapping/invalid_location.cpp:31
+//now because 'T{}' doesn't have a valid end location for now.
+// CHECK-NETX:   File 0, 13:9 -> 13:14 = #3
+// CHECK-NETX:   File 0, 13:18 -> 13:23 = (#0 - #3)

s/NETX/NEXT/ here and below?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147073

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


[PATCH] D146234: [clang] Fix crash when handling nested immediate invocations

2023-04-03 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added a comment.

@aaron.ballman , @cor3ntin are you ok with the patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146234

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


[PATCH] D147422: [clang-format] NFC Document the other space before colon option

2023-04-03 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

Should we extend `SpacesInContainerLiterals` so that it controls JSON colons 
too? If yes, then we don't need `SpaceBeforeJsonColon`. Otherwise, IMO we 
should leave the doc alone.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147422

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


[PATCH] D147422: [clang-format] NFC Document the other space before colon option

2023-04-03 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D147422#4240021 , @owenpan wrote:

> Should we extend `SpacesInContainerLiterals` so that it controls JSON colons 
> too? If yes, then we don't need `SpaceBeforeJsonColon`. Otherwise, IMO we 
> should leave the doc alone.

My concern for `SpacesInContainerLiterals` is that it impacts arrays contents 
too '[ 1, 2, 3 ]'.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147422

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


[PATCH] D147422: [clang-format] NFC Document the other space before colon option

2023-04-03 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D147422#4239701 , @Herald wrote:

> NOTE: Clang-Format Team Automated Review Comment
>
> It looks like your clang-format review does not contain any unit tests, 
> please try to ensure all code changes have a unit test (unless this is an 
> `NFC` or refactoring, adding documentation etc..)
>
> Add you unit tests in `clang/unittests/Format` and build `ninja FormatTests` 
> we recommend using the `verifyFormat(xxx)` format of unit tests rather than 
> `EXPECT_EQ` as this will ensure you change is tolerant to random whitespace 
> changes (see FormatTest.cpp as an example)
>
> For situations where your change is altering the TokenAnnotator.cpp which can 
> happen if you are trying to improve the annotation phase to ensure we are 
> correctly identifying the type of a token, please add a token annotator test 
> in `TokenAnnotatorTest.cpp`

Thanks for testing this automated comment ;-) , I've fixed some of the 
grammatical issue and made it so it won't fire if NFC is in the title.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147422

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


[clang] 968b417 - [clang][Interp] Fix derived-to-base casts for >1 levels

2023-04-03 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-03T11:35:55+02:00
New Revision: 968b4172f6a9878e56dc911f3f9df089d2a9134f

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

LOG: [clang][Interp] Fix derived-to-base casts for >1 levels

The GetPtrBasePop op we were using only works for direct base classes.

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 733247787d760..ad802f72aad4c 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -85,15 +85,8 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
 if (!this->visit(SubExpr))
   return false;
 
-const CXXRecordDecl *FromDecl = getRecordDecl(SubExpr);
-assert(FromDecl);
-const CXXRecordDecl *ToDecl = getRecordDecl(CE);
-assert(ToDecl);
-const Record *R = getRecord(FromDecl);
-const Record::Base *ToBase = R->getBase(ToDecl);
-assert(ToBase);
-
-return this->emitGetPtrBasePop(ToBase->Offset, CE);
+return this->emitDerivedToBaseCasts(getRecordTy(SubExpr->getType()),
+getRecordTy(CE->getType()), CE);
   }
 
   case CK_FloatingCast: {
@@ -1873,6 +1866,38 @@ void ByteCodeExprGen::emitCleanup() {
 C->emitDestruction();
 }
 
+template 
+bool ByteCodeExprGen::emitDerivedToBaseCasts(
+const RecordType *DerivedType, const RecordType *BaseType, const Expr *E) {
+  // Pointer of derived type is already on the stack.
+  const auto *FinalDecl = cast(BaseType->getDecl());
+  const RecordDecl *CurDecl = DerivedType->getDecl();
+  const Record *CurRecord = getRecord(CurDecl);
+  assert(CurDecl && FinalDecl);
+  for (;;) {
+assert(CurRecord->getNumBases() > 0);
+// One level up
+for (const Record::Base &B : CurRecord->bases()) {
+  const auto *BaseDecl = cast(B.Decl);
+
+  if (BaseDecl == FinalDecl || BaseDecl->isDerivedFrom(FinalDecl)) {
+// This decl will lead us to the final decl, so emit a base cast.
+if (!this->emitGetPtrBasePop(B.Offset, E))
+  return false;
+
+CurRecord = B.R;
+CurDecl = BaseDecl;
+break;
+  }
+}
+if (CurDecl == FinalDecl)
+  return true;
+  }
+
+  llvm_unreachable("Couldn't find the base class?");
+  return false;
+}
+
 /// When calling this, we have a pointer of the local-to-destroy
 /// on the stack.
 /// Emit destruction of record types (or arrays of record types).

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 4baf5d433c9e0..af5b4678b0703 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -260,6 +260,8 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   }
 
   bool emitRecordDestruction(const Descriptor *Desc);
+  bool emitDerivedToBaseCasts(const RecordType *DerivedType,
+  const RecordType *BaseType, const Expr *E);
 
 protected:
   /// Variable to storage mapping.

diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index 448e1c0eb7223..188db827fe08b 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -250,6 +250,21 @@ struct S {
 constexpr S s;
 static_assert(s.m() == 1, "");
 
+#if __cplusplus >= 201703L
+namespace BaseInit {
+  class A {public: int a;};
+  class B : public A {};
+  class C : public A {};
+  class D : public B, public C {};
+
+  // FIXME: Enable this once we support the initialization.
+  // This initializes D::B::A::a and not D::C::A::a.
+  //constexpr D d{12};
+  //static_assert(d.B::a == 12);
+  //static_assert(d.C::a == 0);
+};
+#endif
+
 namespace MI {
   class A {
   public:



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


[PATCH] D143480: [clang][Interp] Fix derived-to-base casts for >1 levels

2023-04-03 Thread Timm Bäder 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 rG968b4172f6a9: [clang][Interp] Fix derived-to-base casts for 
>1 levels (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D143480?vs=504022&id=510435#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143480

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/test/AST/Interp/records.cpp


Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -250,6 +250,21 @@
 constexpr S s;
 static_assert(s.m() == 1, "");
 
+#if __cplusplus >= 201703L
+namespace BaseInit {
+  class A {public: int a;};
+  class B : public A {};
+  class C : public A {};
+  class D : public B, public C {};
+
+  // FIXME: Enable this once we support the initialization.
+  // This initializes D::B::A::a and not D::C::A::a.
+  //constexpr D d{12};
+  //static_assert(d.B::a == 12);
+  //static_assert(d.C::a == 0);
+};
+#endif
+
 namespace MI {
   class A {
   public:
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -260,6 +260,8 @@
   }
 
   bool emitRecordDestruction(const Descriptor *Desc);
+  bool emitDerivedToBaseCasts(const RecordType *DerivedType,
+  const RecordType *BaseType, const Expr *E);
 
 protected:
   /// Variable to storage mapping.
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -85,15 +85,8 @@
 if (!this->visit(SubExpr))
   return false;
 
-const CXXRecordDecl *FromDecl = getRecordDecl(SubExpr);
-assert(FromDecl);
-const CXXRecordDecl *ToDecl = getRecordDecl(CE);
-assert(ToDecl);
-const Record *R = getRecord(FromDecl);
-const Record::Base *ToBase = R->getBase(ToDecl);
-assert(ToBase);
-
-return this->emitGetPtrBasePop(ToBase->Offset, CE);
+return this->emitDerivedToBaseCasts(getRecordTy(SubExpr->getType()),
+getRecordTy(CE->getType()), CE);
   }
 
   case CK_FloatingCast: {
@@ -1873,6 +1866,38 @@
 C->emitDestruction();
 }
 
+template 
+bool ByteCodeExprGen::emitDerivedToBaseCasts(
+const RecordType *DerivedType, const RecordType *BaseType, const Expr *E) {
+  // Pointer of derived type is already on the stack.
+  const auto *FinalDecl = cast(BaseType->getDecl());
+  const RecordDecl *CurDecl = DerivedType->getDecl();
+  const Record *CurRecord = getRecord(CurDecl);
+  assert(CurDecl && FinalDecl);
+  for (;;) {
+assert(CurRecord->getNumBases() > 0);
+// One level up
+for (const Record::Base &B : CurRecord->bases()) {
+  const auto *BaseDecl = cast(B.Decl);
+
+  if (BaseDecl == FinalDecl || BaseDecl->isDerivedFrom(FinalDecl)) {
+// This decl will lead us to the final decl, so emit a base cast.
+if (!this->emitGetPtrBasePop(B.Offset, E))
+  return false;
+
+CurRecord = B.R;
+CurDecl = BaseDecl;
+break;
+  }
+}
+if (CurDecl == FinalDecl)
+  return true;
+  }
+
+  llvm_unreachable("Couldn't find the base class?");
+  return false;
+}
+
 /// When calling this, we have a pointer of the local-to-destroy
 /// on the stack.
 /// Emit destruction of record types (or arrays of record types).


Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -250,6 +250,21 @@
 constexpr S s;
 static_assert(s.m() == 1, "");
 
+#if __cplusplus >= 201703L
+namespace BaseInit {
+  class A {public: int a;};
+  class B : public A {};
+  class C : public A {};
+  class D : public B, public C {};
+
+  // FIXME: Enable this once we support the initialization.
+  // This initializes D::B::A::a and not D::C::A::a.
+  //constexpr D d{12};
+  //static_assert(d.B::a == 12);
+  //static_assert(d.C::a == 0);
+};
+#endif
+
 namespace MI {
   class A {
   public:
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -260,6 +260,8 @@
   }
 
   bool emitRecordDestruction(const Descriptor *Desc);
+  bool emitDerivedToBaseCasts(const RecordType *DerivedType,
+  const RecordType *BaseType, const Expr *E);
 
 protected:
   /// Variable to storage mapping.
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===

[PATCH] D146757: [Driver] Enable defining multilib print options independently of flags

2023-04-03 Thread Michael Platings via Phabricator via cfe-commits
michaelplatings added a comment.

@phosek ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146757

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


[PATCH] D141389: [DFSAN] Add support for strnlen, strncat, strsep, sscanf and _tolower

2023-04-03 Thread Tomasz Kuchta via Phabricator via cfe-commits
tkuchta updated this revision to Diff 510442.
tkuchta added a comment.

Applied the latest review comments for strsep


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

https://reviews.llvm.org/D141389

Files:
  compiler-rt/lib/dfsan/dfsan_custom.cpp
  compiler-rt/lib/dfsan/done_abilist.txt
  compiler-rt/test/dfsan/custom.cpp

Index: compiler-rt/test/dfsan/custom.cpp
===
--- compiler-rt/test/dfsan/custom.cpp
+++ compiler-rt/test/dfsan/custom.cpp
@@ -1627,6 +1627,51 @@
 #endif
 }
 
+void test_strsep() {
+  char *s = strdup("Hello world/");
+  char *delim = strdup(" /");
+
+  char *p_s = s;
+  char *base = s;
+  char *p_delim = delim;
+
+  // taint delim bytes
+  dfsan_set_label(i_label, p_delim, strlen(p_delim));
+  // taint delim pointer
+  dfsan_set_label(j_label, &p_delim, sizeof(&p_delim));
+  // taint the string data bytes
+  dfsan_set_label(k_label, s, 5);
+  // taint the string pointer
+  dfsan_set_label(m_label, &p_s, sizeof(&p_s));
+
+  char *rv = strsep(&p_s, p_delim);
+  assert(rv == &base[0]);
+#ifdef STRICT_DATA_DEPENDENCIES
+  ASSERT_LABEL(rv, m_label);
+  ASSERT_READ_LABEL(rv, strlen(rv), k_label);
+#else
+  ASSERT_LABEL(rv, dfsan_union(dfsan_union(i_label, j_label),
+   dfsan_union(k_label, m_label)));
+  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, p_s);
+#endif
+
+  // taint the remaining string's pointer
+  char **pp_s = &p_s;
+  char **pp_s_base = pp_s;
+  dfsan_set_label(n_label, pp_s, sizeof(pp_s));
+
+  rv = strsep(pp_s, p_delim);
+
+  assert(rv == &base[6]);
+#ifdef STRICT_DATA_DEPENDENCIES
+  ASSERT_LABEL(rv, n_label);
+  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, *pp_s);
+#else
+  ASSERT_LABEL(rv, dfsan_union(dfsan_union(i_label, j_label), n_label));
+  ASSERT_INIT_ORIGIN_EQ_ORIGIN(&rv, *pp_s);
+#endif
+}
+
 void test_memchr() {
   char str1[] = "str1";
   dfsan_set_label(i_label, &str1[3], 1);
@@ -2041,6 +2086,7 @@
   test_strncmp();
   test_strncpy();
   test_strpbrk();
+  test_strsep();
   test_strrchr();
   test_strstr();
   test_strtod();
Index: compiler-rt/lib/dfsan/done_abilist.txt
===
--- compiler-rt/lib/dfsan/done_abilist.txt
+++ compiler-rt/lib/dfsan/done_abilist.txt
@@ -283,6 +283,7 @@
 fun:strpbrk=custom
 fun:strrchr=custom
 fun:strstr=custom
+fun:strsep=custom
 
 # Functions which take action based on global state, such as running a callback
 # set by a separate function.
Index: compiler-rt/lib/dfsan/dfsan_custom.cpp
===
--- compiler-rt/lib/dfsan/dfsan_custom.cpp
+++ compiler-rt/lib/dfsan/dfsan_custom.cpp
@@ -204,6 +204,58 @@
   return const_cast(ret);
 }
 
+SANITIZER_INTERFACE_ATTRIBUTE char *__dfsw_strsep(char **s, const char *delim,
+  dfsan_label s_label,
+  dfsan_label delim_label,
+  dfsan_label *ret_label) {
+  dfsan_label base_label = dfsan_read_label(s, sizeof(*s));
+  char *base = *s;
+  char *res = strsep(s, delim);
+  if (res != *s) {
+char *token_start = res;
+int token_length = strlen(res);
+// the delimiter byte has been set to NULL
+dfsan_set_label(0, token_start + token_length, 1);
+  }
+
+  if (flags().strict_data_dependencies) {
+*ret_label = res ? base_label : 0;
+  } else {
+size_t s_bytes_read = (res ? strlen(res) : strlen(base)) + 1;
+*ret_label = dfsan_union(
+dfsan_union(base_label, dfsan_read_label(base, sizeof(s_bytes_read))),
+dfsan_union(dfsan_read_label(delim, strlen(delim) + 1),
+dfsan_union(s_label, delim_label)));
+  }
+
+  return res;
+}
+
+SANITIZER_INTERFACE_ATTRIBUTE char *__dfso_strsep(
+char **s, const char *delim, dfsan_label s_label, dfsan_label delim_label,
+dfsan_label *ret_label, dfsan_origin s_origin, dfsan_origin delim_origin,
+dfsan_origin *ret_origin) {
+  dfsan_origin base_origin = dfsan_read_origin_of_first_taint(s, sizeof(*s));
+  char *base = *s;
+  char *res = __dfsw_strsep(s, delim, s_label, delim_label, ret_label);
+  if (flags().strict_data_dependencies) {
+if (res)
+  *ret_origin = base_origin;
+  } else {
+if (*ret_label) {
+  if (base_origin) {
+*ret_origin = base_origin;
+  } else {
+dfsan_origin o =
+dfsan_read_origin_of_first_taint(delim, strlen(delim) + 1);
+*ret_origin = o ? o : (s_label ? s_origin : delim_origin);
+  }
+}
+  }
+
+  return res;
+}
+
 static int dfsan_memcmp_bcmp(const void *s1, const void *s2, size_t n,
  size_t *bytes_read) {
   const char *cs1 = (const char *) s1, *cs2 = (const char *) s2;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147315: [clang-tidy] support unscoped enumerations in readability-static-accessed-through-instance

2023-04-03 Thread Congcong Cai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGedd6a33984ee: [clang-tidy] support unscoped enumerations in 
readability-static-accessed… (authored by HerrCai0907).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147315

Files:
  
clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/readability/static-accessed-through-instance.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp
@@ -1,10 +1,21 @@
 // RUN: %check_clang_tidy %s readability-static-accessed-through-instance %t -- -- -isystem %S/Inputs/static-accessed-through-instance
 #include <__clang_cuda_builtin_vars.h>
 
+enum OutEnum {
+  E0,
+};
+
 struct C {
   static void foo();
   static int x;
   int nsx;
+  enum {
+Anonymous,
+  };
+  enum E {
+E1,
+  };
+  using enum OutEnum;
   void mf() {
 (void)&x;// OK, x is accessed inside the struct.
 (void)&C::x; // OK, x is accessed using a qualified-id.
@@ -144,6 +155,16 @@
   c1->x; // 2
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
   // CHECK-FIXES: {{^}}  C::x; // 2{{$}}
+  c1->Anonymous; // 3
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  C::Anonymous; // 3{{$}}
+  c1->E1; // 4
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  C::E1; // 4{{$}}
+  c1->E0; // 5
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member
+  // CHECK-FIXES: {{^}}  C::E0; // 5{{$}}
+
   c1->nsx; // OK, nsx is a non-static member.
 
   const C *c2 = new C();
Index: clang-tools-extra/docs/clang-tidy/checks/readability/static-accessed-through-instance.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/readability/static-accessed-through-instance.rst
+++ clang-tools-extra/docs/clang-tidy/checks/readability/static-accessed-through-instance.rst
@@ -15,11 +15,15 @@
   struct C {
 static void foo();
 static int x;
+enum { E1 };
+enum E { E2 };
   };
 
   C *c1 = new C();
   c1->foo();
   c1->x;
+  c1->E1;
+  c1->E2;
 
 is changed to:
 
@@ -28,4 +32,6 @@
   C *c1 = new C();
   C::foo();
   C::x;
+  C::E1;
+  C::E2;
 
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -254,6 +254,10 @@
   ` check when warning would
   be unnecessarily emitted for template dependent ``if constexpr``.
 
+- Improved :doc:`readability-static-accessed-through-instance
+  ` check to 
+  support unscoped enumerations through instances.
+
 - Fixed a false positive in :doc:`cppcoreguidelines-slicing
   ` check when warning would be
   emitted in constructor for virtual base class initialization.
Index: clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
@@ -39,7 +39,8 @@
 void StaticAccessedThroughInstanceCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   memberExpr(hasDeclaration(anyOf(cxxMethodDecl(isStaticStorageClass()),
-  varDecl(hasStaticStorageDuration()
+  varDecl(hasStaticStorageDuration()),
+  enumConstantDecl(
   .bind("memberExpression"),
   this);
 }
@@ -64,15 +65,15 @@
   : BaseExpr->getType().getUnqualifiedType();
 
   const ASTContext *AstContext = Result.Context;
-  PrintingPolicy PrintingPolicyWithSupressedTag(AstContext->getLangOpts());
-  PrintingPolicyWithSupressedTag.SuppressTagKeyword = true;
-  PrintingPolicyWithSupressedTag.SuppressUnwrittenScope = true;
+  PrintingPolicy PrintingPolicyWithSuppressedTag(AstContext->getLangOpts());
+  PrintingPolicyWithSuppressedTag.SuppressTagKeyword = true;
+  PrintingPolicyWithSuppressedTag.SuppressUnwrittenScope = true;
 
-  PrintingPolicyWithSupressedTag.PrintCanonicalTypes =
+  PrintingPolicyWithSuppressedTag.PrintCanonicalTypes =
   !BaseExpr->getType()->isTypedefNameType();
 
   std::string BaseTypeName =
-  BaseType.getAsString(PrintingPolicyWithSupressedTag);
+  BaseType.getAsStrin

[clang-tools-extra] edd6a33 - [clang-tidy] support unscoped enumerations in readability-static-accessed-through-instance

2023-04-03 Thread Congcong Cai via cfe-commits

Author: Congcong Cai
Date: 2023-04-03T12:58:35+02:00
New Revision: edd6a33984eeb57bd4e8d3459878cc7a66825389

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

LOG: [clang-tidy] support unscoped enumerations in 
readability-static-accessed-through-instance

fixed [60810](https://github.com/llvm/llvm-project/issues/60810)
unscoped enumerations in class can also be checked by 
`readability-static-accessed-through-instance`
add matcher for `enumConstantDecl` to match format
```
struct {
enum { E1 };
};
```
The filter of member expression and the fix hint should be same as other 
condition.

Reviewed By: PiotrZSL

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

Added: 


Modified: 

clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/docs/clang-tidy/checks/readability/static-accessed-through-instance.rst

clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
 
b/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
index b23b67e6261d..4bb14850d602 100644
--- 
a/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
@@ -39,7 +39,8 @@ void StaticAccessedThroughInstanceCheck::storeOptions(
 void StaticAccessedThroughInstanceCheck::registerMatchers(MatchFinder *Finder) 
{
   Finder->addMatcher(
   memberExpr(hasDeclaration(anyOf(cxxMethodDecl(isStaticStorageClass()),
-  varDecl(hasStaticStorageDuration()
+  varDecl(hasStaticStorageDuration()),
+  enumConstantDecl(
   .bind("memberExpression"),
   this);
 }
@@ -64,15 +65,15 @@ void StaticAccessedThroughInstanceCheck::check(
   : BaseExpr->getType().getUnqualifiedType();
 
   const ASTContext *AstContext = Result.Context;
-  PrintingPolicy PrintingPolicyWithSupressedTag(AstContext->getLangOpts());
-  PrintingPolicyWithSupressedTag.SuppressTagKeyword = true;
-  PrintingPolicyWithSupressedTag.SuppressUnwrittenScope = true;
+  PrintingPolicy PrintingPolicyWithSuppressedTag(AstContext->getLangOpts());
+  PrintingPolicyWithSuppressedTag.SuppressTagKeyword = true;
+  PrintingPolicyWithSuppressedTag.SuppressUnwrittenScope = true;
 
-  PrintingPolicyWithSupressedTag.PrintCanonicalTypes =
+  PrintingPolicyWithSuppressedTag.PrintCanonicalTypes =
   !BaseExpr->getType()->isTypedefNameType();
 
   std::string BaseTypeName =
-  BaseType.getAsString(PrintingPolicyWithSupressedTag);
+  BaseType.getAsString(PrintingPolicyWithSuppressedTag);
 
   // Do not warn for CUDA built-in variables.
   if (StringRef(BaseTypeName).startswith("__cuda_builtin_"))

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 099211e59254..8a82e4e5ca56 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -254,6 +254,10 @@ Changes in existing checks
   ` check when warning 
would
   be unnecessarily emitted for template dependent ``if constexpr``.
 
+- Improved :doc:`readability-static-accessed-through-instance
+  ` check to 
+  support unscoped enumerations through instances.
+
 - Fixed a false positive in :doc:`cppcoreguidelines-slicing
   ` check when warning would be
   emitted in constructor for virtual base class initialization.

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/readability/static-accessed-through-instance.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/readability/static-accessed-through-instance.rst
index 879b87c2feb5..23d12f418366 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/readability/static-accessed-through-instance.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/readability/static-accessed-through-instance.rst
@@ -15,11 +15,15 @@ The following code:
   struct C {
 static void foo();
 static int x;
+enum { E1 };
+enum E { E2 };
   };
 
   C *c1 = new C();
   c1->foo();
   c1->x;
+  c1->E1;
+  c1->E2;
 
 is changed to:
 
@@ -28,4 +32,6 @@ is changed to:
   C *c1 = new C();
   C::foo();
   C::x;
+  C::E1;
+  C::E2;
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp
index 5b1265dcc355..6d4a03421913 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp
+++ 
b/clang-tools-extra/te

[PATCH] D147395: [Clangd] Make the type hint length limit configurable

2023-04-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

Thanks for the contribution!




Comment at: clang-tools-extra/clangd/Config.h:151
+// Limit the length of type names in inlay hints.
+size_t TypeNameLimit = 32;
   } InlayHints;

I would extend it a bit more -- 0 means no limit. 

Can you also add a unittest in `TEST(TypeHints, LongTypeName)` in 
`InlayHintTests.cpp`? 



Comment at: clang-tools-extra/clangd/ConfigFragment.h:326
+/// Limit the length of type name hints.
+std::optional> TypeNameLimit;
   };

if we add `uint32Value` method (see my other comment), then the type is 
`std::optional>`. 



Comment at: clang-tools-extra/clangd/ConfigYAML.cpp:258
+Dict.handle("TypeNameLimit", [&](Node &N) {
+  if (auto Value = scalarValue(N, "TypeNameLimit"))
+F.TypeNameLimit = *Value;

Similar to the `boolValue`, I think it would be better to have a `uint32Value` 
method (this is the first time that we have an integer in the config), 
something like below

```
 std::optional> uint32Value(Node &N, llvm::StringRef Desc) {
   if (auto Scalar = scalarValue(N, Desc)) {
unsigned long long n;
if (getAsUnsignedInteger(Scalar, 0, n)) {
   warning(Desc + "invalid number", N);
   return;
}
return Located(n, Scalar->Range);
}
return std::nullopt;
}
```




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147395

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


[PATCH] D146987: [Assignment Tracking] Enable by default

2023-04-03 Thread Orlando Cazalet-Hyams via Phabricator via cfe-commits
Orlando added a comment.

Thank you @uabelho for the reproducer-  I've added a fix  in D147435 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146987

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


[PATCH] D146557: [MLIR][OpenMP] Refactoring how map clause is processed

2023-04-03 Thread Akash Banerjee via Phabricator via cfe-commits
TIFitis marked 2 inline comments as not done.
TIFitis added a comment.

Polite request for reviews. Thanks :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146557

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


[clang] db3dcdc - [clang][Interp] Fix initializing base class members

2023-04-03 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-03T13:51:04+02:00
New Revision: db3dcdc08ce06e301cdcc75e2849315a47d7a28d

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

LOG: [clang][Interp] Fix initializing base class members

For the given test case, we were trying to initialize a member of C,
which doesn't have any. Get the proper base pointer instead and
initialize the members there.

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/Interp.cpp
clang/lib/AST/Interp/Record.cpp
clang/lib/AST/Interp/Record.h
clang/test/AST/Interp/cxx20.cpp
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index ad802f72aad4c..665f60d572ea7 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1370,12 +1370,12 @@ bool 
ByteCodeExprGen::visitRecordInitializer(const Expr *Initializer) {
 
 unsigned InitIndex = 0;
 for (const Expr *Init : InitList->inits()) {
-  const Record::Field *FieldToInit = R->getField(InitIndex);
 
   if (!this->emitDupPtr(Initializer))
 return false;
 
   if (std::optional T = classify(Init)) {
+const Record::Field *FieldToInit = R->getField(InitIndex);
 if (!this->visit(Init))
   return false;
 
@@ -1385,16 +1385,29 @@ bool 
ByteCodeExprGen::visitRecordInitializer(const Expr *Initializer) {
 if (!this->emitPopPtr(Initializer))
   return false;
   } else {
-// Non-primitive case. Get a pointer to the field-to-initialize
-// on the stack and recurse into visitInitializer().
-if (!this->emitGetPtrField(FieldToInit->Offset, Init))
-  return false;
+// Initializer for a direct base class.
+if (const Record::Base *B = R->getBase(Init->getType())) {
+  if (!this->emitGetPtrBasePop(B->Offset, Init))
+return false;
 
-if (!this->visitInitializer(Init))
-  return false;
+  if (!this->visitInitializer(Init))
+return false;
 
-if (!this->emitPopPtr(Initializer))
-  return false;
+  if (!this->emitPopPtr(Initializer))
+return false;
+} else {
+  const Record::Field *FieldToInit = R->getField(InitIndex);
+  // Non-primitive case. Get a pointer to the field-to-initialize
+  // on the stack and recurse into visitInitializer().
+  if (!this->emitGetPtrField(FieldToInit->Offset, Init))
+return false;
+
+  if (!this->visitInitializer(Init))
+return false;
+
+  if (!this->emitPopPtr(Initializer))
+return false;
+}
   }
   ++InitIndex;
 }

diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index 554e9a8e2d204..3af8027ddeb53 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -434,7 +434,7 @@ static bool CheckFieldsInitialized(InterpState &S, CodePtr 
OpPC,
 
   // Check Fields in all bases
   for (const Record::Base &B : R->bases()) {
-Pointer P = Pointer(BasePtr.block(), B.Offset);
+Pointer P = BasePtr.atField(B.Offset);
 Result &= CheckFieldsInitialized(S, OpPC, P, B.R);
   }
 

diff  --git a/clang/lib/AST/Interp/Record.cpp b/clang/lib/AST/Interp/Record.cpp
index f440c4705051e..c8cbdb314f512 100644
--- a/clang/lib/AST/Interp/Record.cpp
+++ b/clang/lib/AST/Interp/Record.cpp
@@ -39,6 +39,16 @@ const Record::Base *Record::getBase(const RecordDecl *FD) 
const {
   return It->second;
 }
 
+const Record::Base *Record::getBase(QualType T) const {
+  if (!T->isRecordType())
+return nullptr;
+
+  const RecordDecl *RD = T->getAs()->getDecl();
+  if (auto It = BaseMap.find(RD); It != BaseMap.end())
+return It->second;
+  return nullptr;
+}
+
 const Record::Base *Record::getVirtualBase(const RecordDecl *FD) const {
   auto It = VirtualBaseMap.find(FD);
   assert(It != VirtualBaseMap.end() && "Missing virtual base");

diff  --git a/clang/lib/AST/Interp/Record.h b/clang/lib/AST/Interp/Record.h
index 1742cb1cc4ee6..52173fffa5447 100644
--- a/clang/lib/AST/Interp/Record.h
+++ b/clang/lib/AST/Interp/Record.h
@@ -61,6 +61,8 @@ class Record final {
   const Field *getField(const FieldDecl *FD) const;
   /// Returns a base descriptor.
   const Base *getBase(const RecordDecl *FD) const;
+  /// Returns a base descriptor.
+  const Base *getBase(QualType T) const;
   /// Returns a virtual base descriptor.
   const Base *getVirtualBase(const RecordDecl *RD) const;
   // Returns the destructor of the record, if any.

diff  --git a/clang/test/AST/Interp/cxx20.cpp b/clang/test/A

[PATCH] D143466: [clang][Interp] Fix initializing base class members

2023-04-03 Thread Timm Bäder 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 rGdb3dcdc08ce0: [clang][Interp] Fix initializing base class 
members (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143466

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Record.cpp
  clang/lib/AST/Interp/Record.h
  clang/test/AST/Interp/cxx20.cpp
  clang/test/AST/Interp/records.cpp

Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -252,16 +252,23 @@
 
 #if __cplusplus >= 201703L
 namespace BaseInit {
+  class _A {public: int a;};
+  class _B : public _A {};
+  class _C : public _B {};
+
+  constexpr _C c{12};
+  constexpr const _B &b = c;
+  static_assert(b.a == 12);
+
   class A {public: int a;};
   class B : public A {};
   class C : public A {};
   class D : public B, public C {};
 
-  // FIXME: Enable this once we support the initialization.
   // This initializes D::B::A::a and not D::C::A::a.
-  //constexpr D d{12};
-  //static_assert(d.B::a == 12);
-  //static_assert(d.C::a == 0);
+  constexpr D d{12};
+  static_assert(d.B::a == 12);
+  static_assert(d.C::a == 0);
 };
 #endif
 
Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -272,6 +272,69 @@
// ref-note {{in call to}}
 };
 
+namespace BaseInit {
+  struct Base {
+int a;
+  };
+
+  struct Intermediate : Base {
+int b;
+  };
+
+  struct Final : Intermediate {
+int c;
+
+constexpr Final(int a, int b, int c) : c(c) {}
+  };
+
+  static_assert(Final{1, 2, 3}.c == 3, ""); // OK
+  static_assert(Final{1, 2, 3}.a == 0, ""); // expected-error {{not an integral constant expression}} \
+// expected-note {{read of object outside its lifetime}} \
+// ref-error {{not an integral constant expression}} \
+// ref-note {{read of uninitialized object}}
+
+
+  struct Mixin  {
+int b;
+
+constexpr Mixin() = default;
+constexpr Mixin(int b) : b(b) {}
+  };
+
+  struct Final2 : Base, Mixin {
+int c;
+
+constexpr Final2(int a, int b, int c) : Mixin(b), c(c) {}
+constexpr Final2(int a, int b, int c, bool) : c(c) {}
+  };
+
+  static_assert(Final2{1, 2, 3}.c == 3, ""); // OK
+  static_assert(Final2{1, 2, 3}.b == 2, ""); // OK
+  static_assert(Final2{1, 2, 3}.a == 0, ""); // expected-error {{not an integral constant expression}} \
+ // expected-note {{read of object outside its lifetime}} \
+ // ref-error {{not an integral constant expression}} \
+ // ref-note {{read of uninitialized object}}
+
+
+  struct Mixin3  {
+int b;
+  };
+
+  struct Final3 : Base, Mixin3 {
+int c;
+
+constexpr Final3(int a, int b, int c) : c(c) { this->b = b; }
+constexpr Final3(int a, int b, int c, bool) : c(c) {}
+  };
+
+  static_assert(Final3{1, 2, 3}.c == 3, ""); // OK
+  static_assert(Final3{1, 2, 3}.b == 2, ""); // OK
+  static_assert(Final3{1, 2, 3}.a == 0, ""); // expected-error {{not an integral constant expression}} \
+ // expected-note {{read of object outside its lifetime}} \
+ // ref-error {{not an integral constant expression}} \
+ // ref-note {{read of uninitialized object}}
+};
+
 namespace Destructors {
 
   class Inc final {
Index: clang/lib/AST/Interp/Record.h
===
--- clang/lib/AST/Interp/Record.h
+++ clang/lib/AST/Interp/Record.h
@@ -61,6 +61,8 @@
   const Field *getField(const FieldDecl *FD) const;
   /// Returns a base descriptor.
   const Base *getBase(const RecordDecl *FD) const;
+  /// Returns a base descriptor.
+  const Base *getBase(QualType T) const;
   /// Returns a virtual base descriptor.
   const Base *getVirtualBase(const RecordDecl *RD) const;
   // Returns the destructor of the record, if any.
Index: clang/lib/AST/Interp/Record.cpp
===
--- clang/lib/AST/Interp/Record.cpp
+++ clang/lib/AST/Interp/Record.cpp
@@ -39,6 +39,16 @@
   return It->second;
 }
 
+const Record::Base *Record::getBase(QualType T) const {
+  if (!T->isRecordType())
+return nullptr;
+
+  const RecordDecl *RD = T->getAs()->getDecl();
+  if (auto It = BaseMap.find(RD); It != BaseMap.end())
+return It->se

[PATCH] D147414: [python] Expose clang_Location_isInSystemHeader

2023-04-03 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! Do you need someone to land this on your behalf? If so, please let me 
know what name and email address you would like for patch attribution.

In D147414#4239453 , @R2RT wrote:

> I thought about adding it into release notes, but recently Python section has 
> got removed from ReleaseNotes.rst, so I am not sure what to do now: 
> https://reviews.llvm.org/D142578

The section was removed mostly because the python bindings weren't getting a 
lot of updates. I think this deserves a release note, so let's add the python 
bindings section back in and put a note under it for this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147414

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


[PATCH] D147369: [clang][Interp] Support empty initlist initializers for complex types

2023-04-03 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


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147369

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


[PATCH] D147044: [clangd] Implement cross reference request for #include lines.

2023-04-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:443
+  // No match for this provider in the includes list.
+  return {};
+}

`return std::nullopt`



Comment at: clang-tools-extra/clangd/IncludeCleaner.h:87
+std::optional
+firstMatchedProvider(const include_cleaner::Includes &Includes,
+ llvm::ArrayRef Providers);

can you also move tests related to this functionality from HoverTests into 
IncludeCleanerTests ?



Comment at: clang-tools-extra/clangd/XRefs.cpp:1320
 
+ReferencesResult maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
+URIForFile URIMainFile) {

can you put this into anon namespace?

we should also change the return type to `std::optional`, as 
we can "legitimately" have empty result for an include, e.g. it's unused or all 
of the refs are implicit etc.



Comment at: clang-tools-extra/clangd/XRefs.cpp:1324
+  const SourceManager &SM = AST.getSourceManager();
+  auto Includes = AST.getIncludeStructure().MainFileIncludes;
+  auto ConvertedMainFileIncludes = convertIncludes(SM, Includes);

`const auto &Includes = AST.getIncludeStructure().MainFileIncludes;` (`&` is 
the important bit, as we're copying all of them otherwise)



Comment at: clang-tools-extra/clangd/XRefs.cpp:1325
+  auto Includes = AST.getIncludeStructure().MainFileIncludes;
+  auto ConvertedMainFileIncludes = convertIncludes(SM, Includes);
+  for (auto &Inc : Includes) {

let's move this into the for loop, after we've found a matching include to not 
necessarily create a copy of all the includes again.

nit: you can also write the loop below as following and reduce some nesting.
```
auto IncludeOnLine = llvm::find_if(Includes, [&Pos](const Inclusion& Inc) { 
return Inc.HashLine == Pos.Line; });
if (IncludeOnLine == Includes.end())
  return Results;
const auto &Inc = *IncludeOnLine;
...
```



Comment at: clang-tools-extra/clangd/XRefs.cpp:1348
+  auto Loc = SM.getFileLoc(Ref.RefLocation);
+  for (const auto &H : Providers) {
+auto MatchingIncludes = ConvertedMainFileIncludes.match(H);

VitaNuo wrote:
> kadircet wrote:
> > we're implementing and testing this logic twice now, once in here and once 
> > in hover. can we instead have a helper in `IncludeCleaner.h` that looks 
> > like:
> > ```
> > std::optional firstSatisfiedProvider(const 
> > include_cleaner::Includes& Includes, 
> > llvm::ArrayRef Providers);
> > // I'd actually return the matching `std::vector` (the 
> > highest ranked provider that matched some includes in main file), and check 
> > if the include of interest is part of that set for rest of the operations.
> > // Since it represents both the provider and the include in the main file. 
> > whereas the provider on it's own doesn't say anything about which include 
> > in main file triggered satisfaction.
> > ```
> > and turn these call sites into
> > ```
> > auto Provider = firstSatisfiedProvider(ConvertedMainFileIncludes, 
> > Providers);
> > if(!Provider || ReferencedInclude.match(Provider).empty())
> >   return;
> > // Include in question provides the symbol, do magic.
> > ```
> Is the comment under the code in the first snippet a mistake/outdated 
> content? It confused me.
that wasn't supposed to be a comment **in** the code but rather a comment 
**for** the code :D i was suggesting to return the set of `Include`s matched by 
the first provider, rather than returning the provider. but feel free to keep 
it as-is.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147044

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


[PATCH] D147307: [clang] Consider artificial always inline builtin as inline builtins

2023-04-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a reviewer: rjmccall.
aaron.ballman added a comment.

I don't feel particularly qualified to review this, but my reading of the GCC 
docs suggest that this attribute should only impact debug information and 
nothing else about codegen. However, 
`FunctionDecl::isInlineBuiltinDeclaration()` is used within 
`CodeGenFunction::GenerateCode()` and so I wonder if the change is correct or 
not.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147307

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


[PATCH] D141497: [clang][Interp] Record initialization via conditional operator

2023-04-03 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.

I'm fine with this approach.


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

https://reviews.llvm.org/D141497

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


[clang] fd86789 - [clang-format] Don't allow variable decls to have trailing return arrows

2023-04-03 Thread Emilia Dreamer via cfe-commits

Author: Emilia Dreamer
Date: 2023-04-03T15:54:21+03:00
New Revision: fd86789962964a98157e8159c3d95cdc241942e3

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

LOG: [clang-format] Don't allow variable decls to have trailing return arrows

The heuristic for determining if an arrow is a trailing return arrow
looks for the auto keyword, along with parentheses. This isn't
sufficient, since it also triggers on variable declarations with an auto
type, and with an arrow operator.

This patch makes sure a function declaration is being parsed, instead of
any other declaration.

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

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index b1060bde9dedd..5171952dba43c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1922,7 +1922,7 @@ class AnnotatingParser {
Style.Language == FormatStyle::LK_Java) {
   Current.setType(TT_LambdaArrow);
 } else if (Current.is(tok::arrow) && AutoFound &&
-   (Line.MustBeDeclaration || Line.InPPDirective) &&
+   (Line.MightBeFunctionDecl || Line.InPPDirective) &&
Current.NestingLevel == 0 &&
!Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) {
   // not auto operator->() -> xxx;

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 19b1d96f75ab2..dc2fd4d10c76c 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1477,6 +1477,72 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsC11GenericSelection) {
   EXPECT_TOKEN(Tokens[9], tok::colon, TT_GenericSelectionColon);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsTrailingReturnArrow) {
+  auto Tokens = annotate("auto f() -> int;");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto operator->() -> int;");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[2], tok::arrow, TT_OverloadedOperator);
+  EXPECT_TOKEN(Tokens[5], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto operator++(int) -> int;");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto operator=() -> int;");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto operator=(int) -> int;");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto foo() -> auto { return Val; }");
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("struct S { auto bar() const -> int; };");
+  ASSERT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::arrow, TT_TrailingReturnArrow);
+
+  // Not trailing return arrows
+  Tokens = annotate("auto a = b->c;");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("auto a = (b)->c;");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("auto a = b()->c;");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("auto a = b->c();");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("decltype(auto) a = b()->c;");
+  ASSERT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("void f() { auto a = b->c(); }");
+  ASSERT_EQ(Tokens.size(), 16u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("void f() { auto a = b()->c; }");
+  ASSERT_EQ(Tokens.size(), 16u) << Tokens;
+  EXPECT_TOKEN(Tokens[11], tok::arrow, TT_Unknown);
+
+  // Mixed
+  Tokens = annotate("auto f() -> int { auto a = b()->c; }");
+  ASSERT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_TrailingReturnArrow);
+  EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsVerilogOperators) {
   auto Annotate = [this](llvm::StringRef Code) {
 return annotate(Code, getLLVMStyle(FormatStyle::LK_Verilog));




[PATCH] D147377: [clang-format] Don't allow variable decls to have trailing return arrows

2023-04-03 Thread Emilia Dreamer 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 rGfd8678996296: [clang-format] Don't allow variable decls 
to have trailing return arrows (authored by rymiel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147377

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1477,6 +1477,72 @@
   EXPECT_TOKEN(Tokens[9], tok::colon, TT_GenericSelectionColon);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsTrailingReturnArrow) {
+  auto Tokens = annotate("auto f() -> int;");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto operator->() -> int;");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[2], tok::arrow, TT_OverloadedOperator);
+  EXPECT_TOKEN(Tokens[5], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto operator++(int) -> int;");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto operator=() -> int;");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto operator=(int) -> int;");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto foo() -> auto { return Val; }");
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("struct S { auto bar() const -> int; };");
+  ASSERT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::arrow, TT_TrailingReturnArrow);
+
+  // Not trailing return arrows
+  Tokens = annotate("auto a = b->c;");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("auto a = (b)->c;");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("auto a = b()->c;");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("auto a = b->c();");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("decltype(auto) a = b()->c;");
+  ASSERT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("void f() { auto a = b->c(); }");
+  ASSERT_EQ(Tokens.size(), 16u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::arrow, TT_Unknown);
+
+  Tokens = annotate("void f() { auto a = b()->c; }");
+  ASSERT_EQ(Tokens.size(), 16u) << Tokens;
+  EXPECT_TOKEN(Tokens[11], tok::arrow, TT_Unknown);
+
+  // Mixed
+  Tokens = annotate("auto f() -> int { auto a = b()->c; }");
+  ASSERT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_TrailingReturnArrow);
+  EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsVerilogOperators) {
   auto Annotate = [this](llvm::StringRef Code) {
 return annotate(Code, getLLVMStyle(FormatStyle::LK_Verilog));
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1922,7 +1922,7 @@
Style.Language == FormatStyle::LK_Java) {
   Current.setType(TT_LambdaArrow);
 } else if (Current.is(tok::arrow) && AutoFound &&
-   (Line.MustBeDeclaration || Line.InPPDirective) &&
+   (Line.MightBeFunctionDecl || Line.InPPDirective) &&
Current.NestingLevel == 0 &&
!Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) {
   // not auto operator->() -> xxx;


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1477,6 +1477,72 @@
   EXPECT_TOKEN(Tokens[9], tok::colon, TT_GenericSelectionColon);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsTrailingReturnArrow) {
+  auto Tokens = annotate("auto f() -> int;");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto operator->() -> int;");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[2], tok::arrow, TT_OverloadedOperator);
+  EXPECT_TOKEN(Tokens[5], tok::arrow, TT_TrailingReturnArrow);
+
+  Tokens = annotate("auto oper

[PATCH] D146376: Update static_assert message for redundant cases

2023-04-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

The changes need a release note and please do add more text to the 
`expected-error` comments so we can see what the diagnostic actually produces 
(instead of just `{{failed}}`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146376

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


[PATCH] D132819: [RISCV] Add MC support of RISCV zcmp Extension

2023-04-03 Thread Xinlong Wu via Phabricator via cfe-commits
VincentWu updated this revision to Diff 510467.
VincentWu added a comment.
Herald added subscribers: jobnoorman, jdoerfert.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D132819

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
  llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.cpp
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.cpp
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVInstPrinter.h
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVMCCodeEmitter.cpp
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/lib/Target/RISCV/RISCVInstrInfoZc.td
  llvm/lib/Target/RISCV/RISCVRegisterInfo.td
  llvm/lib/Target/RISCV/RISCVSchedRocket.td
  llvm/lib/Target/RISCV/RISCVSchedSiFive7.td
  llvm/test/CodeGen/RISCV/O0-pipeline.ll
  llvm/test/CodeGen/RISCV/O3-pipeline.ll
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/rv32zcmp-invalid.s
  llvm/test/MC/RISCV/rv32zcmp-valid.s
  llvm/test/MC/RISCV/rv64zcmp-invalid.s
  llvm/test/MC/RISCV/rv64zcmp-valid.s

Index: llvm/test/MC/RISCV/rv64zcmp-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv64zcmp-valid.s
@@ -0,0 +1,149 @@
+# RUN: llvm-mc %s -triple=riscv64 -mattr=experimental-zcmp -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=experimental-zcmp < %s \
+# RUN: | llvm-objdump --mattr=-c,experimental-zcmp -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefixes=CHECK-ASM-AND-OBJ %s
+
+# CHECK-ASM-AND-OBJ: cm.mvsa01 s1, s0
+# CHECK-ASM: encoding: [0xa2,0xac]
+cm.mvsa01 s1, s0
+
+# CHECK-ASM-AND-OBJ: cm.mva01s s1, s0
+# CHECK-ASM: encoding: [0xe2,0xac]
+cm.mva01s s1, s0
+
+# CHECK-ASM-AND-OBJ: cm.popret   {ra}, 16
+# CHECK-ASM: encoding: [0x42,0xbe]
+cm.popret {ra}, 16
+
+# CHECK-ASM-AND-OBJ: cm.popret   {ra}, 32
+# CHECK-ASM: encoding: [0x46,0xbe]
+cm.popret {ra}, 32
+
+# CHECK-ASM-AND-OBJ: cm.popret   {ra, s0}, 64
+# CHECK-ASM: encoding: [0x5e,0xbe]
+cm.popret {ra, s0}, 64
+
+# CHECK-ASM-AND-OBJ: cm.popret   {ra, s0-s1}, 32
+# CHECK-ASM: encoding: [0x62,0xbe]
+cm.popret {ra,s0-s1}, 32
+
+# CHECK-ASM-AND-OBJ: cm.popret   {ra, s0-s2}, 32
+# CHECK-ASM: encoding: [0x72,0xbe]
+cm.popret {ra, s0-s2}, 32
+
+# CHECK-ASM-AND-OBJ: cm.popret   {ra, s0-s3}, 64
+# CHECK-ASM: encoding: [0x86,0xbe]
+cm.popret {ra, s0-s3}, 64
+
+# CHECK-ASM-AND-OBJ: cm.popret   {ra, s0-s5}, 64
+# CHECK-ASM: encoding: [0xa2,0xbe]
+cm.popret {ra, s0-s5}, 64
+
+# CHECK-ASM-AND-OBJ: cm.popret   {ra, s0-s7}, 80
+# CHECK-ASM: encoding: [0xc2,0xbe]
+cm.popret {ra, s0-s7}, 80
+
+# CHECK-ASM-AND-OBJ: cm.popret   {ra, s0-s11}, 112
+# CHECK-ASM: encoding: [0xf2,0xbe]
+cm.popret {ra, s0-s11}, 112
+
+# CHECK-ASM-AND-OBJ: cm.popretz   {ra}, 16
+# CHECK-ASM: encoding: [0x42,0xbc]
+cm.popretz {ra}, 16
+
+# CHECK-ASM-AND-OBJ: cm.popretz   {ra}, 32
+# CHECK-ASM: encoding: [0x46,0xbc]
+cm.popretz {ra}, 32
+
+# CHECK-ASM-AND-OBJ: cm.popretz   {ra, s0}, 64
+# CHECK-ASM: encoding: [0x5e,0xbc]
+cm.popretz {ra, s0}, 64
+
+# CHECK-ASM-AND-OBJ: cm.popretz   {ra, s0-s1}, 32
+# CHECK-ASM: encoding: [0x62,0xbc]
+cm.popretz {ra, s0-s1}, 32
+
+# CHECK-ASM-AND-OBJ: cm.popretz   {ra, s0-s2}, 32
+# CHECK-ASM: encoding: [0x72,0xbc]
+cm.popretz {ra, s0-s2}, 32
+
+# CHECK-ASM-AND-OBJ: cm.popretz   {ra, s0-s3}, 64
+# CHECK-ASM: encoding: [0x86,0xbc]
+cm.popretz {ra, s0-s3}, 64
+
+# CHECK-ASM-AND-OBJ: cm.popretz   {ra, s0-s5}, 64
+# CHECK-ASM: encoding: [0xa2,0xbc]
+cm.popretz {ra, s0-s5}, 64
+
+# CHECK-ASM-AND-OBJ: cm.popretz   {ra, s0-s7}, 80
+# CHECK-ASM: encoding: [0xc2,0xbc]
+cm.popretz {ra, s0-s7}, 80
+
+# CHECK-ASM-AND-OBJ: cm.popretz   {ra, s0-s11}, 112
+# CHECK-ASM: encoding: [0xf2,0xbc]
+cm.popretz {ra, s0-s11}, 112
+
+# CHECK-ASM-AND-OBJ: cm.pop  {ra}, 16
+# CHECK-ASM: encoding: [0x42,0xba]
+cm.pop {ra}, 16
+
+# CHECK-ASM-AND-OBJ: cm.pop  {ra}, 32
+# CHECK-ASM: encoding: [0x46,0xba]
+cm.pop {ra}, 32
+
+# CHECK-ASM-AND-OBJ: cm.pop  {ra, s0}, 16
+# CHECK-ASM: encoding: [0x52,0xba]
+cm.pop {ra, s0}, 16
+
+# CHECK-ASM-AND-OBJ: cm.pop  {ra, s0-s1}, 32
+# CHECK-ASM: encoding: [0x62,0xba]
+cm.pop {ra, s0-s1}, 32
+
+# CHECK-ASM-AND-OBJ: cm.pop  {ra, s0-s2}, 32
+# CHECK-ASM: encoding: [0x72,0xba]
+cm.pop {ra, s0-s2}, 32
+
+# CHECK-ASM-AND-OBJ: cm.pop  {ra, s0-s5}, 64
+# CHECK-ASM: encoding: [0xa2,0xba]
+cm.pop {ra, s0-s5}, 64
+
+# CHECK-ASM-AND-OBJ: cm.pop  {ra, s0-s7}, 80
+# CHECK-ASM: encoding: [0xc2,0xba]
+cm.pop {ra, s0-s7}, 80
+
+# CHECK-ASM-AND-OBJ: cm.pop  {ra, s0-s11}, 112
+# CHECK-ASM: encoding: [0xf2,0xba]
+cm.pop {ra, s0-s11}, 112
+
+# CHECK-ASM-AND-OBJ: cm.push {ra}, -16
+# CHECK-ASM: encoding: [0x42,0xb8]
+cm.

[PATCH] D147144: [include-cleaner] Report references to operator calls as implicit

2023-04-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 510474.
kadircet marked an inline comment as done.
kadircet added a comment.

- Update to treat operator calls to members as "explicit" fater offline 
discussions. This better aligns with what we do for regular member exprs.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147144

Files:
  clang-tools-extra/include-cleaner/lib/WalkAST.cpp
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -291,13 +291,18 @@
 }
 
 TEST(WalkAST, Operator) {
-  // References to operators are not counted as uses.
-  testWalk("struct string {}; int operator+(string, string);",
-   "int k = string() ^+ string();");
-  testWalk("struct string {int operator+(string); }; ",
-   "int k = string() ^+ string();");
-  testWalk("struct string { friend int operator+(string, string); }; ",
+  // Operator calls are marked as implicit references as they're ADL-used and
+  // type should be providing them.
+  testWalk(
+  "struct string { friend int $implicit^operator+(string, string); }; ",
+  "int k = string() ^+ string();");
+  // Unless they're members, we treat them as regular member expr calls.
+  testWalk("struct $explicit^string {int operator+(string); }; ",
"int k = string() ^+ string();");
+  // Make sure usage is attributed to the alias.
+  testWalk(
+  "struct string {int operator+(string); }; using $explicit^foo = string;",
+  "int k = foo() ^+ string();");
 }
 
 TEST(WalkAST, VarDecls) {
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -91,14 +91,23 @@
 public:
   ASTWalker(DeclCallback Callback) : Callback(Callback) {}
 
+  // Operators are almost always ADL extension points and by design references
+  // to them doesn't count as uses (generally the type should provide them, so
+  // ignore them).
+  // Unless we're using an operator defined as a member, in such cases treat
+  // this as a regular reference.
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 if (!WalkUpFromCXXOperatorCallExpr(S))
   return false;
-
-// Operators are always ADL extension points, by design references to them
-// doesn't count as uses (generally the type should provide them).
-// Don't traverse the callee.
-
+if (auto *CD = S->getCalleeDecl()) {
+  if (llvm::isa(CD)) {
+// Treat this as a regular member reference.
+report(S->getOperatorLoc(), 
getMemberProvider(S->getArg(0)->getType()));
+  } else {
+report(S->getOperatorLoc(), llvm::dyn_cast(CD),
+   RefType::Implicit);
+  }
+}
 for (auto *Arg : S->arguments())
   if (!TraverseStmt(Arg))
 return false;


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -291,13 +291,18 @@
 }
 
 TEST(WalkAST, Operator) {
-  // References to operators are not counted as uses.
-  testWalk("struct string {}; int operator+(string, string);",
-   "int k = string() ^+ string();");
-  testWalk("struct string {int operator+(string); }; ",
-   "int k = string() ^+ string();");
-  testWalk("struct string { friend int operator+(string, string); }; ",
+  // Operator calls are marked as implicit references as they're ADL-used and
+  // type should be providing them.
+  testWalk(
+  "struct string { friend int $implicit^operator+(string, string); }; ",
+  "int k = string() ^+ string();");
+  // Unless they're members, we treat them as regular member expr calls.
+  testWalk("struct $explicit^string {int operator+(string); }; ",
"int k = string() ^+ string();");
+  // Make sure usage is attributed to the alias.
+  testWalk(
+  "struct string {int operator+(string); }; using $explicit^foo = string;",
+  "int k = foo() ^+ string();");
 }
 
 TEST(WalkAST, VarDecls) {
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -91,14 +91,23 @@
 public:
   ASTWalker(DeclCallback Callback) : Callback(Callback) {}
 
+  // Operators are almost always ADL extension points and by design references
+  // to them doesn't count as uses (generally the type should provide them, so
+  // ignor

[PATCH] D147144: [include-cleaner] Report references to operator calls as implicit

2023-04-03 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.

still LG.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147144

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


[PATCH] D146234: [clang] Fix crash when handling nested immediate invocations

2023-04-03 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/D146234/new/

https://reviews.llvm.org/D146234

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


[PATCH] D147044: [clangd] Implement cross reference request for #include lines.

2023-04-03 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 510484.
VitaNuo marked 5 inline comments as done.
VitaNuo added a comment.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147044

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -43,6 +43,10 @@
 using ::testing::UnorderedElementsAreArray;
 using ::testing::UnorderedPointwise;
 
+std::string guard(llvm::StringRef Code) {
+  return "#pragma once\n" + Code.str();
+}
+
 MATCHER_P2(FileRange, File, Range, "") {
   return Location{URIForFile::canonicalize(File, testRoot()), Range} == arg;
 }
@@ -2293,6 +2297,50 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+#include 
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+std::vector vec;
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp"};
+  for (const char *Test : Tests) {
+Annotations T(Test);
+auto TU = TestTU::withCode(T.code());
+TU.ExtraArgs.push_back("-std=c++20");
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+std::vector> ExpectedLocations;
+for (const auto &R : T.ranges())
+  ExpectedLocations.push_back(AllOf(rangeIs(R), attrsAre(0u)));
+for (const auto &P : T.points()) 
+  EXPECT_THAT(findReferences(AST, P, 0).References,
+  UnorderedElementsAreArray(ExpectedLocations))
+  << "Failed for Refs at " << P << "\n"
+  << Test;
+  }
+}
+
 TEST(FindReferences, NeedsIndexForSymbols) {
   const char *Header = "int foo();";
   Annotations Main("int main() { [[f^oo]](); }");
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -9,13 +9,17 @@
 #include "AST.h"
 #include "FindSymbols.h"
 #include "FindTarget.h"
+#include "Headers.h"
 #include "HeuristicResolver.h"
+#include "IncludeCleaner.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "Quality.h"
 #include "Selection.h"
 #include "SourceCode.h"
 #include "URI.h"
+#include "clang-include-cleaner/Analysis.h"
+#include "clang-include-cleaner/Types.h"
 #include "index/Index.h"
 #include "index/Merge.h"
 #include "index/Relation.h"
@@ -48,6 +52,7 @@
 #include "clang/Index/IndexingAction.h"
 #include "clang/Index/IndexingOptions.h"
 #include "clang/Index/USRGeneration.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -61,6 +66,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
+#include 
 #include 
 
 namespace clang {
@@ -1310,6 +1316,63 @@
 return printQualifiedName(*ND);
   return {};
 }
+
+std::optional
+maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
+   URIForFile URIMainFile) {
+  const auto &Includes = AST.getIncludeStructure().MainFileIncludes;
+  auto IncludeOnLine = llvm::find_if(Includes, [&Pos](const Inclusion &Inc) {
+return Inc.HashLine == Pos.line;
+  });
+  if (IncludeOnLine == Includes.end())
+return std::nullopt;
+
+  const auto &Inc = *IncludeOnLine;
+  const SourceManager &SM = AST.getSourceManager();
+  ReferencesResult Results;
+  auto ConvertedMainFileIncludes = convertIncludes(SM, Includes);
+  auto ReferencedInclude = convertIncludes(SM, Inc);
+  include_cleaner::walkUsed(
+  AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
+  AST.getPragmaIncludes(), SM,
+  [&](const include_cleaner::SymbolReference &Ref,
+  llvm::ArrayRef Providers) {
+if (Ref.RT != include_cleaner::RefType::Explicit)
+  return;
+
+auto Provider =
+firstMatchedProvider(ConvertedMainFileIncludes, Providers);
+if (!Provider || ReferencedInclude.match(*Provider).empty())
+  return;
+
+auto Loc = SM.getFileLoc(Ref.RefLocation);
+// File locations can be outside of the main file if macro is
+// expanded through an #include.
+while (SM

[PATCH] D147044: [clangd] Implement cross reference request for #include lines.

2023-04-03 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added a comment.

Thanks for the comments!




Comment at: clang-tools-extra/clangd/IncludeCleaner.h:87
+std::optional
+firstMatchedProvider(const include_cleaner::Includes &Includes,
+ llvm::ArrayRef Providers);

kadircet wrote:
> can you also move tests related to this functionality from HoverTests into 
> IncludeCleanerTests ?
Not really, not sure what you mean.

This function receives a ranked list of providers that should be a result of 
include_cleaner analysis.

If I just test the function based on a fake list of providers, the test will be 
trivial. The current hover test seems to provide more value than that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147044

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


[clang] 58cf70b - [clang][Interp] Fix diagnostics for calling non-constexpr constructors

2023-04-03 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-03T15:42:08+02:00
New Revision: 58cf70b2cdc17a905f7db2ec5a6f9d497f9bd133

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

LOG: [clang][Interp] Fix diagnostics for calling non-constexpr constructors

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/cxx20.cpp
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 665f60d572ea..e5c9b2637b85 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1350,7 +1350,7 @@ bool 
ByteCodeExprGen::visitRecordInitializer(const Expr *Initializer) {
   if (const auto CtorExpr = dyn_cast(Initializer)) {
 const Function *Func = getFunction(CtorExpr->getConstructor());
 
-if (!Func || !Func->isConstexpr())
+if (!Func)
   return false;
 
 // The This pointer is already on the stack because this is an initializer,

diff  --git a/clang/test/AST/Interp/cxx20.cpp b/clang/test/AST/Interp/cxx20.cpp
index cfa9729f4b03..6cb106adf59c 100644
--- a/clang/test/AST/Interp/cxx20.cpp
+++ b/clang/test/AST/Interp/cxx20.cpp
@@ -207,13 +207,15 @@ namespace ConstThis {
   // ref-note {{declared const here}}
 int a;
   public:
-constexpr Foo() {
+constexpr Foo() { // expected-note {{declared here}}
   this->a = 10;
   T = 13; // expected-error {{cannot assign to non-static data member 'T' 
with const-qualified type}} \
   // ref-error {{cannot assign to non-static data member 'T' with 
const-qualified type}}
 }
   };
   constexpr Foo F; // expected-error {{must be initialized by a constant 
expression}} \
+   // FIXME: The following note is wrong. \
+   // expected-note {{undefined constructor 'Foo' cannot be 
used in a constant expression}} \
// ref-error {{must be initialized by a constant 
expression}}
 
 

diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index 37cdf341fbd7..a7085e45ca33 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -308,7 +308,7 @@ namespace MI {
 };
 
 namespace DeriveFailures {
-  struct Base { // ref-note 2{{declared here}}
+  struct Base { // ref-note 2{{declared here}} expected-note {{declared here}}
 int Val;
   };
 
@@ -316,13 +316,15 @@ namespace DeriveFailures {
 int OtherVal;
 
 constexpr Derived(int i) : OtherVal(i) {} // ref-error {{never produces a 
constant expression}} \
-  // ref-note 2{{non-constexpr 
constructor 'Base' cannot be used in a constant expression}}
+  // ref-note 2{{non-constexpr 
constructor 'Base' cannot be used in a constant expression}} \
+  // expected-note {{non-constexpr 
constructor 'Base' cannot be used in a constant expression}}
   };
 
   constexpr Derived D(12); // ref-error {{must be initialized by a constant 
expression}} \
// ref-note {{in call to 'Derived(12)'}} \
// ref-note {{declared here}} \
-   // expected-error {{must be initialized by a 
constant expression}}
+   // expected-error {{must be initialized by a 
constant expression}} \
+   // expected-note {{in call to 'Derived(12)'}}
   static_assert(D.Val == 0, ""); // ref-error {{not an integral constant 
expression}} \
  // ref-note {{initializer of 'D' is not a 
constant expression}} \
  // expected-error {{not an integral constant 
expression}} \
@@ -348,7 +350,8 @@ namespace DeriveFailures {
   };
 
   struct YetAnotherDerived : YetAnotherBase {
-using YetAnotherBase::YetAnotherBase; //ref-note {{declared here}}
+using YetAnotherBase::YetAnotherBase; // ref-note {{declared here}} \
+  // expected-note {{declared here}}
 int OtherVal;
 
 constexpr bool doit() const { return Val == OtherVal; }
@@ -356,8 +359,8 @@ namespace DeriveFailures {
 
   constexpr YetAnotherDerived Oops(0); // ref-error {{must be initialized by a 
constant expression}} \
// ref-note {{constructor inherited 
from base class 'YetAnotherBase' cannot be used in a constant expression}} \
-   // expected-error {{must be initialized 
by a constant expression}}
-   // FIXME: Missing reason for rejection.
+

[PATCH] D145841: [clang][Interp] Fix diagnostics for calling non-constexpr constructors

2023-04-03 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG58cf70b2cdc1: [clang][Interp] Fix diagnostics for calling 
non-constexpr constructors (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D145841?vs=504406&id=510485#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145841

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/cxx20.cpp
  clang/test/AST/Interp/records.cpp


Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -308,7 +308,7 @@
 };
 
 namespace DeriveFailures {
-  struct Base { // ref-note 2{{declared here}}
+  struct Base { // ref-note 2{{declared here}} expected-note {{declared here}}
 int Val;
   };
 
@@ -316,13 +316,15 @@
 int OtherVal;
 
 constexpr Derived(int i) : OtherVal(i) {} // ref-error {{never produces a 
constant expression}} \
-  // ref-note 2{{non-constexpr 
constructor 'Base' cannot be used in a constant expression}}
+  // ref-note 2{{non-constexpr 
constructor 'Base' cannot be used in a constant expression}} \
+  // expected-note {{non-constexpr 
constructor 'Base' cannot be used in a constant expression}}
   };
 
   constexpr Derived D(12); // ref-error {{must be initialized by a constant 
expression}} \
// ref-note {{in call to 'Derived(12)'}} \
// ref-note {{declared here}} \
-   // expected-error {{must be initialized by a 
constant expression}}
+   // expected-error {{must be initialized by a 
constant expression}} \
+   // expected-note {{in call to 'Derived(12)'}}
   static_assert(D.Val == 0, ""); // ref-error {{not an integral constant 
expression}} \
  // ref-note {{initializer of 'D' is not a 
constant expression}} \
  // expected-error {{not an integral constant 
expression}} \
@@ -348,7 +350,8 @@
   };
 
   struct YetAnotherDerived : YetAnotherBase {
-using YetAnotherBase::YetAnotherBase; //ref-note {{declared here}}
+using YetAnotherBase::YetAnotherBase; // ref-note {{declared here}} \
+  // expected-note {{declared here}}
 int OtherVal;
 
 constexpr bool doit() const { return Val == OtherVal; }
@@ -356,8 +359,8 @@
 
   constexpr YetAnotherDerived Oops(0); // ref-error {{must be initialized by a 
constant expression}} \
// ref-note {{constructor inherited 
from base class 'YetAnotherBase' cannot be used in a constant expression}} \
-   // expected-error {{must be initialized 
by a constant expression}}
-   // FIXME: Missing reason for rejection.
+   // expected-error {{must be initialized 
by a constant expression}} \
+   // expected-note {{constructor 
inherited from base class 'YetAnotherBase' cannot be used in a constant 
expression}}
 };
 
 namespace EmptyCtor {
Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -207,13 +207,15 @@
   // ref-note {{declared const here}}
 int a;
   public:
-constexpr Foo() {
+constexpr Foo() { // expected-note {{declared here}}
   this->a = 10;
   T = 13; // expected-error {{cannot assign to non-static data member 'T' 
with const-qualified type}} \
   // ref-error {{cannot assign to non-static data member 'T' with 
const-qualified type}}
 }
   };
   constexpr Foo F; // expected-error {{must be initialized by a constant 
expression}} \
+   // FIXME: The following note is wrong. \
+   // expected-note {{undefined constructor 'Foo' cannot be 
used in a constant expression}} \
// ref-error {{must be initialized by a constant 
expression}}
 
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1350,7 +1350,7 @@
   if (const auto CtorExpr = dyn_cast(Initializer)) {
 const Function *Func = getFunction(CtorExpr->getConstructor());
 
-if (!Func || !Func->isConstexpr())
+if (!Func)
   return false;
 
 // The This pointer is already on the stack because this is an initializer,


Index: clang/test/AST/Interp/records.cpp
==

[PATCH] D147302: [clang][dataflow] Add `create()` methods to `Environment` and `DataflowAnalysisContext`.

2023-04-03 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.

Thanks!




Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:215
   /// Creates an atomic boolean value.
-  AtomicBoolValue &createAtomicBoolValue() {
-return takeOwnership(std::make_unique());
-  }
+  AtomicBoolValue &createAtomicBoolValue() { return create(); 
}
 

Is there any reason for this function anymore or should we deprecate it (and 
the Top version below)? Especially in this object which only used internally 
and not by clients -- the extra two characters don't seem to justify a function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147302

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


[PATCH] D147144: [include-cleaner] Report references to operator calls as implicit

2023-04-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG26ff268b80c5: [include-cleaner] Report references to 
operator calls as implicit (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147144

Files:
  clang-tools-extra/include-cleaner/lib/WalkAST.cpp
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -291,13 +291,18 @@
 }
 
 TEST(WalkAST, Operator) {
-  // References to operators are not counted as uses.
-  testWalk("struct string {}; int operator+(string, string);",
-   "int k = string() ^+ string();");
-  testWalk("struct string {int operator+(string); }; ",
-   "int k = string() ^+ string();");
-  testWalk("struct string { friend int operator+(string, string); }; ",
+  // Operator calls are marked as implicit references as they're ADL-used and
+  // type should be providing them.
+  testWalk(
+  "struct string { friend int $implicit^operator+(string, string); }; ",
+  "int k = string() ^+ string();");
+  // Unless they're members, we treat them as regular member expr calls.
+  testWalk("struct $explicit^string {int operator+(string); }; ",
"int k = string() ^+ string();");
+  // Make sure usage is attributed to the alias.
+  testWalk(
+  "struct string {int operator+(string); }; using $explicit^foo = string;",
+  "int k = foo() ^+ string();");
 }
 
 TEST(WalkAST, VarDecls) {
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -91,14 +91,23 @@
 public:
   ASTWalker(DeclCallback Callback) : Callback(Callback) {}
 
+  // Operators are almost always ADL extension points and by design references
+  // to them doesn't count as uses (generally the type should provide them, so
+  // ignore them).
+  // Unless we're using an operator defined as a member, in such cases treat
+  // this as a regular reference.
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 if (!WalkUpFromCXXOperatorCallExpr(S))
   return false;
-
-// Operators are always ADL extension points, by design references to them
-// doesn't count as uses (generally the type should provide them).
-// Don't traverse the callee.
-
+if (auto *CD = S->getCalleeDecl()) {
+  if (llvm::isa(CD)) {
+// Treat this as a regular member reference.
+report(S->getOperatorLoc(), 
getMemberProvider(S->getArg(0)->getType()));
+  } else {
+report(S->getOperatorLoc(), llvm::dyn_cast(CD),
+   RefType::Implicit);
+  }
+}
 for (auto *Arg : S->arguments())
   if (!TraverseStmt(Arg))
 return false;


Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -291,13 +291,18 @@
 }
 
 TEST(WalkAST, Operator) {
-  // References to operators are not counted as uses.
-  testWalk("struct string {}; int operator+(string, string);",
-   "int k = string() ^+ string();");
-  testWalk("struct string {int operator+(string); }; ",
-   "int k = string() ^+ string();");
-  testWalk("struct string { friend int operator+(string, string); }; ",
+  // Operator calls are marked as implicit references as they're ADL-used and
+  // type should be providing them.
+  testWalk(
+  "struct string { friend int $implicit^operator+(string, string); }; ",
+  "int k = string() ^+ string();");
+  // Unless they're members, we treat them as regular member expr calls.
+  testWalk("struct $explicit^string {int operator+(string); }; ",
"int k = string() ^+ string();");
+  // Make sure usage is attributed to the alias.
+  testWalk(
+  "struct string {int operator+(string); }; using $explicit^foo = string;",
+  "int k = foo() ^+ string();");
 }
 
 TEST(WalkAST, VarDecls) {
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -91,14 +91,23 @@
 public:
   ASTWalker(DeclCallback Callback) : Callback(Callback) {}
 
+  // Operators are almost always ADL extension points and by design references
+  // to them doesn't count as uses (generally the type should provide them, so
+  // ignore them).
+  // Unless we're using an operator defined as a member, 

[PATCH] D146973: [Clang] Implicitly include LLVM libc headers for the GPU

2023-04-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146973

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


[clang-tools-extra] 26ff268 - [include-cleaner] Report references to operator calls as implicit

2023-04-03 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-04-03T15:49:28+02:00
New Revision: 26ff268b80c589fd9f71c1c214af77cd972642ca

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

LOG: [include-cleaner] Report references to operator calls as implicit

Missing these references can result in false negatives in the used-ness
analysis and break builds.

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

Added: 


Modified: 
clang-tools-extra/include-cleaner/lib/WalkAST.cpp
clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/WalkAST.cpp 
b/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
index b10c722b6653a..8a1dd77176cdf 100644
--- a/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ b/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -91,14 +91,23 @@ class ASTWalker : public RecursiveASTVisitor {
 public:
   ASTWalker(DeclCallback Callback) : Callback(Callback) {}
 
+  // Operators are almost always ADL extension points and by design references
+  // to them doesn't count as uses (generally the type should provide them, so
+  // ignore them).
+  // Unless we're using an operator defined as a member, in such cases treat
+  // this as a regular reference.
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 if (!WalkUpFromCXXOperatorCallExpr(S))
   return false;
-
-// Operators are always ADL extension points, by design references to them
-// doesn't count as uses (generally the type should provide them).
-// Don't traverse the callee.
-
+if (auto *CD = S->getCalleeDecl()) {
+  if (llvm::isa(CD)) {
+// Treat this as a regular member reference.
+report(S->getOperatorLoc(), 
getMemberProvider(S->getArg(0)->getType()));
+  } else {
+report(S->getOperatorLoc(), llvm::dyn_cast(CD),
+   RefType::Implicit);
+  }
+}
 for (auto *Arg : S->arguments())
   if (!TraverseStmt(Arg))
 return false;

diff  --git a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
index fd6c6da9d5509..fceec670076c9 100644
--- a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -291,13 +291,18 @@ TEST(WalkAST, ConstructExprs) {
 }
 
 TEST(WalkAST, Operator) {
-  // References to operators are not counted as uses.
-  testWalk("struct string {}; int operator+(string, string);",
-   "int k = string() ^+ string();");
-  testWalk("struct string {int operator+(string); }; ",
-   "int k = string() ^+ string();");
-  testWalk("struct string { friend int operator+(string, string); }; ",
+  // Operator calls are marked as implicit references as they're ADL-used and
+  // type should be providing them.
+  testWalk(
+  "struct string { friend int $implicit^operator+(string, string); }; ",
+  "int k = string() ^+ string();");
+  // Unless they're members, we treat them as regular member expr calls.
+  testWalk("struct $explicit^string {int operator+(string); }; ",
"int k = string() ^+ string();");
+  // Make sure usage is attributed to the alias.
+  testWalk(
+  "struct string {int operator+(string); }; using $explicit^foo = string;",
+  "int k = foo() ^+ string();");
 }
 
 TEST(WalkAST, VarDecls) {



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


[clang] 056042d - [clang][Interp] Fix initializing fields after base class members

2023-04-03 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-03T15:55:11+02:00
New Revision: 056042d21b72a86653f88719c0b54b07e35d2144

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

LOG: [clang][Interp] Fix initializing fields after base class members

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/cxx20.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e5c9b2637b85..ee5dd73159a6 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1384,6 +1384,7 @@ bool 
ByteCodeExprGen::visitRecordInitializer(const Expr *Initializer) {
 
 if (!this->emitPopPtr(Initializer))
   return false;
+++InitIndex;
   } else {
 // Initializer for a direct base class.
 if (const Record::Base *B = R->getBase(Init->getType())) {
@@ -1395,6 +1396,8 @@ bool 
ByteCodeExprGen::visitRecordInitializer(const Expr *Initializer) {
 
   if (!this->emitPopPtr(Initializer))
 return false;
+  // Base initializers don't increase InitIndex, since they don't count
+  // into the Record's fields.
 } else {
   const Record::Field *FieldToInit = R->getField(InitIndex);
   // Non-primitive case. Get a pointer to the field-to-initialize
@@ -1407,9 +1410,9 @@ bool 
ByteCodeExprGen::visitRecordInitializer(const Expr *Initializer) {
 
   if (!this->emitPopPtr(Initializer))
 return false;
+  ++InitIndex;
 }
   }
-  ++InitIndex;
 }
 
 return true;

diff  --git a/clang/test/AST/Interp/cxx20.cpp b/clang/test/AST/Interp/cxx20.cpp
index 6cb106adf59c..37be7a41bf75 100644
--- a/clang/test/AST/Interp/cxx20.cpp
+++ b/clang/test/AST/Interp/cxx20.cpp
@@ -583,3 +583,20 @@ namespace Destructors {
   constexpr Outer O;
   static_assert(O.bar() == 12);
 }
+
+namespace BaseAndFieldInit {
+  struct A {
+int a;
+  };
+
+  struct B : A {
+int b;
+  };
+
+  struct C : B {
+int c;
+  };
+
+  constexpr C c = {1,2,3};
+  static_assert(c.a == 1 && c.b == 2 && c.c == 3);
+}



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


[PATCH] D145860: [clang][Interp] Fix initializing fields after base class members

2023-04-03 Thread Timm Bäder 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 rG056042d21b72: [clang][Interp] Fix initializing fields after 
base class members (authored by tbaeder).

Changed prior to commit:
  https://reviews.llvm.org/D145860?vs=504408&id=510487#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145860

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/cxx20.cpp


Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -583,3 +583,20 @@
   constexpr Outer O;
   static_assert(O.bar() == 12);
 }
+
+namespace BaseAndFieldInit {
+  struct A {
+int a;
+  };
+
+  struct B : A {
+int b;
+  };
+
+  struct C : B {
+int c;
+  };
+
+  constexpr C c = {1,2,3};
+  static_assert(c.a == 1 && c.b == 2 && c.c == 3);
+}
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1384,6 +1384,7 @@
 
 if (!this->emitPopPtr(Initializer))
   return false;
+++InitIndex;
   } else {
 // Initializer for a direct base class.
 if (const Record::Base *B = R->getBase(Init->getType())) {
@@ -1395,6 +1396,8 @@
 
   if (!this->emitPopPtr(Initializer))
 return false;
+  // Base initializers don't increase InitIndex, since they don't count
+  // into the Record's fields.
 } else {
   const Record::Field *FieldToInit = R->getField(InitIndex);
   // Non-primitive case. Get a pointer to the field-to-initialize
@@ -1407,9 +1410,9 @@
 
   if (!this->emitPopPtr(Initializer))
 return false;
+  ++InitIndex;
 }
   }
-  ++InitIndex;
 }
 
 return true;


Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -583,3 +583,20 @@
   constexpr Outer O;
   static_assert(O.bar() == 12);
 }
+
+namespace BaseAndFieldInit {
+  struct A {
+int a;
+  };
+
+  struct B : A {
+int b;
+  };
+
+  struct C : B {
+int c;
+  };
+
+  constexpr C c = {1,2,3};
+  static_assert(c.a == 1 && c.b == 2 && c.c == 3);
+}
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1384,6 +1384,7 @@
 
 if (!this->emitPopPtr(Initializer))
   return false;
+++InitIndex;
   } else {
 // Initializer for a direct base class.
 if (const Record::Base *B = R->getBase(Init->getType())) {
@@ -1395,6 +1396,8 @@
 
   if (!this->emitPopPtr(Initializer))
 return false;
+  // Base initializers don't increase InitIndex, since they don't count
+  // into the Record's fields.
 } else {
   const Record::Field *FieldToInit = R->getField(InitIndex);
   // Non-primitive case. Get a pointer to the field-to-initialize
@@ -1407,9 +1410,9 @@
 
   if (!this->emitPopPtr(Initializer))
 return false;
+  ++InitIndex;
 }
   }
-  ++InitIndex;
 }
 
 return true;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147175: [clang] Add __is_trivially_equality_comparable

2023-04-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Hmmm, is this effectively `std::has_unique_object_representations` (ensuring 
that all bits of the object representation contribute to the value)?




Comment at: clang/lib/AST/Type.cpp:2610
+
+  if (const auto *RecordDecl = CanonicalType->getAsCXXRecordDecl()) {
+if (!RecordDecl->isStandardLayout() || RecordDecl->isUnion())

Dependent types should probably return `false`?



Comment at: clang/lib/AST/Type.cpp:2640
+
+  return false;
+}

I think this might be missing cases, like complex integers, scoped 
enumerations, vector types?, pointer types, atomic versions of these types...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147175

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


[PATCH] D144269: [Analyzer] Show "taint originated here" note of alpha.security.taint.TaintPropagation checker at the correct place

2023-04-03 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

In D144269#4237539 , @dkrupp wrote:

> This is a totally rewritten version of the patch which solely relies on the 
> existing "interestingness" utility to track back the taint propagation.  (And 
>  does not introduce a new FlowID in the ProgramState as requested in the 
> reviews.)
>
> -The new version also places a Note, when the taintedness is propagated to an 
> argument or to a return value. So it should be easier for the user to follow 
> how the taint information is spreading. 
> -"The taint originated here" is printed correctly at the taint source 
> function, which introduces taintedness. (Main goal of this patch.)
>
> Implementation:
> -The createTaintPreTag() function places a NoteTag at the taint propagation 
> function calls, if taintedness is propagated. Then at report creation, the 
> tainted arguments are marked interesting if propagated taintedness is 
> relevant for the bug report.
>
> - The isTainted() function is extended to return the actually tainted 
> SymbolRef. This is important to be able to consistently mark relevant symbol 
> interesting which carries the taintedness in a complex expression.

So this is how you circumvent introducing "transitive interestingness", because 
now you know which symbol to track.

> -createTaintPostTag(..) function places a NoteTag to the taint generating 
> function calls to mark them interesting if they are relevant for a 
> taintedness report. So if they propagated taintedness to interesting 
> symbol(s).
>
> The tests are passing and the reports on the open source projects are much 
> better understandable than before (twin, tmux, curl):
>
> https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=curl_curl-7_66_0_dkrupp_taint_origin_fix_new&run=tmux_2.6_dkrupp_taint_origin_fix_new&run=twin_v0.8.1_dkrupp_taint_origin_fix_new&is-unique=on&diff-type=New&checker-msg=%2auntrusted%2a&checker-msg=Out%20of%20bound%20memory%20access%20%28index%20is%20tainted%29

I've looked at the results you attached and they look good to me.

Do you have an example where two tainted values are contributing to the same 
bug? Something like:

  n <- read();
  m <- read();
  malloc(n+m)

Will both of these values tracked back? What do the notes look like?

---

All in all, I'm pleased to see the improvements. It looks much better now IMO.
Using two NoteTags cleans up the implementation quite a bit, kudos.
I don't think there are major problems with this implementation, so I decided 
to spew your code with my nitpicks :D

Remember to clang-format your code. See 
`clang/tools/clang-format/clang-format-diff.py`.
And there are a few overloads of `getNoteTag()`, and there could be a better 
fit for usecases; you should decide.

I also find it difficult to track how a variable got tainted across assignments 
and computations like in this 

 case.
This observation is completely orthogonal to your patch, I'm just noting it. it 
was bad previously as well.
Maybe we could have a visitor for explaining the taint tracking across 
assignments and computations to complement the NoteTag.

I hope I didn't miss much this time :D




Comment at: clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp:238-244
+if (kind == OOB_Tainted)
+  BT.reset(
+  new BugType(this, "Out-of-bound access", categories::TaintedData));
+else
+  BT.reset(
+  new BugType(this, "Out-of-bound access", categories::LogicError));
+  }





Comment at: clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp:45
 
-void DivZeroChecker::reportBug(
-const char *Msg, ProgramStateRef StateZero, CheckerContext &C,
-std::unique_ptr Visitor) const {
+void DivZeroChecker::reportBug(const char *Msg, std::string Category,
+   ProgramStateRef StateZero, CheckerContext &C,

It feels odd to have both `const char*` and a `std::string` on the same line.
Should we update `const char*` to a more sophisticated type?

I'm thinking of `StringRef`. It seems like that type should be used for the 
`Category` as well since the `PathSensitiveBugReport` constructor takes that, 
so we don't need to have an owning type here.



Comment at: clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.cpp:91-96
+  SymbolRef TSR = isTainted(C.getState(), *DV);
+  if ((stateNotZero && stateZero && TSR)) {
+reportBug("Division by a tainted value, possibly zero",
+  categories::TaintedData, stateZe

[PATCH] D146595: [clang] Add "transparent_stepping" attribute

2023-04-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D146595#4237228 , @aprantl wrote:

> I think `debug_trampoline` both captures the semantics and makes it clear 
> that this is related to debugging.

I'd be fine with this, or `transparent_debug_stepping`, etc. Just something 
other than `transparent` or `trampoline` as those are rather generic terms.

In D146595#4228425 , @arphaman wrote:

> How is this attribute going to handle a trampoline that performs a virtual 
> dispatch from C++ call into Swift? In that case, the target is not known.

Additionally, should you be allowed to write this on a lambda to skip over the 
function call operator? (If so, you may need to move the attribute from the 
lambda declaration onto the function call operator.)




Comment at: clang/include/clang/Basic/Attr.td:775
+  let Spellings = [Clang<"transparent_stepping">];
+  let Subjects = SubjectList<[Function]>;
+  let Documentation = [TransparentSteppingDocs];

ObjC method decls as well?



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:71
 
+static bool getIsTransparentStepping(const Decl *D) {
+  if (!D)

How about something like this ("get is" just sounds weird to me)?



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:6773-6777
+static void handleTransparentStepping(Sema &S, Decl *D,
+  const ParsedAttr &AL) {
+  D->addAttr(::new (S.Context)
+ TransparentSteppingAttr(S.Context, AL));
+}

Can be removed entirely if we don't have any custom checking logic for it. 
Instead, do `let SimpleHandler = 1;` in the attribute definition in Attr.td.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:9090-9092
+  case ParsedAttr::AT_TransparentStepping:
+handleTransparentStepping(S, D, AL);
+break;

This can also be removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146595

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


[clang-tools-extra] f323e7f - [include-cleaner] Treat member operator calls as implicit

2023-04-03 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-04-03T16:27:23+02:00
New Revision: f323e7f3ca760be786d2584c926edade34c3fbde

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

LOG: [include-cleaner] Treat member operator calls as implicit

26ff268b80c589fd9f71c1c214af77cd972642ca treated member operator calls
as explicit, while trying to treat them the same way as regular member
expressions, which should've been implicit.

Added: 


Modified: 
clang-tools-extra/include-cleaner/lib/WalkAST.cpp
clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/lib/WalkAST.cpp 
b/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
index 8a1dd77176cd..ab1476ea0997 100644
--- a/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ b/clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -95,14 +95,15 @@ class ASTWalker : public RecursiveASTVisitor {
   // to them doesn't count as uses (generally the type should provide them, so
   // ignore them).
   // Unless we're using an operator defined as a member, in such cases treat
-  // this as a regular reference.
+  // these as regular member references.
   bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *S) {
 if (!WalkUpFromCXXOperatorCallExpr(S))
   return false;
 if (auto *CD = S->getCalleeDecl()) {
   if (llvm::isa(CD)) {
 // Treat this as a regular member reference.
-report(S->getOperatorLoc(), 
getMemberProvider(S->getArg(0)->getType()));
+report(S->getOperatorLoc(), getMemberProvider(S->getArg(0)->getType()),
+   RefType::Implicit);
   } else {
 report(S->getOperatorLoc(), llvm::dyn_cast(CD),
RefType::Implicit);

diff  --git a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp 
b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
index fceec670076c..ac2085d82c1d 100644
--- a/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ b/clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -296,12 +296,12 @@ TEST(WalkAST, Operator) {
   testWalk(
   "struct string { friend int $implicit^operator+(string, string); }; ",
   "int k = string() ^+ string();");
-  // Unless they're members, we treat them as regular member expr calls.
-  testWalk("struct $explicit^string {int operator+(string); }; ",
+  // Treat member operators as regular member expr calls.
+  testWalk("struct $implicit^string {int operator+(string); }; ",
"int k = string() ^+ string();");
   // Make sure usage is attributed to the alias.
   testWalk(
-  "struct string {int operator+(string); }; using $explicit^foo = string;",
+  "struct string {int operator+(string); }; using $implicit^foo = string;",
   "int k = foo() ^+ string();");
 }
 



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


[clang] 8c8b4d2 - [Clang] Update test checks (NFC)

2023-04-03 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2023-04-03T16:33:34+02:00
New Revision: 8c8b4d24f019e51900f15e008b52a05cf1e66381

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

LOG: [Clang] Update test checks (NFC)

These were affected by 9b5ff4436e446e9df97ee37b3bcf9ba029c7d9aa.

Added: 


Modified: 
clang/test/OpenMP/bug54082.c

Removed: 




diff  --git a/clang/test/OpenMP/bug54082.c b/clang/test/OpenMP/bug54082.c
index 64702017dcde6..beaebeb21cb77 100644
--- a/clang/test/OpenMP/bug54082.c
+++ b/clang/test/OpenMP/bug54082.c
@@ -99,7 +99,7 @@ void foo() {
 // CHECK-NEXT:[[CONV:%.*]] = inttoptr i64 [[TMP1]] to ptr
 // CHECK-NEXT:[[DOTX__VOID_ADDR:%.*]] = tail call ptr @__kmpc_alloc(i32 
[[TMP0]], i64 8, ptr [[CONV]])
 // CHECK-NEXT:call void @__kmpc_for_static_init_4(ptr nonnull 
@[[GLOB1:[0-9]+]], i32 [[TMP0]], i32 34, ptr nonnull [[DOTOMP_IS_LAST]], ptr 
nonnull [[DOTOMP_LB]], ptr nonnull [[DOTOMP_UB]], ptr nonnull 
[[DOTOMP_STRIDE]], i32 1, i32 1)
-// CHECK-NEXT:[[TMP2:%.*]] = load i32, ptr [[DOTOMP_UB]], align 4, !tbaa 
[[TBAA6]]
+// CHECK-NEXT:[[TMP2:%.*]] = load i32, ptr [[DOTOMP_UB]], align 4
 // CHECK-NEXT:[[COND:%.*]] = call i32 @llvm.smin.i32(i32 [[TMP2]], i32 
1023)
 // CHECK-NEXT:store i32 [[COND]], ptr [[DOTOMP_UB]], align 4, !tbaa 
[[TBAA6]]
 // CHECK-NEXT:call void @__kmpc_for_static_fini(ptr nonnull @[[GLOB1]], 
i32 [[TMP0]])



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


[PATCH] D145088: [RISCV] Add attribute(riscv_rvv_vector_bits(N)) based on AArch64 arm_sve_vector_bits.

2023-04-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: erichkeane, rjmccall, efriedma.
aaron.ballman added a comment.

Adding Erich as attributes code owner and John/Eli as ABI code owners.




Comment at: clang/lib/Sema/SemaType.cpp:8265
+  // The attribute vector size must match -mrvv-vector-bits.
+  // FIXME: LMUL from type and scale it.
+  if (VecSize != VScale->first * llvm::RISCV::RVVBitsPerBlock) {

Should this be done as part of this patch (are we accepting code we shouldn't 
be accepting)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145088

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


[clang] b15a946 - [clang][Interp][NFC] Refactor VisitDeclRefExpr

2023-04-03 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-03T16:42:25+02:00
New Revision: b15a946b9f59f91518ae5e2cb6125592d9c1bf3c

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

LOG: [clang][Interp][NFC] Refactor VisitDeclRefExpr

Make it clearer that we only need to check for variables and parameters
if we don't have the easy case. Also only do the IsReference check if
necessary.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index ee5dd73159a6..e620b4f9b2f6 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1840,37 +1840,41 @@ bool ByteCodeExprGen::VisitUnaryOperator(const 
UnaryOperator *E) {
 
 template 
 bool ByteCodeExprGen::VisitDeclRefExpr(const DeclRefExpr *E) {
-  const auto *Decl = E->getDecl();
+  const auto *D = E->getDecl();
+
+  if (const auto *ECD = dyn_cast(D)) {
+return this->emitConst(ECD->getInitVal(), E);
+  } else if (const auto *BD = dyn_cast(D)) {
+return this->visit(BD->getBinding());
+  } else if (const auto *FuncDecl = dyn_cast(D)) {
+const Function *F = getFunction(FuncDecl);
+return F && this->emitGetFnPtr(F, E);
+  }
+
   // References are implemented via pointers, so when we see a DeclRefExpr
   // pointing to a reference, we need to get its value directly (i.e. the
   // pointer to the actual value) instead of a pointer to the pointer to the
   // value.
-  bool IsReference = Decl->getType()->isReferenceType();
+  bool IsReference = D->getType()->isReferenceType();
 
-  if (auto It = Locals.find(Decl); It != Locals.end()) {
+  // Check for local/global variables and parameters.
+  if (auto It = Locals.find(D); It != Locals.end()) {
 const unsigned Offset = It->second.Offset;
 
 if (IsReference)
   return this->emitGetLocal(PT_Ptr, Offset, E);
 return this->emitGetPtrLocal(Offset, E);
-  } else if (auto GlobalIndex = P.getGlobal(Decl)) {
+  } else if (auto GlobalIndex = P.getGlobal(D)) {
 if (IsReference)
   return this->emitGetGlobal(PT_Ptr, *GlobalIndex, E);
 
 return this->emitGetPtrGlobal(*GlobalIndex, E);
-  } else if (const auto *PVD = dyn_cast(Decl)) {
+  } else if (const auto *PVD = dyn_cast(D)) {
 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
   if (IsReference)
 return this->emitGetParam(PT_Ptr, It->second, E);
   return this->emitGetPtrParam(It->second, E);
 }
-  } else if (const auto *ECD = dyn_cast(Decl)) {
-return this->emitConst(ECD->getInitVal(), E);
-  } else if (const auto *BD = dyn_cast(Decl)) {
-return this->visit(BD->getBinding());
-  } else if (const auto *FuncDecl = dyn_cast(Decl)) {
-const Function *F = getFunction(FuncDecl);
-return F && this->emitGetFnPtr(F, E);
   }
 
   return false;



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


[PATCH] D147302: [clang][dataflow] Add `create()` methods to `Environment` and `DataflowAnalysisContext`.

2023-04-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme updated this revision to Diff 510496.
mboehme marked an inline comment as done.
mboehme added a comment.

Changes in response to review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147302

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

Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -312,8 +312,7 @@
 
   if (Member->getType()->isReferenceType()) {
 auto &MemberLoc = ThisLoc.getChild(*Member);
-Env.setValue(MemberLoc, Env.takeOwnership(std::make_unique(
-*InitStmtLoc)));
+Env.setValue(MemberLoc, Env.create(*InitStmtLoc));
   } else {
 auto &MemberLoc = ThisLoc.getChild(*Member);
 Env.setValue(MemberLoc, *InitStmtVal);
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -237,7 +237,7 @@
   Env.setStorageLocation(*S, *DeclLoc);
 } else {
   auto &Loc = Env.createStorageLocation(*S);
-  auto &Val = Env.takeOwnership(std::make_unique(*DeclLoc));
+  auto &Val = Env.create(*DeclLoc);
   Env.setStorageLocation(*S, Loc);
   Env.setValue(Loc, Val);
 }
@@ -276,8 +276,7 @@
   // FIXME: reuse the ReferenceValue instead of creating a new one.
   if (auto *InitExprLoc =
   Env.getStorageLocation(*InitExpr, SkipPast::Reference)) {
-auto &Val =
-Env.takeOwnership(std::make_unique(*InitExprLoc));
+auto &Val = Env.create(*InitExprLoc);
 Env.setValue(Loc, Val);
   }
 } else if (auto *InitExprVal = Env.getValue(*InitExpr, SkipPast::None)) {
@@ -423,8 +422,8 @@
 
   auto &Loc = Env.createStorageLocation(*S);
   Env.setStorageLocation(*S, Loc);
-  Env.setValue(Loc, Env.takeOwnership(std::make_unique(
-SubExprVal->getPointeeLoc(;
+  Env.setValue(Loc,
+   Env.create(SubExprVal->getPointeeLoc()));
   break;
 }
 case UO_AddrOf: {
@@ -437,8 +436,7 @@
 break;
 
   auto &PointerLoc = Env.createStorageLocation(*S);
-  auto &PointerVal =
-  Env.takeOwnership(std::make_unique(*PointeeLoc));
+  auto &PointerVal = Env.create(*PointeeLoc);
   Env.setStorageLocation(*S, PointerLoc);
   Env.setValue(PointerLoc, PointerVal);
   break;
@@ -468,8 +466,7 @@
 
 auto &Loc = Env.createStorageLocation(*S);
 Env.setStorageLocation(*S, Loc);
-Env.setValue(Loc, Env.takeOwnership(
-  std::make_unique(*ThisPointeeLoc)));
+Env.setValue(Loc, Env.create(*ThisPointeeLoc));
   }
 
   void VisitReturnStmt(const ReturnStmt *S) {
@@ -523,8 +520,7 @@
 } else {
   auto &Loc = Env.createStorageLocation(*S);
   Env.setStorageLocation(*S, Loc);
-  Env.setValue(Loc, Env.takeOwnership(
-std::make_unique(*VarDeclLoc)));
+  Env.setValue(Loc, Env.create(*VarDeclLoc));
 }
 return;
   }
@@ -558,8 +554,7 @@
 } else {
   auto &Loc = Env.createStorageLocation(*S);
   Env.setStorageLocation(*S, Loc);
-  Env.setValue(
-  Loc, Env.takeOwnership(std::make_unique(MemberLoc)));
+  Env.setValue(Loc, Env.create(MemberLoc));
 }
   }
 
Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -221,9 +221,9 @@
 /// Creates a symbolic value for an `optional` value using `HasValueVal` as the
 /// symbolic value of its "has_value" property.
 StructValue &createOptionalValue(Environment &Env, BoolValue &HasValueVal) {
-  auto OptionalVal = std::make_unique();
-  setHasValue(*OptionalVal, HasValueVal);
-  return Env.takeOwnership(std::move(OptionalVal));
+  auto &OptionalVal = Env.create();
+  setHasValue(OptionalVal, HasValueVal);
+  return OptionalVal;
 }
 
 /// Returns the symbolic value that represents the "has_value" property of the
@@ -312,8 +312,8 @@
 return nullptr;
   auto &ValueLoc = Env.createStorageLocation(Ty);
   E

[PATCH] D147302: [clang][dataflow] Add `create()` methods to `Environment` and `DataflowAnalysisContext`.

2023-04-03 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked an inline comment as done.
mboehme added inline comments.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:215
   /// Creates an atomic boolean value.
-  AtomicBoolValue &createAtomicBoolValue() {
-return takeOwnership(std::make_unique());
-  }
+  AtomicBoolValue &createAtomicBoolValue() { return create(); 
}
 

ymandel wrote:
> Is there any reason for this function anymore or should we deprecate it (and 
> the Top version below)? Especially in this object which only used internally 
> and not by clients -- the extra two characters don't seem to justify a 
> function.
I had wondered the same thing. I've added `LLVM_DEPRECATED` to both.

(I'm not changing callers in this patch because I'd like to avoid expanding the 
size of the patch.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147302

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


[clang] 192c2c5 - [clang][Interp] Ignore StaticAssertDecls

2023-04-03 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-03T16:56:58+02:00
New Revision: 192c2c5c89477e28d0129f37a7d262112585b353

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

LOG: [clang][Interp] Ignore StaticAssertDecls

They have already been handled before, but we can't just return false
when we encounter one.

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

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeStmtGen.cpp
clang/test/AST/Interp/functions.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp 
b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
index 1735b9b0272b..6faa3f9a47a9 100644
--- a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -224,6 +224,9 @@ bool ByteCodeStmtGen::visitCompoundStmt(
 template 
 bool ByteCodeStmtGen::visitDeclStmt(const DeclStmt *DS) {
   for (auto *D : DS->decls()) {
+if (isa(D))
+  continue;
+
 const auto *VD = dyn_cast(D);
 if (!VD)
   return false;

diff  --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index 2b44f42486d3..4b81e7d6be3b 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -9,11 +9,28 @@ constexpr int gimme5() {
 static_assert(gimme5() == 5, "");
 
 
-template constexpr T identity(T t) { return t; }
+template constexpr T identity(T t) {
+  static_assert(true);
+  return t;
+}
 static_assert(identity(true), "");
 static_assert(identity(true), ""); /// Compiled bytecode should be cached
 static_assert(!identity(false), "");
 
+template
+constexpr bool sameSize() {
+  static_assert(sizeof(A) == sizeof(B), ""); // expected-error {{static 
assertion failed}} \
+ // ref-error {{static assertion 
failed}} \
+ // expected-note {{evaluates to}} 
\
+ // ref-note {{evaluates to}}
+  return true;
+}
+static_assert(sameSize(), "");
+static_assert(sameSize(), "");
+static_assert(sameSize(), ""); // expected-note {{in instantiation 
of function template specialization}} \
+   // ref-note {{in instantiation of 
function template specialization}}
+
+
 constexpr auto add(int a, int b) -> int {
   return identity(a) + identity(b);
 }



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


[PATCH] D144272: [clang][Interp] Ignore StaticAssertDecls

2023-04-03 Thread Timm Bäder 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 rG192c2c5c8947: [clang][Interp] Ignore StaticAssertDecls 
(authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144272

Files:
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/test/AST/Interp/functions.cpp


Index: clang/test/AST/Interp/functions.cpp
===
--- clang/test/AST/Interp/functions.cpp
+++ clang/test/AST/Interp/functions.cpp
@@ -9,11 +9,28 @@
 static_assert(gimme5() == 5, "");
 
 
-template constexpr T identity(T t) { return t; }
+template constexpr T identity(T t) {
+  static_assert(true);
+  return t;
+}
 static_assert(identity(true), "");
 static_assert(identity(true), ""); /// Compiled bytecode should be cached
 static_assert(!identity(false), "");
 
+template
+constexpr bool sameSize() {
+  static_assert(sizeof(A) == sizeof(B), ""); // expected-error {{static 
assertion failed}} \
+ // ref-error {{static assertion 
failed}} \
+ // expected-note {{evaluates to}} 
\
+ // ref-note {{evaluates to}}
+  return true;
+}
+static_assert(sameSize(), "");
+static_assert(sameSize(), "");
+static_assert(sameSize(), ""); // expected-note {{in instantiation 
of function template specialization}} \
+   // ref-note {{in instantiation of 
function template specialization}}
+
+
 constexpr auto add(int a, int b) -> int {
   return identity(a) + identity(b);
 }
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -224,6 +224,9 @@
 template 
 bool ByteCodeStmtGen::visitDeclStmt(const DeclStmt *DS) {
   for (auto *D : DS->decls()) {
+if (isa(D))
+  continue;
+
 const auto *VD = dyn_cast(D);
 if (!VD)
   return false;


Index: clang/test/AST/Interp/functions.cpp
===
--- clang/test/AST/Interp/functions.cpp
+++ clang/test/AST/Interp/functions.cpp
@@ -9,11 +9,28 @@
 static_assert(gimme5() == 5, "");
 
 
-template constexpr T identity(T t) { return t; }
+template constexpr T identity(T t) {
+  static_assert(true);
+  return t;
+}
 static_assert(identity(true), "");
 static_assert(identity(true), ""); /// Compiled bytecode should be cached
 static_assert(!identity(false), "");
 
+template
+constexpr bool sameSize() {
+  static_assert(sizeof(A) == sizeof(B), ""); // expected-error {{static assertion failed}} \
+ // ref-error {{static assertion failed}} \
+ // expected-note {{evaluates to}} \
+ // ref-note {{evaluates to}}
+  return true;
+}
+static_assert(sameSize(), "");
+static_assert(sameSize(), "");
+static_assert(sameSize(), ""); // expected-note {{in instantiation of function template specialization}} \
+   // ref-note {{in instantiation of function template specialization}}
+
+
 constexpr auto add(int a, int b) -> int {
   return identity(a) + identity(b);
 }
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -224,6 +224,9 @@
 template 
 bool ByteCodeStmtGen::visitDeclStmt(const DeclStmt *DS) {
   for (auto *D : DS->decls()) {
+if (isa(D))
+  continue;
+
 const auto *VD = dyn_cast(D);
 if (!VD)
   return false;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D145803: [clang][DebugInfo] Emit DW_AT_type of preferred name if available

2023-04-03 Thread Michael Buch via Phabricator via cfe-commits
Michael137 added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145803

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


[clang] 82facc2 - [clang][Interp] Add missing static_assert message

2023-04-03 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-04-03T17:12:05+02:00
New Revision: 82facc2b2462441a83ca35d2d6ef1ab28244a1b3

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

LOG: [clang][Interp] Add missing static_assert message

This broke builders, e.g:
https://lab.llvm.org/buildbot/#builders/139/builds/38457

Added: 


Modified: 
clang/test/AST/Interp/functions.cpp

Removed: 




diff  --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index 4b81e7d6be3b..06edcdeffa70 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -10,7 +10,7 @@ static_assert(gimme5() == 5, "");
 
 
 template constexpr T identity(T t) {
-  static_assert(true);
+  static_assert(true, "");
   return t;
 }
 static_assert(identity(true), "");



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


[PATCH] D144190: [AIX][clang] Storage Locations for Constant Pointers

2023-04-03 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 added a comment.

Ping for review. Specifically, the option is renamed to `-mxcoff-roptr` and 
`-mno-xcoff-roptr` to indicate that this option only affects the `XCOFF` binary 
format, so it is expected to not affect `ELF` or other formats.

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144190

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


[PATCH] D147419: [clang-tidy] ignore NRVO const variables in performance-no-automatic-move.

2023-04-03 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL accepted this revision.
PiotrZSL added a comment.

Current change is correct.
This check could be improved in future.
LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147419

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


[PATCH] D147419: [clang-tidy] ignore NRVO const variables in performance-no-automatic-move.

2023-04-03 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

Add release notes entry !.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147419

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


[PATCH] D147417: [clang-tidy] Do not emit bugprone-exception-escape warnings from coroutines

2023-04-03 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape-coro.cpp:91
+const auto d_ShouldNotDiag = [](const int a, const int b) -> task {
+  // CHECK-MESSAGES-NOT: :[[@LINE-1]]:30: warning: an exception may be thrown 
in function 'operator()' which should not throw exceptions
+  if (b == 0)

And based on ChuanqiXu comment, same here.

"All exceptions thrown in coroutine bodies are caught and
unhandled_exception member of the coroutine promise type is called."
This isn't expected behaviour, as it may hide exception.
Based on that we should assume, if there is noexcept, then it should not throw, 
and if its no noexcept, then it could throw. No point to change default 
behaviour then. 

Other option is to add check option to handle this.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147417

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


[PATCH] D147395: [Clangd] Make the type hint length limit configurable

2023-04-03 Thread Yi Zhang via Phabricator via cfe-commits
zhangyi1357 updated this revision to Diff 510508.
zhangyi1357 added a comment.

Add uint32Value() for uint32_t type parsing in config file.
For TypeNameLimit config, support no limit with value 0.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147395

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/InlayHints.cpp


Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -688,7 +688,8 @@
   return;
 
 std::string TypeName = T.getAsString(Policy);
-if (TypeName.length() < Cfg.InlayHints.TypeNameLimit)
+if (Cfg.InlayHints.TypeNameLimit == 0 ||
+TypeName.length() < Cfg.InlayHints.TypeNameLimit)
   addInlayHint(R, HintSide::Right, InlayHintKind::Type, Prefix, TypeName,
/*Suffix=*/"");
   }
Index: clang-tools-extra/clangd/ConfigYAML.cpp
===
--- clang-tools-extra/clangd/ConfigYAML.cpp
+++ clang-tools-extra/clangd/ConfigYAML.cpp
@@ -255,7 +255,7 @@
 F.Designators = *Value;
 });
 Dict.handle("TypeNameLimit", [&](Node &N) {
-  if (auto Value = scalarValue(N, "TypeNameLimit"))
+  if (auto Value = uint32Value(N, "TypeNameLimit"))
 F.TypeNameLimit = *Value;
 });
 Dict.parse(N);
@@ -379,6 +379,17 @@
 return std::nullopt;
   }
 
+  std::optional> uint32Value(Node &N, llvm::StringRef Desc) {
+if (auto Scalar = scalarValue(N, Desc)) {
+  unsigned long long Num;
+  if (!llvm::getAsUnsignedInteger(**Scalar, 0, Num)) {
+return Located(Num, Scalar->Range);
+  }
+}
+warning(Desc + " invalid number", N);
+return std::nullopt;
+  }
+
   // Try to parse a list of single scalar values, or just a single value.
   std::optional>> scalarValues(Node &N) {
 std::vector> Result;
Index: clang-tools-extra/clangd/ConfigFragment.h
===
--- clang-tools-extra/clangd/ConfigFragment.h
+++ clang-tools-extra/clangd/ConfigFragment.h
@@ -322,8 +322,8 @@
 std::optional> DeducedTypes;
 /// Show designators in aggregate initialization.
 std::optional> Designators;
-/// Limit the length of type name hints.
-std::optional> TypeNameLimit;
+/// Limit the length of type name hints. (0 means no limit)
+std::optional> TypeNameLimit;
   };
   InlayHintsBlock InlayHints;
 };
Index: clang-tools-extra/clangd/ConfigCompile.cpp
===
--- clang-tools-extra/clangd/ConfigCompile.cpp
+++ clang-tools-extra/clangd/ConfigCompile.cpp
@@ -614,7 +614,7 @@
 if (F.TypeNameLimit)
   Out.Apply.push_back(
   [Value(**F.TypeNameLimit)](const Params &, Config &C) {
-C.InlayHints.TypeNameLimit = stoul(Value);
+C.InlayHints.TypeNameLimit = Value;
   });
   }
 
Index: clang-tools-extra/clangd/Config.h
===
--- clang-tools-extra/clangd/Config.h
+++ clang-tools-extra/clangd/Config.h
@@ -147,8 +147,8 @@
 bool Parameters = true;
 bool DeducedTypes = true;
 bool Designators = true;
-// Limit the length of type names in inlay hints.
-size_t TypeNameLimit = 32;
+// Limit the length of type names in inlay hints. (0 means no limit)
+uint32_t TypeNameLimit = 32;
   } InlayHints;
 };
 


Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -688,7 +688,8 @@
   return;
 
 std::string TypeName = T.getAsString(Policy);
-if (TypeName.length() < Cfg.InlayHints.TypeNameLimit)
+if (Cfg.InlayHints.TypeNameLimit == 0 ||
+TypeName.length() < Cfg.InlayHints.TypeNameLimit)
   addInlayHint(R, HintSide::Right, InlayHintKind::Type, Prefix, TypeName,
/*Suffix=*/"");
   }
Index: clang-tools-extra/clangd/ConfigYAML.cpp
===
--- clang-tools-extra/clangd/ConfigYAML.cpp
+++ clang-tools-extra/clangd/ConfigYAML.cpp
@@ -255,7 +255,7 @@
 F.Designators = *Value;
 });
 Dict.handle("TypeNameLimit", [&](Node &N) {
-  if (auto Value = scalarValue(N, "TypeNameLimit"))
+  if (auto Value = uint32Value(N, "TypeNameLimit"))
 F.TypeNameLimit = *Value;
 });
 Dict.parse(N);
@@ -379,6 +379,17 @@
 return std::nullopt;
   }
 
+  std::optional> uint32Value(Node &N, llvm::StringRef Desc) {
+if (auto Scalar = scalarValue(N, Desc)) {
+  unsigned long long Num;
+  if

[PATCH] D147395: [Clangd] Make the type hint length limit configurable

2023-04-03 Thread Yi Zhang via Phabricator via cfe-commits
zhangyi1357 marked 2 inline comments as done.
zhangyi1357 added a comment.

In D147395#4240227 , @hokein wrote:

> Thanks for the contribution!

It's really interesting for me. Thanks for your time reviewing!




Comment at: clang-tools-extra/clangd/Config.h:151
+// Limit the length of type names in inlay hints.
+size_t TypeNameLimit = 32;
   } InlayHints;

hokein wrote:
> I would extend it a bit more -- 0 means no limit. 
> 
> Can you also add a unittest in `TEST(TypeHints, LongTypeName)` in 
> `InlayHintTests.cpp`? 
> 0 means no limit.
This is quite a good idea. I've done it.

For unittest, there is already `TEST(TypeHints, LongTypeName)` in 
`InlayHintTests.cpp`. Do you mean add more tests in the same `TEST` or another 
`TEST` with TypeNameLimit configured?



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147395

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


[PATCH] D147073: [Coverage] Handle invalid end location of an expression/statement.

2023-04-03 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu marked an inline comment as done.
zequanwu added a comment.

In D147073#4240017 , @hans wrote:

> I'm not familiar with this code. I suppose the question is whether it's 
> reasonable for this code to expect that the source locations are always valid 
> or not?

Yes.

For `0 ? T{} : T{};`, the both branches have valid start location but 
invalid end location. See comments at 
https://github.com/llvm/llvm-project/issues/45481#issuecomment-1487267814.

For the `std::strong_ordering`, I found that `DeclRefExpr` in the 
ConditionalOperator's true branch has invalid start and end locations. It might 
because it's inside a `PseudoObjectExpr`. Maybe we should simply just skip 
visiting `PseudoObjectExpr`, I see that its begin and end location are the 
same. I'm not familiar with that expression, so, I just handled it by adding 
checks for validating begin and end locations.

  PseudoObjectExpr 0x629f3bf0 'const strong_ordering':'const class 
std::strong_ordering' lvalue
  |-BinaryOperator 0x629f3bd0 'const strong_ordering':'const class 
std::strong_ordering' lvalue '<=>'
  | |-MemberExpr 0x629f3848 'const S':'const struct S' lvalue .value 
0x629f34d0
  | | `-DeclRefExpr 0x629f3808 'const MyStruct':'const struct MyStruct' 
lvalue ParmVar 0x629f31b0 'lhs' 'const MyStruct &'
  | `-MemberExpr 0x629f3878 'const S':'const struct S' lvalue .value 
0x629f34d0
  |   `-DeclRefExpr 0x629f3828 'const MyStruct':'const struct MyStruct' 
lvalue ParmVar 0x629f3238 'rhs' 'const MyStruct &'
  |-OpaqueValueExpr 0x629f38a8 'const S':'const struct S' lvalue
  | `-MemberExpr 0x629f3848 'const S':'const struct S' lvalue .value 
0x629f34d0
  |   `-DeclRefExpr 0x629f3808 'const MyStruct':'const struct MyStruct' 
lvalue ParmVar 0x629f31b0 'lhs' 'const MyStruct &'
  |-OpaqueValueExpr 0x629f38c0 'const S':'const struct S' lvalue
  | `-MemberExpr 0x629f3878 'const S':'const struct S' lvalue .value 
0x629f34d0
  |   `-DeclRefExpr 0x629f3828 'const MyStruct':'const struct MyStruct' 
lvalue ParmVar 0x629f3238 'rhs' 'const MyStruct &'
  `-ConditionalOperator 0x629f3ba0 'const strong_ordering':'const class 
std::strong_ordering' lvalue
|-CXXOperatorCallExpr 0x629f3970 '_Bool' '==' adl
| |-ImplicitCastExpr 0x629f3958 '_Bool (*)(const S &, const S &)' 

| | `-DeclRefExpr 0x629f38d8 '_Bool (const S &, const S &)' lvalue 
Function 0x629f2a40 'operator==' '_Bool (const S &, const S &)'
| |-OpaqueValueExpr 0x629f38a8 'const S':'const struct S' lvalue
| | `-MemberExpr 0x629f3848 'const S':'const struct S' lvalue .value 
0x629f34d0
| |   `-DeclRefExpr 0x629f3808 'const MyStruct':'const struct MyStruct' 
lvalue ParmVar 0x629f31b0 'lhs' 'const MyStruct &'
| `-OpaqueValueExpr 0x629f38c0 'const S':'const struct S' lvalue
|   `-MemberExpr 0x629f3878 'const S':'const struct S' lvalue .value 
0x629f34d0
| `-DeclRefExpr 0x629f3828 'const MyStruct':'const struct MyStruct' 
lvalue ParmVar 0x629f3238 'rhs' 'const MyStruct &'
|-DeclRefExpr 0x629f3b80 'const strong_ordering':'const class 
std::strong_ordering' lvalue Var 0x629a4ed8 'equal' 'const 
strong_ordering':'const class std::strong_ordering'
`-ConditionalOperator 0x629f3b50 'const strong_ordering':'const class 
std::strong_ordering' lvalue
  |-CXXOperatorCallExpr 0x629f3ab0 '_Bool' '<' adl
  | |-ImplicitCastExpr 0x629f3a98 '_Bool (*)(const S &, const S &)' 

  | | `-DeclRefExpr 0x629f3a78 '_Bool (const S &, const S &)' lvalue 
Function 0x629f27a0 'operator<' '_Bool (const S &, const S &)'
  | |-OpaqueValueExpr 0x629f38a8 'const S':'const struct S' lvalue
  | | `-MemberExpr 0x629f3848 'const S':'const struct S' lvalue .value 
0x629f34d0
  | |   `-DeclRefExpr 0x629f3808 'const MyStruct':'const struct 
MyStruct' lvalue ParmVar 0x629f31b0 'lhs' 'const MyStruct &'
  | `-OpaqueValueExpr 0x629f38c0 'const S':'const struct S' lvalue
  |   `-MemberExpr 0x629f3878 'const S':'const struct S' lvalue .value 
0x629f34d0
  | `-DeclRefExpr 0x629f3828 'const MyStruct':'const struct 
MyStruct' lvalue ParmVar 0x629f3238 'rhs' 'const MyStruct &'
  |-DeclRefExpr 0x629f3b30 'const strong_ordering':'const class 
std::strong_ordering' lvalue Var 0x629a4c50 'less' 'const 
strong_ordering':'const class std::strong_ordering'
  `-DeclRefExpr 0x629f3ae8 'const strong_ordering':'const class 
std::strong_ordering' lvalue Var 0x629a5388 'greater' 'const 
strong_ordering':'const class std::strong_ordering'




Comment at: clang/test/CoverageMapping/invalid_location.cpp:31
+//now because 'T{}' doesn't have a valid end location for now.
+// CHECK-NETX:   File 0, 13:9 -> 13:14 = #3
+// CHECK-NETX:   File 0, 13:18 -> 13:23 = (#0 - #3)

hans wr

[PATCH] D147073: [Coverage] Handle invalid end location of an expression/statement.

2023-04-03 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 510514.
zequanwu added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147073

Files:
  clang/lib/CodeGen/CoverageMappingGen.cpp
  clang/test/CoverageMapping/invalid_location.cpp

Index: clang/test/CoverageMapping/invalid_location.cpp
===
--- /dev/null
+++ clang/test/CoverageMapping/invalid_location.cpp
@@ -0,0 +1,92 @@
+// RUN: %clang_cc1 -mllvm -emptyline-comment-coverage=false -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -std=c++20 -stdlib=libc++ -triple %itanium_abi_triple %s | FileCheck %s
+
+namespace std { template  class initializer_list {}; }
+
+template  struct T {
+  T(std::initializer_list, int = int());
+  bool b;
+};
+
+template  struct S1 {
+  static void foo() {
+class C;
+0 ? T{} : T{};
+0 ? 1 : 2;
+  }
+};
+
+void bar() {
+  S1::foo();
+}
+
+
+// CHECK:  _ZN2S1IiE3fooEv:
+// CHECK-NEXT:   File 0, 11:21 -> 15:4 = #0
+// CHECK-NEXT:   File 0, 13:5 -> 13:6 = #0
+// CHECK-NEXT:   Branch,File 0, 13:5 -> 13:6 = 0, 0
+// CHECK-NEXT:   Gap,File 0, 13:8 -> 13:9 = #1
+// FIXME: It's supposed to have two different counters for true and false
+//branches at line 13 as it has for line 14, shown below. It's missing
+//now because 'T{}' doesn't have a valid end location for now.
+//Once it's fixed, correct the following two "CHECK-NETX" and #3 and #2
+//may need to swap positions.
+// CHECK-NETX:   File 0, 13:9 -> 13:14 = #3
+// CHECK-NETX:   File 0, 13:18 -> 13:23 = (#0 - #3)
+
+// CHECK-NEXT:   File 0, 14:5 -> 14:6 = #0
+// CHECK-NEXT:   Branch,File 0, 14:5 -> 14:6 = 0, 0
+// CHECK-NEXT:   Gap,File 0, 14:8 -> 14:9 = #2
+// CHECK-NEXT:   File 0, 14:9 -> 14:10 = #2
+// CHECK-NEXT:   File 0, 14:13 -> 14:14 = (#0 - #2)
+
+// No crash for following example.
+// See https://github.com/llvm/llvm-project/issues/45481
+namespace std {
+class strong_ordering;
+
+// Mock how STD defined unspecified parameters for the operators below.
+struct _CmpUnspecifiedParam {
+  consteval
+  _CmpUnspecifiedParam(int _CmpUnspecifiedParam::*) noexcept {}
+};
+
+struct strong_ordering {
+  signed char value;
+
+  friend constexpr bool operator==(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value == 0;
+  }
+  friend constexpr bool operator<(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value < 0;
+  }
+  friend constexpr bool operator>(strong_ordering v,
+  _CmpUnspecifiedParam) noexcept {
+return v.value > 0;
+  }
+  friend constexpr bool operator>=(strong_ordering v,
+   _CmpUnspecifiedParam) noexcept {
+return v.value >= 0;
+  }
+  static const strong_ordering equal, greater, less;
+};
+constexpr strong_ordering strong_ordering::equal = {0};
+constexpr strong_ordering strong_ordering::greater = {1};
+constexpr strong_ordering strong_ordering::less = {-1};
+} // namespace std
+
+struct S {
+friend bool operator<(const S&, const S&);
+friend bool operator==(const S&, const S&);
+};
+
+struct MyStruct {
+friend bool operator==(MyStruct const& lhs, MyStruct const& rhs) = delete;
+friend std::strong_ordering operator<=>(MyStruct const& lhs, MyStruct const& rhs) = default;
+S value;
+};
+
+void foo(MyStruct bar){
+(void)(bar <=> bar);
+}
Index: clang/lib/CodeGen/CoverageMappingGen.cpp
===
--- clang/lib/CodeGen/CoverageMappingGen.cpp
+++ clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -602,6 +602,13 @@
   MostRecentLocation = *StartLoc;
 }
 
+// If either location is invalid, set it to std::nullopt to avoid
+// letting users of RegionStack think that region has a valid start/end
+// location.
+if (StartLoc && StartLoc->isInvalid())
+  StartLoc = std::nullopt;
+if (EndLoc && EndLoc->isInvalid())
+  EndLoc = std::nullopt;
 RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc);
 
 return RegionStack.size() - 1;
@@ -624,7 +631,8 @@
 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
 while (RegionStack.size() > ParentIndex) {
   SourceMappingRegion &Region = RegionStack.back();
-  if (Region.hasStartLoc()) {
+  if (Region.hasStartLoc() &&
+  (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
 SourceLocation StartLoc = Region.getBeginLoc();
 SourceLocation EndLoc = Region.hasEndLoc()
 ? Region.getEndLoc()
@@ -691,7 +699,7 @@
 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
 assert(SpellingRegion(SM, Region).isInSourceOrder());
 SourceRegions.push_back(Region);
-}
+   

[PATCH] D147449: [include-cleaner] Only ignore builtins without a header

2023-04-03 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: hokein.
Herald added a project: All.
kadircet requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Certain standard library functions (e.g. std::move) are also implemented
as builtins. This patch moves filtering logic to the symbol->header
mapping phase to rather generate these references without any providers
only when we don't have a mapping.
That way we can also map them to header names mentioned in the builtin
mappings.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147449

Files:
  clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
  clang-tools-extra/include-cleaner/lib/WalkAST.cpp
  clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -327,11 +327,5 @@
   testWalk("enum class E : int {};", "enum class ^E : int ;");
 }
 
-TEST(WalkAST, BuiltinSymbols) {
-  testWalk(R"cpp(
-extern "C" int __builtin_popcount(unsigned int) noexcept;
-  )cpp", "int x = ^__builtin_popcount(1);");
-}
-
 } // namespace
 } // namespace clang::include_cleaner
Index: clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/AnalysisTest.cpp
@@ -93,12 +93,14 @@
   void $bar^bar($private^Private $p^p) {
 $foo^foo();
 std::$vector^vector $vconstructor^$v^v;
+$builtin^__builtin_popcount(1);
+std::$move^move(3);
   }
   )cpp");
   Inputs.Code = Code.code();
   Inputs.ExtraFiles["header.h"] = guard(R"cpp(
   void foo();
-  namespace std { class vector {}; }
+  namespace std { class vector {}; int&& move(int&&); }
   )cpp");
   Inputs.ExtraFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "path/public.h"
@@ -112,6 +114,7 @@
   auto PublicFile = Header("\"path/public.h\"");
   auto MainFile = Header(SM.getFileEntryForID(SM.getMainFileID()));
   auto VectorSTL = Header(*tooling::stdlib::Header::named(""));
+  auto UtilitySTL = Header(*tooling::stdlib::Header::named(""));
   EXPECT_THAT(
   offsetToProviders(AST, SM),
   UnorderedElementsAre(
@@ -122,8 +125,9 @@
   Pair(Code.point("foo"), UnorderedElementsAre(HeaderFile)),
   Pair(Code.point("vector"), UnorderedElementsAre(VectorSTL)),
   Pair(Code.point("vconstructor"), UnorderedElementsAre(VectorSTL)),
-  Pair(Code.point("v"), UnorderedElementsAre(MainFile))
-  ));
+  Pair(Code.point("v"), UnorderedElementsAre(MainFile)),
+  Pair(Code.point("builtin"), testing::IsEmpty()),
+  Pair(Code.point("move"), UnorderedElementsAre(UtilitySTL;
 }
 
 TEST_F(WalkUsedTest, MultipleProviders) {
Index: clang-tools-extra/include-cleaner/lib/WalkAST.cpp
===
--- clang-tools-extra/include-cleaner/lib/WalkAST.cpp
+++ clang-tools-extra/include-cleaner/lib/WalkAST.cpp
@@ -35,9 +35,6 @@
   RefType RT = RefType::Explicit) {
 if (!ND || Loc.isInvalid())
   return;
-// Don't report builtin symbols.
-if (const auto *II = ND->getIdentifier(); II && II->getBuiltinID() > 0)
-  return;
 Callback(Loc, *cast(ND->getCanonicalDecl()), RT);
   }
 
Index: clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
===
--- clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
+++ clang-tools-extra/include-cleaner/lib/FindHeaders.cpp
@@ -10,18 +10,21 @@
 #include "TypesInternal.h"
 #include "clang-include-cleaner/Record.h"
 #include "clang-include-cleaner/Types.h"
+#include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclBase.h"
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Tooling/Inclusions/StandardLibrary.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
-#include 
+#include 
 #include 
 
 namespace clang::include_cleaner {
@@ -106,37 +109,68 @@
   return Results;
 }
 
-// Special-case the ambiguous standard library symbols (e.g. std::move) which
-// are not supported by the tooling stdlib lib.
-llvm::SmallVector>
-headersForSpecialSymbol(const Symbol &S, const SourceManager &SM,
-const PragmaIncludes *PI) {
-  if (S.kind() != Symbol::Declaration || !S.declarat

[PATCH] D147349: [C2x] Implement support for empty brace initialization (WG14 N2900 and WG14 N3011)

2023-04-03 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

So not necessary to this patch, but I suspect the non-trivially constructible 
types could just be solved the same way we do for zero-init of these types in 
fixed-size arrays, right?  Its a bit more complicated, but the IR is probably 
just as do-able: https://godbolt.org/z/Gqf65xr8M
There, in the in it of %6 is the only place the length matters, since it looks 
like we do a 'begin/end' type emit for it.  %2 is kept as the 'current element 
being processed', and %6 is the 'end', and %5 is the 'begin'.

That said, only a few small comments/questions.




Comment at: clang/lib/CodeGen/CGExprAgg.cpp:1670
+// in C++, we can safely memset the array memory to zero.
+CGF.EmitNullInitialization(Dest.getAddress(), ExprToVisit->getType());
+return;

I'd probably prefer an assert for 'initializer is empty' here to confirm this, 
but else this seems fine.



Comment at: clang/test/C/C2x/n2900_n3011_2.c:41
+void test_zero_size_array() {
+  int unknown_size[] = {};
+  // CHECK: define {{.*}} void @test_zero_size_array

This is strange... why is this not an error?  What is this supposed to mean?



Comment at: clang/test/C/C2x/n2900_n3011_2.c:55
+  // CHECK-NEXT: store i32 12, ptr %[[I]]
+  // CHECK-NEXT: %[[MEM0:.+]] = load i32, ptr %[[I]]
+  // CHECK-NEXT: %[[MEM1:.+]] = zext i32 %[[MEM0]] to i64

These MEM# names are horrible to read :/  But the test is doing the right thing 
it appears.



Comment at: clang/test/C/C2x/n2900_n3011_2.c:96
+void test_nested_structs() {
+  struct T t1 = { 1, {} };
+  struct T t2 = { 1, { 2, {} } };

A VLA of these things still works right?  Is that worth a test?


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

https://reviews.llvm.org/D147349

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


[PATCH] D147395: [Clangd] Make the type hint length limit configurable

2023-04-03 Thread Yi Zhang via Phabricator via cfe-commits
zhangyi1357 updated this revision to Diff 510521.
zhangyi1357 marked an inline comment as not done.
zhangyi1357 added a comment.

Try to fix the build problem.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147395

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/InlayHints.cpp


Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -688,7 +688,8 @@
   return;
 
 std::string TypeName = T.getAsString(Policy);
-if (TypeName.length() < TypeNameLimit)
+if (Cfg.InlayHints.TypeNameLimit == 0 ||
+TypeName.length() < Cfg.InlayHints.TypeNameLimit)
   addInlayHint(R, HintSide::Right, InlayHintKind::Type, Prefix, TypeName,
/*Suffix=*/"");
   }
@@ -714,8 +715,6 @@
   // the policies are initialized for more details.)
   PrintingPolicy TypeHintPolicy;
   PrintingPolicy StructuredBindingPolicy;
-
-  static const size_t TypeNameLimit = 32;
 };
 
 } // namespace
Index: clang-tools-extra/clangd/ConfigYAML.cpp
===
--- clang-tools-extra/clangd/ConfigYAML.cpp
+++ clang-tools-extra/clangd/ConfigYAML.cpp
@@ -254,6 +254,10 @@
   if (auto Value = boolValue(N, "Designators"))
 F.Designators = *Value;
 });
+Dict.handle("TypeNameLimit", [&](Node &N) {
+  if (auto Value = uint32Value(N, "TypeNameLimit"))
+F.TypeNameLimit = *Value;
+});
 Dict.parse(N);
   }
 
@@ -375,6 +379,17 @@
 return std::nullopt;
   }
 
+  std::optional> uint32Value(Node &N, llvm::StringRef Desc) {
+if (auto Scalar = scalarValue(N, Desc)) {
+  unsigned long long Num;
+  if (!llvm::getAsUnsignedInteger(**Scalar, 0, Num)) {
+return Located(Num, Scalar->Range);
+  }
+}
+warning(Desc + " invalid number", N);
+return std::nullopt;
+  }
+
   // Try to parse a list of single scalar values, or just a single value.
   std::optional>> scalarValues(Node &N) {
 std::vector> Result;
Index: clang-tools-extra/clangd/ConfigFragment.h
===
--- clang-tools-extra/clangd/ConfigFragment.h
+++ clang-tools-extra/clangd/ConfigFragment.h
@@ -322,6 +322,8 @@
 std::optional> DeducedTypes;
 /// Show designators in aggregate initialization.
 std::optional> Designators;
+/// Limit the length of type name hints. (0 means no limit)
+std::optional> TypeNameLimit;
   };
   InlayHintsBlock InlayHints;
 };
Index: clang-tools-extra/clangd/ConfigCompile.cpp
===
--- clang-tools-extra/clangd/ConfigCompile.cpp
+++ clang-tools-extra/clangd/ConfigCompile.cpp
@@ -611,6 +611,11 @@
   Out.Apply.push_back([Value(**F.Designators)](const Params &, Config &C) {
 C.InlayHints.Designators = Value;
   });
+if (F.TypeNameLimit)
+  Out.Apply.push_back(
+  [Value(**F.TypeNameLimit)](const Params &, Config &C) {
+C.InlayHints.TypeNameLimit = Value;
+  });
   }
 
   constexpr static llvm::SourceMgr::DiagKind Error = llvm::SourceMgr::DK_Error;
Index: clang-tools-extra/clangd/Config.h
===
--- clang-tools-extra/clangd/Config.h
+++ clang-tools-extra/clangd/Config.h
@@ -147,6 +147,8 @@
 bool Parameters = true;
 bool DeducedTypes = true;
 bool Designators = true;
+// Limit the length of type names in inlay hints. (0 means no limit)
+uint32_t TypeNameLimit = 32;
   } InlayHints;
 };
 


Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -688,7 +688,8 @@
   return;
 
 std::string TypeName = T.getAsString(Policy);
-if (TypeName.length() < TypeNameLimit)
+if (Cfg.InlayHints.TypeNameLimit == 0 ||
+TypeName.length() < Cfg.InlayHints.TypeNameLimit)
   addInlayHint(R, HintSide::Right, InlayHintKind::Type, Prefix, TypeName,
/*Suffix=*/"");
   }
@@ -714,8 +715,6 @@
   // the policies are initialized for more details.)
   PrintingPolicy TypeHintPolicy;
   PrintingPolicy StructuredBindingPolicy;
-
-  static const size_t TypeNameLimit = 32;
 };
 
 } // namespace
Index: clang-tools-extra/clangd/ConfigYAML.cpp
===
--- clang-tools-extra/clangd/ConfigYAML.cpp
+++ clang-tools-extra/clangd/ConfigYAML.cpp
@@ -254,6 +254,10 @@
   if (auto Value = boolValue(N, "Designators"))
 F.Designators = *Value;
 });
+Dict.h

[PATCH] D147395: [Clangd] Make the type hint length limit configurable

2023-04-03 Thread Yi Zhang via Phabricator via cfe-commits
zhangyi1357 added a comment.

In D147395#4240227 , @hokein wrote:

> Thanks for the contribution!

It's quite interesting for me. Thanks for your time reviewing and your great 
advice!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147395

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


[PATCH] D147307: [clang] Consider artificial always inline builtin as inline builtins

2023-04-03 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

I'd be fine with just dropping the check for GNUInline.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147307

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


[PATCH] D147419: [clang-tidy] ignore NRVO const variables in performance-no-automatic-move.

2023-04-03 Thread Logan Gnanapragasam via Phabricator via cfe-commits
gnanabit updated this revision to Diff 510532.
gnanabit added a comment.

Add release notes entry.

Thanks for the reviews! Happy to reword the release notes if they are unclear.

@courbet or @PiotrZSL, I don't have commit access. Can you land this patch for
me? Please use "Logan Gnanapragasam (gnana...@google.com)" to commit the change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147419

Files:
  clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp
@@ -33,10 +33,15 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
 }
 
-Obj PositiveSelfConstValue() {
-  const Obj obj = Make();
-  return obj;
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
+Obj PositiveCantNrvo(bool b) {
+  const Obj obj1;
+  const Obj obj2;
+  if (b) {
+return obj1;
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: constness of 'obj1' prevents automatic move [performance-no-automatic-move]
+  }
+  return obj2;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj2' prevents automatic move [performance-no-automatic-move]
 }
 
 // FIXME: Ideally we would warn here too.
@@ -54,18 +59,32 @@
 // Negatives.
 
 StatusOr Temporary() {
-  return Make();
+  return Make();
 }
 
 StatusOr ConstTemporary() {
   return Make();
 }
 
-StatusOr Nrvo() {
+StatusOr ConvertingMoveConstructor() {
   Obj obj = Make();
   return obj;
 }
 
+Obj ConstNrvo() {
+  const Obj obj = Make();
+  return obj;
+}
+
+Obj NotNrvo(bool b) {
+  Obj obj1;
+  Obj obj2;
+  if (b) {
+return obj1;
+  }
+  return obj2;
+}
+
 StatusOr Ref() {
   Obj &obj = Make();
   return obj;
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -271,6 +271,10 @@
   ` when using
   ``DISABLED_`` in the test suite name.
 
+- Fixed a false positive in :doc:`performance-no-automatic-move
+  ` when warning would be
+  emitted for a const local variable to which NRVO is applied.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
@@ -16,6 +16,12 @@
 
 namespace clang::tidy::performance {
 
+namespace {
+
+AST_MATCHER(VarDecl, isNRVOVariable) { return Node.isNRVOVariable(); }
+
+} // namespace
+
 NoAutomaticMoveCheck::NoAutomaticMoveCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -23,8 +29,9 @@
   utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
 
 void NoAutomaticMoveCheck::registerMatchers(MatchFinder *Finder) {
-  const auto ConstLocalVariable =
+  const auto NonNrvoConstLocalVariable =
   varDecl(hasLocalStorage(), unless(hasType(lValueReferenceType())),
+  unless(isNRVOVariable()),
   hasType(qualType(
   isConstQualified(),
   hasCanonicalType(matchers::isExpensiveToCopy()),
@@ -48,7 +55,7 @@
cxxConstructExpr(
hasDeclaration(LValueRefCtor),
hasArgument(0, ignoringParenImpCasts(declRefExpr(
-  to(ConstLocalVariable)
+  to(NonNrvoConstLocalVariable)
.bind("ctor_call")),
   this);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D145088: [RISCV] Add attribute(riscv_rvv_vector_bits(N)) based on AArch64 arm_sve_vector_bits.

2023-04-03 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: clang/lib/Sema/SemaType.cpp:8234
+ ParsedAttr &Attr, Sema &S) {
+  // Target must have SVE.
+  if (!S.Context.getTargetInfo().hasFeature("zve32x")) {

I need to fix this comment.



Comment at: clang/lib/Sema/SemaType.cpp:8265
+  // The attribute vector size must match -mrvv-vector-bits.
+  // FIXME: LMUL from type and scale it.
+  if (VecSize != VScale->first * llvm::RISCV::RVVBitsPerBlock) {

aaron.ballman wrote:
> Should this be done as part of this patch (are we accepting code we shouldn't 
> be accepting)?
No. I need to phrase this FIXME better. I'm only accepting types that have 
LMUL=1. (length multiplier). This is enforced in `Type::isRVVVLSBuiltinType()` 
where there's another FIXME about LMUL=1.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D145088

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


[PATCH] D147411: [clang-tidy] Fix readability-static-accessed-through-instance check for anonymous structs

2023-04-03 Thread André Schackier via Phabricator via cfe-commits
AMS21 updated this revision to Diff 510537.
AMS21 marked 2 inline comments as done.
AMS21 added a comment.

Implement suggested way of checking for anonymous structs
Add a new more tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147411

Files:
  
clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability/static-accessed-through-instance.cpp
@@ -285,3 +285,60 @@
 // CHECK-MESSAGES-NOT: :[[@LINE-1]]:10: warning: static member
 
 } // namespace Bugzilla_48758
+
+// https://github.com/llvm/llvm-project/issues/61736
+namespace llvm_issue_61736
+{
+
+struct {
+  static void f() {}
+} AnonStruct, *AnonStructPointer;
+
+class {
+  public:
+  static void f() {}
+} AnonClass, *AnonClassPointer;
+
+void testAnonymousStructAndClass() {
+  AnonStruct.f();
+  AnonStructPointer->f();
+
+  AnonClass.f();
+  AnonClassPointer->f();
+}
+
+struct Embedded {
+  struct {
+static void f() {}
+  } static EmbeddedStruct, *EmbeddedStructPointer;
+
+  class {
+public:
+  static void f() {}
+  } static EmbeddedClass, *EmbeddedClassPointer;
+};
+
+void testEmbeddedAnonymousStructAndClass() {
+  Embedded::EmbeddedStruct.f();
+  Embedded::EmbeddedStructPointer->f();
+
+  Embedded::EmbeddedClass.f();
+  Embedded::EmbeddedClassPointer->f();
+
+  Embedded E;
+  E.EmbeddedStruct.f();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member accessed through instance [readability-static-accessed-through-instance]
+  // CHECK-FIXES: {{^}}  llvm_issue_61736::Embedded::EmbeddedStruct.f();{{$}}
+  E.EmbeddedStructPointer->f();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member accessed through instance [readability-static-accessed-through-instance]
+  // CHECK-FIXES: {{^}}  llvm_issue_61736::Embedded::EmbeddedStructPointer->f();{{$}}
+
+  E.EmbeddedClass.f();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member accessed through instance [readability-static-accessed-through-instance]
+  // CHECK-FIXES: {{^}}  llvm_issue_61736::Embedded::EmbeddedClass.f();{{$}}
+  E.EmbeddedClassPointer->f();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member accessed through instance [readability-static-accessed-through-instance]
+  // CHECK-FIXES: {{^}}  llvm_issue_61736::Embedded::EmbeddedClassPointer->f();{{$}}
+}
+
+} // namespace llvm_issue_61736
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -267,6 +267,10 @@
   string for ``Prefix`` or ``Suffix`` options could result in the style not
   being used.
 
+- Fixed an issue in :doc:`readability-static-accessed-through-instance
+  ` when using
+  anonymous structs or classes.
+
 - Fixed an issue in :doc:`google-readability-avoid-underscore-in-googletest-name
   ` when using
   ``DISABLED_`` in the test suite name.
Index: clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
@@ -58,7 +58,7 @@
   if (isa(BaseExpr))
 return;
 
-  QualType BaseType =
+  const QualType BaseType =
   BaseExpr->getType()->isPointerType()
   ? BaseExpr->getType()->getPointeeType().getUnqualifiedType()
   : BaseExpr->getType().getUnqualifiedType();
@@ -74,6 +74,11 @@
   std::string BaseTypeName =
   BaseType.getAsString(PrintingPolicyWithSupressedTag);
 
+  // Ignore anonymous structs/classes which will not have an identifier
+  const RecordDecl *RecDecl = BaseType->getAsCXXRecordDecl();
+  if (!RecDecl || RecDecl->getIdentifier() == nullptr)
+return;
+
   // Do not warn for CUDA built-in variables.
   if (StringRef(BaseTypeName).startswith("__cuda_builtin_"))
 return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147414: [python] Expose clang_Location_isInSystemHeader

2023-04-03 Thread Artur Ryt via Phabricator via cfe-commits
R2RT updated this revision to Diff 510542.
R2RT added a comment.

Bring back Python section in release notes and document new 
`is_in_system_header` property.


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

https://reviews.llvm.org/D147414

Files:
  clang/bindings/python/clang/cindex.py
  clang/bindings/python/tests/cindex/test_location.py
  clang/docs/ReleaseNotes.rst


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -436,6 +436,13 @@
 Sanitizers
 --
 
+Python Binding Changes
+--
+
+The following methods have been added:
+
+- `clang_Location_isInSystemHeader` exposed via `is_in_system_header` property
+  of `Location` class.
 
 Additional Information
 ==
Index: clang/bindings/python/tests/cindex/test_location.py
===
--- clang/bindings/python/tests/cindex/test_location.py
+++ clang/bindings/python/tests/cindex/test_location.py
@@ -7,6 +7,7 @@
 from clang.cindex import File
 from clang.cindex import SourceLocation
 from clang.cindex import SourceRange
+from clang.cindex import TranslationUnit
 from .util import get_cursor
 from .util import get_tu
 
@@ -103,3 +104,17 @@
 location3 = SourceLocation.from_position(tu, file, 1, 6)
 range3 = SourceRange.from_locations(location1, location3)
 self.assertNotEqual(range1, range3)
+
+def test_is_system_location(self):
+header = os.path.normpath('./fake/fake.h')
+tu = TranslationUnit.from_source('fake.c', 
[f'-isystem{os.path.dirname(header)}'], unsaved_files = [
+('fake.c', """
+#include 
+int one;
+"""),
+(header, "int two();")
+])
+one = get_cursor(tu, 'one')
+two = get_cursor(tu, 'two')
+self.assertFalse(one.location.is_in_system_header)
+self.assertTrue(two.location.is_in_system_header)
Index: clang/bindings/python/clang/cindex.py
===
--- clang/bindings/python/clang/cindex.py
+++ clang/bindings/python/clang/cindex.py
@@ -286,6 +286,11 @@
 """Get the file offset represented by this source location."""
 return self._get_instantiation()[3]
 
+@property
+def is_in_system_header(self):
+"""Returns true if the given source location is in a system header."""
+return conf.lib.clang_Location_isInSystemHeader(self)
+
 def __eq__(self, other):
 return conf.lib.clang_equalLocations(self, other)
 
@@ -4131,6 +4136,10 @@
[Cursor],
c_longlong),
 
+  ("clang_Location_isInSystemHeader",
+   [SourceLocation],
+   bool),
+
   ("clang_Type_getAlignOf",
[Type],
c_longlong),


Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -436,6 +436,13 @@
 Sanitizers
 --
 
+Python Binding Changes
+--
+
+The following methods have been added:
+
+- `clang_Location_isInSystemHeader` exposed via `is_in_system_header` property
+  of `Location` class.
 
 Additional Information
 ==
Index: clang/bindings/python/tests/cindex/test_location.py
===
--- clang/bindings/python/tests/cindex/test_location.py
+++ clang/bindings/python/tests/cindex/test_location.py
@@ -7,6 +7,7 @@
 from clang.cindex import File
 from clang.cindex import SourceLocation
 from clang.cindex import SourceRange
+from clang.cindex import TranslationUnit
 from .util import get_cursor
 from .util import get_tu
 
@@ -103,3 +104,17 @@
 location3 = SourceLocation.from_position(tu, file, 1, 6)
 range3 = SourceRange.from_locations(location1, location3)
 self.assertNotEqual(range1, range3)
+
+def test_is_system_location(self):
+header = os.path.normpath('./fake/fake.h')
+tu = TranslationUnit.from_source('fake.c', [f'-isystem{os.path.dirname(header)}'], unsaved_files = [
+('fake.c', """
+#include 
+int one;
+"""),
+(header, "int two();")
+])
+one = get_cursor(tu, 'one')
+two = get_cursor(tu, 'two')
+self.assertFalse(one.location.is_in_system_header)
+self.assertTrue(two.location.is_in_system_header)
Index: clang/bindings/python/clang/cindex.py
===
--- clang/bindings/python/clang/cindex.py
+++ clang/bindings/python/clang/cindex.py
@@ -286,6 +286,11 @@
 """Get the file offset represented by this source location."""
 return self._get_instantiation()[3]
 
+@property
+def is_in_system_header(self):
+"""Returns true if the given source location is in a system header."""
+return conf.lib.clang_Location

[clang-tools-extra] e51f467 - [clang-tidy] ignore NRVO const variables in performance-no-automatic-move.

2023-04-03 Thread Piotr Zegar via cfe-commits

Author: Logan Gnanapragasam
Date: 2023-04-03T17:01:59Z
New Revision: e51f46705e2876fbbdb59d4f1ba43fa6ecf78611

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

LOG: [clang-tidy] ignore NRVO const variables in performance-no-automatic-move.

In the following code:

```cc
struct Obj {
  Obj();
  Obj(const Obj &);
  Obj(Obj &&);
  virtual ~Obj();
};

Obj ConstNrvo() {
  const Obj obj;
  return obj;
}
```

performance-no-automatic-move warns about the constness of `obj`. However, NRVO
is applied to `obj`, so the `const` should have no effect on performance.

This change modifies the matcher to exclude NRVO variables.

#clang-tidy

Reviewed By: courbet, PiotrZSL

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
index b9c411e26699..42bf8ff83186 100644
--- a/clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
@@ -16,6 +16,12 @@ using namespace clang::ast_matchers;
 
 namespace clang::tidy::performance {
 
+namespace {
+
+AST_MATCHER(VarDecl, isNRVOVariable) { return Node.isNRVOVariable(); }
+
+} // namespace
+
 NoAutomaticMoveCheck::NoAutomaticMoveCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -23,8 +29,9 @@ NoAutomaticMoveCheck::NoAutomaticMoveCheck(StringRef Name,
   utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
 
 void NoAutomaticMoveCheck::registerMatchers(MatchFinder *Finder) {
-  const auto ConstLocalVariable =
+  const auto NonNrvoConstLocalVariable =
   varDecl(hasLocalStorage(), unless(hasType(lValueReferenceType())),
+  unless(isNRVOVariable()),
   hasType(qualType(
   isConstQualified(),
   hasCanonicalType(matchers::isExpensiveToCopy()),
@@ -48,7 +55,7 @@ void NoAutomaticMoveCheck::registerMatchers(MatchFinder 
*Finder) {
cxxConstructExpr(
hasDeclaration(LValueRefCtor),
hasArgument(0, ignoringParenImpCasts(declRefExpr(
-  to(ConstLocalVariable)
+  to(NonNrvoConstLocalVariable)
.bind("ctor_call")),
   this);
 }

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 8a82e4e5ca56..13a06efcf563 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -275,6 +275,10 @@ Changes in existing checks
   ` 
when using
   ``DISABLED_`` in the test suite name.
 
+- Fixed a false positive in :doc:`performance-no-automatic-move
+  ` when warning would be
+  emitted for a const local variable to which NRVO is applied.
+
 Removed checks
 ^^
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp
index 6ca59b6bb902..d365f7de8b7c 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp
@@ -33,10 +33,15 @@ NonTemplate PositiveNonTemplateConstValue() {
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents 
automatic move [performance-no-automatic-move]
 }
 
-Obj PositiveSelfConstValue() {
-  const Obj obj = Make();
-  return obj;
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents 
automatic move [performance-no-automatic-move]
+Obj PositiveCantNrvo(bool b) {
+  const Obj obj1;
+  const Obj obj2;
+  if (b) {
+return obj1;
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: constness of 'obj1' prevents 
automatic move [performance-no-automatic-move]
+  }
+  return obj2;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj2' prevents 
automatic move [performance-no-automatic-move]
 }
 
 // FIXME: Ideally we would warn here too.
@@ -54,18 +59,32 @@ StatusOr PositiveStatusOrLifetimeExtension() {
 // Negatives.
 
 StatusOr Temporary() {
-  return Make();
+  return Make();
 }
 
 StatusOr ConstTemporary() {
   return Make();
 }
 
-StatusOr Nrvo() {
+StatusOr ConvertingMoveConstructor() {
   Obj obj = Make();
   return obj;
 }
 
+Obj ConstNrvo() {
+  const Obj o

[PATCH] D147419: [clang-tidy] ignore NRVO const variables in performance-no-automatic-move.

2023-04-03 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe51f46705e28: [clang-tidy] ignore NRVO const variables in 
performance-no-automatic-move. (authored by gnanabit, committed by PiotrZSL).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147419

Files:
  clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance/no-automatic-move.cpp
@@ -33,10 +33,15 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
 }
 
-Obj PositiveSelfConstValue() {
-  const Obj obj = Make();
-  return obj;
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
+Obj PositiveCantNrvo(bool b) {
+  const Obj obj1;
+  const Obj obj2;
+  if (b) {
+return obj1;
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: constness of 'obj1' prevents automatic move [performance-no-automatic-move]
+  }
+  return obj2;
+  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj2' prevents automatic move [performance-no-automatic-move]
 }
 
 // FIXME: Ideally we would warn here too.
@@ -54,18 +59,32 @@
 // Negatives.
 
 StatusOr Temporary() {
-  return Make();
+  return Make();
 }
 
 StatusOr ConstTemporary() {
   return Make();
 }
 
-StatusOr Nrvo() {
+StatusOr ConvertingMoveConstructor() {
   Obj obj = Make();
   return obj;
 }
 
+Obj ConstNrvo() {
+  const Obj obj = Make();
+  return obj;
+}
+
+Obj NotNrvo(bool b) {
+  Obj obj1;
+  Obj obj2;
+  if (b) {
+return obj1;
+  }
+  return obj2;
+}
+
 StatusOr Ref() {
   Obj &obj = Make();
   return obj;
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -275,6 +275,10 @@
   ` when using
   ``DISABLED_`` in the test suite name.
 
+- Fixed a false positive in :doc:`performance-no-automatic-move
+  ` when warning would be
+  emitted for a const local variable to which NRVO is applied.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
===
--- clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
+++ clang-tools-extra/clang-tidy/performance/NoAutomaticMoveCheck.cpp
@@ -16,6 +16,12 @@
 
 namespace clang::tidy::performance {
 
+namespace {
+
+AST_MATCHER(VarDecl, isNRVOVariable) { return Node.isNRVOVariable(); }
+
+} // namespace
+
 NoAutomaticMoveCheck::NoAutomaticMoveCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -23,8 +29,9 @@
   utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
 
 void NoAutomaticMoveCheck::registerMatchers(MatchFinder *Finder) {
-  const auto ConstLocalVariable =
+  const auto NonNrvoConstLocalVariable =
   varDecl(hasLocalStorage(), unless(hasType(lValueReferenceType())),
+  unless(isNRVOVariable()),
   hasType(qualType(
   isConstQualified(),
   hasCanonicalType(matchers::isExpensiveToCopy()),
@@ -48,7 +55,7 @@
cxxConstructExpr(
hasDeclaration(LValueRefCtor),
hasArgument(0, ignoringParenImpCasts(declRefExpr(
-  to(ConstLocalVariable)
+  to(NonNrvoConstLocalVariable)
.bind("ctor_call")),
   this);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D146973: [Clang] Implicitly include LLVM libc headers for the GPU

2023-04-03 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:1196-1197
 
+  // If we are compiling for a GPU target we want to override the system 
headers
+  // with ones created by the 'libc' project if present.
+  if (!Args.hasArg(options::OPT_nostdinc) &&

Please add a TODO with some details outlining what it's supposed to do, the 
issues we've discussed, and that this is intended to be a temporary solution 
(famous last words, I know).




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146973

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


[PATCH] D146973: [Clang] Implicitly include LLVM libc headers for the GPU

2023-04-03 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:1196-1197
 
+  // If we are compiling for a GPU target we want to override the system 
headers
+  // with ones created by the 'libc' project if present.
+  if (!Args.hasArg(options::OPT_nostdinc) &&

tra wrote:
> Please add a TODO with some details outlining what it's supposed to do, the 
> issues we've discussed, and that this is intended to be a temporary solution 
> (famous last words, I know).
> 
> 
I'm not sure if we should consider this temporary, we simply need to ensure 
that the headers in this directory are compatible with the host environment 
somehow.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146973

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


[PATCH] D147414: [python] Expose clang_Location_isInSystemHeader

2023-04-03 Thread Artur Ryt via Phabricator via cfe-commits
R2RT added a comment.

In D147414#4240343 , @aaron.ballman 
wrote:

> LGTM! Do you need someone to land this on your behalf? If so, please let me 
> know what name and email address you would like for patch attribution.
>
> In D147414#4239453 , @R2RT wrote:
>
>> I thought about adding it into release notes, but recently Python section 
>> has got removed from ReleaseNotes.rst, so I am not sure what to do now: 
>> https://reviews.llvm.org/D142578
>
> The section was removed mostly because the python bindings weren't getting a 
> lot of updates. I think this deserves a release note, so let's add the python 
> bindings section back in and put a note under it for this.

I've brought back Python section with relevant note.

I have no idea how to land it, it is my first contribution here, so maybe it 
will be easier this way.
Please attribute it to Artur Ryt , thanks :)


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

https://reviews.llvm.org/D147414

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


[PATCH] D147411: [clang-tidy] Fix readability-static-accessed-through-instance check for anonymous structs

2023-04-03 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL accepted this revision.
PiotrZSL added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147411

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


[PATCH] D147349: [C2x] Implement support for empty brace initialization (WG14 N2900 and WG14 N3011)

2023-04-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked 4 inline comments as done.
aaron.ballman added a comment.

In D147349#4240847 , @erichkeane 
wrote:

> So not necessary to this patch, but I suspect the non-trivially constructible 
> types could just be solved the same way we do for zero-init of these types in 
> fixed-size arrays, right?  Its a bit more complicated, but the IR is probably 
> just as do-able: https://godbolt.org/z/Gqf65xr8M
> There, in the in it of %6 is the only place the length matters, since it 
> looks like we do a 'begin/end' type emit for it.  %2 is kept as the 'current 
> element being processed', and %6 is the 'end', and %5 is the 'begin'.
>
> That said, only a few small comments/questions.

It's possible, but I'm also not convinced extending C++'s already inscrutable 
initialization rules is a good idea, especially given that it relates to VLAs 
(which are already a bit questionable as an extension to C++ IMO).




Comment at: clang/lib/CodeGen/CGExprAgg.cpp:1670
+// in C++, we can safely memset the array memory to zero.
+CGF.EmitNullInitialization(Dest.getAddress(), ExprToVisit->getType());
+return;

erichkeane wrote:
> I'd probably prefer an assert for 'initializer is empty' here to confirm 
> this, but else this seems fine.
I can add that assert, sure.



Comment at: clang/test/C/C2x/n2900_n3011_2.c:41
+void test_zero_size_array() {
+  int unknown_size[] = {};
+  // CHECK: define {{.*}} void @test_zero_size_array

erichkeane wrote:
> This is strange... why is this not an error?  What is this supposed to mean?
Heh, this one took me a few minutes to convince myself is correct. This creates 
a zero-length array, which we support as an extension. There's a corresponding 
Sema test on n2900_n3011.c:18 that shows the behavior of the extension 
diagnostics in this case.



Comment at: clang/test/C/C2x/n2900_n3011_2.c:55
+  // CHECK-NEXT: store i32 12, ptr %[[I]]
+  // CHECK-NEXT: %[[MEM0:.+]] = load i32, ptr %[[I]]
+  // CHECK-NEXT: %[[MEM1:.+]] = zext i32 %[[MEM0]] to i64

erichkeane wrote:
> These MEM# names are horrible to read :/  But the test is doing the right 
> thing it appears.
If you have suggestions for better names, I'm happy to use them.



Comment at: clang/test/C/C2x/n2900_n3011_2.c:96
+void test_nested_structs() {
+  struct T t1 = { 1, {} };
+  struct T t2 = { 1, { 2, {} } };

erichkeane wrote:
> A VLA of these things still works right?  Is that worth a test?
I can add a test for that, sure.


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

https://reviews.llvm.org/D147349

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


[PATCH] D143704: [flang] Feature list plugin

2023-04-03 Thread Ethan Luis McDonough via Phabricator via cfe-commits
elmcdonough updated this revision to Diff 510553.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143704

Files:
  flang/examples/CMakeLists.txt
  flang/examples/FeatureList/CMakeLists.txt
  flang/examples/FeatureList/FeatureList.cpp
  flang/test/CMakeLists.txt
  flang/test/Examples/feature-list-class.f90
  flang/test/Examples/feature-list-functions.f90

Index: flang/test/Examples/feature-list-functions.f90
===
--- /dev/null
+++ flang/test/Examples/feature-list-functions.f90
@@ -0,0 +1,76 @@
+! UNSUPPORTED: system-windows
+! REQUIRES: plugins, shell, examples
+
+! RUN: %flang_fc1 -load %llvmshlibdir/flangFeatureList%pluginext \
+! RUN:-plugin feature-list %s 2>&1 | FileCheck %s
+
+program list_features_test
+implicit none
+call test_sub(test_func(2, 3), 4)
+contains
+subroutine test_sub(a, b)
+integer, intent(in) :: a, b
+print "(I0)", a + b
+end subroutine
+
+integer function test_func(a, b)
+integer, intent(in) :: a, b
+test_func = a * b
+end function
+end program list_features_test
+
+! CHECK: Name: 19
+! CHECK-NEXT: Expr: 11
+! CHECK-NEXT: DataRef: 5
+! CHECK-NEXT: Designator: 5
+! CHECK-NEXT: ActualArg: 4
+! CHECK-NEXT: ActualArgSpec: 4
+! CHECK-NEXT: EntityDecl: 4
+! CHECK-NEXT: LiteralConstant: 4
+! CHECK-NEXT: ActionStmt: 3
+! CHECK-NEXT: Block: 3
+! CHECK-NEXT: DeclarationTypeSpec: 3
+! CHECK-NEXT: ExecutableConstruct: 3
+! CHECK-NEXT: ExecutionPart: 3
+! CHECK-NEXT: ExecutionPartConstruct: 3
+! CHECK-NEXT: ImplicitPart: 3
+! CHECK-NEXT: IntLiteralConstant: 3
+! CHECK-NEXT: IntegerTypeSpec: 3
+! CHECK-NEXT: IntrinsicTypeSpec: 3
+! CHECK-NEXT: SpecificationPart: 3
+! CHECK-NEXT: AttrSpec: 2
+! CHECK-NEXT: Call: 2
+! CHECK-NEXT: DeclarationConstruct: 2
+! CHECK-NEXT: DummyArg: 2
+! CHECK-NEXT: IntentSpec: 2
+! CHECK-NEXT: IntentSpec::Intent: 2
+! CHECK-NEXT: InternalSubprogram: 2
+! CHECK-NEXT: ProcedureDesignator: 2
+! CHECK-NEXT: SpecificationConstruct: 2
+! CHECK-NEXT: TypeDeclarationStmt: 2
+! CHECK-NEXT: AssignmentStmt: 1
+! CHECK-NEXT: CallStmt: 1
+! CHECK-NEXT: CharLiteralConstant: 1
+! CHECK-NEXT: ContainsStmt: 1
+! CHECK-NEXT: EndFunctionStmt: 1
+! CHECK-NEXT: EndProgramStmt: 1
+! CHECK-NEXT: EndSubroutineStmt: 1
+! CHECK-NEXT: Expr::Add: 1
+! CHECK-NEXT: Expr::Multiply: 1
+! CHECK-NEXT: Format: 1
+! CHECK-NEXT: FunctionReference: 1
+! CHECK-NEXT: FunctionStmt: 1
+! CHECK-NEXT: FunctionSubprogram: 1
+! CHECK-NEXT: ImplicitPartStmt: 1
+! CHECK-NEXT: ImplicitStmt: 1
+! CHECK-NEXT: InternalSubprogramPart: 1
+! CHECK-NEXT: MainProgram: 1
+! CHECK-NEXT: OutputItem: 1
+! CHECK-NEXT: PrefixSpec: 1
+! CHECK-NEXT: PrintStmt: 1
+! CHECK-NEXT: Program: 1
+! CHECK-NEXT: ProgramStmt: 1
+! CHECK-NEXT: ProgramUnit: 1
+! CHECK-NEXT: SubroutineStmt: 1
+! CHECK-NEXT: SubroutineSubprogram: 1
+! CHECK-NEXT: Variable: 1
Index: flang/test/Examples/feature-list-class.f90
===
--- /dev/null
+++ flang/test/Examples/feature-list-class.f90
@@ -0,0 +1,88 @@
+! UNSUPPORTED: system-windows
+! REQUIRES: plugins, shell, examples
+
+! RUN: %flang_fc1 -load %llvmshlibdir/flangFeatureList%pluginext \
+! RUN:-plugin feature-list %s 2>&1 | FileCheck %s
+
+module list_features_test
+implicit none
+
+type :: test_class_1
+integer :: a
+real :: b
+contains
+procedure :: sum => sum_test_class_1
+procedure :: set => set_values_test_class_1
+end type
+contains
+real function sum_test_class_1(self)
+class(test_class_1), intent(in) :: self
+sum_test_class_1 = self%a + self%b
+end function
+
+subroutine set_values_test_class_1(self, a, b)
+class(test_class_1), intent(out) :: self
+integer, intent(in) :: a, b
+self%a = a
+self%b = b
+end subroutine
+end module list_features_test
+
+! CHECK: Name: 32
+! CHECK-NEXT: DataRef: 11
+! CHECK-NEXT: Designator: 7
+! CHECK-NEXT: DeclarationTypeSpec: 6
+! CHECK-NEXT: Expr: 5
+! CHECK-NEXT: DeclarationConstruct: 4
+! CHECK-NEXT: EntityDecl: 4
+! CHECK-NEXT: IntrinsicTypeSpec: 4
+! CHECK-NEXT: SpecificationConstruct: 4
+! CHECK-NEXT: StructureComponent: 4
+! CHECK-NEXT: ActionStmt: 3
+! CHECK-NEXT: AssignmentStmt: 3
+! CHECK-NEXT: AttrSpec: 3
+! CHECK-NEXT: DummyArg: 3
+! CHECK-NEXT: ExecutableConstruct: 3
+! CHECK-NEXT: ExecutionPartConstruct: 3
+! CHECK-NEXT: ImplicitPart: 3
+! CHECK-NEXT: IntentSpec: 3
+! CHECK-NEXT: IntentSpec::Intent: 3
+! CHECK-NEXT: SpecificationPart: 3
+! CHECK-NEXT: TypeDeclarationStmt: 3
+! CHECK-NEXT: Variable: 3
+! CHECK-NEXT: Block: 2
+! CHECK-NEXT: ComponentDecl: 2
+! CHECK-NEXT: ComponentDefStmt: 2
+! CHECK-NEXT: ComponentOrFill: 2
+! CHECK-NEXT: ContainsStmt: 2
+! CHECK-NEXT: DataComponentDefStmt: 2
+! CHECK-NEXT: DeclarationTypeSpec::Class: 2
+! CHECK-NEXT: DerivedTypeS

[PATCH] D147349: [C2x] Implement support for empty brace initialization (WG14 N2900 and WG14 N3011)

2023-04-03 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/test/C/C2x/n2900_n3011_2.c:51
+  // CHECK: define {{.*}} void @test_vla
+  // CHECK-NEXT: entry:
+  // CHECK-NEXT: %[[I:.+]] = alloca i32

so 'entry' isn't really a stable name AFAIK.  So this might fail in test 
configs that do the 'erase names' thing.  That said, a buildbot hasn't caught 
one of those in a long time, so *shrug*.



Comment at: clang/test/C/C2x/n2900_n3011_2.c:55
+  // CHECK-NEXT: store i32 12, ptr %[[I]]
+  // CHECK-NEXT: %[[MEM0:.+]] = load i32, ptr %[[I]]
+  // CHECK-NEXT: %[[MEM1:.+]] = zext i32 %[[MEM0]] to i64

aaron.ballman wrote:
> erichkeane wrote:
> > These MEM# names are horrible to read :/  But the test is doing the right 
> > thing it appears.
> If you have suggestions for better names, I'm happy to use them.
`I`: `I_PTR`
`MEM0`: `I_VAL`
`MEM1`: `NUM_ELTS` (or `I_AS_64B`?).
`MEM3`: `COPY_BYTES`

Though, this all becomes a bit easier with 'i' in code being named `num_elts` 
or something.
`NUM_ELTS_PTR`
`NUM_ELTS`
`NUM_ELTS_EXT`
`BYTES_TO_COPY`




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

https://reviews.llvm.org/D147349

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


[clang] f263bd8 - [Clang] Implicitly include LLVM libc headers for the GPU

2023-04-03 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2023-04-03T12:57:21-05:00
New Revision: f263bd8f7d4c82af9672803e6d8d57f25c929d00

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

LOG: [Clang] Implicitly include LLVM libc headers for the GPU

There is currently work to support basic `libc` functionality on the
GPU. Some basic information about the projects can be found at
https://libc.llvm.org/gpu_mode.html. Typically, including the system
headers on the GPU will result in an error. For this reason the LLVM
`libc` project will generate its own headers that can be used with the
GPU.

The problem is that these headers will use the same name as the system headers.
For that reason, D146970 places it in the `llvm-libc` subfolder. In order to
still pick these files up, this patch adds changes in clang to default to
searching this directory when targeting the GPU. This lets offloading languages
such as OpenMP use the system `string.h` when compiling for the host and then
the LLVM libc `string.h` when targeting the GPU.

Depends on D146970

Reviewed By: tra

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

Added: 
clang/test/Driver/gpu-libc-headers.c

Modified: 
clang/lib/Driver/ToolChains/Clang.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 41fe89337d1b1..a17db9b9ceb79 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1157,6 +1157,24 @@ void Clang::AddPreprocessingOptions(Compilation &C, 
const JobAction &JA,
   if (JA.isOffloading(Action::OFK_HIP))
 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
 
+  // If we are compiling for a GPU target we want to override the system 
headers
+  // with ones created by the 'libc' project if present.
+  if (!Args.hasArg(options::OPT_nostdinc) &&
+  !Args.hasArg(options::OPT_nogpuinc) &&
+  !Args.hasArg(options::OPT_nobuiltininc) &&
+  (getToolChain().getTriple().isNVPTX() ||
+   getToolChain().getTriple().isAMDGCN())) {
+
+  // Add include/gpu-none-libc/* to our system include path. This lets us 
use
+  // GPU-specific system headers first. These headers should be made to be
+  // compatible with the host environment's headers.
+  SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
+  llvm::sys::path::append(P, "include");
+  llvm::sys::path::append(P, "gpu-none-llvm");
+  CmdArgs.push_back("-c-isystem");
+  CmdArgs.push_back(Args.MakeArgString(P));
+  }
+
   // If we are offloading to a target via OpenMP we need to include the
   // openmp_wrappers folder which contains alternative system headers.
   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&

diff  --git a/clang/test/Driver/gpu-libc-headers.c 
b/clang/test/Driver/gpu-libc-headers.c
new file mode 100644
index 0..c8f772f102d03
--- /dev/null
+++ b/clang/test/Driver/gpu-libc-headers.c
@@ -0,0 +1,22 @@
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp 
--sysroot=./ \
+// RUN: -fopenmp-targets=amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp 
--sysroot=./ \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS
+// RUN:   %clang -### --target=nvptx64-nvidia-cuda -march=sm_70 -nogpulib 
--sysroot=./ %s 2>&1 | \
+// RUN: FileCheck %s --check-prefix=CHECK-HEADERS
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib 
--sysroot=./ %s 2>&1 | \
+// RUN: FileCheck %s --check-prefix=CHECK-HEADERS
+// CHECK-HEADERS: "-cc1"{{.*}}"-c-isystem" 
"{{.*}}include/gpu-none-llvm"{{.*}}"-isysroot" "./"
+
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
+// RUN: -nogpuinc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
+// RUN: -nostdinc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
+// RUN: -nobuiltininc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// CHECK-HEADERS-DISABLED-NOT: "-cc1"{{.*}}"-c-isystem" 
"{{.*}}include/gpu-none-llvm"



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


[PATCH] D146973: [Clang] Implicitly include LLVM libc headers for the GPU

2023-04-03 Thread Joseph Huber 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 rGf263bd8f7d4c: [Clang] Implicitly include LLVM libc headers 
for the GPU (authored by jhuber6).

Changed prior to commit:
  https://reviews.llvm.org/D146973?vs=509090&id=510560#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146973

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/gpu-libc-headers.c


Index: clang/test/Driver/gpu-libc-headers.c
===
--- /dev/null
+++ clang/test/Driver/gpu-libc-headers.c
@@ -0,0 +1,22 @@
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp 
--sysroot=./ \
+// RUN: -fopenmp-targets=amdgcn-amd-amdhsa 
-Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp 
--sysroot=./ \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda 
-Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS
+// RUN:   %clang -### --target=nvptx64-nvidia-cuda -march=sm_70 -nogpulib 
--sysroot=./ %s 2>&1 | \
+// RUN: FileCheck %s --check-prefix=CHECK-HEADERS
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib 
--sysroot=./ %s 2>&1 | \
+// RUN: FileCheck %s --check-prefix=CHECK-HEADERS
+// CHECK-HEADERS: "-cc1"{{.*}}"-c-isystem" 
"{{.*}}include/gpu-none-llvm"{{.*}}"-isysroot" "./"
+
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
+// RUN: -nogpuinc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
+// RUN: -nostdinc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
+// RUN: -nobuiltininc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
+// CHECK-HEADERS-DISABLED-NOT: "-cc1"{{.*}}"-c-isystem" 
"{{.*}}include/gpu-none-llvm"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -1157,6 +1157,24 @@
   if (JA.isOffloading(Action::OFK_HIP))
 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
 
+  // If we are compiling for a GPU target we want to override the system 
headers
+  // with ones created by the 'libc' project if present.
+  if (!Args.hasArg(options::OPT_nostdinc) &&
+  !Args.hasArg(options::OPT_nogpuinc) &&
+  !Args.hasArg(options::OPT_nobuiltininc) &&
+  (getToolChain().getTriple().isNVPTX() ||
+   getToolChain().getTriple().isAMDGCN())) {
+
+  // Add include/gpu-none-libc/* to our system include path. This lets us 
use
+  // GPU-specific system headers first. These headers should be made to be
+  // compatible with the host environment's headers.
+  SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
+  llvm::sys::path::append(P, "include");
+  llvm::sys::path::append(P, "gpu-none-llvm");
+  CmdArgs.push_back("-c-isystem");
+  CmdArgs.push_back(Args.MakeArgString(P));
+  }
+
   // If we are offloading to a target via OpenMP we need to include the
   // openmp_wrappers folder which contains alternative system headers.
   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&


Index: clang/test/Driver/gpu-libc-headers.c
===
--- /dev/null
+++ clang/test/Driver/gpu-libc-headers.c
@@ -0,0 +1,22 @@
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp --sysroot=./ \
+// RUN: -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa --offload-arch=gfx908  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp --sysroot=./ \
+// RUN: -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target=nvptx64-nvidia-cuda --offload-arch=sm_70  \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS
+// RUN:   %clang -### --target=nvptx64-nvidia-cuda -march=sm_70 -nogpulib --sysroot=./ %s 2>&1 | \
+// RUN: FileCheck %s --check-prefix=CHECK-HEADERS
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib --sysroot=./ %s 2>&1 | \
+// RUN: FileCheck %s --check-prefix=CHECK-HEADERS
+// CHECK-HEADERS: "-cc1"{{.*}}"-c-isystem" "{{.*}}include/gpu-none-llvm"{{.*}}"-isysroot" "./"
+
+// RUN:   %clang -### --target=amdgcn-amd-am

[PATCH] D146973: [Clang] Implicitly include LLVM libc headers for the GPU

2023-04-03 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:1196-1197
 
+  // If we are compiling for a GPU target we want to override the system 
headers
+  // with ones created by the 'libc' project if present.
+  if (!Args.hasArg(options::OPT_nostdinc) &&

jhuber6 wrote:
> tra wrote:
> > Please add a TODO with some details outlining what it's supposed to do, the 
> > issues we've discussed, and that this is intended to be a temporary 
> > solution (famous last words, I know).
> > 
> > 
> I'm not sure if we should consider this temporary, we simply need to ensure 
> that the headers in this directory are compatible with the host environment 
> somehow.
> we simply need to ensure that the headers in this directory are compatible 
> with the host environment somehow.

The problem is that you probably do not have the *correct* host environment to 
be compatible with, yet. You do need to compile the host headers with the 
host-specific macros defined and that will make some of the code in them 
uncompileable for NVPTX (e.g due to inline asm or unavailable builtins). 

Nor do we have the long-term solution for the "compatible, somehow" part, as 
we're replacing part of the host headers, implementation of which we do not 
control. 

We can drop the 'temporary' part, but I think the story here is far from over, 
so a prominent TODO is needed.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146973

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


[PATCH] D147461: [Headers] Add some intrinsic function descriptions to immintrin.h

2023-04-03 Thread Paul Robinson via Phabricator via cfe-commits
probinson created this revision.
probinson added reviewers: RKSimon, pengfei.
Herald added a project: All.
probinson requested review of this revision.

https://reviews.llvm.org/D147461

Files:
  clang/lib/Headers/immintrin.h

Index: clang/lib/Headers/immintrin.h
===
--- clang/lib/Headers/immintrin.h
+++ clang/lib/Headers/immintrin.h
@@ -284,18 +284,45 @@
 
 #if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) ||  \
 defined(__RDRND__)
+/// Returns a 16-bit hardware-generated random value.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  RDRAND  instruction.
+///
+/// \param __p
+///Pointer to a 16-bit location to place the random value.
+/// \returns 1 if the value was successfully generated, 0 otherwise.
 static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("rdrnd")))
 _rdrand16_step(unsigned short *__p)
 {
   return (int)__builtin_ia32_rdrand16_step(__p);
 }
 
+/// Returns a 32-bit hardware-generated random value.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  RDRAND  instruction.
+///
+/// \param __p
+///Pointer to a 32-bit location to place the random value.
+/// \returns 1 if the value was successfully generated, 0 otherwise.
 static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("rdrnd")))
 _rdrand32_step(unsigned int *__p)
 {
   return (int)__builtin_ia32_rdrand32_step(__p);
 }
 
+/// Returns a 64-bit hardware-generated random value.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  RDRAND  instruction.
+///
+/// \param __p
+///Pointer to a 64-bit location to place the random value.
+/// \returns 1 if the value was successfully generated, 0 otherwise.
 #ifdef __x86_64__
 static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("rdrnd")))
 _rdrand64_step(unsigned long long *__p)
@@ -325,48 +352,108 @@
 #if !(defined(_MSC_VER) || defined(__SCE__)) || __has_feature(modules) ||  \
 defined(__FSGSBASE__)
 #ifdef __x86_64__
+/// Reads the FS base register.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  RDFSBASE  instruction.
+///
+/// \returns The lower 32 bits of the FS base register.
 static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__, __target__("fsgsbase")))
 _readfsbase_u32(void)
 {
   return __builtin_ia32_rdfsbase32();
 }
 
+/// Reads the FS base register.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  RDFSBASE  instruction.
+///
+/// \returns The contents of the FS base register.
 static __inline__ unsigned long long __attribute__((__always_inline__, __nodebug__, __target__("fsgsbase")))
 _readfsbase_u64(void)
 {
   return __builtin_ia32_rdfsbase64();
 }
 
+/// Reads the GS base register.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  RDGSBASE  instruction.
+///
+/// \returns The lower 32 bits of the GS base register.
 static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__, __target__("fsgsbase")))
 _readgsbase_u32(void)
 {
   return __builtin_ia32_rdgsbase32();
 }
 
+/// Reads the GS base register.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  RDGSBASE  instruction.
+///
+/// \returns The contents of the GS base register.
 static __inline__ unsigned long long __attribute__((__always_inline__, __nodebug__, __target__("fsgsbase")))
 _readgsbase_u64(void)
 {
   return __builtin_ia32_rdgsbase64();
 }
 
+/// Modifies the FS base register.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  WRFSBASE  instruction.
+///
+/// \param __V
+///Value to use for the lower 32 bits of the FS base register.
 static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("fsgsbase")))
 _writefsbase_u32(unsigned int __V)
 {
   __builtin_ia32_wrfsbase32(__V);
 }
 
+/// Modifies the FS base register.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  WRFSBASE  instruction.
+///
+/// \param __V
+///Value to use for the FS base register.
 static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("fsgsbase")))
 _writefsbase_u64(unsigned long long __V)
 {
   __builtin_ia32_wrfsbase64(__V);
 }
 
+/// Modifies the GS base register.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  WRGSBASE  instruction.
+///
+/// \param __V
+///Value to use for the lower 32 bits of the GS base register.
 static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("fsgsbase")))
 _writegsbase_u32(unsigned int __V)
 {
   __builtin_ia32_wrgsbase32(__V);
 }
 
+/// Modifies the GS base register.
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  WRFSBASE  instruction.
+///
+/// \param __V
+///Value to use for GS base register.
 static __inline__ void __attribute__((__always_inline__, __nodebug__, __target__("fsgsbase")))
 _writegsb

[PATCH] D147461: [Headers] Add some intrinsic function descriptions to immintrin.h

2023-04-03 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

FTR, I'll be working my way through a bunch of intrinsics over the next month 
or so, trying not to do too many at once. Mostly AVX2 but also some others.


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

https://reviews.llvm.org/D147461

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


[PATCH] D147349: [C2x] Implement support for empty brace initialization (WG14 N2900 and WG14 N3011)

2023-04-03 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 510574.
aaron.ballman marked 4 inline comments as done.
aaron.ballman added a comment.

Update based on review feedback:

- Added an assertion to codegen that a VLA with an initializer is an empty 
initializer
- Updated the codegen tests to use better identifiers
- Added a codegen test for empty initialization of VLA of structures


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

https://reviews.llvm.org/D147349

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/Parse/ParseInit.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/test/C/C2x/n2900_n3011.c
  clang/test/C/C2x/n2900_n3011_2.c
  clang/test/Sema/array-init.c
  clang/test/Sema/complex-init-list.c
  clang/test/Sema/compound-literal.c
  clang/test/Sema/flexible-array-init.c
  clang/test/Sema/gnu-flags.c
  clang/test/Sema/sizeless-1.c
  clang/test/Sema/vla.c
  clang/test/SemaObjC/property.m
  clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
  clang/www/c_status.html

Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -1083,11 +1083,11 @@
 

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2900.htm";>N2900
-Unknown
+Clang 17
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3011.htm";>N3011
-Unknown
+Clang 17
   
 
   Not-so-magic: typeof
Index: clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
===
--- clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
+++ clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
@@ -28,37 +28,34 @@
   intel_sub_group_avc_sic_result_t result_sic = ss;
   intel_sub_group_avc_ime_result_single_reference_streamout_t sstreamout = v;
   intel_sub_group_avc_ime_result_dual_reference_streamout_t dstreamin_list = {0x0, 0x1};
-  intel_sub_group_avc_ime_dual_reference_streamin_t dstreamin_list2 = {};
   intel_sub_group_avc_ime_single_reference_streamin_t dstreamin_list3 = {c};
   intel_sub_group_avc_ime_dual_reference_streamin_t dstreamin_list4 = {1};
 #ifdef EXT
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_mce_payload_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_payload_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ref_payload_t' with an expression of incompatible type '__private float'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_sic_payload_t' with an expression of incompatible type '__private struct st'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_mce_result_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_result_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ref_result_t' with an expression of incompatible type '__private float'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_sic_result_t' with an expression of incompatible type '__private struct st'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_result_single_reference_streamout_t' with an expression of incompatible type '__private void *__private'}}
-// expected-warning@-14 {{excess elements in struct initializer}}
-// expected-error@-14 {{scalar initializer cannot be empty}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_single_reference_streamin_t' with an expression of incompatible type '__private char'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_dual_reference_streamin_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_mce_payload_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ime_payload_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ref_payload_t' with an expression of incompatible type '__private float'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_sic_payload_t' with an expression of incompatible type '__private struct st'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_mce_result_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ime_result_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__

[PATCH] D147383: [clang-tidy] Allow bugprone-unchecked-optional-access to handle calls to `std::forward`

2023-04-03 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL accepted this revision.
PiotrZSL added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:589-591
+  if (LocArg == nullptr) {
+return;
+  }

```
if (LocArg == nullptr)
return;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147383

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


[clang] 5d8aaad - [C2x] Implement support for empty brace initialization (WG14 N2900 and WG14 N3011)

2023-04-03 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-04-03T15:22:52-04:00
New Revision: 5d8aaad4452f60ba8902e921d9bed606713a8f26

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

LOG: [C2x] Implement support for empty brace initialization (WG14 N2900 and 
WG14 N3011)

This implements support for allowing {} to consistently zero initialize
objects. We already supported most of this work as a GNU extension, but
the C2x feature goes beyond what the GNU extension allowed.

The changes in this patch are:

* Removed the -Wgnu-empty-initializer warning group. The extension is
  now a C2x extension warning instead. Note that use of
  `-Wno-gnu-empty-initializer seems` to be quite low in the wild
(https://sourcegraph.com/search?q=context%3Aglobal+-file%3A.*test.*+%22-Wno-gnu-empty-initializer%22&patternType=standard&sm=1&groupBy=repo
  which currently only gives 8 hits total), so this is not expected to
  be an overly disruptive change. But I'm adding the clang vendors
  review group just in case this expectation is wrong.
* Reworded the diagnostic wording to be about a C2x extension, added a
  pre-C2x compat warning.
* Allow {} to zero initialize a VLA

This functionality is exposed as an extension in all older C modes
(same as the GNU extension was), but does *not* allow the extension for
VLA initialization in C++ due to concern about handling non-trivially
constructible types.

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

Added: 
clang/test/C/C2x/n2900_n3011.c
clang/test/C/C2x/n2900_n3011_2.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticCommonKinds.td
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/lib/CodeGen/CGExprAgg.cpp
clang/lib/Parse/ParseInit.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaInit.cpp
clang/test/Sema/array-init.c
clang/test/Sema/complex-init-list.c
clang/test/Sema/compound-literal.c
clang/test/Sema/flexible-array-init.c
clang/test/Sema/gnu-flags.c
clang/test/Sema/sizeless-1.c
clang/test/Sema/vla.c
clang/test/SemaObjC/property.m
clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
clang/www/c_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index cd9aae998a503..53a0541ed290a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -121,6 +121,18 @@ C2x Feature Support
   which introduces the ``bool``, ``static_assert``, ``alignas``, ``alignof``,
   and ``thread_local`` keywords in C2x.
 
+- Implemented `WG14 N2900 
`_
+  and `WG14 N3011 
`_
+  which allows for empty braced initialization in C.
+
+  .. code-block:: c
+
+struct S { int x, y } s = {}; // Initializes s.x and s.y to 0
+
+  As part of this change, the ``-Wgnu-empty-initializer`` warning group was
+  removed, as this is no longer a GNU extension but a C2x extension. You can
+  use ``-Wno-c2x-extensions`` to silence the extension warning instead.
+
 Non-comprehensive list of changes in this release
 -
 - Clang now saves the address of ABI-indirect function parameters on the stack,

diff  --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td 
b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index f574b0f0171b7..bac77299671c5 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -130,6 +130,12 @@ def warn_cxx20_compat_consteval : Warning<
 def warn_missing_type_specifier : Warning<
   "type specifier missing, defaults to 'int'">,
   InGroup, DefaultIgnore;
+
+def ext_c_empty_initializer : Extension<
+  "use of an empty initializer is a C2x extension">, InGroup;
+def warn_c2x_compat_empty_initializer : Warning<
+  "use of an empty initializer is incompatible with C standards before C2x">,
+  InGroup, DefaultIgnore;
 }
 
 let CategoryName = "Nullability Issue" in {

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 0d2829d64501f..31f64f4eceb7c 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -256,7 +256,6 @@ def EmptyBody : DiagGroup<"empty-body">;
 def Exceptions : DiagGroup<"exceptions">;
 def DeclarationAfterStatement : DiagGroup<"declaration-after-statement">;
 
-def GNUEmptyInitializer : DiagGroup<"gnu-empty-initializer">;
 def GNUEmptyStruct : DiagGroup<"gnu-empty-struct">;
 def ExtraTokens : DiagGroup<"extra-tokens">;
 def CXX98CompatExtraSemi : DiagGroup<"c++98-compat-extra-semi">;
@@ -1135,7 +1134,7 @@ def 

[PATCH] D147349: [C2x] Implement support for empty brace initialization (WG14 N2900 and WG14 N3011)

2023-04-03 Thread Aaron Ballman 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 rG5d8aaad4452f: [C2x] Implement support for empty brace 
initialization (WG14 N2900 and WG14… (authored by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147349

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticCommonKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/Parse/ParseInit.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/test/C/C2x/n2900_n3011.c
  clang/test/C/C2x/n2900_n3011_2.c
  clang/test/Sema/array-init.c
  clang/test/Sema/complex-init-list.c
  clang/test/Sema/compound-literal.c
  clang/test/Sema/flexible-array-init.c
  clang/test/Sema/gnu-flags.c
  clang/test/Sema/sizeless-1.c
  clang/test/Sema/vla.c
  clang/test/SemaObjC/property.m
  clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
  clang/www/c_status.html

Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -1083,11 +1083,11 @@
 

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2900.htm";>N2900
-Unknown
+Clang 17
   

 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3011.htm";>N3011
-Unknown
+Clang 17
   
 
   Not-so-magic: typeof
Index: clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
===
--- clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
+++ clang/test/SemaOpenCL/intel-subgroup-avc-ext-types.cl
@@ -28,37 +28,34 @@
   intel_sub_group_avc_sic_result_t result_sic = ss;
   intel_sub_group_avc_ime_result_single_reference_streamout_t sstreamout = v;
   intel_sub_group_avc_ime_result_dual_reference_streamout_t dstreamin_list = {0x0, 0x1};
-  intel_sub_group_avc_ime_dual_reference_streamin_t dstreamin_list2 = {};
   intel_sub_group_avc_ime_single_reference_streamin_t dstreamin_list3 = {c};
   intel_sub_group_avc_ime_dual_reference_streamin_t dstreamin_list4 = {1};
 #ifdef EXT
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_mce_payload_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_payload_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ref_payload_t' with an expression of incompatible type '__private float'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_sic_payload_t' with an expression of incompatible type '__private struct st'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_mce_result_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_result_t' with an expression of incompatible type 'int'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ref_result_t' with an expression of incompatible type '__private float'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_sic_result_t' with an expression of incompatible type '__private struct st'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_result_single_reference_streamout_t' with an expression of incompatible type '__private void *__private'}}
-// expected-warning@-14 {{excess elements in struct initializer}}
-// expected-error@-14 {{scalar initializer cannot be empty}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_single_reference_streamin_t' with an expression of incompatible type '__private char'}}
-// expected-error@-14 {{initializing '__private intel_sub_group_avc_ime_dual_reference_streamin_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_mce_payload_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ime_payload_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ref_payload_t' with an expression of incompatible type '__private float'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_sic_payload_t' with an expression of incompatible type '__private struct st'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_mce_result_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ime_result_t' with an expression of incompatible type 'int'}}
+// expected-error@-13 {{initializing '__private intel_sub_group_avc_ref_result_t' with an expression of incom

[PATCH] D146178: [Clang][Sema] Fix comparison of constraint expressions

2023-04-03 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/lib/Sema/SemaConcept.cpp:775-776
+static bool IsInsideImplicitFullTemplateSpecialization(const DeclContext *DC) {
+  auto *CTSDecl = dyn_cast_or_null(
+  DC->getOuterLexicalRecordContext());
+  return CTSDecl && !isa(CTSDecl) &&

This doesn't look right to me; there could be a class template nested inside a 
non-templated class, so I think you would need to walk up the enclosing 
`DeclContext`s one by one checking each in turn. But, we might be inside a 
function template specialization or variable template specialization instead, 
in some weird cases:

```
template concept C = true;
template auto L = [] U>() {};
struct Q {
  template U> friend constexpr auto decltype(L)::operator()() const;
};
```

... so I think we want a different approach than looking for an enclosing class 
template specialization declaration.

Can we skip this check entirely, and instead always compute and substitute the 
template instantiation arguments as is done below? That computation will walk 
the enclosing contexts for us in a careful way that properly handles cases like 
this lambda-in-variable-template situation. If we find we get zero levels of 
template argument list, we can skip doing the actual substitution as an 
optimization.



Comment at: clang/lib/Sema/SemaOverload.cpp:1303
+OldTemplate->getTemplateParameters(), false, TPL_TemplateMatch,
+SourceLocation(), false /* PartialOrdering */);
 bool SameReturnType = Context.hasSameType(Old->getDeclaredReturnType(),

rsmith wrote:
> shafik wrote:
> > nit
> Just remove the final parameter; it has a default argument of `false` and no 
> other call site passes `false` here.  (I'm working on removing this parameter 
> in a different change.)
You can remove the `SourceLocation()` argument too; there's an identical 
default argument.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146178

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


cfe-commits@lists.llvm.org

2023-04-03 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.

Looks great! LGTM except there's some dead code.




Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:570-573
+if (const auto *ArraySubst =
+dyn_cast(Node->getSubExpr()))
+  if (const auto *DRE =
+  dyn_cast(ArraySubst->getBase()->IgnoreImpCasts())) {

These `dyn_cast`s are already checked by the matcher. They can be turned into 
`cast`s and this function can return `{DRE}` unconditionally.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:1002
+
+  if (DREs.size() == 1)
+if (const auto *VD = dyn_cast(DREs.front()->getDecl())) {

Similarly, this check is redundant, it's already guaranteed by the matcher.



Comment at: clang/lib/Analysis/UnsafeBufferUsage.cpp:1077-1079
+  if (const auto *ArraySub = dyn_cast(Node->getSubExpr()))
+if (const auto *DRE =
+dyn_cast(ArraySub->getBase()->IgnoreImpCasts())) {

Same here!


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

https://reviews.llvm.org/D143128

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


  1   2   >