[PATCH] D145579: [Clang][Flang][AMDGPU] Add support for AMDGPU to Flang driver

2023-03-28 Thread Dominik Adamski via Phabricator via cfe-commits
domada added a comment.

In D145579#4224157 , @tschuett wrote:

> Do you want to move the AMDGPU changes into AMDGPU.cpp next to AMD.cpp? From 
> the conversation, there seems to be more target specific behaviours.

@tschuett No. I don't plan to further refactor AMDGPU::TargeTInfo Clang class. 
My current goal is to add function attributes to the LLVM IR for Fortran OpenMP 
code and I don't need to make more changes in Clang to finish my goal.


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

https://reviews.llvm.org/D145579

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


[PATCH] D146929: [clang-tidy] Ignore unevaluated exprs in rvalue-reference-param-not-moved

2023-03-28 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbd7628461b3f: [clang-tidy] Ignore unevaluated exprs in 
rvalue-reference-param-not-moved (authored by ccotter, committed by PiotrZSL).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146929

Files:
  clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
  clang-tools-extra/clang-tidy/utils/Matchers.h
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp
@@ -156,6 +156,13 @@
   Obj moved = std::move((o));
 }
 
+void does_not_move_in_evaluated(Obj&& o) {
+  // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: rvalue reference parameter 'o' is never moved from inside the function body [cppcoreguidelines-rvalue-reference-param-not-moved]
+  using result_t = decltype(std::move(o));
+  unsigned size = sizeof(std::move(o));
+  Obj moved = o;
+}
+
 template 
 struct mypair {
   T1 first;
Index: clang-tools-extra/clang-tidy/utils/Matchers.h
===
--- clang-tools-extra/clang-tidy/utils/Matchers.h
+++ clang-tools-extra/clang-tidy/utils/Matchers.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_MATCHERS_H
 
 #include "TypeTraits.h"
+#include "clang/AST/ExprConcepts.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include 
 
@@ -48,6 +49,23 @@
   return pointerType(pointee(qualType(isConstQualified(;
 }
 
+AST_MATCHER(Expr, hasUnevaluatedContext) {
+  if (isa(Node) || isa(Node))
+return true;
+  if (const auto *UnaryExpr = dyn_cast(&Node)) {
+switch (UnaryExpr->getKind()) {
+case UETT_SizeOf:
+case UETT_AlignOf:
+  return true;
+default:
+  return false;
+}
+  }
+  if (const auto *TypeIDExpr = dyn_cast(&Node))
+return !TypeIDExpr->isPotentiallyEvaluated();
+  return false;
+}
+
 // A matcher implementation that matches a list of type name regular expressions
 // against a NamedDecl. If a regular expression contains the substring "::"
 // matching will occur against the qualified name, otherwise only the typename.
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
@@ -7,6 +7,7 @@
 //===--===//
 
 #include "RvalueReferenceParamNotMovedCheck.h"
+#include "../utils/Matchers.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 
@@ -14,6 +15,8 @@
 
 namespace clang::tidy::cppcoreguidelines {
 
+using matchers::hasUnevaluatedContext;
+
 namespace {
 AST_MATCHER_P(LambdaExpr, valueCapturesVar, DeclarationMatcher, VarMatcher) {
   return std::find_if(Node.capture_begin(), Node.capture_end(),
@@ -39,16 +42,18 @@
 
   StatementMatcher MoveCallMatcher =
   callExpr(
+  argumentCountIs(1),
   anyOf(callee(functionDecl(hasName("::std::move"))),
 callee(unresolvedLookupExpr(hasAnyDeclaration(
 namedDecl(hasUnderlyingDecl(hasName("::std::move"))),
-  argumentCountIs(1),
   hasArgument(
   0, argumentOf(
  AllowPartialMove,
  declRefExpr(to(equalsBoundNode("param"))).bind("ref"))),
   unless(hasAncestor(
-  lambdaExpr(valueCapturesVar(equalsBoundNode("param"))
+  lambdaExpr(valueCapturesVar(equalsBoundNode("param"),
+  unless(anyOf(hasAncestor(typeLoc()),
+   hasAncestor(expr(hasUnevaluatedContext())
   .bind("move-call");
 
   Finder->addMatcher(
Index: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -10,13 +10,13 @@
 
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
-#include "clang/AST/ExprConcepts.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/STLExtras.h"
 
 #include "../utils/ExprSequence.h"
+#include "../utils/Matchers.h"
 #include 
 
 using namespac

[clang-tools-extra] bd76284 - [clang-tidy] Ignore unevaluated exprs in rvalue-reference-param-not-moved

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

Author: Chris Cotter
Date: 2023-03-28T07:05:12Z
New Revision: bd7628461b3f7dc3d1071b12686dc53515634f4c

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

LOG: [clang-tidy] Ignore unevaluated exprs in rvalue-reference-param-not-moved

Ignore unevaluated expressions in rvalue-reference-param-not-moved
check since they are not actual uses of a move().

Reviewed By: PiotrZSL

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp

clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
clang-tools-extra/clang-tidy/utils/Matchers.h

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/rvalue-reference-param-not-moved.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
index c10c3652a153a..c5b6b541096ca 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -10,13 +10,13 @@
 
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
-#include "clang/AST/ExprConcepts.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/STLExtras.h"
 
 #include "../utils/ExprSequence.h"
+#include "../utils/Matchers.h"
 #include 
 
 using namespace clang::ast_matchers;
@@ -24,24 +24,9 @@ using namespace clang::tidy::utils;
 
 namespace clang::tidy::bugprone {
 
-namespace {
+using matchers::hasUnevaluatedContext;
 
-AST_MATCHER(Expr, hasUnevaluatedContext) {
-  if (isa(Node) || isa(Node))
-return true;
-  if (const auto *UnaryExpr = dyn_cast(&Node)) {
-switch (UnaryExpr->getKind()) {
-case UETT_SizeOf:
-case UETT_AlignOf:
-  return true;
-default:
-  return false;
-}
-  }
-  if (const auto *TypeIDExpr = dyn_cast(&Node))
-return !TypeIDExpr->isPotentiallyEvaluated();
-  return false;
-}
+namespace {
 
 /// Contains information about a use-after-move.
 struct UseAfterMove {
@@ -86,7 +71,6 @@ class UseAfterMoveFinder {
 
 } // namespace
 
-
 // Matches nodes that are
 // - Part of a decltype argument or class template argument (we check this by
 //   seeing if they are children of a TypeLoc), or

diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
index eb67df05411a0..da49d5610e229 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/RvalueReferenceParamNotMovedCheck.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "RvalueReferenceParamNotMovedCheck.h"
+#include "../utils/Matchers.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 
@@ -14,6 +15,8 @@ using namespace clang::ast_matchers;
 
 namespace clang::tidy::cppcoreguidelines {
 
+using matchers::hasUnevaluatedContext;
+
 namespace {
 AST_MATCHER_P(LambdaExpr, valueCapturesVar, DeclarationMatcher, VarMatcher) {
   return std::find_if(Node.capture_begin(), Node.capture_end(),
@@ -39,16 +42,18 @@ void 
RvalueReferenceParamNotMovedCheck::registerMatchers(MatchFinder *Finder) {
 
   StatementMatcher MoveCallMatcher =
   callExpr(
+  argumentCountIs(1),
   anyOf(callee(functionDecl(hasName("::std::move"))),
 callee(unresolvedLookupExpr(hasAnyDeclaration(
 namedDecl(hasUnderlyingDecl(hasName("::std::move"))),
-  argumentCountIs(1),
   hasArgument(
   0, argumentOf(
  AllowPartialMove,
  declRefExpr(to(equalsBoundNode("param"))).bind("ref"))),
   unless(hasAncestor(
-  lambdaExpr(valueCapturesVar(equalsBoundNode("param"))
+  lambdaExpr(valueCapturesVar(equalsBoundNode("param"),
+  unless(anyOf(hasAncestor(typeLoc()),
+   hasAncestor(expr(hasUnevaluatedContext())
   .bind("move-call");
 
   Finder->addMatcher(

diff  --git a/clang-tools-extra/clang-tidy/utils/Matchers.h 
b/clang-tools-extra/clang-tidy/utils/Matchers.h
index b3b2c8c636174..1e085f59b69ed 100644
--- a/clang-tools-extra/clang-tidy/utils/Matchers.h
+++ b/clang-tools-extra/clang-tidy/utils/Matchers.h
@@ -10,6 +10,7 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_MATCHERS_H
 
 #include "TypeTraits.h"
+#include "clang/AST/ExprConcepts.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include 
 
@@ -48,6 +49,23 @@ AST_MATCHER_FUNCTION(

[PATCH] D145579: [Clang][Flang][AMDGPU] Add support for AMDGPU to Flang driver

2023-03-28 Thread Thorsten via Phabricator via cfe-commits
tschuett added a comment.

I wanted to ask whether you want to put an AMDGPU.cpp and AMD.cpp file in the 
flang/lib/Frontend directory.


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

https://reviews.llvm.org/D145579

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


[PATCH] D146507: [clang][dataflow][NFC] Eliminate StmtToEnvMap interface.

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

Rebase to head


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146507

Files:
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  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
@@ -40,29 +40,6 @@
 namespace clang {
 namespace dataflow {
 
-class StmtToEnvMapImpl : public StmtToEnvMap {
-public:
-  StmtToEnvMapImpl(
-  const ControlFlowContext &CFCtx,
-  llvm::ArrayRef>
-  BlockToState)
-  : CFCtx(CFCtx), BlockToState(BlockToState) {}
-
-  const Environment *getEnvironment(const Stmt &S) const override {
-auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
-assert(BlockIt != CFCtx.getStmtToBlock().end());
-if (!CFCtx.isBlockReachable(*BlockIt->getSecond()))
-  return nullptr;
-const auto &State = BlockToState[BlockIt->getSecond()->getBlockID()];
-assert(State);
-return &State->Env;
-  }
-
-private:
-  const ControlFlowContext &CFCtx;
-  llvm::ArrayRef> BlockToState;
-};
-
 /// Returns the index of `Block` in the successors of `Pred`.
 static int blockIndexInPredecessor(const CFGBlock &Pred,
const CFGBlock &Block) {
@@ -269,7 +246,7 @@
 TypeErasedDataflowAnalysisState PredState = *MaybePredState;
 if (Analysis.builtinOptions()) {
   if (const Stmt *PredTerminatorStmt = Pred->getTerminatorStmt()) {
-const StmtToEnvMapImpl StmtToEnv(AC.CFCtx, AC.BlockStates);
+const StmtToEnvMap StmtToEnv(AC.CFCtx, AC.BlockStates);
 auto [Cond, CondValue] =
 TerminatorVisitor(StmtToEnv, PredState.Env,
   blockIndexInPredecessor(*Pred, Block))
@@ -304,7 +281,7 @@
   AnalysisContext &AC) {
   const Stmt *S = Elt.getStmt();
   assert(S != nullptr);
-  transfer(StmtToEnvMapImpl(AC.CFCtx, AC.BlockStates), *S, InputState.Env);
+  transfer(StmtToEnvMap(AC.CFCtx, AC.BlockStates), *S, InputState.Env);
 }
 
 /// Built-in transfer function for `CFGInitializer`.
Index: clang/include/clang/Analysis/FlowSensitive/Transfer.h
===
--- clang/include/clang/Analysis/FlowSensitive/Transfer.h
+++ clang/include/clang/Analysis/FlowSensitive/Transfer.h
@@ -17,6 +17,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h"
 
 namespace clang {
 namespace dataflow {
@@ -24,12 +25,26 @@
 /// Maps statements to the environments of basic blocks that contain them.
 class StmtToEnvMap {
 public:
-  virtual ~StmtToEnvMap() = default;
-
-  /// Retrieves the environment of the basic block that contains `S`.
-  /// If `S` is reachable, returns a non-null pointer to the environment.
-  /// If `S` is not reachable, returns nullptr.
-  virtual const Environment *getEnvironment(const Stmt &S) const = 0;
+  StmtToEnvMap(const ControlFlowContext &CFCtx,
+   llvm::ArrayRef>
+   BlockToState)
+  : CFCtx(CFCtx), BlockToState(BlockToState) {}
+
+  /// Returns the environment of the basic block that contains `S`.
+  /// The result is guaranteed never to be null.
+  virtual const Environment *getEnvironment(const Stmt &S) const {
+auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
+assert(BlockIt != CFCtx.getStmtToBlock().end());
+if (!CFCtx.isBlockReachable(*BlockIt->getSecond()))
+  return nullptr;
+const auto &State = BlockToState[BlockIt->getSecond()->getBlockID()];
+assert(State);
+return &State->Env;
+  }
+
+private:
+  const ControlFlowContext &CFCtx;
+  llvm::ArrayRef> BlockToState;
 };
 
 /// Evaluates `S` and updates `Env` accordingly.


Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -40,29 +40,6 @@
 namespace clang {
 namespace dataflow {
 
-class StmtToEnvMapImpl : public StmtToEnvMap {
-public:
-  StmtToEnvMapImpl(
-  const ControlFlowContext &CFCtx,
-  llvm::ArrayRef>
-  BlockToState)
-  : CFCtx(CFCtx), BlockToState(BlockToState) {}
-
-  const Environment *getEnvironment(const Stmt &S) const override {
-auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
-assert(BlockIt != CFCtx.getStmtToBlock().end());
-if (!CFCtx.is

[PATCH] D70401: [RISCV] CodeGen of RVE and ilp32e/lp64e ABIs

2023-03-28 Thread Edmund Raile via Phabricator via cfe-commits
recallmenot added a comment.

In D70401#4205333 , @pcwang-thead 
wrote:

> In D70401#4204511 , @recallmenot 
> wrote:
>
>> Hi, I'm working on CH32V003 for rust and it uses RV32EC core.
>> I tried replacing my distros llvm and clang with a patched version of this 
>> like this:
>>
>>   git clone https://aur.archlinux.org/llvm-git.git
>>   cd llvm-git
>>   mkdir src
>>   cd src
>>   git clone https://github.com/llvm/llvm-project.git
>>   cd llvm-project
>>   arc patch D70401
>>   cd ../..
>>   mv llvm-config.h src/
>>   makepkg -es
>>   sudo pacman -Rd --nodeps clang llvm
>>   makepkg -eid
>>
>> but that bricked my xfce-wayland-manjaro DE (one screen black)
>> And in config.toml if I put
>>
>>   [build]
>>   target = "riscv32i-unknown-none-elf"
>>   rustflags = [
>>  "-C", "target-feature=+e,+c"
>>   ]
>>
>> then build with cargo build
>> LLVM still complains it doesn't implement CodeGen for RV32E yet
>> What am I doing wrong?
>> Ended up reverting to repository llvm and clang, desktop now works again but 
>> CodeGen is obviously missing.
>
> I don't see any obvious problem here.
> I am not familiar with rust. Is `riscv32i-unknown-none-elf` a valid target 
> for `rustc`, it should be something like `riscv32-unknown-elf` in LLVM I 
> think. And is `target-feature=+e,+c` the right way to specify features?
> Can you please provide the whole command/arguments passed to LLVM?

Yeah so I looked at the at the target files of rustc, telling rustc to do RV32I 
will indeed result in RV32 and the way to enable the E and C features seems to 
be correct, BUT:
rust uses their own "special sauce" version of llvm and rustc needs to be built 
against that to enable the new features. I tried to apply (patch) the diff 
directly to rusts llvm branch but there were many errors, and I couldn't figure 
out how to apply them manually since some things are different.
I'm stuck, this is all way beyond my understanding. Sorry I can't test it for 
you guys.
What I did was:

  git clone https://github.com/rust-lang/rust.git
  cd rust
  nvim config.toml

  [llvm]
  download-ci-llvm = false

then I started building with

  ./x.py build

and as soon as the rust-llvm source was downloaded completely I aborted 
(CTRL+C).

then downloaded the raw diff from this page (button top right) into the rust 
llvm dir, opened a terminal in that dir and tried to patch with

  patch -p1 < D70401.diff

but that gives lots of errors
resolving them manually seems way beyond me, especially since patch seems to 
already use fuzzy matching


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70401

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


[PATCH] D146844: [clang-format] Handle '_' in ud-suffix for IntegerLiteralSeparator

2023-03-28 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

I'm not going to use it, but I like what you've done ;-)


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

https://reviews.llvm.org/D146844

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


[PATCH] D147030: [Clang][Driver] Default Generic_GCC::IsIntegratedAssemblerDefault to true

2023-03-28 Thread Brad Smith via Phabricator via cfe-commits
brad created this revision.
brad added a reviewer: MaskRay.
brad added a project: clang.
Herald added subscribers: s.egerton, simoncook, fedor.sergeev.
Herald added a project: All.
brad requested review of this revision.
Herald added a subscriber: pcwang-thead.

Invert the logic and have the default being true. Disable the few spots where 
it looks like IAS is currently not used.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147030

Files:
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/test/Driver/integrated-as.c


Index: clang/test/Driver/integrated-as.c
===
--- clang/test/Driver/integrated-as.c
+++ clang/test/Driver/integrated-as.c
@@ -12,5 +12,4 @@
 
 // NOFIAS-NOT: cc1as
 // NOFIAS: -cc1
-// NOFIAS: "-fno-verbose-asm"
 // NOFIAS: -no-integrated-as
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2916,44 +2916,15 @@
 
 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
   switch (getTriple().getArch()) {
-  case llvm::Triple::aarch64:
-  case llvm::Triple::aarch64_be:
-  case llvm::Triple::amdgcn:
-  case llvm::Triple::arm:
-  case llvm::Triple::armeb:
-  case llvm::Triple::avr:
-  case llvm::Triple::bpfel:
-  case llvm::Triple::bpfeb:
-  case llvm::Triple::csky:
-  case llvm::Triple::hexagon:
-  case llvm::Triple::lanai:
-  case llvm::Triple::loongarch32:
-  case llvm::Triple::loongarch64:
-  case llvm::Triple::m68k:
-  case llvm::Triple::mips:
-  case llvm::Triple::mipsel:
-  case llvm::Triple::mips64:
-  case llvm::Triple::mips64el:
-  case llvm::Triple::msp430:
-  case llvm::Triple::ppc:
-  case llvm::Triple::ppcle:
-  case llvm::Triple::ppc64:
-  case llvm::Triple::ppc64le:
-  case llvm::Triple::r600:
-  case llvm::Triple::riscv32:
-  case llvm::Triple::riscv64:
-  case llvm::Triple::sparc:
-  case llvm::Triple::sparcel:
-  case llvm::Triple::sparcv9:
-  case llvm::Triple::systemz:
-  case llvm::Triple::thumb:
-  case llvm::Triple::thumbeb:
-  case llvm::Triple::ve:
-  case llvm::Triple::x86:
-  case llvm::Triple::x86_64:
-return true;
-  default:
+  case llvm::Triple::nvptx:
+  case llvm::Triple::nvptx64:
+  case llvm::Triple::xcore:
 return false;
+  default:
+if (getTriple().getVendor() == llvm::Triple::Myriad)
+  return false;
+else
+  return true;
   }
 }
 


Index: clang/test/Driver/integrated-as.c
===
--- clang/test/Driver/integrated-as.c
+++ clang/test/Driver/integrated-as.c
@@ -12,5 +12,4 @@
 
 // NOFIAS-NOT: cc1as
 // NOFIAS: -cc1
-// NOFIAS: "-fno-verbose-asm"
 // NOFIAS: -no-integrated-as
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2916,44 +2916,15 @@
 
 bool Generic_GCC::IsIntegratedAssemblerDefault() const {
   switch (getTriple().getArch()) {
-  case llvm::Triple::aarch64:
-  case llvm::Triple::aarch64_be:
-  case llvm::Triple::amdgcn:
-  case llvm::Triple::arm:
-  case llvm::Triple::armeb:
-  case llvm::Triple::avr:
-  case llvm::Triple::bpfel:
-  case llvm::Triple::bpfeb:
-  case llvm::Triple::csky:
-  case llvm::Triple::hexagon:
-  case llvm::Triple::lanai:
-  case llvm::Triple::loongarch32:
-  case llvm::Triple::loongarch64:
-  case llvm::Triple::m68k:
-  case llvm::Triple::mips:
-  case llvm::Triple::mipsel:
-  case llvm::Triple::mips64:
-  case llvm::Triple::mips64el:
-  case llvm::Triple::msp430:
-  case llvm::Triple::ppc:
-  case llvm::Triple::ppcle:
-  case llvm::Triple::ppc64:
-  case llvm::Triple::ppc64le:
-  case llvm::Triple::r600:
-  case llvm::Triple::riscv32:
-  case llvm::Triple::riscv64:
-  case llvm::Triple::sparc:
-  case llvm::Triple::sparcel:
-  case llvm::Triple::sparcv9:
-  case llvm::Triple::systemz:
-  case llvm::Triple::thumb:
-  case llvm::Triple::thumbeb:
-  case llvm::Triple::ve:
-  case llvm::Triple::x86:
-  case llvm::Triple::x86_64:
-return true;
-  default:
+  case llvm::Triple::nvptx:
+  case llvm::Triple::nvptx64:
+  case llvm::Triple::xcore:
 return false;
+  default:
+if (getTriple().getVendor() == llvm::Triple::Myriad)
+  return false;
+else
+  return true;
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D147003: [clang-format] JSON Add ability to add a space before the colon

2023-03-28 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay marked an inline comment as done.
MyDeveloperDay added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:4155
 if (Right.is(tok::colon))
-  return false;
+  return Style.SpaceBeforeJsonColon;
   } else if (Style.isCSharp()) {

owenpan wrote:
> Do we need to check if `Left.is(tok::string_literal)`?
Hmm... maybe... I guess I was thinking all colons in JSON are to the right of 
string literals? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147003

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


[PATCH] D70401: [RISCV] CodeGen of RVE and ilp32e/lp64e ABIs

2023-03-28 Thread Wang Pengcheng via Phabricator via cfe-commits
pcwang-thead added a comment.

In D70401#4226549 , @recallmenot wrote:

> In D70401#4205333 , @pcwang-thead 
> wrote:
>
>> In D70401#4204511 , @recallmenot 
>> wrote:
>>
>>> Hi, I'm working on CH32V003 for rust and it uses RV32EC core.
>>> I tried replacing my distros llvm and clang with a patched version of this 
>>> like this:
>>>
>>>   git clone https://aur.archlinux.org/llvm-git.git
>>>   cd llvm-git
>>>   mkdir src
>>>   cd src
>>>   git clone https://github.com/llvm/llvm-project.git
>>>   cd llvm-project
>>>   arc patch D70401
>>>   cd ../..
>>>   mv llvm-config.h src/
>>>   makepkg -es
>>>   sudo pacman -Rd --nodeps clang llvm
>>>   makepkg -eid
>>>
>>> but that bricked my xfce-wayland-manjaro DE (one screen black)
>>> And in config.toml if I put
>>>
>>>   [build]
>>>   target = "riscv32i-unknown-none-elf"
>>>   rustflags = [
>>> "-C", "target-feature=+e,+c"
>>>   ]
>>>
>>> then build with cargo build
>>> LLVM still complains it doesn't implement CodeGen for RV32E yet
>>> What am I doing wrong?
>>> Ended up reverting to repository llvm and clang, desktop now works again 
>>> but CodeGen is obviously missing.
>>
>> I don't see any obvious problem here.
>> I am not familiar with rust. Is `riscv32i-unknown-none-elf` a valid target 
>> for `rustc`, it should be something like `riscv32-unknown-elf` in LLVM I 
>> think. And is `target-feature=+e,+c` the right way to specify features?
>> Can you please provide the whole command/arguments passed to LLVM?
>
> Yeah so I looked at the at the target files of rustc, telling rustc to do 
> RV32I will indeed result in RV32 and the way to enable the E and C features 
> seems to be correct, BUT:
> rust uses their own "special sauce" version of llvm and rustc needs to be 
> built against that to enable the new features. I tried to apply (patch) the 
> diff directly to rusts llvm branch but there were many errors, and I couldn't 
> figure out how to apply them manually since some things are different.
> I'm stuck, this is all way beyond my understanding. Sorry I can't test it for 
> you guys.
> What I did was:
>
>   git clone https://github.com/rust-lang/rust.git
>   cd rust
>   nvim config.toml
>
>   [llvm]
>   download-ci-llvm = false
>
> then I started building with
>
>   ./x.py build
>
> and as soon as the rust-llvm source was downloaded completely I aborted 
> (CTRL+C).
>
> then downloaded the raw diff from this page (button top right) into the rust 
> llvm dir, opened a terminal in that dir and tried to patch with
>
>   patch -p1 < D70401.diff
>
> but that gives lots of errors
> resolving them manually seems way beyond me, especially since patch seems to 
> already use fuzzy matching

So it seems that rust uses its own llvm branch based on released llvm branch, 
so I think you may download old version of this patch which is near the 
baseline of rust llvm branch and try again. :-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70401

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


[PATCH] D146507: [clang][dataflow][NFC] Eliminate StmtToEnvMap interface.

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

Changes in response to review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146507

Files:
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  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
@@ -40,29 +40,6 @@
 namespace clang {
 namespace dataflow {
 
-class StmtToEnvMapImpl : public StmtToEnvMap {
-public:
-  StmtToEnvMapImpl(
-  const ControlFlowContext &CFCtx,
-  llvm::ArrayRef>
-  BlockToState)
-  : CFCtx(CFCtx), BlockToState(BlockToState) {}
-
-  const Environment *getEnvironment(const Stmt &S) const override {
-auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
-assert(BlockIt != CFCtx.getStmtToBlock().end());
-if (!CFCtx.isBlockReachable(*BlockIt->getSecond()))
-  return nullptr;
-const auto &State = BlockToState[BlockIt->getSecond()->getBlockID()];
-assert(State);
-return &State->Env;
-  }
-
-private:
-  const ControlFlowContext &CFCtx;
-  llvm::ArrayRef> BlockToState;
-};
-
 /// Returns the index of `Block` in the successors of `Pred`.
 static int blockIndexInPredecessor(const CFGBlock &Pred,
const CFGBlock &Block) {
@@ -269,7 +246,7 @@
 TypeErasedDataflowAnalysisState PredState = *MaybePredState;
 if (Analysis.builtinOptions()) {
   if (const Stmt *PredTerminatorStmt = Pred->getTerminatorStmt()) {
-const StmtToEnvMapImpl StmtToEnv(AC.CFCtx, AC.BlockStates);
+const StmtToEnvMap StmtToEnv(AC.CFCtx, AC.BlockStates);
 auto [Cond, CondValue] =
 TerminatorVisitor(StmtToEnv, PredState.Env,
   blockIndexInPredecessor(*Pred, Block))
@@ -304,7 +281,7 @@
   AnalysisContext &AC) {
   const Stmt *S = Elt.getStmt();
   assert(S != nullptr);
-  transfer(StmtToEnvMapImpl(AC.CFCtx, AC.BlockStates), *S, InputState.Env);
+  transfer(StmtToEnvMap(AC.CFCtx, AC.BlockStates), *S, InputState.Env);
 }
 
 /// Built-in transfer function for `CFGInitializer`.
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -36,6 +36,16 @@
 namespace clang {
 namespace dataflow {
 
+const Environment *StmtToEnvMap::getEnvironment(const Stmt &S) const {
+  auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
+  assert(BlockIt != CFCtx.getStmtToBlock().end());
+  if (!CFCtx.isBlockReachable(*BlockIt->getSecond()))
+return nullptr;
+  const auto &State = BlockToState[BlockIt->getSecond()->getBlockID()];
+  assert(State);
+  return &State->Env;
+}
+
 static BoolValue &evaluateBooleanEquality(const Expr &LHS, const Expr &RHS,
   Environment &Env) {
   if (auto *LHSValue =
Index: clang/include/clang/Analysis/FlowSensitive/Transfer.h
===
--- clang/include/clang/Analysis/FlowSensitive/Transfer.h
+++ clang/include/clang/Analysis/FlowSensitive/Transfer.h
@@ -17,6 +17,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h"
 
 namespace clang {
 namespace dataflow {
@@ -24,12 +25,18 @@
 /// Maps statements to the environments of basic blocks that contain them.
 class StmtToEnvMap {
 public:
-  virtual ~StmtToEnvMap() = default;
-
-  /// Retrieves the environment of the basic block that contains `S`.
-  /// If `S` is reachable, returns a non-null pointer to the environment.
-  /// If `S` is not reachable, returns nullptr.
-  virtual const Environment *getEnvironment(const Stmt &S) const = 0;
+  StmtToEnvMap(const ControlFlowContext &CFCtx,
+   llvm::ArrayRef>
+   BlockToState)
+  : CFCtx(CFCtx), BlockToState(BlockToState) {}
+
+  /// Returns the environment of the basic block that contains `S`.
+  /// The result is guaranteed never to be null.
+  const Environment *getEnvironment(const Stmt &S) const;
+
+private:
+  const ControlFlowContext &CFCtx;
+  llvm::ArrayRef> BlockToState;
 };
 
 /// Evaluates `S` and updates `Env` accordingly.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D146507: [clang][dataflow][NFC] Eliminate StmtToEnvMap interface.

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



Comment at: clang/include/clang/Analysis/FlowSensitive/Transfer.h:35
+  /// The result is guaranteed never to be null.
+  virtual const Environment *getEnvironment(const Stmt &S) const {
+auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));

gribozavr2 wrote:
> Drop virtual?
Duh. Thanks for catching. Done!



Comment at: clang/include/clang/Analysis/FlowSensitive/Transfer.h:36-40
+auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
+assert(BlockIt != CFCtx.getStmtToBlock().end());
+const auto &State = BlockToState[BlockIt->getSecond()->getBlockID()];
+assert(State);
+return &State->Env;

ymandel wrote:
> Nit: why inline vs putting the definition in Transfer.cpp? I don't have a 
> good sense for the size cutoff on this decision but if it's only used there, 
> then might make sense just to keep the header leaner.
Good point. Done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146507

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


[PATCH] D146507: [clang][dataflow][NFC] Eliminate StmtToEnvMap interface.

2023-03-28 Thread Martin Böhme via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
mboehme marked 2 inline comments as done.
Closed by commit rG0608541aa4b5: [clang][dataflow][NFC] Eliminate StmtToEnvMap 
interface. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146507

Files:
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  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
@@ -40,29 +40,6 @@
 namespace clang {
 namespace dataflow {
 
-class StmtToEnvMapImpl : public StmtToEnvMap {
-public:
-  StmtToEnvMapImpl(
-  const ControlFlowContext &CFCtx,
-  llvm::ArrayRef>
-  BlockToState)
-  : CFCtx(CFCtx), BlockToState(BlockToState) {}
-
-  const Environment *getEnvironment(const Stmt &S) const override {
-auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
-assert(BlockIt != CFCtx.getStmtToBlock().end());
-if (!CFCtx.isBlockReachable(*BlockIt->getSecond()))
-  return nullptr;
-const auto &State = BlockToState[BlockIt->getSecond()->getBlockID()];
-assert(State);
-return &State->Env;
-  }
-
-private:
-  const ControlFlowContext &CFCtx;
-  llvm::ArrayRef> BlockToState;
-};
-
 /// Returns the index of `Block` in the successors of `Pred`.
 static int blockIndexInPredecessor(const CFGBlock &Pred,
const CFGBlock &Block) {
@@ -269,7 +246,7 @@
 TypeErasedDataflowAnalysisState PredState = *MaybePredState;
 if (Analysis.builtinOptions()) {
   if (const Stmt *PredTerminatorStmt = Pred->getTerminatorStmt()) {
-const StmtToEnvMapImpl StmtToEnv(AC.CFCtx, AC.BlockStates);
+const StmtToEnvMap StmtToEnv(AC.CFCtx, AC.BlockStates);
 auto [Cond, CondValue] =
 TerminatorVisitor(StmtToEnv, PredState.Env,
   blockIndexInPredecessor(*Pred, Block))
@@ -304,7 +281,7 @@
   AnalysisContext &AC) {
   const Stmt *S = Elt.getStmt();
   assert(S != nullptr);
-  transfer(StmtToEnvMapImpl(AC.CFCtx, AC.BlockStates), *S, InputState.Env);
+  transfer(StmtToEnvMap(AC.CFCtx, AC.BlockStates), *S, InputState.Env);
 }
 
 /// Built-in transfer function for `CFGInitializer`.
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -36,6 +36,16 @@
 namespace clang {
 namespace dataflow {
 
+const Environment *StmtToEnvMap::getEnvironment(const Stmt &S) const {
+  auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
+  assert(BlockIt != CFCtx.getStmtToBlock().end());
+  if (!CFCtx.isBlockReachable(*BlockIt->getSecond()))
+return nullptr;
+  const auto &State = BlockToState[BlockIt->getSecond()->getBlockID()];
+  assert(State);
+  return &State->Env;
+}
+
 static BoolValue &evaluateBooleanEquality(const Expr &LHS, const Expr &RHS,
   Environment &Env) {
   if (auto *LHSValue =
Index: clang/include/clang/Analysis/FlowSensitive/Transfer.h
===
--- clang/include/clang/Analysis/FlowSensitive/Transfer.h
+++ clang/include/clang/Analysis/FlowSensitive/Transfer.h
@@ -17,6 +17,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h"
 
 namespace clang {
 namespace dataflow {
@@ -24,12 +25,18 @@
 /// Maps statements to the environments of basic blocks that contain them.
 class StmtToEnvMap {
 public:
-  virtual ~StmtToEnvMap() = default;
-
-  /// Retrieves the environment of the basic block that contains `S`.
-  /// If `S` is reachable, returns a non-null pointer to the environment.
-  /// If `S` is not reachable, returns nullptr.
-  virtual const Environment *getEnvironment(const Stmt &S) const = 0;
+  StmtToEnvMap(const ControlFlowContext &CFCtx,
+   llvm::ArrayRef>
+   BlockToState)
+  : CFCtx(CFCtx), BlockToState(BlockToState) {}
+
+  /// Returns the environment of the basic block that contains `S`.
+  /// The result is guaranteed never to be null.
+  const Environment *getEnvironment(const Stmt &S) const;
+
+private:
+  const ControlFlowContext &CFCtx;
+  llvm::ArrayRef> BlockToState;
 };
 
 /// Evaluates `S` and updates `Env` accordingly.

[clang] 0608541 - [clang][dataflow][NFC] Eliminate StmtToEnvMap interface.

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

Author: Martin Braenne
Date: 2023-03-28T08:05:57Z
New Revision: 0608541aa4b5932c092251b846e7b87576e4f2d4

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

LOG: [clang][dataflow][NFC] Eliminate StmtToEnvMap interface.

Instead, we turn StmtToEnvMap into a concrete class with the implementation 
that used to live in StmtToEnvMapImpl.

The layering issue that originally required the indirection through the
`StmtToEnvMap` interface no longer exists.

Reviewed By: ymandel, xazax.hun, gribozavr2

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/Transfer.h
clang/lib/Analysis/FlowSensitive/Transfer.cpp
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/Transfer.h 
b/clang/include/clang/Analysis/FlowSensitive/Transfer.h
index db3d780bf35e5..58bb77c4905c5 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Transfer.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Transfer.h
@@ -17,6 +17,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h"
 
 namespace clang {
 namespace dataflow {
@@ -24,12 +25,18 @@ namespace dataflow {
 /// Maps statements to the environments of basic blocks that contain them.
 class StmtToEnvMap {
 public:
-  virtual ~StmtToEnvMap() = default;
-
-  /// Retrieves the environment of the basic block that contains `S`.
-  /// If `S` is reachable, returns a non-null pointer to the environment.
-  /// If `S` is not reachable, returns nullptr.
-  virtual const Environment *getEnvironment(const Stmt &S) const = 0;
+  StmtToEnvMap(const ControlFlowContext &CFCtx,
+   llvm::ArrayRef>
+   BlockToState)
+  : CFCtx(CFCtx), BlockToState(BlockToState) {}
+
+  /// Returns the environment of the basic block that contains `S`.
+  /// The result is guaranteed never to be null.
+  const Environment *getEnvironment(const Stmt &S) const;
+
+private:
+  const ControlFlowContext &CFCtx;
+  llvm::ArrayRef> BlockToState;
 };
 
 /// Evaluates `S` and updates `Env` accordingly.

diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index a1ed37da54c28..be5c9992a6d9d 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -36,6 +36,16 @@
 namespace clang {
 namespace dataflow {
 
+const Environment *StmtToEnvMap::getEnvironment(const Stmt &S) const {
+  auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
+  assert(BlockIt != CFCtx.getStmtToBlock().end());
+  if (!CFCtx.isBlockReachable(*BlockIt->getSecond()))
+return nullptr;
+  const auto &State = BlockToState[BlockIt->getSecond()->getBlockID()];
+  assert(State);
+  return &State->Env;
+}
+
 static BoolValue &evaluateBooleanEquality(const Expr &LHS, const Expr &RHS,
   Environment &Env) {
   if (auto *LHSValue =

diff  --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp 
b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
index 08bcd5e65e379..8e821e5a75d4a 100644
--- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -40,29 +40,6 @@
 namespace clang {
 namespace dataflow {
 
-class StmtToEnvMapImpl : public StmtToEnvMap {
-public:
-  StmtToEnvMapImpl(
-  const ControlFlowContext &CFCtx,
-  llvm::ArrayRef>
-  BlockToState)
-  : CFCtx(CFCtx), BlockToState(BlockToState) {}
-
-  const Environment *getEnvironment(const Stmt &S) const override {
-auto BlockIt = CFCtx.getStmtToBlock().find(&ignoreCFGOmittedNodes(S));
-assert(BlockIt != CFCtx.getStmtToBlock().end());
-if (!CFCtx.isBlockReachable(*BlockIt->getSecond()))
-  return nullptr;
-const auto &State = BlockToState[BlockIt->getSecond()->getBlockID()];
-assert(State);
-return &State->Env;
-  }
-
-private:
-  const ControlFlowContext &CFCtx;
-  llvm::ArrayRef> BlockToState;
-};
-
 /// Returns the index of `Block` in the successors of `Pred`.
 static int blockIndexInPredecessor(const CFGBlock &Pred,
const CFGBlock &Block) {
@@ -269,7 +246,7 @@ computeBlockInputState(const CFGBlock &Block, 
AnalysisContext &AC) {
 TypeErasedDataflowAnalysisState PredState = *MaybePredState;
 if (Analysis.builtinOptions()) {
   if (const Stmt *PredTerminatorStmt = Pred->getTerminatorStmt()) {
-const StmtToEnvMapImpl StmtToEnv(AC.CFCtx, AC.BlockSta

[PATCH] D146244: [clangd] Show used symbols on #include line hover.

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



Comment at: clang-tools-extra/clangd/Hover.cpp:1173
+if (Ref.RT != include_cleaner::RefType::Explicit ||
+UsedSymbolNames.find(getRefName(Ref)) != UsedSymbolNames.end())
+  return;

creating these symbol names for every reference is still a lot of waste, you 
can directly cache `Ref.Target` pointers, which are a lot cheaper. you can also 
store them in an `llvm::DenseSet` (`std::set` has O(logN) 
operation times). afterwards you can call `getRefName` only once, on the decls 
that we care about, and llvm::sort the result.

also because you're using just the declname, we might get erroneous 
de-duplication (symbols might have same name under different qualifiers) and 
all of a sudden `ns1::Foo` might suppress the analysis of `ns2::Foo` because 
logic here will think we've already seen a symbol named `Foo`



Comment at: clang-tools-extra/clangd/Hover.cpp:1178
+  // Find the highest-rank #include'd provider
+  const auto &MatchingIncludes = ConvertedMainFileIncludes.match(H);
+  if (MatchingIncludes.empty())

you can't actually keep a reference here, return is a value type. just `auto 
MatchingIncludes = ..`;



Comment at: clang-tools-extra/clangd/Hover.cpp:1178
+  // Find the highest-rank #include'd provider
+  const auto &MatchingIncludes = ConvertedMainFileIncludes.match(H);
+  if (MatchingIncludes.empty())

kadircet wrote:
> you can't actually keep a reference here, return is a value type. just `auto 
> MatchingIncludes = ..`;
nit: this might read easier with:
```
auto MatchingIncludes = ConvertedMainFileIncludes.match(H);
// No match for this provider in the main file.
if (MatchingIncludes.empty())
  continue;
// Check if our include matched this provider.
for (auto *MatchingInc : MatchingIncludes) {
  if (MatchingInc->Line == Inc.HashLine + 1)
UsedSymbolNames.insert(getRefName(Ref));
// Don't look for rest of the providers once we've found a match in the main 
file.
break;
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146244

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


[PATCH] D147032: [clang][dataflow][NFC] Put TransferVisitor in an unnamed namespace.

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

This avoids the risk of ODR violations.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147032

Files:
  clang/lib/Analysis/FlowSensitive/Transfer.cpp


Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -129,6 +129,8 @@
   return &UnpackedVal;
 }
 
+namespace {
+
 class TransferVisitor : public ConstStmtVisitor {
 public:
   TransferVisitor(const StmtToEnvMap &StmtToEnv, Environment &Env)
@@ -874,6 +876,8 @@
   Environment &Env;
 };
 
+} // namespace
+
 void transfer(const StmtToEnvMap &StmtToEnv, const Stmt &S, Environment &Env) {
   TransferVisitor(StmtToEnv, Env).Visit(&S);
 }


Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -129,6 +129,8 @@
   return &UnpackedVal;
 }
 
+namespace {
+
 class TransferVisitor : public ConstStmtVisitor {
 public:
   TransferVisitor(const StmtToEnvMap &StmtToEnv, Environment &Env)
@@ -874,6 +876,8 @@
   Environment &Env;
 };
 
+} // namespace
+
 void transfer(const StmtToEnvMap &StmtToEnv, const Stmt &S, Environment &Env) {
   TransferVisitor(StmtToEnv, Env).Visit(&S);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D146188: [Clang][DOC] Add documentation in for __builtin_flt_rounds and __builtin_set_flt_rounds

2023-03-28 Thread xiongji90 via Phabricator via cfe-commits
xiongji90 updated this revision to Diff 508925.
xiongji90 added a comment.

Add floating point environment section in UserManual.rst


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146188

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/UsersManual.rst


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -1368,6 +1368,24 @@
 Controlling Floating Point Behavior
 ---
 
+.. _floating-point-environment:
+
+Accessing the floating point environment
+
+Many targets allow floating point operations to be configured to control things
+such as how inexact results should be rounded and how exceptional conditions
+should be handled. This configuration is called the floating point environment.
+C and C++ restrict access to the floating point environment by default, and the
+compiler is allowed to assume that all operations are performed in the default
+environment. When code is compiled in this default mode, operations that depend
+on the environment (such as floating-point arithmetic and `FLT_ROUNDS`) may 
have
+undefined behavior if the dynamic environment is not the default environment; 
for
+example, `FLT_ROUNDS` may or may not simply return its default value for the 
target
+instead of reading the dynamic environment, and floating-point operations may 
be
+optimized as if the dynamic environment were the default.  Similarly, it is 
undefined
+behavior to change the floating point environment in this default mode, for 
example
+by calling the `fesetround` function.
+
 Clang provides a number of ways to control floating point behavior, including
 with command line options and source pragmas. This section
 describes the various floating point semantic modes and the corresponding 
options.
Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -3246,7 +3246,7 @@
 
double __builtin_canonicalize(double);
float __builtin_canonicalizef(float);
-   long double__builtin_canonicalizel(long double);
+   long double __builtin_canonicalizel(long double);
 
 Returns the platform specific canonical encoding of a floating point
 number. This canonicalization is useful for implementing certain
@@ -3254,6 +3254,28 @@
 `_ for
 more information on the semantics.
 
+``__builtin_flt_rounds`` and ``__builtin_set_flt_rounds``
+-
+
+.. code-block:: c
+
+   int __builtin_flt_rounds();
+   void __builtin_set_flt_rounds(int);
+
+Returns and sets current floating point rounding mode. The encoding of returned
+values and input parameters is same as the result of FLT_ROUNDS, specified by C
+standard:
+0  - toward zero
+1  - to nearest, ties to even
+2  - toward positive infinity
+3  - toward negative infinity
+4  - to nearest, ties away from zero
+The effect of passing some other value to ``__builtin_flt_rounds`` is
+implementation-defined. ``__builtin_set_flt_rounds`` is currently only 
supported
+to work on x86, x86_64, Arm and AArch64 targets. These builtins read and modify
+the floating-point environment, which is not always allowed and may have 
unexpected
+behavior. Please see the section on `Accessing the floating point environment 
`_
 for more information.
+
 String builtins
 ---
 


Index: clang/docs/UsersManual.rst
===
--- clang/docs/UsersManual.rst
+++ clang/docs/UsersManual.rst
@@ -1368,6 +1368,24 @@
 Controlling Floating Point Behavior
 ---
 
+.. _floating-point-environment:
+
+Accessing the floating point environment
+
+Many targets allow floating point operations to be configured to control things
+such as how inexact results should be rounded and how exceptional conditions
+should be handled. This configuration is called the floating point environment.
+C and C++ restrict access to the floating point environment by default, and the
+compiler is allowed to assume that all operations are performed in the default
+environment. When code is compiled in this default mode, operations that depend
+on the environment (such as floating-point arithmetic and `FLT_ROUNDS`) may have
+undefined behavior if the dynamic environment is not the default environment; for
+example, `FLT_ROUNDS` may or may not simply return its default value for the target
+instead of reading the dynamic environment, and floating-point operations may be
+optimized as if the dynamic environment were the de

[PATCH] D144870: [Clang][DebugInfo] Emit zero size bitfields in the debug info to delimit bitfields in different allocation units.

2023-03-28 Thread Juan Manuel Martinez Caamaño via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG488185cca387: [Clang][DebugInfo][AMDGPU] Emit zero size 
bitfields in the debug info to… (authored by jmmartinez).

Changed prior to commit:
  https://reviews.llvm.org/D144870?vs=508538&id=508926#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144870

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/CodeGen/TargetInfo.h
  clang/test/CodeGen/debug-info-bitfield-0-struct.c

Index: clang/test/CodeGen/debug-info-bitfield-0-struct.c
===
--- /dev/null
+++ clang/test/CodeGen/debug-info-bitfield-0-struct.c
@@ -0,0 +1,119 @@
+// RUN: %clang_cc1 -triple x86_64-unk-unk -o - -emit-llvm -debug-info-kind=limited %s | FileCheck --check-prefixes NOSEPARATOR,BOTH %s
+// RUN: %clang_cc1 -triple amdgcn-unk-unk -o - -emit-llvm -debug-info-kind=limited %s | FileCheck --check-prefixes SEPARATOR,BOTH %s
+
+struct First {
+  // BOTH-DAG: ![[FIRST:[0-9]+]] = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "First", file: !{{[0-9]+}}, line: {{[0-9]+}}, size: 32, elements: ![[FIRST_ELEMENTS:[0-9]+]])
+  // BOTH-DAG: ![[FIRST_ELEMENTS]] = !{![[FIRST_X:[0-9]+]], ![[FIRST_Y:[0-9]+]]}
+  // BOTH-DAG: ![[FIRST_X]] = !DIDerivedType(tag: DW_TAG_member, name: "x", scope: ![[FIRST]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, size: 4, flags: DIFlagBitField, extraData: i64 0)
+  // BOTH-DAG: ![[FIRST_Y]] = !DIDerivedType(tag: DW_TAG_member, name: "y", scope: ![[FIRST]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, size: 4, offset: 4, flags: DIFlagBitField, extraData: i64 0)
+  int : 0;
+  int x : 4;
+  int y : 4;
+};
+
+struct FirstDuplicate {
+  // BOTH-DAG: ![[FIRSTDUP:[0-9]+]] = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "FirstDuplicate", file: !{{[0-9]+}}, line: {{[0-9]+}}, size: 32, elements: ![[FIRSTDUP_ELEMENTS:[0-9]+]])
+  // BOTH-DAG: ![[FIRSTDUP_ELEMENTS]] = !{![[FIRSTDUP_X:[0-9]+]], ![[FIRSTDUP_Y:[0-9]+]]}
+  // BOTH-DAG: ![[FIRSTDUP_X]] = !DIDerivedType(tag: DW_TAG_member, name: "x", scope: ![[FIRSTDUP]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, size: 4, flags: DIFlagBitField, extraData: i64 0)
+  // BOTH-DAG: ![[FIRSTDUP_Y]] = !DIDerivedType(tag: DW_TAG_member, name: "y", scope: ![[FIRSTDUP]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, size: 4, offset: 4, flags: DIFlagBitField, extraData: i64 0)
+  int : 0;
+  int : 0;
+  int x : 4;
+  int y : 4;
+};
+
+struct Second {
+  // BOTH-DAG: ![[SECOND:[0-9]+]] = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "Second", file: !{{[0-9]+}}, line: {{[0-9]+}}, size: 64, elements: ![[SECOND_ELEMENTS:[0-9]+]])
+
+  // NOSEPARATOR-DAG: ![[SECOND_ELEMENTS]] = !{![[SECOND_X:[0-9]+]], ![[SECOND_Y:[0-9]+]]}
+  // SEPARATOR-DAG: ![[SECOND_ELEMENTS]] = !{![[SECOND_X:[0-9]+]], ![[SECOND_ZERO:[0-9]+]], ![[SECOND_Y:[0-9]+]]}
+
+  // BOTH-DAG: ![[SECOND_X]] = !DIDerivedType(tag: DW_TAG_member, name: "x", scope: ![[SECOND]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, size: 4, flags: DIFlagBitField, extraData: i64 0)
+  // SEPARATOR-DAG: ![[SECOND_ZERO]] = !DIDerivedType(tag: DW_TAG_member, scope: ![[SECOND]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, offset: 32, flags: DIFlagBitField, extraData: i64 32)
+  // BOTH-DAG: ![[SECOND_Y]] = !DIDerivedType(tag: DW_TAG_member, name: "y", scope: ![[SECOND]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, size: 4, offset: 32, flags: DIFlagBitField, extraData: i64 32)
+  int x : 4;
+  int : 0;
+  int y : 4;
+};
+
+struct SecondDuplicate {
+  // BOTH-DAG: ![[SECONDDUP:[0-9]+]] = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "SecondDuplicate", file: !{{[0-9]+}}, line: {{[0-9]+}}, size: 64, elements: ![[SECONDDUP_ELEMENTS:[0-9]+]])
+
+  // NOSEPARATOR-DAG: ![[SECONDDUP_ELEMENTS]] = !{![[SECONDDUP_X:[0-9]+]], ![[SECONDDUP_Y:[0-9]+]]}
+  // SEPARATOR-DAG: ![[SECONDDUP_ELEMENTS]] = !{![[SECONDDUP_X:[0-9]+]], ![[SECONDDUP_ZERO:[0-9]+]], ![[SECONDDUP_Y:[0-9]+]]}
+
+  // BOTH-DAG: ![[SECONDDUP_X]] = !DIDerivedType(tag: DW_TAG_member, name: "x", scope: ![[SECONDDUP]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, size: 4, flags: DIFlagBitField, extraData: i64 0)
+  // SEPARATOR-DAG: ![[SECONDDUP_ZERO]] = !DIDerivedType(tag: DW_TAG_member, scope: ![[SECONDDUP]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, offset: 32, flags: DIFlagBitField, extraData: i64 32)
+  // BOTH-DAG: ![[SECONDDUP_Y]] = !DIDerivedType(tag: DW_TAG_member, name: "y", scope: ![[SECONDDUP]], file: !{{[0-9]+}}, line: {{[0-9]+}}, baseType: !{{[0-9]+}}, size: 4, offset: 32, flags: DIFlagBitField, extraData: i64 32)
+  int x : 4;
+  int : 0;
+  int : 0;
+  int y : 4;
+};
+
+struct Last {
+  // BOTH-DA

[clang] 488185c - [Clang][DebugInfo][AMDGPU] Emit zero size bitfields in the debug info to delimit bitfields in different allocation units.

2023-03-28 Thread Juan Manuel MARTINEZ CAAMAÑO via cfe-commits

Author: Juan Manuel MARTINEZ CAAMAÑO
Date: 2023-03-28T10:07:32+02:00
New Revision: 488185cca3871a0ef2ec3b9b4c642dc6db6eeea5

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

LOG: [Clang][DebugInfo][AMDGPU] Emit zero size bitfields in the debug info to 
delimit bitfields in different allocation units.

Consider the following sturctures when targetting:

  struct foo {
int space[4];
char a : 8;
char b : 8;
char x : 8;
char y : 8;
  };

  struct bar {
int space[4];
char a : 8;
char b : 8;
char : 0;
char x : 8;
char y : 8;
  };

Even if both structs have the same layout in memory, they are handled
differenlty by the AMDGPU ABI.

With the following code:

// clang --target=amdgcn-amd-amdhsa -g -O1 example.c -S
char use_foo(struct foo f) { return f.y; }
char use_bar(struct bar b) { return b.y; }

For use_foo, the 'y' field is passed in v4
; v_ashrrev_i32_e32 v0, 24, v4
; s_setpc_b64 s[30:31]

For use_bar, the 'y' field is passed in v5
; v_bfe_i32 v0, v5, 8, 8
; s_setpc_b64 s[30:31]

To make this distinction, we record a single 0-size bitfield for every member 
that is preceded
by it.

Reviewed By: probinson

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

Added: 
clang/test/CodeGen/debug-info-bitfield-0-struct.c

Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGDebugInfo.h
clang/lib/CodeGen/TargetInfo.cpp
clang/lib/CodeGen/TargetInfo.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 0b4c24ac2555d..a5d2cf9650276 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -18,6 +18,7 @@
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
 #include "ConstantEmitter.h"
+#include "TargetInfo.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/DeclFriend.h"
@@ -1483,9 +1484,9 @@ llvm::DIType *CGDebugInfo::CreateType(const FunctionType 
*Ty,
   return F;
 }
 
-llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
-  llvm::DIScope *RecordTy,
-  const RecordDecl *RD) {
+llvm::DIDerivedType *
+CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
+llvm::DIScope *RecordTy, const RecordDecl *RD) 
{
   StringRef Name = BitFieldDecl->getName();
   QualType Ty = BitFieldDecl->getType();
   SourceLocation Loc = BitFieldDecl->getLocation();
@@ -1516,6 +1517,78 @@ llvm::DIType *CGDebugInfo::createBitFieldType(const 
FieldDecl *BitFieldDecl,
   Flags, DebugType, Annotations);
 }
 
+llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded(
+const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,
+llvm::ArrayRef PreviousFieldsDI, const RecordDecl *RD) {
+
+  if (!CGM.getTargetCodeGenInfo().shouldEmitDWARFBitFieldSeparators())
+return nullptr;
+
+  /*
+  Add a *single* zero-bitfield separator between two non-zero bitfields
+  separated by one or more zero-bitfields. This is used to distinguish between
+  structures such the ones below, where the memory layout is the same, but how
+  the ABI assigns fields to registers 
diff ers.
+
+  struct foo {
+int space[4];
+char a : 8; // on amdgpu, passed on v4
+char b : 8;
+char x : 8;
+char y : 8;
+  };
+  struct bar {
+int space[4];
+char a : 8; // on amdgpu, passed on v4
+char b : 8;
+char : 0;
+char x : 8; // passed on v5
+char y : 8;
+  };
+  */
+  if (PreviousFieldsDI.empty())
+return nullptr;
+
+  // If we already emitted metadata for a 0-length bitfield, nothing to do 
here.
+  auto *PreviousMDEntry =
+  PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back();
+  auto *PreviousMDField =
+  dyn_cast_or_null(PreviousMDEntry);
+  if (!PreviousMDField || !PreviousMDField->isBitField() ||
+  PreviousMDField->getSizeInBits() == 0)
+return nullptr;
+
+  auto PreviousBitfield = RD->field_begin();
+  std::advance(PreviousBitfield, BitFieldDecl->getFieldIndex() - 1);
+
+  assert(PreviousBitfield->isBitField());
+
+  ASTContext &Context = CGM.getContext();
+  if (!PreviousBitfield->isZeroLengthBitField(Context))
+return nullptr;
+
+  QualType Ty = PreviousBitfield->getType();
+  SourceLocation Loc = PreviousBitfield->getLocation();
+  llvm::DIFile *VUnit = getOrCreateFile(Loc);
+  llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
+  llvm::DIScope *RecordTy = BitFieldDI->getScope();
+
+  llvm::DIFile *File = getOrCreateFile(Loc);
+  unsigned Line = getLineNumber(Loc);
+
+  uint64_t StorageOffsetInBits =
+  cast(BitFieldDI->getStorageOffsetInBits())
+  ->getZExtValue();
+
+  llvm::DINode:

[PATCH] D146188: [Clang][DOC] Add documentation in for __builtin_flt_rounds and __builtin_set_flt_rounds

2023-03-28 Thread xiongji90 via Phabricator via cfe-commits
xiongji90 added a comment.

In D146188#4224902 , @rjmccall wrote:

> In D146188#4223249 , @xiongji90 
> wrote:
>
>> Hi, @rjmccall and @sepavloff 
>> In UserManual, we include a section `Controlling Floating Point Behavior`: 
>> https://github.com/llvm/llvm-project/blob/main/clang/docs/UsersManual.rst#controlling-floating-point-behavior
>>  , now we need to add a new section for floating-point environment, do we 
>> need to add the new section in parallel with `Controlling Floating Point 
>> Behavior` section or just put the section under `Controlling Floating Point 
>> Behavior`? And current `Controlling Floating Point Behavior` includes 
>> following description:
>> `Clang provides a number of ways to control floating point behavior, 
>> including with command line options and source pragmas.`
>> So, we need to update it to `Clang provides a number of ways to control 
>> floating point behavior, including with command line options, source pragmas 
>> and builtins.` and mention __builtin_flt_rounds, __builtin_set_flt_rounds in 
>> this section. Does this meet your expectation?
>
> I think you should add a subsection to Controlling Floating Point Behavior 
> about the floating-point environment.  You should not mention these builtins 
> there specifically — if you want an example function that reads or modifies 
> the environment, you should use one of the standard APIs like the 
> `FLT_ROUNDS` macro or the `fesetround` function.  You should also add the 
> documentation for these builtins where you've currently got it, and that 
> documentation can cross-reference to Controlling Floating Point Behavior.  
> Does that make sense?

Hi, @rjmccall 
I created floating point environment section, does it meet your expectation?
Thanks very much.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146188

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


[PATCH] D144870: [Clang][DebugInfo] Emit zero size bitfields in the debug info to delimit bitfields in different allocation units.

2023-03-28 Thread Juan Manuel Martinez Caamaño via Phabricator via cfe-commits
jmmartinez added a comment.

In D144870#4225437 , @probinson wrote:

> One entirely optional suggestion on the test. LGTM.

Thanks! I used `SECONDDUP` and `FIRSTDUP`.

And thanks a lot for the reviews!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144870

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


[PATCH] D147003: [clang-format] JSON Add ability to add a space before the colon

2023-03-28 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:4155
 if (Right.is(tok::colon))
-  return false;
+  return Style.SpaceBeforeJsonColon;
   } else if (Style.isCSharp()) {

MyDeveloperDay wrote:
> owenpan wrote:
> > Do we need to check if `Left.is(tok::string_literal)`?
> Hmm... maybe... I guess I was thinking all colons in JSON are to the right of 
> string literals? 
I think you're right. Please ignore my comment then, or maybe add an assertion 
if you like.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147003

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


[PATCH] D146634: [clang][USR] Prevent crashes when parameter lists have nulls

2023-03-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 508934.
kadircet added a comment.
Herald added a project: clang-tools-extra.

- Add test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146634

Files:
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang/lib/Index/USRGeneration.cpp


Index: clang/lib/Index/USRGeneration.cpp
===
--- clang/lib/Index/USRGeneration.cpp
+++ clang/lib/Index/USRGeneration.cpp
@@ -262,6 +262,12 @@
 
   // Mangle in type information for the arguments.
   for (auto *PD : D->parameters()) {
+// FIXME: Make sure we don't have nullptrs in parameter lists of function
+// decls.
+if (!PD) {
+  IgnoreResults = true;
+  return;
+}
 Out << '#';
 VisitType(PD->getType());
   }
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -4002,6 +4002,19 @@
   EXPECT_EQ(Second.activeParameter, 1);
 }
 
+TEST(CompletionTest, NoCrashTests) {
+  llvm::StringLiteral Cases[] = {
+  R"cpp(
+template  struct Foo {};
+auto a = [x(3)](Foo<^>){};
+)cpp",
+  };
+  for (auto Case : Cases) {
+SCOPED_TRACE(Case);
+auto Completions = completions(Case);
+  }
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang


Index: clang/lib/Index/USRGeneration.cpp
===
--- clang/lib/Index/USRGeneration.cpp
+++ clang/lib/Index/USRGeneration.cpp
@@ -262,6 +262,12 @@
 
   // Mangle in type information for the arguments.
   for (auto *PD : D->parameters()) {
+// FIXME: Make sure we don't have nullptrs in parameter lists of function
+// decls.
+if (!PD) {
+  IgnoreResults = true;
+  return;
+}
 Out << '#';
 VisitType(PD->getType());
   }
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -4002,6 +4002,19 @@
   EXPECT_EQ(Second.activeParameter, 1);
 }
 
+TEST(CompletionTest, NoCrashTests) {
+  llvm::StringLiteral Cases[] = {
+  R"cpp(
+template  struct Foo {};
+auto a = [x(3)](Foo<^>){};
+)cpp",
+  };
+  for (auto Case : Cases) {
+SCOPED_TRACE(Case);
+auto Completions = completions(Case);
+  }
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D146971: [Sema] Populate declarations inside TypeLocs for some invalid types

2023-03-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

i've added a reproducer for https://reviews.llvm.org/D146634, can you patch 
that into here? unfortunately i couldn't get it to crash in any place other 
than through clangd.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146971

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


[PATCH] D146101: [clang-format] Add DesignatedInitializerIndentWidth option.

2023-03-28 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/ContinuationIndenter.cpp:1665-1669
+  const auto DesignatedInitializerIndentWidth =
+  Style.DesignatedInitializerIndentWidth < 0
+  ? Style.ContinuationIndentWidth
+  : Style.DesignatedInitializerIndentWidth;
+  NewIndent = CurrentState.LastSpace + DesignatedInitializerIndentWidth;

jp4a50 wrote:
> owenpan wrote:
> > owenpan wrote:
> > > Using -1 to mean `ContinuationIndentWidth` is unnecessary and somewhat 
> > > confusing IMO.
> > Please disregard my comment above.
> Just to make sure we are on the same page, does this mean that you are happy 
> with the approach of using `-1` as a default value to indicate that 
> `ContinuationIndentWidth` should be used?
> 
> I did initially consider using `std::optional` and using empty 
> optional to indicate that `ContinuationIndentWidth` should be used but I saw 
> that `PPIndentWidth` was using `-1` to default to using `IndentWidth` so I 
> followed that precedent.
Yep! I would prefer the `optional`, but as you pointed out, we already got 
`PPIndentWidth`using `-1`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146101

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


[PATCH] D146892: [documentation]Fixed Random Typo

2023-03-28 Thread Sam Tebbs via Phabricator via cfe-commits
samtebbs added a comment.

Thank you Ayushi. Since you don't have commit access yet, I can commit it for 
you if you'd like. I do wonder if we should change the commit title to be 
something like "[documentation] Fix some typos". What do you think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146892

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


[PATCH] D147034: [clangd] Replace the hacky include-cleaner macro-reference implementation.

2023-03-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Now MainFileMacros preserves enough information, we perform a just-in-time
convertion to interop with include-cleaner::Macro for include-cleaer features.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147034

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -189,6 +189,10 @@
 #define DEF(X) const Foo *X;
 #define BAZ(X) const X x
 
+// No missing include insertion for ambiguous macro refs.
+#if defined(FOO)
+#endif
+
   void foo() {
 $b[[b]]();
 
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -136,22 +136,33 @@
 }
 
 std::vector
-collectMacroReferences(ParsedAST &AST) {
+convertMacroReferences(ParsedAST &AST) {
   const auto &SM = AST.getSourceManager();
-  //  FIXME: !!this is a hacky way to collect macro references.
-  std::vector Macros;
   auto &PP = AST.getPreprocessor();
-  for (const syntax::Token &Tok :
-   AST.getTokens().spelledTokens(SM.getMainFileID())) {
-auto Macro = locateMacroAt(Tok, PP);
-if (!Macro)
-  continue;
-if (auto DefLoc = Macro->Info->getDefinitionLoc(); DefLoc.isValid())
-  Macros.push_back(
-  {Tok.location(),
-   include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok.text(SM)),
-  DefLoc},
-   include_cleaner::RefType::Explicit});
+  std::vector Macros;
+  for (const auto &MAndRefs : AST.getMacros().MacroRefs) {
+for (const auto &Ref : MAndRefs.second) {
+  auto L = sourceLocationInMainFile(SM, Ref.Rng.start);
+  if (!L) {
+llvm::consumeError(L.takeError());
+continue;
+  }
+  if (const auto *Tok =
+ AST.getTokens().spelledTokenAt(*L)) {
+auto Macro = locateMacroAt(*Tok, PP);
+if (!Macro)
+  continue;
+
+if (auto DefLoc = Macro->Info->getDefinitionLoc(); DefLoc.isValid())
+  Macros.push_back(
+  {Tok->location(),
+   include_cleaner::Macro{
+   /*Name=*/PP.getIdentifierInfo(Tok->text(SM)), DefLoc},
+   Ref.InConditionalDirective
+   ? include_cleaner::RefType::Implicit
+   : include_cleaner::RefType::Explicit});
+  }
+}
   }
   return Macros;
 }
@@ -360,7 +371,7 @@
   const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());
 
   std::vector Macros =
-  collectMacroReferences(AST);
+  convertMacroReferences(AST);
   std::vector MissingIncludes;
   llvm::DenseSet Used;
   trace::Span Tracer("include_cleaner::walkUsed");


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -189,6 +189,10 @@
 #define DEF(X) const Foo *X;
 #define BAZ(X) const X x
 
+// No missing include insertion for ambiguous macro refs.
+#if defined(FOO)
+#endif
+
   void foo() {
 $b[[b]]();
 
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -136,22 +136,33 @@
 }
 
 std::vector
-collectMacroReferences(ParsedAST &AST) {
+convertMacroReferences(ParsedAST &AST) {
   const auto &SM = AST.getSourceManager();
-  //  FIXME: !!this is a hacky way to collect macro references.
-  std::vector Macros;
   auto &PP = AST.getPreprocessor();
-  for (const syntax::Token &Tok :
-   AST.getTokens().spelledTokens(SM.getMainFileID())) {
-auto Macro = locateMacroAt(Tok, PP);
-if (!Macro)
-  continue;
-if (auto DefLoc = Macro->Info->getDefinitionLoc(); DefLoc.isValid())
-  Macros.push_back(
-  {Tok.location(),
-   include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok.text(SM)),
-  DefLoc},
-   include_cleaner::RefType::Explicit});
+  std::vector Macros;
+  for (const auto &MAndRefs : AST.getMacros().MacroRefs) {
+for (const auto &Ref : MAndRefs.second) {
+  auto L = sourceLocationInMainFile(SM, Ref.Rng.start);
+  if (!L) {
+llvm::consumeError(L.takeError());
+continue;
+  }
+  if (cons

[PATCH] D146370: [Clang][OpenMP]Solved the the always truth condition in Arm64

2023-03-28 Thread Sam Tebbs via Phabricator via cfe-commits
samtebbs added a comment.

Thank you Samuel. Since you don't have commit access, I can commit this for you 
if you'd like.


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

https://reviews.llvm.org/D146370

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


[clang] 1b59809 - [C++20] [Modules] Don't create duplicated deduction guides for duplicated classes

2023-03-28 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2023-03-28T17:51:38+08:00
New Revision: 1b5980997bc03659a41329c3dff96ff274e13d85

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

LOG: [C++20] [Modules] Don't create duplicated deduction guides for duplicated 
classes

Close https://github.com/llvm/llvm-project/issues/56916

Within C++20 modules, we may have multiple same constructors in
multiple same RecordDecls. And it doesn't make sense naturally to create
duplicated deduction guides for the duplicated constructors.

Added: 
clang/test/Modules/pr56916.cppm

Modified: 
clang/docs/StandardCPlusPlusModules.rst
clang/lib/Sema/SemaTemplate.cpp
clang/test/Modules/pr61317.cppm

Removed: 




diff  --git a/clang/docs/StandardCPlusPlusModules.rst 
b/clang/docs/StandardCPlusPlusModules.rst
index ab34ba03ba14c..e14bbe4e1c655 100644
--- a/clang/docs/StandardCPlusPlusModules.rst
+++ b/clang/docs/StandardCPlusPlusModules.rst
@@ -660,26 +660,6 @@ the orders matter here in the case.
 
 This is tracked in: https://github.com/llvm/llvm-project/issues/61465
 
-Ambiguous deduction guide
-~
-
-Currently, when we call deduction guides in global module fragment,
-we may get incorrect diagnosing message like: `ambiguous deduction`.
-
-So if we're using deduction guide from global module fragment, we probably 
need to write:
-
-.. code-block:: c++
-
-  std::lock_guard lk(mutex);
-
-instead of
-
-.. code-block:: c++
-
-  std::lock_guard lk(mutex);
-
-This is tracked in: https://github.com/llvm/llvm-project/issues/56916
-
 Ignored PreferredName Attribute
 ~~~
 

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index c3338e4eaed28..befc1e73c4f35 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2601,13 +2601,21 @@ void Sema::DeclareImplicitDeductionGuides(TemplateDecl 
*Template,
   // FIXME: Skip constructors for which deduction must necessarily fail (those
   // for which some class template parameter without a default argument never
   // appears in a deduced context).
+  llvm::SmallPtrSet ProcessedCtors;
   bool AddedAny = false;
   for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
 D = D->getUnderlyingDecl();
 if (D->isInvalidDecl() || D->isImplicit())
   continue;
+
 D = cast(D->getCanonicalDecl());
 
+// Within C++20 modules, we may have multiple same constructors in
+// multiple same RecordDecls. And it doesn't make sense to create
+// duplicated deduction guides for the duplicated constructors.
+if (ProcessedCtors.count(D))
+  continue;
+
 auto *FTD = dyn_cast(D);
 auto *CD =
 dyn_cast_or_null(FTD ? FTD->getTemplatedDecl() : 
D);
@@ -2622,6 +2630,7 @@ void Sema::DeclareImplicitDeductionGuides(TemplateDecl 
*Template,
 }))
   continue;
 
+ProcessedCtors.insert(D);
 Transform.transformConstructor(FTD, CD);
 AddedAny = true;
   }

diff  --git a/clang/test/Modules/pr56916.cppm b/clang/test/Modules/pr56916.cppm
new file mode 100644
index 0..a8b49f0f6ff19
--- /dev/null
+++ b/clang/test/Modules/pr56916.cppm
@@ -0,0 +1,41 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+//
+// RUN: %clang_cc1 -std=c++20 %t/A.cppm -emit-module-interface -o %t/M-A.pcm
+// RUN: %clang_cc1 -std=c++20 %t/B.cppm -emit-module-interface -o %t/M-B.pcm
+// RUN: %clang_cc1 -std=c++20 %t/M.cppm -emit-module-interface -o %t/M.pcm \
+// RUN: -fprebuilt-module-path=%t
+// RUN: %clang_cc1 -std=c++20 %t/Use.cpp -fmodule-file=M=%t/M.pcm 
-fsyntax-only \
+// RUN: -verify
+
+//--- foo.h
+template 
+class Templ {
+public:
+Templ(T a) {}
+};
+
+//--- A.cppm
+module;
+#include "foo.h"
+export module M:A;
+export using ::Templ;
+
+//--- B.cppm
+module;
+#include "foo.h"
+export module M:B;
+
+//--- M.cppm
+export module M;
+export import :A;
+export import :B;
+
+//--- Use.cpp
+// expected-no-diagnostics
+import M;
+
+void func() {
+Templ t(5);
+}

diff  --git a/clang/test/Modules/pr61317.cppm b/clang/test/Modules/pr61317.cppm
index 4b9c1a3e97eab..4b54d26dc5a63 100644
--- a/clang/test/Modules/pr61317.cppm
+++ b/clang/test/Modules/pr61317.cppm
@@ -13,7 +13,7 @@
 #define _FOO
 
 template  struct Foo {
-  Foo(T) {}
+  Foo(T f) {}
 };
 
 template  Foo(T&) -> Foo;
@@ -24,6 +24,16 @@ struct Bar {
   void baz() const {}
 };
 
+template  struct Foo2 {
+  Foo2(T f) {}
+};
+
+struct Bar2 {
+  template 
+requires requires { Foo2{T()}; }
+  void baz2() const {}
+};
+
 #endif
 
 //--- A.cppm
@@ -32,6 +42,7 @@ module;
 export module A;
 export using ::Foo;
 export using ::Bar;
+export using ::Bar2;
 
 //--- B.cppm
 module;
@@ -46,4 +57,7 @@ import B;
 void use() {
   Bar _; 
   _.baz();
+
+  Bar2 __; 
+  __.baz2();
 }


[clang] 1bc2d43 - [clang][dataflow][NFC] Put TransferVisitor in an unnamed namespace.

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

Author: Martin Braenne
Date: 2023-03-28T10:03:39Z
New Revision: 1bc2d43e5c8fd0ec2e1a7e364fb42272ed7fb158

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

LOG: [clang][dataflow][NFC] Put TransferVisitor in an unnamed namespace.

This avoids the risk of ODR violations.

Reviewed By: gribozavr2

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

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/Transfer.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index be5c9992a6d9d..d255d27e52c45 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -139,6 +139,8 @@ static Value *maybeUnpackLValueExpr(const Expr &E, 
Environment &Env) {
   return &UnpackedVal;
 }
 
+namespace {
+
 class TransferVisitor : public ConstStmtVisitor {
 public:
   TransferVisitor(const StmtToEnvMap &StmtToEnv, Environment &Env)
@@ -884,6 +886,8 @@ class TransferVisitor : public 
ConstStmtVisitor {
   Environment &Env;
 };
 
+} // namespace
+
 void transfer(const StmtToEnvMap &StmtToEnv, const Stmt &S, Environment &Env) {
   TransferVisitor(StmtToEnv, Env).Visit(&S);
 }



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


[PATCH] D147032: [clang][dataflow][NFC] Put TransferVisitor in an unnamed namespace.

2023-03-28 Thread Martin Böhme via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1bc2d43e5c8f: [clang][dataflow][NFC] Put TransferVisitor in 
an unnamed namespace. (authored by mboehme).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D147032

Files:
  clang/lib/Analysis/FlowSensitive/Transfer.cpp


Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -139,6 +139,8 @@
   return &UnpackedVal;
 }
 
+namespace {
+
 class TransferVisitor : public ConstStmtVisitor {
 public:
   TransferVisitor(const StmtToEnvMap &StmtToEnv, Environment &Env)
@@ -884,6 +886,8 @@
   Environment &Env;
 };
 
+} // namespace
+
 void transfer(const StmtToEnvMap &StmtToEnv, const Stmt &S, Environment &Env) {
   TransferVisitor(StmtToEnv, Env).Visit(&S);
 }


Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -139,6 +139,8 @@
   return &UnpackedVal;
 }
 
+namespace {
+
 class TransferVisitor : public ConstStmtVisitor {
 public:
   TransferVisitor(const StmtToEnvMap &StmtToEnv, Environment &Env)
@@ -884,6 +886,8 @@
   Environment &Env;
 };
 
+} // namespace
+
 void transfer(const StmtToEnvMap &StmtToEnv, const Stmt &S, Environment &Env) {
   TransferVisitor(StmtToEnv, Env).Visit(&S);
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D146892: [documentation] Fix some typos

2023-03-28 Thread Ayushi Shukla via Phabricator via cfe-commits
ayushi-8102 added a comment.

Yeah I think It would be better this way!
I have changed the commit title.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146892

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


[PATCH] D146244: [clangd] Show used symbols on #include line hover.

2023-03-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 508948.
VitaNuo marked 3 inline comments as done.
VitaNuo added a comment.
Herald added a subscriber: mgrang.

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146244

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

Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -10,6 +10,7 @@
 #include "Annotations.h"
 #include "Config.h"
 #include "Hover.h"
+#include "TestFS.h"
 #include "TestIndex.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
@@ -2980,6 +2981,88 @@
 EXPECT_EQ(Case.HI.present().asMarkdown(), Case.ExpectedMarkdown);
 }
 
+TEST(Hover, UsedSymbols) {
+  struct {
+const char *Code;
+const std::function ExpectedBuilder;
+  } Cases[] = {{R"cpp(
+  #include ^"bar.h"
+  int fstBar = bar1();
+  int sndBar = bar2();
+  Bar bar;
+  int macroBar = BAR;
+)cpp",
+[](HoverInfo &HI) {
+  HI.UsedSymbolNames = {"BAR", "Bar", "bar1", "bar2"};
+}},
+   {R"cpp(
+  #in^clude 
+  std::vector vec;
+)cpp",
+[](HoverInfo &HI) { HI.UsedSymbolNames = {"vector"}; }},
+   {R"cpp(
+  #in^clude "public.h"
+  #include "private.h"
+  int fooVar = foo();
+)cpp",
+[](HoverInfo &HI) { HI.UsedSymbolNames = {"foo"}; }},
+   {R"cpp(
+  #include "bar.h"
+  #include "for^ward.h"
+  Bar *x;
+)cpp",
+[](HoverInfo &HI) { HI.UsedSymbolNames = {}; }},
+   {R"cpp(
+  #include "b^ar.h"
+  #define DEF(X) const Bar *X
+  DEF(a);
+)cpp",
+[](HoverInfo &HI) { HI.UsedSymbolNames = {"Bar"}; }},
+{R"cpp(
+  #in^clude "bar.h"
+  #define BAZ(X) const X x
+  BAZ(Bar);
+)cpp",
+[](HoverInfo &HI) { HI.UsedSymbolNames = {"Bar"}; }
+}
+};
+  for (const auto &Case : Cases) {
+Annotations Code{Case.Code};
+SCOPED_TRACE(Code.code());
+
+TestTU TU;
+TU.Filename = "foo.cpp";
+TU.Code = Code.code();
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["private.h"] = guard(R"cpp(
+  // IWYU pragma: private, include "public.h"
+  int foo(); 
+)cpp");
+TU.AdditionalFiles["public.h"] = guard("");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.AdditionalFiles["forward.h"] = guard("class Bar;");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+auto H = getHover(AST, Code.point(), format::getLLVMStyle(), nullptr);
+ASSERT_TRUE(H);
+HoverInfo Expected;
+Case.ExpectedBuilder(Expected);
+SCOPED_TRACE(H->present().asMarkdown());
+EXPECT_EQ(H->UsedSymbolNames, Expected.UsedSymbolNames);
+  }
+}
+
 TEST(Hover, DocsFromIndex) {
   Annotations T(R"cpp(
   template  class X {};
@@ -3369,7 +3452,21 @@
   R"(stdio.h
 
 /usr/include/stdio.h)",
-  }};
+  },
+  {[](HoverInfo &HI) {
+ HI.Name = "foo.h";
+ HI.UsedSymbolNames = {"Foo", "Bar", "Baz"};
+   },
+   R"(foo.h
+
+provides Foo, Bar, Baz)"},
+  {[](HoverInfo &HI) {
+ HI.Name = "foo.h";
+ HI.UsedSymbolNames = {"Foo", "Bar", "Baz", "Foobar", "Qux", "Quux"};
+   },
+   R"(foo.h
+
+provides Foo, Bar, Baz, Foobar, Qux and 1 more)"}};
 
   for (const auto &C : Cases) {
 HoverInfo HI;
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -78,6 +78,9 @@
 /// representation. The spelling contains the ""<> characters.
 std::string spellHeader(ParsedAST &AST, const FileEntry *Ma

[PATCH] D146244: [clangd] Show used symbols on #include line hover.

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

Thanks for the comments, see the updated version.




Comment at: clang-tools-extra/clangd/Hover.cpp:1173
+if (Ref.RT != include_cleaner::RefType::Explicit ||
+UsedSymbolNames.find(getRefName(Ref)) != UsedSymbolNames.end())
+  return;

kadircet wrote:
> creating these symbol names for every reference is still a lot of waste, you 
> can directly cache `Ref.Target` pointers, which are a lot cheaper. you can 
> also store them in an `llvm::DenseSet` (`std::set` has O(logN) 
> operation times). afterwards you can call `getRefName` only once, on the 
> decls that we care about, and llvm::sort the result.
> 
> also because you're using just the declname, we might get erroneous 
> de-duplication (symbols might have same name under different qualifiers) and 
> all of a sudden `ns1::Foo` might suppress the analysis of `ns2::Foo` because 
> logic here will think we've already seen a symbol named `Foo`
Ok, I am storing `include_cleaner::Symbols` now (not the Decls, since those 
would require a switch on the symbol kind, etc.) and `llvm::sort`'ing the 
result then.



Comment at: clang-tools-extra/clangd/Hover.cpp:1178
+  // Find the highest-rank #include'd provider
+  const auto &MatchingIncludes = ConvertedMainFileIncludes.match(H);
+  if (MatchingIncludes.empty())

kadircet wrote:
> kadircet wrote:
> > you can't actually keep a reference here, return is a value type. just 
> > `auto MatchingIncludes = ..`;
> nit: this might read easier with:
> ```
> auto MatchingIncludes = ConvertedMainFileIncludes.match(H);
> // No match for this provider in the main file.
> if (MatchingIncludes.empty())
>   continue;
> // Check if our include matched this provider.
> for (auto *MatchingInc : MatchingIncludes) {
>   if (MatchingInc->Line == Inc.HashLine + 1)
> UsedSymbolNames.insert(getRefName(Ref));
> // Don't look for rest of the providers once we've found a match in the main 
> file.
> break;
> }
> ```
```
for (auto *MatchingInc : MatchingIncludes) {
  if (MatchingInc->Line == Inc.HashLine + 1)
UsedSymbolNames.insert(getRefName(Ref));
}
```
I'm not sure I agree that this snippet is better. It's more verbose than the 
current version, and IMO matching the hovered include against the provider is 
quite readable already. 

I'm using your suggestions for the comments now, thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146244

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


[PATCH] D146814: [Flang] Add debug flag to enable current debug information pass

2023-03-28 Thread Sacha Ballantyne via Phabricator via cfe-commits
SBallantyne updated this revision to Diff 508949.
SBallantyne marked an inline comment as done.
SBallantyne added a comment.

Add common function addDebugKindInfo, update warning message


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146814

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CodeGenOptions.def
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/include/flang/Tools/CLOptions.inc
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mlir-debug-pass-pipeline.f90

Index: flang/test/Driver/mlir-debug-pass-pipeline.f90
===
--- /dev/null
+++ flang/test/Driver/mlir-debug-pass-pipeline.f90
@@ -0,0 +1,83 @@
+! Test the debug pass pipeline
+
+! RUN: %flang -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline -o /dev/null %s 2>&1 | FileCheck --check-prefixes=ALL,NO-DEBUG %s
+
+! RUN: %flang -g0 -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,NO-DEBUG %s
+! RUN: %flang -g -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG %s
+! RUN: %flang -g1 -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG %s
+! RUN: %flang -gline-tables-only -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG %s
+! RUN: %flang -gline-directives-only -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG,DEBUG-DIRECTIVES %s
+! RUN: %flang -g2 -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG,DEBUG-CONSTRUCT %s
+! RUN: %flang -g3 -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG,DEBUG-CONSTRUCT %s
+
+! RUN: not %flang_fc1 -debug-info-kind=invalid -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=DEBUG-ERR %s
+
+! REQUIRES: asserts
+
+end program
+
+! DEBUG-CONSTRUCT: warning: Unsupported debug option: constructor
+! DEBUG-DIRECTIVES: warning: Unsupported debug option: line-directives-only
+!
+! DEBUG-ERR: error: invalid value 'invalid' in '-debug-info-kind=invalid'
+! DEBUG-ERR-NOT: Pass statistics report
+
+! ALL: Pass statistics report
+
+! ALL: Fortran::lower::VerifierPass
+! ALL-NEXT: LowerHLFIRIntrinsics
+! ALL-NEXT: BufferizeHLFIR
+! ALL-NEXT: ConvertHLFIRtoFIR
+! ALL-NEXT: CSE
+! Ideally, we need an output with only the pass names, but
+! there is currently no way to get that, so in order to
+! guarantee that the passes are in the expected order
+! (i.e. use -NEXT) we have to check the statistics output as well.
+! ALL-NEXT:   (S) 0 num-cse'd - Number of operations CSE'd
+! ALL-NEXT:   (S) 0 num-dce'd - Number of operations DCE'd
+
+! ALL-NEXT: 'func.func' Pipeline
+! ALL-NEXT:   ArrayValueCopy
+! ALL-NEXT:   CharacterConversion
+
+! ALL-NEXT: Canonicalizer
+! ALL-NEXT: SimplifyRegionLite
+! ALL-NEXT: CSE
+! ALL-NEXT:   (S) 0 num-cse'd - Number of operations CSE'd
+! ALL-NEXT:   (S) 0 num-dce'd - Number of operations DCE'd
+
+! ALL-NEXT: 'func.func' Pipeline
+! ALL-NEXT:   MemoryAllocationOpt
+
+! ALL-NEXT: Inliner
+! ALL-NEXT: SimplifyRegionLite
+! ALL-NEXT: CSE
+! ALL-NEXT:   (S) 0 num-cse'd - Number of operations CSE'd
+! ALL-NEXT:   (S) 0 num-dce'd - Number of operations DCE'd
+
+! ALL-NEXT: 'func.func' Pipeline
+! ALL-NEXT:   PolymorphicOpConversion
+! ALL-NEXT:   CFGConversion
+
+! ALL-NEXT: SCFToControlFlow
+! ALL-NEXT: Canonicalizer
+! ALL-NEXT: SimplifyRegionLite
+! ALL-NEXT: CSE
+! ALL-NEXT:   (S) 0 num-cse'd - Number of operations CSE'd
+! ALL-NEXT:   (S) 0 num-dce'd - Number of operations DCE'd
+! ALL-NEXT: BoxedProcedurePass
+
+! ALL-NEXT: Pipeline Collection : ['fir.global', 'func.func']
+! ALL-NEXT:   'fir.global' Pipeline
+! ALL-NEXT:AbstractResultOnGlobalOpt
+! ALL-NEXT:  'func.func' Pipeline
+! ALL-NEXT:AbstractResultOnFuncOpt
+
+! ALL-NEXT: CodeGenRewrite
+! ALL-NEXT:   (S) 0 num-dce'd - Number of operations eliminated
+! ALL-NEXT: TargetRewrite
+! ALL-NEXT: ExternalNameConversion
+! DEBUG-NEXT: AddDebugFoundation
+! NO-DEBUG-NOT: AddDebugFoundation
+! ALL-NEXT: FIRToLLVMLowering
+! ALL-NOT: LLVMIRLoweringPass
Index: f

[PATCH] D146908: [clang][MinGW] Add asan link flags before other libs and objects

2023-03-28 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

I tested this, and this does fix the repro from the linked issue.

I wonder if we do want to move all of these before the app itself, or if it's 
enough to just move the reference to `asan_dynamic-.dll.a` earlier, and 
keep the rest as it was? Especially the whole-archive bit ends up linking a 
bunch of things statically, ordered way before the app itself. On one hand, I 
wonder if it would have subtle effects that we don't notice until way later, 
and we should only change as little as we need (moving the import library 
reference earlier), or if there are other potential benefits to moving the 
wholearchive-linked bits earlier too? (I'm wondering about things like 
constructor execution orders and such.)




Comment at: clang/test/Driver/mingw-sanitizers.c:1
-// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-I686 %s
-// ASAN-I686: "{{.*}}libclang_rt.asan_dynamic-i386.dll.a"
-// ASAN-I686: "{{[^"]*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a"
-// ASAN-I686: "--require-defined" "___asan_seh_interceptor"
-// ASAN-I686: "--whole-archive" 
"{{.*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a" "--no-whole-archive"
-
-// RUN: %clang -target x86_64-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-X86_64 %s
-// ASAN-X86_64: "{{.*}}libclang_rt.asan_dynamic-x86_64.dll.a"
+// RUN: echo -n > %t.a
+// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address -lcomponent 
%/t.a 2>&1 | FileCheck --check-prefixes=ASAN-ALL,ASAN-I686 -DINPUT=%/t.a %s

Hm, what does this do - some sort of more portable version of just touching a 
file to create it?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146908

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


[PATCH] D147037: [Clang][ICE] Corrected invalid invalid parameter index on some attributes with invalid indices applied to varargs functions

2023-03-28 Thread Samuel Maina via Phabricator via cfe-commits
samuelmaina created this revision.
Herald added a subscriber: arphaman.
Herald added a reviewer: aaron.ballman.
Herald added a project: All.
samuelmaina requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147037

Files:
  clang/lib/Sema/SemaDeclAttr.cpp


Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -3763,7 +3763,8 @@
   ParamIdx Idx;
   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
 return;
-
+  if (Idx.getASTIndex() >= getFunctionOrMethodNumParams(D))
+return;
   // Make sure the format string is really a string.
   QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
 


Index: clang/lib/Sema/SemaDeclAttr.cpp
===
--- clang/lib/Sema/SemaDeclAttr.cpp
+++ clang/lib/Sema/SemaDeclAttr.cpp
@@ -3763,7 +3763,8 @@
   ParamIdx Idx;
   if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
 return;
-
+  if (Idx.getASTIndex() >= getFunctionOrMethodNumParams(D))
+return;
   // Make sure the format string is really a string.
   QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136103: OpenMP asynchronous memory copy support

2023-03-28 Thread Jan-Patrick Lehr via Phabricator via cfe-commits
jplehr updated this revision to Diff 508955.
jplehr added a comment.
Herald added a subscriber: sunshaoce.

Rebase to make ready for land


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136103

Files:
  openmp/libomptarget/include/interop.h
  openmp/libomptarget/src/api.cpp
  openmp/libomptarget/src/exports
  openmp/libomptarget/src/private.h
  openmp/libomptarget/test/api/omp_target_memcpy_async1.c
  openmp/libomptarget/test/api/omp_target_memcpy_async2.c
  openmp/libomptarget/test/api/omp_target_memcpy_rect_async1.c
  openmp/libomptarget/test/api/omp_target_memcpy_rect_async2.c

Index: openmp/libomptarget/test/api/omp_target_memcpy_rect_async2.c
===
--- /dev/null
+++ openmp/libomptarget/test/api/omp_target_memcpy_rect_async2.c
@@ -0,0 +1,89 @@
+// RUN: %libomptarget-compile-run-and-check-nvptx64-nvidia-cuda
+
+#include 
+#include 
+
+#define NUM_DIMS 3
+
+int main () {
+  int d = omp_get_default_device ();
+  int id = omp_get_initial_device ();
+  int a[128], b[64], c[128], e[16], q[128], i;
+  void *p;
+  
+  if (d < 0 || d >= omp_get_num_devices ())
+d = id;
+
+  p = omp_target_alloc (130 * sizeof (int), d);
+  if (p == NULL)
+return 0;
+  
+  for (i = 0; i < 128; i++)
+q[i] = 0;
+  if (omp_target_memcpy (p, q, 128 * sizeof (int), 0, 0, d, id) != 0)
+abort ();
+  
+  size_t volume[NUM_DIMS] = { 2, 2, 3 };
+  size_t dst_offsets[NUM_DIMS] = { 0, 0, 0 };
+  size_t src_offsets[NUM_DIMS] = { 0, 0, 0 };
+  size_t dst_dimensions[NUM_DIMS] = { 3, 4, 5 };
+  size_t src_dimensions[NUM_DIMS] = { 2, 3, 4 };
+  
+  for (i = 0; i < 128; i++)
+a[i] = 42;
+  for (i = 0; i < 64; i++)
+b[i] = 24;
+  for (i = 0; i < 128; i++)
+c[i] = 0;
+  for (i = 0; i < 16; i++)
+e[i] = 77;
+
+  omp_depend_t obj[2];
+  
+#pragma omp parallel num_threads(5)
+#pragma omp single
+  {
+#pragma omp task depend (out: p)
+omp_target_memcpy (p, a, 128 * sizeof (int), 0, 0, d, id);
+
+#pragma omp task depend(inout: p)
+omp_target_memcpy (p, b, 64 * sizeof (int), 0, 0, d, id);
+
+#pragma omp task depend(out: c)
+for (i = 0; i < 128; i++)
+  c[i] = i + 1;
+
+#pragma omp depobj(obj[0]) depend(inout: p)
+#pragma omp depobj(obj[1]) depend(in: c)
+
+/*  This produces: 1 2 3 - - 5 6 7 - - at positions 0..9 and
+	13 14 15 - - 17 18 19 - - at positions 20..29.  */
+omp_target_memcpy_rect_async (p, c, sizeof (int), NUM_DIMS, volume,
+  dst_offsets, src_offsets, dst_dimensions,
+  src_dimensions, d, id, 2, obj);
+
+#pragma omp task depend(in: p)
+omp_target_memcpy (p, e, 16 * sizeof (int), 0, 0, d, id);
+  }
+  
+#pragma omp taskwait
+  
+  if (omp_target_memcpy (q, p, 128 * sizeof(int), 0, 0, id, d) != 0)
+abort ();
+  
+  for (i = 0; i < 16; ++i)
+if (q[i] != 77)
+  abort ();
+  if (q[20] != 13 || q[21] != 14 || q[22] != 15 || q[25] != 17 || q[26] != 18
+  || q[27] != 19)
+abort ();
+  for (i = 28; i < 64; ++i)
+if (q[i] != 24)
+  abort ();
+  for (i = 64; i < 128; ++i)
+   if (q[i] != 42)
+ abort ();
+  
+  omp_target_free (p, d);
+  return 0;
+}
Index: openmp/libomptarget/test/api/omp_target_memcpy_rect_async1.c
===
--- /dev/null
+++ openmp/libomptarget/test/api/omp_target_memcpy_rect_async1.c
@@ -0,0 +1,66 @@
+// RUN: %libomptarget-compile-run-and-check-nvptx64-nvidia-cuda
+
+#include 
+#include 
+#include 
+
+#define NUM_DIMS 3
+
+int main() {
+  int d = omp_get_default_device ();
+  int id = omp_get_initial_device ();
+  int q[128], q2[128], i;
+  void *p;
+  
+  if (d < 0 || d >= omp_get_num_devices ())
+d = id;
+  
+  p = omp_target_alloc (130 * sizeof (int), d);
+  if (p == NULL)
+return 0;
+
+  if (omp_target_memcpy_rect_async (NULL, NULL, 0, 0, NULL, NULL, NULL, NULL,
+NULL, d, id, 0, NULL) < 3
+  || omp_target_memcpy_rect_async (NULL, NULL, 0, 0, NULL, NULL, NULL, NULL,
+   NULL, id, d, 0, NULL) < 3
+  || omp_target_memcpy_rect_async (NULL, NULL, 0, 0, NULL, NULL, NULL, NULL,
+   NULL, id, id, 0, NULL) < 3)
+abort ();
+ 
+  for (i = 0; i < 128; i++)
+q[i] = 0;
+  if (omp_target_memcpy (p, q, 128 * sizeof (int), 0, 0, d, id) != 0)
+abort ();
+  
+  for (i = 0; i < 128; i++)
+q[i] = i + 1;
+  
+  size_t volume[NUM_DIMS] = { 1, 2, 3 };
+  size_t dst_offsets[NUM_DIMS] = { 0, 0, 0 };
+  size_t src_offsets[NUM_DIMS] = { 0, 0, 0 };
+  size_t dst_dimensions[NUM_DIMS] = { 3, 4, 5 };
+  size_t src_dimensions[NUM_DIMS] = { 2, 3, 4 };
+  
+  if (omp_target_memcpy_rect_async (p, q, sizeof (int), NUM_DIMS, volume,
+dst_offsets, src_offsets, dst_dimensions,
+src_dimensions, d, id, 0, NULL) != 0)
+abort ();
+  
+#pragma omp taskwait
+  
+  for (i = 0; i < 128; i++)
+q2[i] = 0;
+  if (omp_target_memcpy (q2, p, 128 * sizeof (int), 0, 0, id, d) != 0)
+   

[PATCH] D139010: [clang][WebAssembly] Implement support for table types and builtins

2023-03-28 Thread Paulo Matos via Phabricator via cfe-commits
pmatos added a comment.

@aaron.ballman Any further comments on this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139010

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


[PATCH] D146814: [Flang] Add debug flag to enable current debug information pass

2023-03-28 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski accepted this revision.
awarzynski added a comment.
This revision is now accepted and ready to land.

LGTM, thanks for working on this! (please fix the name in CommonArgs.h before 
landing this)

It would be great to see a test that checks for debug info in the generated 
FIR/MLIR/LLVM-IR/ASM file. But that could happen in a separate patch.




Comment at: clang/lib/Driver/ToolChains/CommonArgs.h:111
+llvm::codegenoptions::DebugInfoKind
+DebugLevelToInfoKind(const llvm::opt::Arg &A);
+

CamelCase or camelCase? ;-)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146814

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


[PATCH] D146971: [Sema] Populate declarations inside TypeLocs for some invalid types

2023-03-28 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

In D146971#4224540 , @erichkeane 
wrote:

> Ah, hrmph. I guess I was just hoping for some assert (perhaps even in 
> `GetFullTypeForDeclarator`?) to assert in order to give future folks a hint 
> as to why their change crashes?  Basically, whenever the 
> `FunctionType`/`FunctionTypeLoc` are 'finalized' as a check perhaps?  Not 
> really looking for a refactor, so much as an assert to prevent us from 
> getting here again.

Yeah, that makes a lot of sense. We need to fix the `FIXMEs` for that to work, 
I'm eager to try this in follow-ups. But probably not in this particular change 
as it seems like a lot of work and this is already moving in the right 
direction.

We probably need asserts in two places: `GetFullTypeForDeclarator` and 
`getTrivialTypeSourceInfo`.
I'm less worried about the former, but fixing `getTrivialTypeSourceInfo` might 
be harder as it has a lot of call sites and I suspect some of them actually 
pass `FunctionType` as inputs. The assert would basically prohibit creating 
`FunctionTypeLoc` without parameter declarations.
I don't think it's unreasonable, the code that produces `FunctionTypeLoc` 
without having parameters should either find the corresponding parameters or be 
rewritten to use `QualType`  instead of `TypeLoc`, which does not need 
parameters.
But I expect this to be a lot of work to actually update the callsites, and 
this will probably take quite some time.




Comment at: clang/lib/Sema/SemaType.cpp:5949
   assert(!T.isNull() && "T must not be null at the end of this function");
-  if (D.isInvalidType())
+  if (!AreDeclaratorChunksValid)
 return Context.getTrivialTypeSourceInfo(T);

erichkeane wrote:
> ilya-biryukov wrote:
> > erichkeane wrote:
> > > Shouldn't the `D.setInvalidType(true)` in each of the branches work here? 
> > >  So this variable is unnecessary?  Else this is a good change IMO. 
> > (Let me know if I'm misreading the suggestion, I was not sure if my 
> > understanding is correct).
> > If we call `setInvalidType` more, we would actually get more crashes as the 
> > problematic branch is the one that calls `getTrivialTypeSourceInfo`.
> > To avoid the extra variable, we could instead ensure that the type always 
> > gets replaced with something trivial `T = Context.IntTy`. But I didn't want 
> > to go this path because this causes worse error recovery (going from 
> > something like `void()` to ``) and 
> > possibly correctness issues (e.g. will we start getting function-decls or 
> > lambdas that do not have function types and other assertions may fire).
> My suggestion was that `setInvalidType` is called everywhere that 
> `AreDeclatorChunksValid` above (sans 1 perhaps?). So my question was whether 
> this introduced variable was necessary.
Ah, thanks for clarifying the question.
`setInvalidType` is called in much more places and the point of this patch is 
to capture a subcategory of invalid types that still follow the declarator 
structure.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146971

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


[PATCH] D140722: [OpenMP] Prefix outlined and reduction func names with original func's name

2023-03-28 Thread Itay Bookstein via Phabricator via cfe-commits
nextsilicon-itay-bookstein added a comment.

Passes CI. How should I proceed w.r.t. libomptarget tests?


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

https://reviews.llvm.org/D140722

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


[PATCH] D146908: [clang][MinGW] Add asan link flags before other libs and objects

2023-03-28 Thread Alvin Wong via Phabricator via cfe-commits
alvinhochun added a comment.

In D146908#4226926 , @mstorsjo wrote:

> I tested this, and this does fix the repro from the linked issue.

Thanks for testing!

> I wonder if we do want to move all of these before the app itself, or if it's 
> enough to just move the reference to `asan_dynamic-.dll.a` earlier, and 
> keep the rest as it was? Especially the whole-archive bit ends up linking a 
> bunch of things statically, ordered way before the app itself. On one hand, I 
> wonder if it would have subtle effects that we don't notice until way later, 
> and we should only change as little as we need (moving the import library 
> reference earlier), or if there are other potential benefits to moving the 
> wholearchive-linked bits earlier too? (I'm wondering about things like 
> constructor execution orders and such.)

That is a valid concern, especially if we want to backport this change to 16.x. 
I didn't think about this clearly before. With this in mind, I would change the 
patch to only add a duplicate of `asan_dynamic-.dll.a` early and keep the 
existing flags at their old position.

I can do some experiments with the new asan test setup I have and see if there 
are other benefits of moving the other flags. That will be for separate patches.




Comment at: clang/test/Driver/mingw-sanitizers.c:1
-// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-I686 %s
-// ASAN-I686: "{{.*}}libclang_rt.asan_dynamic-i386.dll.a"
-// ASAN-I686: "{{[^"]*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a"
-// ASAN-I686: "--require-defined" "___asan_seh_interceptor"
-// ASAN-I686: "--whole-archive" 
"{{.*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a" "--no-whole-archive"
-
-// RUN: %clang -target x86_64-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-X86_64 %s
-// ASAN-X86_64: "{{.*}}libclang_rt.asan_dynamic-x86_64.dll.a"
+// RUN: echo -n > %t.a
+// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address -lcomponent 
%/t.a 2>&1 | FileCheck --check-prefixes=ASAN-ALL,ASAN-I686 -DINPUT=%/t.a %s

mstorsjo wrote:
> Hm, what does this do - some sort of more portable version of just touching a 
> file to create it?
Yeah that's just creating the file (though it would also overwrite the existing 
content). I believe lit has `echo` built-in but `touch` may not be available on 
Windows so this seems like a good idea to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146908

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


[PATCH] D146908: [clang][MinGW] Add asan link flags before other libs and objects

2023-03-28 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added inline comments.



Comment at: clang/test/Driver/mingw-sanitizers.c:1
-// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-I686 %s
-// ASAN-I686: "{{.*}}libclang_rt.asan_dynamic-i386.dll.a"
-// ASAN-I686: "{{[^"]*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a"
-// ASAN-I686: "--require-defined" "___asan_seh_interceptor"
-// ASAN-I686: "--whole-archive" 
"{{.*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a" "--no-whole-archive"
-
-// RUN: %clang -target x86_64-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-X86_64 %s
-// ASAN-X86_64: "{{.*}}libclang_rt.asan_dynamic-x86_64.dll.a"
+// RUN: echo -n > %t.a
+// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address -lcomponent 
%/t.a 2>&1 | FileCheck --check-prefixes=ASAN-ALL,ASAN-I686 -DINPUT=%/t.a %s

alvinhochun wrote:
> mstorsjo wrote:
> > Hm, what does this do - some sort of more portable version of just touching 
> > a file to create it?
> Yeah that's just creating the file (though it would also overwrite the 
> existing content). I believe lit has `echo` built-in but `touch` may not be 
> available on Windows so this seems like a good idea to me.
Ah, I see. FWIW, the lit tests in general do assume a handful of unix utilities 
- we seem to have unconditional uses of `touch` in various tests. The lit tests 
check if these tools are available in path, and if they aren't, it tries to 
locate an installation of Git for Windows (which contains what's needed) and 
add that to the path internally: 
https://github.com/llvm/llvm-project/blob/llvmorg-17-init/llvm/utils/lit/lit/llvm/config.py#L29-L35


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146908

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


[PATCH] D146908: [clang][MinGW] Add asan link flags before other libs and objects

2023-03-28 Thread Alvin Wong via Phabricator via cfe-commits
alvinhochun added inline comments.



Comment at: clang/test/Driver/mingw-sanitizers.c:1
-// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-I686 %s
-// ASAN-I686: "{{.*}}libclang_rt.asan_dynamic-i386.dll.a"
-// ASAN-I686: "{{[^"]*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a"
-// ASAN-I686: "--require-defined" "___asan_seh_interceptor"
-// ASAN-I686: "--whole-archive" 
"{{.*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a" "--no-whole-archive"
-
-// RUN: %clang -target x86_64-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-X86_64 %s
-// ASAN-X86_64: "{{.*}}libclang_rt.asan_dynamic-x86_64.dll.a"
+// RUN: echo -n > %t.a
+// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address -lcomponent 
%/t.a 2>&1 | FileCheck --check-prefixes=ASAN-ALL,ASAN-I686 -DINPUT=%/t.a %s

mstorsjo wrote:
> alvinhochun wrote:
> > mstorsjo wrote:
> > > Hm, what does this do - some sort of more portable version of just 
> > > touching a file to create it?
> > Yeah that's just creating the file (though it would also overwrite the 
> > existing content). I believe lit has `echo` built-in but `touch` may not be 
> > available on Windows so this seems like a good idea to me.
> Ah, I see. FWIW, the lit tests in general do assume a handful of unix 
> utilities - we seem to have unconditional uses of `touch` in various tests. 
> The lit tests check if these tools are available in path, and if they aren't, 
> it tries to locate an installation of Git for Windows (which contains what's 
> needed) and add that to the path internally: 
> https://github.com/llvm/llvm-project/blob/llvmorg-17-init/llvm/utils/lit/lit/llvm/config.py#L29-L35
I suppose that works. Would you prefer to use touch here too?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146908

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


[PATCH] D146908: [clang][MinGW] Add asan link flags before other libs and objects

2023-03-28 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added inline comments.



Comment at: clang/test/Driver/mingw-sanitizers.c:1
-// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-I686 %s
-// ASAN-I686: "{{.*}}libclang_rt.asan_dynamic-i386.dll.a"
-// ASAN-I686: "{{[^"]*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a"
-// ASAN-I686: "--require-defined" "___asan_seh_interceptor"
-// ASAN-I686: "--whole-archive" 
"{{.*}}libclang_rt.asan_dynamic_runtime_thunk-i386.a" "--no-whole-archive"
-
-// RUN: %clang -target x86_64-windows-gnu %s -### -fsanitize=address 2>&1 | 
FileCheck --check-prefix=ASAN-X86_64 %s
-// ASAN-X86_64: "{{.*}}libclang_rt.asan_dynamic-x86_64.dll.a"
+// RUN: echo -n > %t.a
+// RUN: %clang -target i686-windows-gnu %s -### -fsanitize=address -lcomponent 
%/t.a 2>&1 | FileCheck --check-prefixes=ASAN-ALL,ASAN-I686 -DINPUT=%/t.a %s

alvinhochun wrote:
> mstorsjo wrote:
> > alvinhochun wrote:
> > > mstorsjo wrote:
> > > > Hm, what does this do - some sort of more portable version of just 
> > > > touching a file to create it?
> > > Yeah that's just creating the file (though it would also overwrite the 
> > > existing content). I believe lit has `echo` built-in but `touch` may not 
> > > be available on Windows so this seems like a good idea to me.
> > Ah, I see. FWIW, the lit tests in general do assume a handful of unix 
> > utilities - we seem to have unconditional uses of `touch` in various tests. 
> > The lit tests check if these tools are available in path, and if they 
> > aren't, it tries to locate an installation of Git for Windows (which 
> > contains what's needed) and add that to the path internally: 
> > https://github.com/llvm/llvm-project/blob/llvmorg-17-init/llvm/utils/lit/lit/llvm/config.py#L29-L35
> I suppose that works. Would you prefer to use touch here too?
I don't have a strong opinion, but with touch I know what is intended, while 
this stopped my reading, wondering what the flag to `echo` does and if this is 
meant to have any specific function other than creating the file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146908

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


[clang] 83c90e6 - [clang] Fix consteval initializers of temporaries

2023-03-28 Thread Mariya Podchishchaeva via cfe-commits

Author: Mariya Podchishchaeva
Date: 2023-03-28T07:41:53-04:00
New Revision: 83c90e623a308a6313783f320eeaabc7e3f9f4b2

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

LOG: [clang] Fix consteval initializers of temporaries

When a potential immediate invocation is met, it is immediately wrapped by a
`ConstantExpr`. There is also a TreeTransform that removes this `ConstantExpr`
wrapper when corresponding expression evaluation context is popped.
So, in case initializer was an immediate invocation, `CXXTemporaryObjectExpr`
was wrapped by a `ConstantExpr`, and that caused additional unnecessary
`CXXFunctionalCastExpr` to be added, which later confused the TreeTransform
that rebuilds immediate invocations, so it was adding unnecessary
constructor call.

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

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaExprCXX.cpp
clang/test/SemaCXX/cxx2a-consteval.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 295532a9bfeca..882e5069e4539 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -238,6 +238,9 @@ Bug Fixes in This Version
   the initializer, so it behaves consistently with other ``VarDecls`` and ends
   on the last token of initializer, instead of right angle bracket of
   the template argument list.
+- Fix false-positive diagnostic issued for consteval initializers of temporary
+  objects.
+  (`#60286 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index e7f3852ae34cd..d5aeb38245ad7 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -1590,6 +1590,9 @@ Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
   Expr *Inner = Result.get();
   if (CXXBindTemporaryExpr *BTE = 
dyn_cast_or_null(Inner))
 Inner = BTE->getSubExpr();
+  if (auto *CE = dyn_cast(Inner);
+  CE && CE->isImmediateInvocation())
+Inner = CE->getSubExpr();
   if (!isa(Inner) &&
   !isa(Inner)) {
 // If we created a CXXTemporaryObjectExpr, that node also represents the

diff  --git a/clang/test/SemaCXX/cxx2a-consteval.cpp 
b/clang/test/SemaCXX/cxx2a-consteval.cpp
index 3047c3f51b5ec..0ffa6bc3b404e 100644
--- a/clang/test/SemaCXX/cxx2a-consteval.cpp
+++ b/clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -1050,3 +1050,18 @@ void test() {
 
 }
 }
+
+namespace GH60286 {
+
+struct A {
+  int i = 0;
+
+  consteval A() {}
+  A(const A&) { i = 1; }
+  consteval int f() { return i; }
+};
+
+constexpr auto B = A{A{}}.f();
+static_assert(B == 0);
+
+}



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


[PATCH] D146801: [clang] Fix consteval initializers of temporaries

2023-03-28 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG83c90e623a30: [clang] Fix consteval initializers of 
temporaries (authored by Fznamznon).

Changed prior to commit:
  https://reviews.llvm.org/D146801?vs=508524&id=508963#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146801

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp


Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -1050,3 +1050,18 @@
 
 }
 }
+
+namespace GH60286 {
+
+struct A {
+  int i = 0;
+
+  consteval A() {}
+  A(const A&) { i = 1; }
+  consteval int f() { return i; }
+};
+
+constexpr auto B = A{A{}}.f();
+static_assert(B == 0);
+
+}
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -1590,6 +1590,9 @@
   Expr *Inner = Result.get();
   if (CXXBindTemporaryExpr *BTE = 
dyn_cast_or_null(Inner))
 Inner = BTE->getSubExpr();
+  if (auto *CE = dyn_cast(Inner);
+  CE && CE->isImmediateInvocation())
+Inner = CE->getSubExpr();
   if (!isa(Inner) &&
   !isa(Inner)) {
 // If we created a CXXTemporaryObjectExpr, that node also represents the
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -238,6 +238,9 @@
   the initializer, so it behaves consistently with other ``VarDecls`` and ends
   on the last token of initializer, instead of right angle bracket of
   the template argument list.
+- Fix false-positive diagnostic issued for consteval initializers of temporary
+  objects.
+  (`#60286 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -1050,3 +1050,18 @@
 
 }
 }
+
+namespace GH60286 {
+
+struct A {
+  int i = 0;
+
+  consteval A() {}
+  A(const A&) { i = 1; }
+  consteval int f() { return i; }
+};
+
+constexpr auto B = A{A{}}.f();
+static_assert(B == 0);
+
+}
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -1590,6 +1590,9 @@
   Expr *Inner = Result.get();
   if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null(Inner))
 Inner = BTE->getSubExpr();
+  if (auto *CE = dyn_cast(Inner);
+  CE && CE->isImmediateInvocation())
+Inner = CE->getSubExpr();
   if (!isa(Inner) &&
   !isa(Inner)) {
 // If we created a CXXTemporaryObjectExpr, that node also represents the
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -238,6 +238,9 @@
   the initializer, so it behaves consistently with other ``VarDecls`` and ends
   on the last token of initializer, instead of right angle bracket of
   the template argument list.
+- Fix false-positive diagnostic issued for consteval initializers of temporary
+  objects.
+  (`#60286 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D146986: Downgrade reserved module identifier error into a warning

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

In D146986#4225275 , @dblaikie wrote:

> Presumably adding an alias for `#pragma clang system_header` called 
> `system_module` wouldn't be too hard? (though the pragma is also being 
> removed from libc++ soon, I think, in favor of `-isystem` usage, so maybe 
> that's a sign the pragma's not a great way to do)

It wouldn't be hard to add, but the modules group wanted to see if we can find 
some common feature that all the implementations implement instead of relying 
on different extensions for different compilers, IIUC. So that could be a 
pragma, or it could be an attribute attached to the module name, etc.

> Presumably the line marker issue would be less significant for a module? 
> Since there's no complex line marking, inclusion, etc, going on - it's just 
> where the actual .cppm file is located/how it's found? (though yeah, that 
> might get weird for building .pcms - since you're going to name the source 
> file directly on the command line, it's not going to be found via any isystem 
> lookup, etc... )

The trouble is maintenance. Someone ran into a problem where they added code to 
the module and then diagnostics started showing up on the wrong lines because 
of the line marker.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146986

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


[PATCH] D146148: Float_t and double_t types shouldn't be modified by #pragma clang fp eval_method

2023-03-28 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

In D146148#4224862 , @rjmccall wrote:

> In D146148#4224094 , @aaron.ballman 
> wrote:
>
>> In D146148#4222306 , @zahiraam 
>> wrote:
>>
>>> In D146148#4221651 , @rjmccall 
>>> wrote:
>>>
 Zahira, this is what I was asking you when I asked whether modifying the 
 math.h header was acceptable: whether you were prepared to accept that the 
 warning would only fire on system math.h headers that we'd modified, or 
 whether you cared about making it work with non-cooperative headers.  I 
 wasn't asking if you were willing to change the test code.
>>>
>>> Okay sorry about the confusion. I think the diagnostic should fire when the 
>>> user is including system's math.h and using float_t inside a scope 
>>> cotaining a #pragma clang fp eval-method. 
>>> I am not sure what you mean by "cooperative headers"?
>>
>> Ones that know about the special marking and use it (cooperative) or ones 
>> that don't use the special marking (uncooperative). My intuition is that 
>> we'll want this to work with any math.h because the problem still exists if 
>> you use an older C standard library release with a newer Clang.
>
> Right.  It's not a great solution for standard stuff like this.
>
 - We add a math.h compiler header that `#include_next`s the system math.h 
 and then adds the attribute.  I believe you can just add an attribute to a 
 typedef retroactively with something like `typedef float_t float_t 
 __attribute__((whatever))`.
>>>
>>> So when a user writes:
>>>
>>>   #include 
>>>int foo()
>>>{
>>>   #pragma clang fp eval_method(source)
>>>  return sizeof(float_t);
>>>}
>>>
>>> It would be as though the user wrote:
>>>
>>>   #include "math.h"
>>>   int foo()
>>>   {
>>>  #pragma clang fp eval_method(source)
>>> return sizeof(float_t);
>>>   }
>>>
>>> where the content of this new math header being:
>>>
>>>   #include_next 
>>>   typedef float_t float_t __attribute__((whatever));
>>>   typedef double_t double_t __attribute__((whatever));
>>
>> Correct.
>
> Right.  To be clear, this is a general thing that we already do to a bunch of 
> other headers.  It doesn't require any special handling, the compiler's 
> include directory is just the first entry on the search list for system 
> headers.
>
 - We do checks on every typedef declaration.  There's a builtin-identifier 
 trick that we do with library functions that we should be able to 
 generalize to typedefs, so you wouldn't need to actually do string 
 comparisons, you'd just check whether the `IdentifierInfo*` was storing a 
 special ID.  We'd set that up in `initializeBuiltins` at the start of the 
 translation unit, so the overhead would just be that we'd create two extra 
 `IdentifierInfo*`s in every TU.

 The builtin ID logic is currently specific to builtin *functions*, and I 
 don't think we'd want to hack typedef names into that.  But the same 
 storage in `IdentifierInfo*` is also used for identifying the ObjC 
 context-sensitive keywords, by just offsetting the builtin IDs by the 
 NUM_OBJC_KEYWORD.  You should be able to generalize that by also 
 introducing a concept of a builtin *type* name, so that e.g. IDs in 
 [0,NUM_OBJC_KEYWORDS) are ObjCKeywordKinds, IDs in [NUM_OBJC_KEYWORDS, 
 NUM_OBJC_KEYWORDS+NUM_BUILTIN_TYPES) are BuiltinTypeKinds (when you 
 subtract NUM_OBJC_KEYWORDS), and IDs in 
 [NUM_OBJC_KEYWORDS+NUM_BUILTIN_TYPES,∞) are builtin function IDs (when you 
 subtract NUM_OBJC_KEYWORDS+NUM_BUILTIN_TYPES).
>>>
>>> Need to look at this more closely to understand what you are suggesting.
>>
>> Basically, he's saying that instead of doing a string comparison against the 
>> name of the typedef, we can ask the typedef for its `IdentifierInfo *` for 
>> the name and do a pointer comparison against an `IdentiferInfo *` that's 
>> cached.
>
> That's a trick we could do, but I'm actually suggesting a step better than 
> that.  The way we handle builtin functions is that we have bits in the 
> `IdentifierInfo` structure saying that the identifier is a builtin name.  
> Those bits are generally ignored except by a few places in Sema that check 
> for them during lookup.  We eagerly create those identifiers and set those 
> bits at the start of the TU.  We could do the same trick for these names, so 
> that when we're declaring a typedef at global scope we just check whether the 
> name is special and trigger some special processing only if so.  It would add 
> a very, very small overhead to processing every typedef declaration, 
> comparable to the overhead we add to processing every function declaration in 
> order to support the declaration of "builtin" library functions.
>
>>> @rjmccall do you have a preference for any one of

[PATCH] D144003: [clang][analyzer] Improve bug reports of StdLibraryFunctionsChecker.

2023-03-28 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

Please run this on open source projects and upload the results.




Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:164-166
+/// This function is called when the current constraint represents the
+/// opposite of a constraint that was not satisfied in a given state, but
+/// the opposite is satisfied. In this case the available information in 
the

I know what you mean, but this could use an example.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:168-170
+/// description about the original constraint violation. This can be get by
+/// try to narrow the current constraint while it remains satisfied in the
+/// given program state. If useful information is found it is put into

This sentence makes so sense, unfortunately :( Could you rephrase, and, again, 
support it with an example?



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:803
+if (ValuesPrinted)
+  MsgOs << " that is out of the accepted range; It should be ";
+else

Looking at the tests, this adds very little how about this:
" that is out of the accepted range; It should be " -> ", but should be "

Do you agree? I won't die on this hill, and am willing to accept this is good 
as-is if you really think that it is.

The other case is fine.



Comment at: clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:807
+VC->describe(Call, C.getState(), Summary, MsgOs);
+// NegatedVC->describeBug1(Call, N->getState(), Summary, MsgOs);
 Msg[0] = toupper(Msg[0]);

Did you mean to leave this here?



Comment at: 
clang/test/Analysis/std-c-library-functions-arg-constraints-notes.cpp:18
   __not_null(nullptr); // \
-  // expected-warning{{The 1st argument to '__not_null' should not be NULL}}
+  // expected-warning{{The 1st argument to '__not_null' is NULL that is out of 
the accepted range; It should be not NULL [}}
 }

This english is broken, but more importantly, this is the one scenario where 
the original message was just good enough -- in fact, better. How about either
1. Restoring the original message (by somehow excluding `NotNullConstraint` in 
the new `describe()`)
2. Or saying something like "The 1st argument to '__not_null' is NULL, but 
should be non-NULL"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144003

___
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-03-28 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D146973#4225645 , @jhuber6 wrote:

> In D146973#4225641 , @aaron.ballman 
> wrote:
>
>>> 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.
>>
>> How do we avoid ABI issues when the two headers get sufficiently out of 
>> sync? (In general, I'm pretty surprised to hear we would want different 
>> headers for the GPU and the system -- does this affect conformance 
>> requirements from the C standard?)
>
> I'm not entirely sure if there's a good method. I think no matter what we do 
> we'll need to implement some kind of 'glue'. I think most should be fine if 
> we go by the C-standard. We expect pointer sizes and everything to be 
> compatible at least.

Hmmm, I've had experience with SYCL as to how it goes when you have difference 
between host and device; those kinds of bugs are incredibly hard to track down. 
Pointer sizes being compatible is a good start, but you need integer widths, 
floating point formats, structure layout decisions, macro definitions, etc to 
all be the same as well. Having only one set of headers that can be used helps 
users avoid these sort of problems.

>> Excuse my ignorance on this point, but is llvm-libc intended to work with 
>> any compiler other than Clang? (e.g., will other compilers need to do this 
>> dance as well?)
>
> Right now the GPU target I'm working on can only be built with `clang` and it 
> will be that way for the foreseeable future.

So we're comfortable painting ourselves into a corner where llvm-libc is only 
usable with Clang, depending on the target?


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] D146986: Downgrade reserved module identifier error into a warning

2023-03-28 Thread Iain Sandoe via Phabricator via cfe-commits
iains added a comment.

+1 for this as an interim solution.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146986

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


[PATCH] D146814: [Flang] Add debug flag to enable current debug information pass

2023-03-28 Thread Sacha Ballantyne via Phabricator via cfe-commits
SBallantyne updated this revision to Diff 508970.
SBallantyne marked an inline comment as done.
SBallantyne added a comment.

Fix case issue. As for tests for debug information being generated, these are 
already covered by various tests in flang/tests/Transforms, namely 
debug-line-table.fir, debug-line-table-existing.fir etc.
While the tests are invoked through fir-opt instead of a flang flag, it is the 
same pass that is verified to be run in the tests added so is covered.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146814

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.h
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CodeGenOptions.def
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/include/flang/Tools/CLOptions.inc
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/mlir-debug-pass-pipeline.f90

Index: flang/test/Driver/mlir-debug-pass-pipeline.f90
===
--- /dev/null
+++ flang/test/Driver/mlir-debug-pass-pipeline.f90
@@ -0,0 +1,83 @@
+! Test the debug pass pipeline
+
+! RUN: %flang -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline -o /dev/null %s 2>&1 | FileCheck --check-prefixes=ALL,NO-DEBUG %s
+
+! RUN: %flang -g0 -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,NO-DEBUG %s
+! RUN: %flang -g -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG %s
+! RUN: %flang -g1 -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG %s
+! RUN: %flang -gline-tables-only -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG %s
+! RUN: %flang -gline-directives-only -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG,DEBUG-DIRECTIVES %s
+! RUN: %flang -g2 -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG,DEBUG-CONSTRUCT %s
+! RUN: %flang -g3 -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=ALL,DEBUG,DEBUG-CONSTRUCT %s
+
+! RUN: not %flang_fc1 -debug-info-kind=invalid -S -mmlir --mlir-pass-statistics -mmlir --mlir-pass-statistics-display=pipeline %s -o /dev/null 2>&1 | FileCheck --check-prefixes=DEBUG-ERR %s
+
+! REQUIRES: asserts
+
+end program
+
+! DEBUG-CONSTRUCT: warning: Unsupported debug option: constructor
+! DEBUG-DIRECTIVES: warning: Unsupported debug option: line-directives-only
+!
+! DEBUG-ERR: error: invalid value 'invalid' in '-debug-info-kind=invalid'
+! DEBUG-ERR-NOT: Pass statistics report
+
+! ALL: Pass statistics report
+
+! ALL: Fortran::lower::VerifierPass
+! ALL-NEXT: LowerHLFIRIntrinsics
+! ALL-NEXT: BufferizeHLFIR
+! ALL-NEXT: ConvertHLFIRtoFIR
+! ALL-NEXT: CSE
+! Ideally, we need an output with only the pass names, but
+! there is currently no way to get that, so in order to
+! guarantee that the passes are in the expected order
+! (i.e. use -NEXT) we have to check the statistics output as well.
+! ALL-NEXT:   (S) 0 num-cse'd - Number of operations CSE'd
+! ALL-NEXT:   (S) 0 num-dce'd - Number of operations DCE'd
+
+! ALL-NEXT: 'func.func' Pipeline
+! ALL-NEXT:   ArrayValueCopy
+! ALL-NEXT:   CharacterConversion
+
+! ALL-NEXT: Canonicalizer
+! ALL-NEXT: SimplifyRegionLite
+! ALL-NEXT: CSE
+! ALL-NEXT:   (S) 0 num-cse'd - Number of operations CSE'd
+! ALL-NEXT:   (S) 0 num-dce'd - Number of operations DCE'd
+
+! ALL-NEXT: 'func.func' Pipeline
+! ALL-NEXT:   MemoryAllocationOpt
+
+! ALL-NEXT: Inliner
+! ALL-NEXT: SimplifyRegionLite
+! ALL-NEXT: CSE
+! ALL-NEXT:   (S) 0 num-cse'd - Number of operations CSE'd
+! ALL-NEXT:   (S) 0 num-dce'd - Number of operations DCE'd
+
+! ALL-NEXT: 'func.func' Pipeline
+! ALL-NEXT:   PolymorphicOpConversion
+! ALL-NEXT:   CFGConversion
+
+! ALL-NEXT: SCFToControlFlow
+! ALL-NEXT: Canonicalizer
+! ALL-NEXT: SimplifyRegionLite
+! ALL-NEXT: CSE
+! ALL-NEXT:   (S) 0 num-cse'd - Number of operations CSE'd
+! ALL-NEXT:   (S) 0 num-dce'd - Number of operations DCE'd
+! ALL-NEXT: BoxedProcedurePass
+
+! ALL-NEXT: Pipeline Collection : ['fir.global', 'func.func']
+! ALL-NEXT:   'fir.global' Pipeline
+! ALL-NEXT:AbstractResultOnGlobalOpt
+! ALL-NEXT:  'func.func' Pipeline
+! ALL-NEXT:AbstractResultOnFuncOpt
+
+!

[PATCH] D141824: [clang-repl] Add a command to load dynamic libraries

2023-03-28 Thread Anubhab Ghosh via Phabricator via cfe-commits
argentite updated this revision to Diff 508971.
argentite marked an inline comment as done.
argentite added a comment.

Changed test to use a separate Input file for the dynamic library generation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141824

Files:
  clang/include/clang/Interpreter/Interpreter.h
  clang/lib/Interpreter/IncrementalExecutor.h
  clang/lib/Interpreter/Interpreter.cpp
  clang/test/Interpreter/Inputs/dynamic-library-test.cpp
  clang/test/Interpreter/dynamic-library.cpp
  clang/tools/clang-repl/ClangRepl.cpp

Index: clang/tools/clang-repl/ClangRepl.cpp
===
--- clang/tools/clang-repl/ClangRepl.cpp
+++ clang/tools/clang-repl/ClangRepl.cpp
@@ -123,6 +123,13 @@
 }
 continue;
   }
+  if (Line->rfind("%lib ", 0) == 0) {
+if (auto Err = Interp->LoadDynamicLibrary(Line->data() + 5)) {
+  llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
+  HasError = true;
+}
+continue;
+  }
 
   if (auto Err = Interp->ParseAndExecute(*Line)) {
 llvm::logAllUnhandledErrors(std::move(Err), llvm::errs(), "error: ");
Index: clang/test/Interpreter/dynamic-library.cpp
===
--- /dev/null
+++ clang/test/Interpreter/dynamic-library.cpp
@@ -0,0 +1,19 @@
+// REQUIRES: host-supports-jit, system-linux
+
+// RUN: %clang -xc++ -o %T/libdynamic-library-test.so -fPIC -shared -DLIBRARY %S/Inputs/dynamic-library-test.cpp
+// RUN: cat %s | env LD_LIBRARY_PATH=%T:$LD_LIBRARY_PATH clang-repl | FileCheck %s
+
+#include 
+
+extern int ultimate_answer;
+int calculate_answer();
+
+%lib libdynamic-library-test.so
+
+printf("Return value: %d\n", calculate_answer());
+// CHECK: Return value: 5
+
+printf("Variable: %d\n", ultimate_answer);
+// CHECK-NEXT: Variable: 42
+
+%quit
Index: clang/test/Interpreter/Inputs/dynamic-library-test.cpp
===
--- /dev/null
+++ clang/test/Interpreter/Inputs/dynamic-library-test.cpp
@@ -0,0 +1,6 @@
+int ultimate_answer = 0;
+
+int calculate_answer() {
+  ultimate_answer = 42;
+  return 5;
+}
Index: clang/lib/Interpreter/Interpreter.cpp
===
--- clang/lib/Interpreter/Interpreter.cpp
+++ clang/lib/Interpreter/Interpreter.cpp
@@ -29,6 +29,7 @@
 #include "clang/Frontend/TextDiagnosticBuffer.h"
 #include "clang/Lex/PreprocessorOptions.h"
 
+#include "llvm/ExecutionEngine/Orc/LLJIT.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/Errc.h"
 #include "llvm/TargetParser/Host.h"
@@ -203,10 +204,13 @@
   return IncrParser->getCI();
 }
 
-const llvm::orc::LLJIT *Interpreter::getExecutionEngine() const {
-  if (IncrExecutor)
-return IncrExecutor->getExecutionEngine();
-  return nullptr;
+llvm::Expected Interpreter::getExecutionEngine() {
+  if (!IncrExecutor) {
+if (auto Err = CreateExecutor())
+  return Err;
+  }
+
+  return IncrExecutor->GetExecutionEngine();
 }
 
 llvm::Expected
@@ -214,14 +218,21 @@
   return IncrParser->Parse(Code);
 }
 
+llvm::Error Interpreter::CreateExecutor() {
+  const clang::TargetInfo &TI =
+  getCompilerInstance()->getASTContext().getTargetInfo();
+  llvm::Error Err = llvm::Error::success();
+  auto Executor = std::make_unique(*TSCtx, Err, TI);
+  if (!Err)
+IncrExecutor = std::move(Executor);
+
+  return Err;
+}
+
 llvm::Error Interpreter::Execute(PartialTranslationUnit &T) {
   assert(T.TheModule);
   if (!IncrExecutor) {
-const clang::TargetInfo &TI =
-getCompilerInstance()->getASTContext().getTargetInfo();
-llvm::Error Err = llvm::Error::success();
-IncrExecutor = std::make_unique(*TSCtx, Err, TI);
-
+auto Err = CreateExecutor();
 if (Err)
   return Err;
   }
@@ -283,3 +294,19 @@
   }
   return llvm::Error::success();
 }
+
+llvm::Error Interpreter::LoadDynamicLibrary(const char *name) {
+  auto EE = getExecutionEngine();
+  if (!EE)
+return EE.takeError();
+
+  auto &DL = EE->getDataLayout();
+
+  if (auto DLSG = llvm::orc::DynamicLibrarySearchGenerator::Load(
+  name, DL.getGlobalPrefix()))
+EE->getMainJITDylib().addGenerator(std::move(*DLSG));
+  else
+return DLSG.takeError();
+
+  return llvm::Error::success();
+}
Index: clang/lib/Interpreter/IncrementalExecutor.h
===
--- clang/lib/Interpreter/IncrementalExecutor.h
+++ clang/lib/Interpreter/IncrementalExecutor.h
@@ -53,7 +53,8 @@
   llvm::Error cleanUp();
   llvm::Expected
   getSymbolAddress(llvm::StringRef Name, SymbolNameKind NameKind) const;
-  llvm::orc::LLJIT *getExecutionEngine() const { return Jit.get(); }
+
+  llvm::orc::LLJIT &GetExecutionEngine() { return *Jit; }
 };
 
 } // end namespace clang
Index: clang/include/clang/Interpreter/Interpreter.h
==

[PATCH] D141824: [clang-repl] Add a command to load dynamic libraries

2023-03-28 Thread Anubhab Ghosh via Phabricator via cfe-commits
argentite added inline comments.



Comment at: clang/test/Interpreter/dynamic-library.cpp:1
+// RUN: head -n 7 %s | %clang -xc++ -o %T/libdynamic-library-test.so -fPIC 
-shared -
+int ultimate_answer = 0;

v.g.vassilev wrote:
> sgraenitz wrote:
> > The use of `head` and `tail` here is a creative solution, but I wonder how 
> > well it scales for similar cases in the future in case this becomes a role 
> > model. We have this situation a lot in LLDB: compile an input file and use 
> > the output in a RUN line. It typically uses separate input files for such 
> > purposes (note that "Inputs" folders must be excluded from test discovery 
> > somewhere in lit config), e.g.:
> > https://github.com/llvm/llvm-project/blob/release/16.x/lldb/test/Shell/Breakpoint/jit-loader_jitlink_elf.test
> > 
> > What do you think?
> I agree with that. I've seen that some clang tests surround the code in 
> question with `#ifdef LIB` and then in the invocation they add `-DLIB`.
The `#ifdef` approach does not seem to work with clang-repl yet. It does not 
like unterminated `#ifdef`. So I am going with separate input file. "Inputs" 
folder seems to be excluded globally in `clang/test/lit.cfg.py`.



Comment at: clang/test/Interpreter/dynamic-library.cpp:9
+
+// REQUIRES: host-supports-jit, system-linux
+// RUN: tail -n 16 %s | env LD_LIBRARY_PATH=%T:$LD_LIBRARY_PATH clang-repl | 
FileCheck %s

sgraenitz wrote:
> This requirement applies to the entire file right? The arrangement here may 
> imply the opposite.
Moved it to the top of the file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141824

___
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-03-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo created this revision.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
VitaNuo requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D147044

Files:
  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
@@ -5,8 +5,8 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-#include "Annotations.h"
 #include "AST.h"
+#include "Annotations.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "SourceCode.h"
@@ -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;
 }
@@ -1876,8 +1880,8 @@
 ASSERT_GT(A.points().size(), 0u) << Case;
 for (auto Pos : A.points())
   EXPECT_THAT(findType(AST, Pos),
-  ElementsAre(
-sym("Target", HeaderA.range("Target"), HeaderA.range("Target"
+  ElementsAre(sym("Target", HeaderA.range("Target"),
+  HeaderA.range("Target"
   << Case;
   }
 
@@ -1888,11 +1892,12 @@
 TU.Code = A.code().str();
 ParsedAST AST = TU.build();
 
-EXPECT_THAT(findType(AST, A.point()),
-UnorderedElementsAre(
-  sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
-  sym("smart_ptr", HeaderA.range("smart_ptr"), HeaderA.range("smart_ptr"))
-))
+EXPECT_THAT(
+findType(AST, A.point()),
+UnorderedElementsAre(
+sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
+sym("smart_ptr", HeaderA.range("smart_ptr"),
+HeaderA.range("smart_ptr"
 << Case;
   }
 }
@@ -1901,6 +1906,25 @@
   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["private.h"] = guard(R"cpp(
+// IWYU pragma: private, include "public.h"
+int foo(); 
+  )cpp");
+  TU.AdditionalFiles["public.h"] = guard("");
+  TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+namespace std {
+  template
+  class vector{};
+}
+  )cpp");
+  TU.AdditionalFiles["forward.h"] = guard("class Bar;");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
 
   auto AST = TU.build();
   std::vector> ExpectedLocations;
@@ -2293,6 +2317,42 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp",
+
+  R"cpp([[#in^clude "public.h"]]
+#include "private.h"
+int fooVar = [[foo]]();
+  )cpp",
+
+  R"cpp(#include "bar.h"
+#include "for^ward.h"
+Bar *x;
+  )cpp",
+
+  R"cpp([[#include "b^ar.h"]]
+#define DEF(X) const Bar *X
+[[DEF]](a);
+  )cpp",
+
+  R"cpp([[#in^clude "bar.h"]]
+#define BAZ(X) const X x
+BAZ([[Bar]]);
+  )cpp"};
+  for (const char *Test : Tests)
+checkFindRefs(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
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.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 +51,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 

[PATCH] D146338: [MSVC compatibility][dllimport/dllexport][PS] Allow dllexport/dllimport for classes with UniqueExternalLinkage

2023-03-28 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

lgtm


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

https://reviews.llvm.org/D146338

___
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-03-28 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon updated this revision to Diff 508974.
Fznamznon added a comment.

Rebase, add release note, fix grammar


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146234

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaExpr.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp

Index: clang/test/SemaCXX/cxx2a-consteval.cpp
===
--- clang/test/SemaCXX/cxx2a-consteval.cpp
+++ clang/test/SemaCXX/cxx2a-consteval.cpp
@@ -1065,3 +1065,41 @@
 static_assert(B == 0);
 
 }
+
+namespace GH58207 {
+struct tester {
+consteval tester(const char* name) noexcept { }
+};
+consteval const char* make_name(const char* name) { return name;}
+consteval const char* pad(int P) { return "thestring"; }
+
+int bad = 10; // expected-note 6{{declared here}}
+
+tester glob1(make_name("glob1"));
+tester glob2(make_name("glob2"));
+constexpr tester cglob(make_name("cglob"));
+tester paddedglob(make_name(pad(bad))); // expected-error {{call to consteval function 'GH58207::make_name' is not a constant expression}} \
+// expected-note {{read of non-const variable 'bad' is not allowed in a constant expression}}
+
+constexpr tester glob3 = { make_name("glob3") };
+constexpr tester glob4 = { make_name(pad(bad)) }; // expected-error {{call to consteval function 'GH58207::make_name' is not a constant expression}} \
+  // expected-error {{constexpr variable 'glob4' must be initialized by a constant expression}} \
+  // expected-note 2{{read of non-const variable 'bad' is not allowed in a constant expression}}
+
+auto V = make_name(pad(3));
+auto V1 = make_name(pad(bad)); // expected-error {{call to consteval function 'GH58207::make_name' is not a constant expression}} \
+   // expected-note {{read of non-const variable 'bad' is not allowed in a constant expression}}
+
+
+void foo() {
+  static tester loc1(make_name("loc1"));
+  static constexpr tester loc2(make_name("loc2"));
+  static tester paddedloc(make_name(pad(bad))); // expected-error {{call to consteval function 'GH58207::make_name' is not a constant expression}} \
+// expected-note {{read of non-const variable 'bad' is not allowed in a constant expression}}
+}
+
+void bar() {
+  static tester paddedloc(make_name(pad(bad))); // expected-error {{call to consteval function 'GH58207::make_name' is not a constant expression}} \
+// expected-note {{read of non-const variable 'bad' is not allowed in a constant expression}}
+}
+}
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17847,6 +17847,7 @@
   bool Result = CE->EvaluateAsConstantExpr(
   Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
   if (!Result || !Notes.empty()) {
+SemaRef.FailedImmediateInvocations.insert(CE);
 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
 if (auto *FunctionalCast = dyn_cast(InnerExpr))
   InnerExpr = FunctionalCast->getSubExpr();
@@ -17891,10 +17892,16 @@
  [E](Sema::ImmediateInvocationCandidate Elem) {
return Elem.getPointer() == E;
  });
-  assert(It != IISet.rend() &&
- "ConstantExpr marked IsImmediateInvocation should "
- "be present");
-  It->setInt(1); // Mark as deleted
+  // It is possible that some subexpression of the current immediate
+  // invocation was handled from another expression evaluation context. Do
+  // not handle the current immediate invocation if some of its
+  // subexpressions failed before.
+  if (It == IISet.rend()) {
+if (SemaRef.FailedImmediateInvocations.contains(E))
+  CurrentII->setInt(1);
+  } else {
+It->setInt(1); // Mark as deleted
+  }
 }
 ExprResult TransformConstantExpr(ConstantExpr *E) {
   if (!E->isImmediateInvocation())
@@ -17967,10 +17974,13 @@
   SemaRef.RebuildingImmediateInvocation)
 return;
 
-  /// When we have more then 1 ImmediateInvocationCandidates we need to check
-  /// for nested ImmediateInvocationCandidates. when we have only 1 we only
-  /// need to remove ReferenceToConsteval in the immediate invocation.
-  if (Rec.ImmediateInvocationCandidates.size() > 1) {
+  /// When we have more than 1 ImmediateInvocationCandidates or previously
+  /// failed immediate invocations, we need to check for nested
+  /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
+  /// Otherwise we only need to remove ReferenceToConsteval in the immediate
+  //

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

2023-03-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 508975.
VitaNuo added a comment.

Smaller improvements.


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/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
@@ -5,8 +5,8 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-#include "Annotations.h"
 #include "AST.h"
+#include "Annotations.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "SourceCode.h"
@@ -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;
 }
@@ -1876,8 +1880,8 @@
 ASSERT_GT(A.points().size(), 0u) << Case;
 for (auto Pos : A.points())
   EXPECT_THAT(findType(AST, Pos),
-  ElementsAre(
-sym("Target", HeaderA.range("Target"), HeaderA.range("Target"
+  ElementsAre(sym("Target", HeaderA.range("Target"),
+  HeaderA.range("Target"
   << Case;
   }
 
@@ -1888,11 +1892,12 @@
 TU.Code = A.code().str();
 ParsedAST AST = TU.build();
 
-EXPECT_THAT(findType(AST, A.point()),
-UnorderedElementsAre(
-  sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
-  sym("smart_ptr", HeaderA.range("smart_ptr"), HeaderA.range("smart_ptr"))
-))
+EXPECT_THAT(
+findType(AST, A.point()),
+UnorderedElementsAre(
+sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
+sym("smart_ptr", HeaderA.range("smart_ptr"),
+HeaderA.range("smart_ptr"
 << Case;
   }
 }
@@ -1901,6 +1906,25 @@
   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["private.h"] = guard(R"cpp(
+// IWYU pragma: private, include "public.h"
+int foo(); 
+  )cpp");
+  TU.AdditionalFiles["public.h"] = guard("");
+  TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+namespace std {
+  template
+  class vector{};
+}
+  )cpp");
+  TU.AdditionalFiles["forward.h"] = guard("class Bar;");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
 
   auto AST = TU.build();
   std::vector> ExpectedLocations;
@@ -2293,6 +2317,42 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp",
+
+  R"cpp([[#in^clude "public.h"]]
+#include "private.h"
+int fooVar = [[foo]]();
+  )cpp",
+
+  R"cpp(#include "bar.h"
+#include "for^ward.h"
+Bar *x;
+  )cpp",
+
+  R"cpp([[#include "b^ar.h"]]
+#define DEF(X) const Bar *X
+[[DEF]](a);
+  )cpp",
+
+  R"cpp([[#in^clude "bar.h"]]
+#define BAZ(X) const X x
+BAZ([[Bar]]);
+  )cpp"};
+  for (const char *Test : Tests)
+checkFindRefs(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
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.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 +51,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 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Suppo

[clang] e574833 - Downgrade reserved module identifier error into a warning

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

Author: Aaron Ballman
Date: 2023-03-28T08:53:44-04:00
New Revision: e574833c2bc46a39150156eb973d0efb142bc618

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

LOG: Downgrade reserved module identifier error into a warning

Any project that wants to import std; potentially needs to be able to
build a module that does export std;. We silenced the error diagnostic
if the module identified itself as a system header, but this isn't
quite good enough, what we really need is a way to identify a system
module. It would be nice for that feature to be shared among the major
implementations, so this downgrades the diagnostic from an error to a
warning temporarily to give implementers time to determine what that
mechanism will look like. We may convert this warning back into an
error in a future release of Clang, but it's not guaranteed we will do
so.

Fixes https://github.com/llvm/llvm-project/issues/61446
Differential Revision: https://reviews.llvm.org/D146986

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaModule.cpp
clang/test/Modules/reserved-names-1.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 882e5069e4539..34cfb8e672ef5 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -85,6 +85,13 @@ C++20 Feature Support
   (`#61278 `_)
 - Announced C++20 Coroutines is fully supported on all targets except Windows, 
which
   still has some stability and ABI issues.
+- Downgraded use of a reserved identifier in a module export declaration from
+  an error to a warning under the ``-Wreserved-module-identifier`` warning
+  group. This warning is enabled by default. This addresses `#61446
+  `_ and allows easier
+  building of precompiled modules. This diagnostic may be strengthened into an
+  error again in the future once there is a less fragile way to mark a module
+  as being part of the implementation rather than a user module.
 
 C++2b Feature Support
 ^

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 274f58b1a5ff0..2b6525ca5f866 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -855,8 +855,9 @@ def LargeByValueCopy : DiagGroup<"large-by-value-copy">;
 def DuplicateArgDecl : DiagGroup<"duplicate-method-arg">;
 def SignedEnumBitfield : DiagGroup<"signed-enum-bitfield">;
 
+def ReservedModuleIdentifier : DiagGroup<"reserved-module-identifier">;
 def ReservedIdentifier : DiagGroup<"reserved-identifier",
-[ReservedIdAsMacro]>;
+[ReservedIdAsMacro, ReservedModuleIdentifier]>;
 
 // Unreachable code warning groups.
 //

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 613e4a5006561..79225036f7f2b 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -401,6 +401,8 @@ def warn_reserved_extern_symbol: Warning<
   "it starts with '_' followed by a capital letter|"
   "it contains '__'}1">,
   InGroup, DefaultIgnore;
+def warn_reserved_module_name : Warning<
+  "%0 is a reserved name for a module">, InGroup;
 
 def warn_parameter_size: Warning<
   "%0 is a large (%1 bytes) pass-by-value argument; "
@@ -11249,8 +11251,7 @@ def err_private_module_fragment_not_module_interface : 
Error<
   "private module fragment in module implementation unit">;
 def note_not_module_interface_add_export : Note<
   "add 'export' here if this is intended to be a module interface unit">;
-def err_invalid_module_name : Error<
-  "%0 is %select{an invalid|a reserved}1 name for a module">;
+def err_invalid_module_name : Error<"%0 is an invalid name for a module">;
 def err_extern_def_in_header_unit : Error<
   "non-inline external definitions are not permitted in C++ header units">;
 

diff  --git a/clang/lib/Sema/SemaModule.cpp b/clang/lib/Sema/SemaModule.cpp
index 8c120d278d634..40ebc9ccdcf96 100644
--- a/clang/lib/Sema/SemaModule.cpp
+++ b/clang/lib/Sema/SemaModule.cpp
@@ -156,11 +156,15 @@ static bool DiagReservedModuleName(Sema &S, const 
IdentifierInfo *II,
   if (Reason == Reserved && S.getSourceManager().isInSystemHeader(Loc))
 Reason = Valid;
 
-  if (Reason != Valid) {
-S.Diag(Loc, diag::err_invalid_module_name) << II << (int)Reason;
-return true;
+  switch (Reason) {
+  case Valid:
+return false;
+  case Invalid:
+return S.Diag(Loc, diag::err_invalid_module_name) << II;
+  case Reserved:
+return

[PATCH] D146986: Downgrade reserved module identifier error into a warning

2023-03-28 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe574833c2bc4: Downgrade reserved module identifier error 
into a warning (authored by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146986

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaModule.cpp
  clang/test/Modules/reserved-names-1.cpp

Index: clang/test/Modules/reserved-names-1.cpp
===
--- clang/test/Modules/reserved-names-1.cpp
+++ clang/test/Modules/reserved-names-1.cpp
@@ -1,34 +1,35 @@
-// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=expected,loud %s
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify=expected -Wno-reserved-module-identifier %s
 
 // expected-note@1 15{{add 'module;' to the start of the file to introduce a global module fragment}}
 
-module std;// expected-error {{'std' is a reserved name for a module}}
-module _Test;  // expected-error {{'_Test' is a reserved name for a module}} \
+module std;// loud-warning {{'std' is a reserved name for a module}}
+module _Test;  // loud-warning {{'_Test' is a reserved name for a module}} \
   expected-error {{module declaration must occur at the start of the translation unit}}
 module module; // expected-error {{'module' is an invalid name for a module}} \
   expected-error {{module declaration must occur at the start of the translation unit}}
-module std0;   // expected-error {{'std0' is a reserved name for a module}} \
+module std0;   // loud-warning {{'std0' is a reserved name for a module}} \
   expected-error {{module declaration must occur at the start of the translation unit}}
 
 export module module; // expected-error {{'module' is an invalid name for a module}} \
  expected-error {{module declaration must occur at the start of the translation unit}}
 export module import; // expected-error {{'import' is an invalid name for a module}} \
  expected-error {{module declaration must occur at the start of the translation unit}}
-export module _Test;  // expected-error {{'_Test' is a reserved name for a module}} \
+export module _Test;  // loud-warning {{'_Test' is a reserved name for a module}} \
  expected-error {{module declaration must occur at the start of the translation unit}}
-export module __test; // expected-error {{'__test' is a reserved name for a module}} \
+export module __test; // loud-warning {{'__test' is a reserved name for a module}} \
  expected-error {{module declaration must occur at the start of the translation unit}}
-export module te__st; // expected-error {{'te__st' is a reserved name for a module}} \
+export module te__st; // loud-warning {{'te__st' is a reserved name for a module}} \
  expected-error {{module declaration must occur at the start of the translation unit}}
-export module std;// expected-error {{'std' is a reserved name for a module}} \
+export module std;// loud-warning {{'std' is a reserved name for a module}} \
  expected-error {{module declaration must occur at the start of the translation unit}}
-export module std.foo;// expected-error {{'std' is a reserved name for a module}} \
+export module std.foo;// loud-warning {{'std' is a reserved name for a module}} \
  expected-error {{module declaration must occur at the start of the translation unit}}
-export module std0;   // expected-error {{'std0' is a reserved name for a module}} \
+export module std0;   // loud-warning {{'std0' is a reserved name for a module}} \
  expected-error {{module declaration must occur at the start of the translation unit}}
-export module std100; // expected-error {{'std100' is a reserved name for a module}} \
+export module std100; // loud-warning {{'std100' is a reserved name for a module}} \
  expected-error {{module declaration must occur at the start of the translation unit}}
-export module should_fail._Test; // expected-error {{'_Test' is a reserved name for a module}} \
+export module should_diag._Test; // loud-warning {{'_Test' is a reserved name for a module}} \
 expected-error {{module declaration must occur at the start of the translation unit}}
 
 // Show that being in a system header doesn't save you from diagnostics about
Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -156,11 +156,15 @@
   if (Reason == Reserved && S.getSourceManage

[PATCH] D145579: [Clang][Flang][AMDGPU] Add support for AMDGPU to Flang driver

2023-03-28 Thread Dominik Adamski via Phabricator via cfe-commits
domada updated this revision to Diff 508977.
domada added a comment.

Patch rebased and added new test for checking incorrect wavefront sizes AMDGPU 
target features.


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

https://reviews.llvm.org/D145579

Files:
  clang/lib/Basic/Targets/AMDGPU.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/target-cpu-features-invalid.f90
  flang/test/Driver/target-cpu-features.f90
  llvm/include/llvm/TargetParser/TargetParser.h
  llvm/lib/TargetParser/TargetParser.cpp

Index: llvm/lib/TargetParser/TargetParser.cpp
===
--- llvm/lib/TargetParser/TargetParser.cpp
+++ llvm/lib/TargetParser/TargetParser.cpp
@@ -251,3 +251,216 @@
 
   return T.isAMDGCN() ? getArchNameAMDGCN(ProcKind) : getArchNameR600(ProcKind);
 }
+
+void AMDGPU::fillAMDGPUFeatureMap(StringRef GPU, const Triple &T,
+  StringMap &Features) {
+  // XXX - What does the member GPU mean if device name string passed here?
+  if (T.isAMDGCN()) {
+switch (parseArchAMDGCN(GPU)) {
+case GK_GFX1103:
+case GK_GFX1102:
+case GK_GFX1101:
+case GK_GFX1100:
+  Features["ci-insts"] = true;
+  Features["dot5-insts"] = true;
+  Features["dot7-insts"] = true;
+  Features["dot8-insts"] = true;
+  Features["dot9-insts"] = true;
+  Features["dot10-insts"] = true;
+  Features["dl-insts"] = true;
+  Features["16-bit-insts"] = true;
+  Features["dpp"] = true;
+  Features["gfx8-insts"] = true;
+  Features["gfx9-insts"] = true;
+  Features["gfx10-insts"] = true;
+  Features["gfx10-3-insts"] = true;
+  Features["gfx11-insts"] = true;
+  break;
+case GK_GFX1036:
+case GK_GFX1035:
+case GK_GFX1034:
+case GK_GFX1033:
+case GK_GFX1032:
+case GK_GFX1031:
+case GK_GFX1030:
+  Features["ci-insts"] = true;
+  Features["dot1-insts"] = true;
+  Features["dot2-insts"] = true;
+  Features["dot5-insts"] = true;
+  Features["dot6-insts"] = true;
+  Features["dot7-insts"] = true;
+  Features["dot10-insts"] = true;
+  Features["dl-insts"] = true;
+  Features["16-bit-insts"] = true;
+  Features["dpp"] = true;
+  Features["gfx8-insts"] = true;
+  Features["gfx9-insts"] = true;
+  Features["gfx10-insts"] = true;
+  Features["gfx10-3-insts"] = true;
+  Features["s-memrealtime"] = true;
+  Features["s-memtime-inst"] = true;
+  break;
+case GK_GFX1012:
+case GK_GFX1011:
+  Features["dot1-insts"] = true;
+  Features["dot2-insts"] = true;
+  Features["dot5-insts"] = true;
+  Features["dot6-insts"] = true;
+  Features["dot7-insts"] = true;
+  Features["dot10-insts"] = true;
+  [[fallthrough]];
+case GK_GFX1013:
+case GK_GFX1010:
+  Features["dl-insts"] = true;
+  Features["ci-insts"] = true;
+  Features["16-bit-insts"] = true;
+  Features["dpp"] = true;
+  Features["gfx8-insts"] = true;
+  Features["gfx9-insts"] = true;
+  Features["gfx10-insts"] = true;
+  Features["s-memrealtime"] = true;
+  Features["s-memtime-inst"] = true;
+  break;
+case GK_GFX940:
+  Features["gfx940-insts"] = true;
+  Features["fp8-insts"] = true;
+  Features["atomic-ds-pk-add-16-insts"] = true;
+  Features["atomic-flat-pk-add-16-insts"] = true;
+  Features["atomic-global-pk-add-bf16-inst"] = true;
+  [[fallthrough]];
+case GK_GFX90A:
+  Features["gfx90a-insts"] = true;
+  Features["atomic-buffer-global-pk-add-f16-insts"] = true;
+  [[fallthrough]];
+case GK_GFX908:
+  Features["dot3-insts"] = true;
+  Features["dot4-insts"] = true;
+  Features["dot5-insts"] = true;
+  Features["dot6-insts"] = true;
+  Features["mai-insts"] = true;
+  [[fallthrough]];
+case GK_GFX906:
+  Features["dl-insts"] = true;
+  Features["dot1-insts"] = true;
+  Features["dot2-insts"] = true;
+  Features["dot7-insts"] = true;
+  Features["dot10-insts"] = true;
+  [[fallthrough]];
+case GK_GFX90C:
+case GK_GFX909:
+case GK_GFX904:
+case GK_GFX902:
+case GK_GFX900:
+  Features["gfx9-insts"] = true;
+  [[fallthrough]];
+case GK_GFX810:
+case GK_GFX805:
+case GK_GFX803:
+case GK_GFX802:
+case GK_GFX801:
+  Features["gfx8-insts"] = true;
+  Features["16-bit-insts"] = true;
+  Features["dpp"] = true;
+  Features["s-memrealtime"] = true;
+  [[fallthrough]];
+case GK_GFX705:
+case GK_GFX704:
+case GK_GFX703:
+case GK_GFX702:
+case GK_GFX701:
+case GK_GFX700:
+  Features["ci-insts"] = true;
+  [[fallthrough]];
+case GK_GFX602:
+case GK_GFX601:
+case GK_GFX600:
+  Features["s-memtime-inst"] = true;
+  break;
+case GK_NONE:
+  break;
+   

[PATCH] D145579: [Clang][Flang][AMDGPU] Add support for AMDGPU to Flang driver

2023-03-28 Thread Dominik Adamski via Phabricator via cfe-commits
domada marked 2 inline comments as done.
domada added inline comments.



Comment at: flang/lib/Frontend/FrontendActions.cpp:149
+err.print(errorMsg.data(), llvm::errs());
+unsigned diagID = ci.getDiagnostics().getCustomDiagID(
+clang::DiagnosticsEngine::Error, "Unsupported feature ID");

awarzynski wrote:
> Are you able to add a test that will trigger this?
Yes, please check the newest patch.



Comment at: flang/test/Driver/target-cpu-features.f90:59
+! CHECK-AMDGPU-R600: "-fc1" "-triple" "r600-unknown-unknown"
+! CHECK-AMDGPU-R600-SAME: "-target-cpu" "cayman"

awarzynski wrote:
> Hm, there aren't any "implicit" target features here.
You will see them in MLIR code:
https://reviews.llvm.org/D146612#change-ciOHRHlq0yvL (file: 
mlir/test/Target/LLVMIR/openmp-llvm.mlir )
Clang also does not list these features in command line for AMDGPU. Slightly 
different situation is for example for ARM target. Clang list 3 options as -cc1 
options and it attaches 4 target options to the generated LLVM IR:
```
clang --target=aarch64 t.c -S -emit-llvm -v 
// I see in the command line 3 explicit target features:
// +neon,  +v8a ,  -fmv
// However, generated t.ll contains 4 target features:
"target-features"="+fp-armv8,+neon,+v8a,-fmv"
// It looks like target feature +fp-armv8 is implicit
```


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

https://reviews.llvm.org/D145579

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


[PATCH] D146971: [Sema] Populate declarations inside TypeLocs for some invalid types

2023-03-28 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Sema/SemaType.cpp:5949
   assert(!T.isNull() && "T must not be null at the end of this function");
-  if (D.isInvalidType())
+  if (!AreDeclaratorChunksValid)
 return Context.getTrivialTypeSourceInfo(T);

ilya-biryukov wrote:
> erichkeane wrote:
> > ilya-biryukov wrote:
> > > erichkeane wrote:
> > > > Shouldn't the `D.setInvalidType(true)` in each of the branches work 
> > > > here?  So this variable is unnecessary?  Else this is a good change 
> > > > IMO. 
> > > (Let me know if I'm misreading the suggestion, I was not sure if my 
> > > understanding is correct).
> > > If we call `setInvalidType` more, we would actually get more crashes as 
> > > the problematic branch is the one that calls `getTrivialTypeSourceInfo`.
> > > To avoid the extra variable, we could instead ensure that the type always 
> > > gets replaced with something trivial `T = Context.IntTy`. But I didn't 
> > > want to go this path because this causes worse error recovery (going from 
> > > something like `void()` to ``) and 
> > > possibly correctness issues (e.g. will we start getting function-decls or 
> > > lambdas that do not have function types and other assertions may fire).
> > My suggestion was that `setInvalidType` is called everywhere that 
> > `AreDeclatorChunksValid` above (sans 1 perhaps?). So my question was 
> > whether this introduced variable was necessary.
> Ah, thanks for clarifying the question.
> `setInvalidType` is called in much more places and the point of this patch is 
> to capture a subcategory of invalid types that still follow the declarator 
> structure.
> 
Got it, thanks for the clarification.  I'm OK with this as-is, then.  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146971

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


[PATCH] D145579: [Clang][Flang][AMDGPU] Add support for AMDGPU to Flang driver

2023-03-28 Thread Dominik Adamski via Phabricator via cfe-commits
domada marked an inline comment as done.
domada added a comment.

In D145579#4226542 , @tschuett wrote:

> I wanted to ask whether you want to put an AMDGPU.cpp and AMD.cpp file in the 
> flang/lib/Frontend directory.

@tschuett No, I don't plan to modify further flang/lib/Frontend.


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

https://reviews.llvm.org/D145579

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


[PATCH] D146418: Support for OpenMP 5.0 sec 2.12.7 - Declare Target initializer expressions

2023-03-28 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/Parse/ParseDecl.cpp:2093-2115
+void ParseImplicitDeclareTargetAttr(Decl *TargetDecl) {
+  if (TargetDecl && TargetDecl->hasAttr() &&
+  isa(TargetDecl)) {
+VarDecl *TargetVarDecl = cast(TargetDecl);
+Expr *Ex = TargetVarDecl->getInit()->IgnoreCasts();
+const DeclRefExpr *DeclRef = nullptr;
+if (Ex && isa(Ex) && TargetVarDecl->hasGlobalStorage()) {

RitanyaB wrote:
> ABataev wrote:
> > RitanyaB wrote:
> > > ABataev wrote:
> > > > It has nothing to do with parsing, sema analysis. Make it part of 
> > > > Sema::checkDeclIsAllowedInOpenMPTarget
> > > The Declaration in Sema::checkDeclIsAllowedInOpenMPTarget is incomplete. 
> > > 
> > > ```
> > > VarDecl 0x1582b278  col:7 ptr1 'int **'
> > > `-OMPDeclareTargetDeclAttr 0x1582b2e0  Implicit MT_To DT_Any 1
> > >   `-<<>>
> > > 
> > > ```  
> > > At this point, I do not have access to the initializer expression. Any 
> > > suggestions? 
> > The try to do it ActOnOpenMPDeclareTargetName
> In the absence of a declare target clause, this function is not invoked (in 
> the examples used above, the function is never called). Do you have any 
> suggestions?
For such decls use checkDeclIsAllowedInOpenMPTarget


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146418

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


[PATCH] D146244: [clangd] Show used symbols on #include line hover.

2023-03-28 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

thanks, looks good from my side.




Comment at: clang-tools-extra/clangd/Hover.cpp:1175
+
+for (const include_cleaner::Header &H : Providers) {
+  if (!ConvertedIncludes.match(H).empty()) {

VitaNuo wrote:
> kadircet wrote:
> > note that this will attribute a symbol to it's non-preferred providers too, 
> > e.g. if you have:
> > h1.h:
> > ```
> > struct Foo; // defined in foo.h
> > struct Bar; // defined in bar.h
> > struct Baz; // defined in baz.h
> > struct H1 {};
> > ```
> > 
> > I believe we want the following:
> > main.cc:
> > ```
> > #include foo.h // Provides Foo
> > #include bar.h // Provides Bar
> > #include h1.h // Provides Baz, H1
> > 
> > Foo *x;
> > Bar *y;
> > Baz *z;
> > H1 *h;
> > ```
> > 
> > and not saying that h1.h provides all Foo, Bar, Baz and H1 (otherwise an 
> > LLVM header will always provide dozens of symbols, e.g. 
> > https://github.com/llvm/llvm-project/blob/main/clang/include/clang/AST/Type.h#L109)
> > 
> > Basically in addition to checking that the particular header we're 
> > interested in being a provider, we should also be checking there were no 
> > other providers that are mentioned in the main file with a higher rank.
> Yeah I know that and I've actually assumed until now that it's the correct 
> behavior :) I.e., that we would like to report all the possible providers as 
> providing the symbol, not only the highest ranked one. 
> 
> But what you're saying makes sense too. See the updated version. Also added a 
> smaller version of the above as a test case.
thanks for raising it (I didn't think too much about this case). 

> and not saying that h1.h provides all Foo, Bar, Baz and H1 (otherwise an LLVM 
> header will always provide dozens of symbols, e.g. 
> https://github.com/llvm/llvm-project/blob/main/clang/include/clang/AST/Type.h#L109)

Agree that for this case, we should prevent providing dozens of 
forward-declared symbols.

But the combination behavior of the unused diagnotics and hover can be 
confusing for case where `h1.h` provides all forward declarations and it is not 
the highest provider in any symbol refs of main.cc, so we will:
1) `h1.h` is considered as used -> no unused-include diagnostic 
2) `hover` on `h1.h` doesn't show any provided symbols

My mental model of 2) is that it indicates `h1.h` is not used, which seems to 
conflict with 1).  Maybe we can think it as a feature, for this case, it is 
safe to remove this header.



Comment at: clang-tools-extra/clangd/Hover.cpp:62
 #include 
+#include 
 #include 

nit: this is unused now.



Comment at: clang-tools-extra/clangd/Hover.cpp:1188
+  // in the main file.
+  return;
+}

nit: my personal preference would be using `break` here. 



Comment at: clang-tools-extra/clangd/unittests/HoverTests.cpp:3011
+  #include "bar.h"
+  #include "for^ward.h"
+  Bar *x;

it would be nice to have a comment explaining why we show nothing here (because 
we have a higher provider `bar.h`)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146244

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


[PATCH] D146814: [Flang] Add debug flag to enable current debug information pass

2023-03-28 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thanks for the explanation! Still looking good apart from the function names ;)




Comment at: clang/lib/Driver/ToolChains/CommonArgs.h:111
+llvm::codegenoptions::DebugInfoKind
+DebugLevelToInfoKind(const llvm::opt::Arg &A);
+

awarzynski wrote:
> CamelCase or camelCase? ;-)
Sorry, I meant that this function uses wrong casing. It ought to be 
`debugLevelToInfoKind` and `addDebugInfoKind`: 
https://llvm.org/docs/CodingStandards.html#name-types-functions-variables-and-enumerators-properly


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146814

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


[PATCH] D145579: [Clang][Flang][AMDGPU] Add support for AMDGPU to Flang driver

2023-03-28 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski accepted this revision.
awarzynski added a comment.
This revision is now accepted and ready to land.

Thanks for implementing this, LGTM!


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

https://reviews.llvm.org/D145579

___
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-03-28 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D146973#4227114 , @aaron.ballman 
wrote:

> Hmmm, I've had experience with SYCL as to how it goes when you have 
> difference between host and device; those kinds of bugs are incredibly hard 
> to track down. Pointer sizes being compatible is a good start, but you need 
> integer widths, floating point formats, structure layout decisions, macro 
> definitions, etc to all be the same as well. Having only one set of headers 
> that can be used helps users avoid these sort of problems.

The problem is that we are trying to implement an actual library here. It is, 
in my opinion, completely unreasonable to try to implement a library based off 
of another implementation's specification. What you are suggesting is that we 
implement a GPU library that copies every internal implementation detail that 
GNU has for that platform. So, let's just copy-paste their headers into our 
LLVM `libc` and make sure we copy all of their implementations too. Now what if 
someone wants to use `musl` instead? Do we copy that one as well and have 
everything surrounded by `ifdef`s? Do we just implement some meta libc that is 
compatible with every other `libc`? This is not going to create a usable 
library, and as the person who would presumably need to write it, I'm not going 
to spend my time copying other `libc` headers.

We need to provide fully-custom headers, if this fully-custom header uses 
`#include_next` after we've verified that it doesn't break, that's fine. I'm 
not particularly concerned if a macro or function is undefined between the CPU 
and GPU. The important point is that any symbol or macro we provide in the 
GPU's headers has an implementation that is expected to be compatible with the 
host. It's understandable if the macros and functions map to something slightly 
different, as long as it does what we say it does.

> So we're comfortable painting ourselves into a corner where llvm-libc is only 
> usable with Clang, depending on the target?

There might be somewhat of a misunderstanding here, I'm talking about the GPU 
implementation of `libc` using LLVM's `libc`. Expecting a specific toolchain is 
standard procedure for every single other offloading language. It's how we 
build ROCm device libraries, CUDA device libraries, the OpenMP device runtime, 
etc. LLVM's `libc` project is perfectly fine being compiled with `gcc`, but the 
GPU is such a special case we don't have that luxury and need to use `clang`. 
This is the same approach we do for OpenMP already.


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] D141824: [clang-repl] Add a command to load dynamic libraries

2023-03-28 Thread Stefan Gränitz via Phabricator via cfe-commits
sgraenitz accepted this revision.
sgraenitz added a comment.
This revision is now accepted and ready to land.

Thanks! LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141824

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


[PATCH] D139010: [clang][WebAssembly] Implement support for table types and builtins

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

This will also need someone from the LLVM side to look at the LLVM-specific 
changes. Most of my comments were focused on the behavior of test cases, but 
there may be more comments coming for the code changes once I've got a better 
handle on the test behavior.




Comment at: clang/include/clang/Basic/BuiltinsWebAssembly.def:205-210
+TARGET_BUILTIN(__builtin_wasm_table_set,  "viii", "t", "reference-types")
+TARGET_BUILTIN(__builtin_wasm_table_get,  "iii", "t", "reference-types")
+TARGET_BUILTIN(__builtin_wasm_table_size, "ii", "nt", "reference-types")
+TARGET_BUILTIN(__builtin_wasm_table_grow, "", "nt", "reference-types")
+TARGET_BUILTIN(__builtin_wasm_table_fill, "v", "t", "reference-types")
+TARGET_BUILTIN(__builtin_wasm_table_copy, "vi", "t", "reference-types")

All of these should be documented in `docs/LanguageExtensions.rst` (you can 
make a Web Assembly section if one doesn't already exist; we've historically 
been bad about documenting our builtins).



Comment at: clang/test/Sema/builtins-wasm.c:12-13
+  __builtin_wasm_table_size(table, table);// expected-error {{too 
many arguments to function call, expected 1, have 2}}
+  void *a = __builtin_wasm_table_size(table); // expected-error 
{{incompatible integer to pointer conversion initializing 'void *' with an 
expression of type 'int'}}
+  __externref_t b = __builtin_wasm_table_size(table); // expected-error 
{{initializing '__externref_t' with an expression of incompatible type 'int'}}
+  int c = __builtin_wasm_table_size(table);

Instead of relying on assignment diagnostics to test the return type of the 
call, why not use the language? (Same can be used for the other, similar tests.)
```
#define EXPR_HAS_TYPE(expr, type) _Generic((expr), type : 1, default : 0)

_Static_assert(EXPR_HAS_TYPE(__builtin_wasm_table_size(table), int), "");
```



Comment at: clang/test/Sema/builtins-wasm.c:21
+  __builtin_wasm_table_grow(ref, ref, size); // expected-error 
{{1st argument must be a WebAssembly table}}
+  __builtin_wasm_table_grow(table, table, size); // expected-error 
{{2nd argument must match the element type of the WebAssembly table in the 1st 
argument}}
+  __builtin_wasm_table_grow(table, ref, table);  // expected-error 
{{3rd argument must be an integer}}

I can't make sense of this diagnostic -- what is the element type of the web 
assembly table in the 1st argument? Why is the second argument needed at all if 
it needs to be derived from the type of the first argument and these things 
don't represent values (due to being zero-sized)?



Comment at: clang/test/Sema/builtins-wasm.c:32
+  __builtin_wasm_table_fill(table, table, ref, nelem);   // 
expected-error {{2nd argument must be an integer}}
+  __builtin_wasm_table_fill(table, index, index, ref);   // 
expected-error {{3rd argument must match the element type of the WebAssembly 
table in the 1st argument}}
+  __builtin_wasm_table_fill(table, index, ref, table);   // 
expected-error {{4th argument must be an integer}}

Similar question here about the third argument.



Comment at: clang/test/Sema/wasm-refs-and-tables.c:17
+static __externref_t t6[] = {0}; // expected-error {{only zero-length 
WebAssembly tables are currently supported}}
+__externref_t t7[0]; // expected-error {{WebAssembly table must be 
static}}
+static __externref_t t8[0][0];   // expected-error {{multi-dimensional arrays 
of WebAssembly references are not allowed}}

So why is `extern __externref_t r2;` allowed? Is it because it's not an array 
declaration?



Comment at: clang/test/Sema/wasm-refs-and-tables.c:21-23
+static __externref_t table[0];
+static __externref_t other_table[0] = {};
+

For completeness (should just work)



Comment at: clang/test/Sema/wasm-refs-and-tables.c:48
+void illegal_argument_4(__externref_t ***table);// expected-error 
{{pointer to WebAssembly reference type is not allowed}}
+void illegal_argument_5(__externref_t (*table)[0]); // expected-error {{cannot 
form a pointer to a WebAssembly table}}
+

How about:
```
void foo(__externref_t table[0]);
```
I'd expect this to also not be allowed (that's just a fancy spelling for a 
weird pointer).



Comment at: clang/test/Sema/wasm-refs-and-tables.c:81
+
+  funcref_t func = __builtin_wasm_ref_null_func(0); // expected-error {{too 
many arguments to function call, expected 0, have 1}}
+

Shouldn't this be in builtins-wasm.c instead?



Comment at: clang/test/Sema/wasm-refs-and-tables.c:83-84
+
+  __externref_t lt1[0];   // expected-error {{WebAssembly table cannot 
be declared within a function}}
+  static __externref_t lt2[0];// expected-e

[PATCH] D146814: [Flang] Add debug flag to enable current debug information pass

2023-03-28 Thread Sacha Ballantyne via Phabricator via cfe-commits
SBallantyne added a comment.






Comment at: clang/lib/Driver/ToolChains/CommonArgs.h:111
+llvm::codegenoptions::DebugInfoKind
+DebugLevelToInfoKind(const llvm::opt::Arg &A);
+

awarzynski wrote:
> awarzynski wrote:
> > CamelCase or camelCase? ;-)
> Sorry, I meant that this function uses wrong casing. It ought to be 
> `debugLevelToInfoKind` and `addDebugInfoKind`: 
> https://llvm.org/docs/CodingStandards.html#name-types-functions-variables-and-enumerators-properly
I thought that the general rule was that the style guide should be followed 
apart from when there is already code in a particular style in a file, however 
i have realised that while most functions in this file are `CamelCase`, there 
are some that are `camelCase`, so i am unsure of what is the right way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146814

___
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-03-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 508986.
VitaNuo added a comment.

Formatting.


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/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
@@ -5,8 +5,8 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-#include "Annotations.h"
 #include "AST.h"
+#include "Annotations.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "SourceCode.h"
@@ -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;
 }
@@ -1876,8 +1880,8 @@
 ASSERT_GT(A.points().size(), 0u) << Case;
 for (auto Pos : A.points())
   EXPECT_THAT(findType(AST, Pos),
-  ElementsAre(
-sym("Target", HeaderA.range("Target"), HeaderA.range("Target"
+  ElementsAre(sym("Target", HeaderA.range("Target"),
+  HeaderA.range("Target"
   << Case;
   }
 
@@ -1888,11 +1892,12 @@
 TU.Code = A.code().str();
 ParsedAST AST = TU.build();
 
-EXPECT_THAT(findType(AST, A.point()),
-UnorderedElementsAre(
-  sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
-  sym("smart_ptr", HeaderA.range("smart_ptr"), HeaderA.range("smart_ptr"))
-))
+EXPECT_THAT(
+findType(AST, A.point()),
+UnorderedElementsAre(
+sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
+sym("smart_ptr", HeaderA.range("smart_ptr"),
+HeaderA.range("smart_ptr"
 << Case;
   }
 }
@@ -1901,6 +1906,25 @@
   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["private.h"] = guard(R"cpp(
+// IWYU pragma: private, include "public.h"
+int foo(); 
+  )cpp");
+  TU.AdditionalFiles["public.h"] = guard("");
+  TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+namespace std {
+  template
+  class vector{};
+}
+  )cpp");
+  TU.AdditionalFiles["forward.h"] = guard("class Bar;");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
 
   auto AST = TU.build();
   std::vector> ExpectedLocations;
@@ -2293,6 +2317,42 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp",
+
+  R"cpp([[#in^clude "public.h"]]
+#include "private.h"
+int fooVar = [[foo]]();
+  )cpp",
+
+  R"cpp(#include "bar.h"
+#include "for^ward.h"
+Bar *x;
+  )cpp",
+
+  R"cpp([[#include "b^ar.h"]]
+#define DEF(X) const Bar *X
+[[DEF]](a);
+  )cpp",
+
+  R"cpp([[#in^clude "bar.h"]]
+#define BAZ(X) const X x
+BAZ([[Bar]]);
+  )cpp"};
+  for (const char *Test : Tests)
+checkFindRefs(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
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.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 +51,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 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ost

[PATCH] D146244: [clangd] Show used symbols on #include line hover.

2023-03-28 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.

thanks the pieces i looked at LG too


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146244

___
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-03-28 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 added inline comments.



Comment at: clang/lib/Driver/ToolChains/CommonArgs.cpp:714-716
+if (!Args.hasFlag(options::OPT_fdata_sections,
+  options::OPT_fno_data_sections, UseSeparateSections) &&
+Args.hasArg(options::OPT_fno_data_sections))

hubert.reinterpretcast wrote:
> I think this (undesirably) generates an error even `-mno-roptr` is in effect.
> 
> This logic seems otherwise convoluted. I think the main logic should only 
> care that `data-sections` is off. We can separately assert that 
> `data-sections` is on by default on AIX.
Thanks for catching the error! I am updating the patch to fix the undesirable 
error. 

The checking logic is to make sure we are consistent with how we set 
`-data-sections=0` above (line 705). I will revise the logic to check 
`no_data_sections` if we are ok with the inconsistency. @hubert.reinterpretcast 
could you confirm? 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] D146244: [clangd] Show used symbols on #include line hover.

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

Address review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146244

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

Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -10,6 +10,7 @@
 #include "Annotations.h"
 #include "Config.h"
 #include "Hover.h"
+#include "TestFS.h"
 #include "TestIndex.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
@@ -2980,6 +2981,92 @@
 EXPECT_EQ(Case.HI.present().asMarkdown(), Case.ExpectedMarkdown);
 }
 
+TEST(Hover, UsedSymbols) {
+  struct {
+const char *Code;
+const std::function ExpectedBuilder;
+  } Cases[] = {
+  {R"cpp(
+#include ^"bar.h"
+int fstBar = bar1();
+int sndBar = bar2();
+Bar bar;
+int macroBar = BAR;
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.UsedSymbolNames = {"BAR", "Bar", "bar1", "bar2"};
+   }},
+  {R"cpp(
+#in^clude 
+std::vector vec;
+  )cpp",
+   [](HoverInfo &HI) { HI.UsedSymbolNames = {"vector"}; }},
+  {R"cpp(
+#in^clude "public.h"
+#include "private.h"
+int fooVar = foo();
+  )cpp",
+   [](HoverInfo &HI) { HI.UsedSymbolNames = {"foo"}; }},
+  {R"cpp(
+#include "bar.h"
+#include "for^ward.h"
+Bar *x;
+  )cpp",
+   [](HoverInfo &HI) {
+ HI.UsedSymbolNames = {
+ // No used symbols because bar.h is a higher-ranked provider
+ // for Bar.
+ };
+   }},
+  {R"cpp(
+#include "b^ar.h"
+#define DEF(X) const Bar *X
+DEF(a);
+  )cpp",
+   [](HoverInfo &HI) { HI.UsedSymbolNames = {"Bar"}; }},
+  {R"cpp(
+#in^clude "bar.h"
+#define BAZ(X) const X x
+BAZ(Bar);
+  )cpp",
+   [](HoverInfo &HI) { HI.UsedSymbolNames = {"Bar"}; }}};
+  for (const auto &Case : Cases) {
+Annotations Code{Case.Code};
+SCOPED_TRACE(Code.code());
+
+TestTU TU;
+TU.Filename = "foo.cpp";
+TU.Code = Code.code();
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["private.h"] = guard(R"cpp(
+  // IWYU pragma: private, include "public.h"
+  int foo(); 
+)cpp");
+TU.AdditionalFiles["public.h"] = guard("");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.AdditionalFiles["forward.h"] = guard("class Bar;");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+auto H = getHover(AST, Code.point(), format::getLLVMStyle(), nullptr);
+ASSERT_TRUE(H);
+HoverInfo Expected;
+Case.ExpectedBuilder(Expected);
+SCOPED_TRACE(H->present().asMarkdown());
+EXPECT_EQ(H->UsedSymbolNames, Expected.UsedSymbolNames);
+  }
+}
+
 TEST(Hover, DocsFromIndex) {
   Annotations T(R"cpp(
   template  class X {};
@@ -3369,7 +3456,21 @@
   R"(stdio.h
 
 /usr/include/stdio.h)",
-  }};
+  },
+  {[](HoverInfo &HI) {
+ HI.Name = "foo.h";
+ HI.UsedSymbolNames = {"Foo", "Bar", "Baz"};
+   },
+   R"(foo.h
+
+provides Foo, Bar, Baz)"},
+  {[](HoverInfo &HI) {
+ HI.Name = "foo.h";
+ HI.UsedSymbolNames = {"Foo", "Bar", "Baz", "Foobar", "Qux", "Quux"};
+   },
+   R"(foo.h
+
+provides Foo, Bar, Baz, Foobar, Qux and 1 more)"}};
 
   for (const auto &C : Cases) {
 HoverInfo HI;
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -78,6 +78,9 @@
 /// representation. The spelling contains the ""<> characters.
 std::string spellHeader(ParsedAST &AST, const FileEntry *MainFile,
 include_cleaner::Header Provider);
+
+std::vector
+collectMacroReferences(ParsedAST &AST);
 } // namespace clangd
 } // namespace clang
 
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-t

[PATCH] D146244: [clangd] Show used symbols on #include line hover.

2023-03-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added inline comments.



Comment at: clang-tools-extra/clangd/Hover.cpp:1175
+
+for (const include_cleaner::Header &H : Providers) {
+  if (!ConvertedIncludes.match(H).empty()) {

hokein wrote:
> VitaNuo wrote:
> > kadircet wrote:
> > > note that this will attribute a symbol to it's non-preferred providers 
> > > too, e.g. if you have:
> > > h1.h:
> > > ```
> > > struct Foo; // defined in foo.h
> > > struct Bar; // defined in bar.h
> > > struct Baz; // defined in baz.h
> > > struct H1 {};
> > > ```
> > > 
> > > I believe we want the following:
> > > main.cc:
> > > ```
> > > #include foo.h // Provides Foo
> > > #include bar.h // Provides Bar
> > > #include h1.h // Provides Baz, H1
> > > 
> > > Foo *x;
> > > Bar *y;
> > > Baz *z;
> > > H1 *h;
> > > ```
> > > 
> > > and not saying that h1.h provides all Foo, Bar, Baz and H1 (otherwise an 
> > > LLVM header will always provide dozens of symbols, e.g. 
> > > https://github.com/llvm/llvm-project/blob/main/clang/include/clang/AST/Type.h#L109)
> > > 
> > > Basically in addition to checking that the particular header we're 
> > > interested in being a provider, we should also be checking there were no 
> > > other providers that are mentioned in the main file with a higher rank.
> > Yeah I know that and I've actually assumed until now that it's the correct 
> > behavior :) I.e., that we would like to report all the possible providers 
> > as providing the symbol, not only the highest ranked one. 
> > 
> > But what you're saying makes sense too. See the updated version. Also added 
> > a smaller version of the above as a test case.
> thanks for raising it (I didn't think too much about this case). 
> 
> > and not saying that h1.h provides all Foo, Bar, Baz and H1 (otherwise an 
> > LLVM header will always provide dozens of symbols, e.g. 
> > https://github.com/llvm/llvm-project/blob/main/clang/include/clang/AST/Type.h#L109)
> 
> Agree that for this case, we should prevent providing dozens of 
> forward-declared symbols.
> 
> But the combination behavior of the unused diagnotics and hover can be 
> confusing for case where `h1.h` provides all forward declarations and it is 
> not the highest provider in any symbol refs of main.cc, so we will:
> 1) `h1.h` is considered as used -> no unused-include diagnostic 
> 2) `hover` on `h1.h` doesn't show any provided symbols
> 
> My mental model of 2) is that it indicates `h1.h` is not used, which seems to 
> conflict with 1).  Maybe we can think it as a feature, for this case, it is 
> safe to remove this header.
No solution here, just a comment: this seems to go along the lines of our 
discussion in the sync today, i.e., that we might want to make the unused 
include analysis stricter eventually. So it seems like the general tendency 
might be towards making the unused include analysis stricter, rather than 
showing more provided symbols on hover.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146244

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


[clang-tools-extra] 655baae - [clangd] Show used symbols on #include line hover.

2023-03-28 Thread Viktoriia Bakalova via cfe-commits

Author: Viktoriia Bakalova
Date: 2023-03-28T14:05:34Z
New Revision: 655baae2af0b805a1c3e6d6338a32de05e342357

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

LOG: [clangd] Show used symbols on #include line hover.

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

Added: 


Modified: 
clang-tools-extra/clangd/Hover.cpp
clang-tools-extra/clangd/Hover.h
clang-tools-extra/clangd/IncludeCleaner.cpp
clang-tools-extra/clangd/IncludeCleaner.h
clang-tools-extra/clangd/unittests/HoverTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 27663991a7f3c..b399a12cd90cf 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -12,6 +12,7 @@
 #include "CodeCompletionStrings.h"
 #include "Config.h"
 #include "FindTarget.h"
+#include "Headers.h"
 #include "IncludeCleaner.h"
 #include "ParsedAST.h"
 #include "Selection.h"
@@ -38,11 +39,15 @@
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/CharInfo.h"
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Tooling/Syntax/Tokens.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
@@ -52,6 +57,7 @@
 #include "llvm/Support/Format.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 
 #include 
 #include 
@@ -1134,11 +1140,66 @@ void maybeAddSymbolProviders(ParsedAST &AST, HoverInfo 
&HI,
   HI.Provider = spellHeader(AST, SM.getFileEntryForID(SM.getMainFileID()), H);
 }
 
+// FIXME: similar functions are present in FindHeaders.cpp (symbolName)
+// and IncludeCleaner.cpp (getSymbolName). Introduce a name() method into
+// include_cleaner::Symbol instead.
+std::string getSymbolName(include_cleaner::Symbol Sym) {
+  std::string Name;
+  switch (Sym.kind()) {
+  case include_cleaner::Symbol::Declaration:
+if (const auto *ND = llvm::dyn_cast(&Sym.declaration()))
+  Name = ND->getDeclName().getAsString();
+break;
+  case include_cleaner::Symbol::Macro:
+Name = Sym.macro().Name->getName();
+break;
+  }
+  return Name;
+}
+
+void maybeAddUsedSymbols(ParsedAST &AST, HoverInfo &HI, const Inclusion &Inc) {
+  const SourceManager &SM = AST.getSourceManager();
+  const auto &ConvertedMainFileIncludes =
+  convertIncludes(SM, AST.getIncludeStructure().MainFileIncludes);
+  const auto &HoveredInclude = convertIncludes(SM, llvm::ArrayRef{Inc});
+  llvm::DenseSet UsedSymbols;
+  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 ||
+UsedSymbols.find(Ref.Target) != UsedSymbols.end())
+  return;
+
+for (const include_cleaner::Header &H : Providers) {
+  auto MatchingIncludes = ConvertedMainFileIncludes.match(H);
+  // No match for this provider in the main file.
+  if (MatchingIncludes.empty())
+continue;
+
+  // Check if the hovered include matches this provider.
+  if (!HoveredInclude.match(H).empty())
+UsedSymbols.insert(Ref.Target);
+
+  // Don't look for rest of the providers once we've found a match
+  // in the main file.
+  break;
+}
+  });
+
+  for (const auto &UsedSymbolDecl : UsedSymbols)
+HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
+  llvm::sort(HI.UsedSymbolNames);
+}
+
 } // namespace
 
 std::optional getHover(ParsedAST &AST, Position Pos,
   const format::FormatStyle &Style,
   const SymbolIndex *Index) {
+  static constexpr trace::Metric HoverCountMetric(
+  "hover", trace::Metric::Counter, "case");
   PrintingPolicy PP =
   getPrintingPolicy(AST.getASTContext().getPrintingPolicy());
   const SourceManager &SM = AST.getSourceManager();
@@ -1157,12 +1218,14 @@ std::optional getHover(ParsedAST &AST, 
Position Pos,
   for (const auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
 if (Inc.Resolved.empty() || Inc.HashLine != Pos.line)
   continue;
+HoverCountMetric.record(1, "include");
 HoverInfo HI;
 HI.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
 // FIXME: We don't have a fitting value for Kind.
 HI.Definition =
 URIForFi

[PATCH] D146244: [clangd] Show used symbols on #include line hover.

2023-03-28 Thread Viktoriia Bakalova 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 rG655baae2af0b: [clangd] Show used symbols on #include line 
hover. (authored by VitaNuo).

Changed prior to commit:
  https://reviews.llvm.org/D146244?vs=508994&id=509001#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146244

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

Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -10,6 +10,7 @@
 #include "Annotations.h"
 #include "Config.h"
 #include "Hover.h"
+#include "TestFS.h"
 #include "TestIndex.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
@@ -2980,6 +2981,91 @@
 EXPECT_EQ(Case.HI.present().asMarkdown(), Case.ExpectedMarkdown);
 }
 
+TEST(Hover, UsedSymbols) {
+  struct {
+const char *Code;
+const std::function ExpectedBuilder;
+  } Cases[] = {{R"cpp(
+  #include ^"bar.h"
+  int fstBar = bar1();
+  int sndBar = bar2();
+  Bar bar;
+  int macroBar = BAR;
+)cpp",
+[](HoverInfo &HI) {
+  HI.UsedSymbolNames = {"BAR", "Bar", "bar1", "bar2"};
+}},
+   {R"cpp(
+  #in^clude 
+  std::vector vec;
+)cpp",
+[](HoverInfo &HI) { HI.UsedSymbolNames = {"vector"}; }},
+   {R"cpp(
+  #in^clude "public.h"
+  #include "private.h"
+  int fooVar = foo();
+)cpp",
+[](HoverInfo &HI) { HI.UsedSymbolNames = {"foo"}; }},
+   {R"cpp(
+  #include "bar.h"
+  #include "for^ward.h"
+  Bar *x;
+)cpp",
+[](HoverInfo &HI) {
+  HI.UsedSymbolNames = {
+  // No used symbols, since bar.h is a higher-ranked
+  // provider for Bar.
+  };
+}},
+   {R"cpp(
+  #include "b^ar.h"
+  #define DEF(X) const Bar *X
+  DEF(a);
+)cpp",
+[](HoverInfo &HI) { HI.UsedSymbolNames = {"Bar"}; }},
+   {R"cpp(
+  #in^clude "bar.h"
+  #define BAZ(X) const X x
+  BAZ(Bar);
+)cpp",
+[](HoverInfo &HI) { HI.UsedSymbolNames = {"Bar"}; }}};
+  for (const auto &Case : Cases) {
+Annotations Code{Case.Code};
+SCOPED_TRACE(Code.code());
+
+TestTU TU;
+TU.Filename = "foo.cpp";
+TU.Code = Code.code();
+TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+  #define BAR 5
+  int bar1();
+  int bar2();
+  class Bar {};
+)cpp");
+TU.AdditionalFiles["private.h"] = guard(R"cpp(
+  // IWYU pragma: private, include "public.h"
+  int foo(); 
+)cpp");
+TU.AdditionalFiles["public.h"] = guard("");
+TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+  namespace std {
+template
+class vector{};
+  }
+)cpp");
+TU.AdditionalFiles["forward.h"] = guard("class Bar;");
+TU.ExtraArgs.push_back("-isystem" + testPath("system"));
+
+auto AST = TU.build();
+auto H = getHover(AST, Code.point(), format::getLLVMStyle(), nullptr);
+ASSERT_TRUE(H);
+HoverInfo Expected;
+Case.ExpectedBuilder(Expected);
+SCOPED_TRACE(H->present().asMarkdown());
+EXPECT_EQ(H->UsedSymbolNames, Expected.UsedSymbolNames);
+  }
+}
+
 TEST(Hover, DocsFromIndex) {
   Annotations T(R"cpp(
   template  class X {};
@@ -3369,7 +3455,21 @@
   R"(stdio.h
 
 /usr/include/stdio.h)",
-  }};
+  },
+  {[](HoverInfo &HI) {
+ HI.Name = "foo.h";
+ HI.UsedSymbolNames = {"Foo", "Bar", "Baz"};
+   },
+   R"(foo.h
+
+provides Foo, Bar, Baz)"},
+  {[](HoverInfo &HI) {
+ HI.Name = "foo.h";
+ HI.UsedSymbolNames = {"Foo", "Bar", "Baz", "Foobar", "Qux", "Quux"};
+   },
+   R"(foo.h
+
+provides Foo, Bar, Baz, Foobar, Qux and 1 more)"}};
 
   for (const auto &C : Cases) {
 HoverInfo HI;
Index: clang-tools-extra/clangd/IncludeCleaner.h
=

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

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

In D146973#4227266 , @jhuber6 wrote:

> In D146973#4227114 , @aaron.ballman 
> wrote:
>
>> Hmmm, I've had experience with SYCL as to how it goes when you have 
>> difference between host and device; those kinds of bugs are incredibly hard 
>> to track down. Pointer sizes being compatible is a good start, but you need 
>> integer widths, floating point formats, structure layout decisions, macro 
>> definitions, etc to all be the same as well. Having only one set of headers 
>> that can be used helps users avoid these sort of problems.
>
> The problem is that we are trying to implement an actual library here. It is, 
> in my opinion, completely unreasonable to try to implement a library based 
> off of another implementation's specification.

I am not asking you to implement a library based off another implementation's 
specification. I am relaying implementation experience with the design you've 
chosen for your implementation and how well it's worked in other, related 
projects. Given that two different technologies have both run into this same 
problem, I think the llvm-libc folks should carefully consider the design 
decisions here. If it turns out this is the best way forward, that's fine.

> What you are suggesting is that we implement a GPU library that copies every 
> internal implementation detail that GNU has for that platform. So, let's just 
> copy-paste their headers into our LLVM `libc` and make sure we copy all of 
> their implementations too. Now what if someone wants to use `musl` instead? 
> Do we copy that one as well and have everything surrounded by `ifdef`s? Do we 
> just implement some meta libc that is compatible with every other `libc`? 
> This is not going to create a usable library, and as the person who would 
> presumably need to write it, I'm not going to spend my time copying other 
> `libc` headers.

I'm not asking you to copy other libc headers. I'm pointing out that having two 
separate headers, one for host and one for device, is a recipe for problems in 
practice because these two will invariably get out of sync in really 
fascinating ways that are extremely hard for people to debug. But maybe there's 
a misunderstanding here: I am assuming we consider it to be unsupported to use 
glibc/musl/etc on the host and llvm-libc on the device, but maybe that's a 
faulty assumption.

> The important point is that any symbol or macro we provide in the GPU's 
> headers has an implementation that is expected to be compatible with the 
> host. It's understandable if the macros and functions map to something 
> slightly different, as long as it does what we say it does.
>
>> So we're comfortable painting ourselves into a corner where llvm-libc is 
>> only usable with Clang, depending on the target?
>
> There might be somewhat of a misunderstanding here, I'm talking about the GPU 
> implementation of `libc` using LLVM's `libc`. Expecting a specific toolchain 
> is standard procedure for every single other offloading language. It's how we 
> build ROCm device libraries, CUDA device libraries, the OpenMP device 
> runtime, etc. LLVM's `libc` project is perfectly fine being compiled with 
> `gcc`, but the GPU is such a special case we don't have that luxury and need 
> to use `clang`. This is the same approach we do for OpenMP already.

Ah, yes this was a misunderstanding then, sorry for that.


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] D146385: [clang][ExtractAPI] Complete declaration fragments for TagDecl types defined in a typedef

2023-03-28 Thread R4444 via Phabricator via cfe-commits
Ruturaj4 updated this revision to Diff 509004.
Ruturaj4 added a comment.



1. Updating D146385 : [clang][ExtractAPI] 
Complete declaration fragments for TagDecl types defined in a typedef #
2. Enter a brief description of the changes included in this update.
3. The first line is used as subject, next lines as comment. #
4. If you intended to create a new revision, use:
5. $ arc diff --create

Update main to avoid build failures.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146385

Files:
  clang/include/clang/ExtractAPI/DeclarationFragments.h
  clang/lib/ExtractAPI/ExtractAPIVisitor.cpp
  clang/test/ExtractAPI/typedef_struct_enum.c

Index: clang/test/ExtractAPI/typedef_struct_enum.c
===
--- clang/test/ExtractAPI/typedef_struct_enum.c
+++ clang/test/ExtractAPI/typedef_struct_enum.c
@@ -21,6 +21,12 @@
   simple
 } Test2;
 
+struct Foo;
+typedef struct Foo TypedefedFoo;
+struct Foo {
+int bar;
+};
+
 //--- reference.output.json.in
 {
   "metadata": {
@@ -36,6 +42,11 @@
 "platform": {
   "architecture": "arm64",
   "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
 "name": "macosx"
   },
   "vendor": "apple"
@@ -47,6 +58,12 @@
   "source": "c:@E@Test2@simple",
   "target": "c:@E@Test2",
   "targetFallback": "Test2"
+},
+{
+  "kind": "memberOf",
+  "source": "c:@S@Foo@FI@bar",
+  "target": "c:@S@Foo",
+  "targetFallback": "Foo"
 }
   ],
   "symbols": [
@@ -82,6 +99,14 @@
   "preciseIdentifier": "c:i",
   "spelling": "unsigned int"
 },
+{
+  "kind": "text",
+  "spelling": " { ... } "
+},
+{
+  "kind": "identifier",
+  "spelling": "Test2"
+},
 {
   "kind": "text",
   "spelling": ";"
@@ -187,6 +212,14 @@
   "kind": "identifier",
   "spelling": "Test"
 },
+{
+  "kind": "text",
+  "spelling": " { ... } "
+},
+{
+  "kind": "identifier",
+  "spelling": "Test"
+},
 {
   "kind": "text",
   "spelling": ";"
@@ -225,6 +258,184 @@
   "pathComponents": [
 "Test"
   ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "struct"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "Foo"
+},
+{
+  "kind": "text",
+  "spelling": ";"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:@S@Foo"
+  },
+  "kind": {
+"displayName": "Structure",
+"identifier": "c.struct"
+  },
+  "location": {
+"position": {
+  "character": 8,
+  "line": 10
+},
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "Foo"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "Foo"
+  }
+],
+"title": "Foo"
+  },
+  "pathComponents": [
+"Foo"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "bar"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:@S@Foo@FI@bar"
+  },
+  "kind": {
+"displayName": "Instance Property",
+"identifier": "c.property"
+  },
+  "location": {
+"position": {
+  "character": 9,
+  "line": 11
+},
+"uri": "file://INPUT_DIR/input.h"
+  },
+  "names": {
+"navigator": [
+  {
+"kind": "identifier",
+"spelling": "bar"
+  }
+],
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "bar"
+  }
+],
+"title": "bar"
+  },
+  "pathComponents": [
+"Foo",
+"bar"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "keyword",
+  "spelling": "typedef"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "keyword"

[PATCH] D146418: Support for OpenMP 5.0 sec 2.12.7 - Declare Target initializer expressions

2023-03-28 Thread Ritanya via Phabricator via cfe-commits
RitanyaB marked an inline comment as not done.
RitanyaB added inline comments.



Comment at: clang/lib/Parse/ParseDecl.cpp:2093-2115
+void ParseImplicitDeclareTargetAttr(Decl *TargetDecl) {
+  if (TargetDecl && TargetDecl->hasAttr() &&
+  isa(TargetDecl)) {
+VarDecl *TargetVarDecl = cast(TargetDecl);
+Expr *Ex = TargetVarDecl->getInit()->IgnoreCasts();
+const DeclRefExpr *DeclRef = nullptr;
+if (Ex && isa(Ex) && TargetVarDecl->hasGlobalStorage()) {

ABataev wrote:
> RitanyaB wrote:
> > ABataev wrote:
> > > RitanyaB wrote:
> > > > ABataev wrote:
> > > > > It has nothing to do with parsing, sema analysis. Make it part of 
> > > > > Sema::checkDeclIsAllowedInOpenMPTarget
> > > > The Declaration in Sema::checkDeclIsAllowedInOpenMPTarget is 
> > > > incomplete. 
> > > > 
> > > > ```
> > > > VarDecl 0x1582b278  col:7 ptr1 'int **'
> > > > `-OMPDeclareTargetDeclAttr 0x1582b2e0  Implicit MT_To DT_Any 
> > > > 1
> > > >   `-<<>>
> > > > 
> > > > ```  
> > > > At this point, I do not have access to the initializer expression. Any 
> > > > suggestions? 
> > > The try to do it ActOnOpenMPDeclareTargetName
> > In the absence of a declare target clause, this function is not invoked (in 
> > the examples used above, the function is never called). Do you have any 
> > suggestions?
> For such decls use checkDeclIsAllowedInOpenMPTarget
As mentioned in my previous comment, the Decl in 
checkDeclIsAllowedInOpenMPTarget is not complete and I don't have access to the 
initializer expression hence I am unable to move my functionality into 
checkDeclIsAllowedInOpenMPTarget.
After ParseDeclarationAfterDeclaratorAndAttributes returns, the Decl is 
complete and I can process it accordingly. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146418

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


[clang-tools-extra] 2fccca8 - [clangd] Fix build by replacing unsigned long with std::vector::size_type.

2023-03-28 Thread Viktoriia Bakalova via cfe-commits

Author: Viktoriia Bakalova
Date: 2023-03-28T14:16:50Z
New Revision: 2fccca8d743613fac4d68f7b14799a672394f64b

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

LOG: [clangd] Fix build by replacing unsigned long with std::vector::size_type.

Added: 


Modified: 
clang-tools-extra/clangd/Hover.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index b399a12cd90c..af4fbe58b864 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -1451,7 +1451,7 @@ markup::Document HoverInfo::present() const {
 markup::Paragraph &P = Output.addParagraph();
 P.appendText("provides ");
 
-const unsigned long SymbolNamesLimit = 5;
+const std::vector::size_type SymbolNamesLimit = 5;
 auto Front =
 llvm::ArrayRef(UsedSymbolNames)
 .take_front(std::min(UsedSymbolNames.size(), SymbolNamesLimit));



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


[PATCH] D141824: [clang-repl] Add a command to load dynamic libraries

2023-03-28 Thread Vassil Vassilev via Phabricator via cfe-commits
v.g.vassilev accepted this revision.
v.g.vassilev added a comment.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141824

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


[PATCH] D146148: Float_t and double_t types shouldn't be modified by #pragma clang fp eval_method

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

In D146148#4227088 , @zahiraam wrote:

> In D146148#4224862 , @rjmccall 
> wrote:
>
>> In D146148#4224094 , 
>> @aaron.ballman wrote:
>>
>>> In D146148#4222306 , @zahiraam 
>>> wrote:
>>>
 In D146148#4221651 , @rjmccall 
 wrote:

> Zahira, this is what I was asking you when I asked whether modifying the 
> math.h header was acceptable: whether you were prepared to accept that 
> the warning would only fire on system math.h headers that we'd modified, 
> or whether you cared about making it work with non-cooperative headers.  
> I wasn't asking if you were willing to change the test code.

 Okay sorry about the confusion. I think the diagnostic should fire when 
 the user is including system's math.h and using float_t inside a scope 
 cotaining a #pragma clang fp eval-method. 
 I am not sure what you mean by "cooperative headers"?
>>>
>>> Ones that know about the special marking and use it (cooperative) or ones 
>>> that don't use the special marking (uncooperative). My intuition is that 
>>> we'll want this to work with any math.h because the problem still exists if 
>>> you use an older C standard library release with a newer Clang.
>>
>> Right.  It's not a great solution for standard stuff like this.
>>
> - We add a math.h compiler header that `#include_next`s the system math.h 
> and then adds the attribute.  I believe you can just add an attribute to 
> a typedef retroactively with something like `typedef float_t float_t 
> __attribute__((whatever))`.

 So when a user writes:

   #include 
int foo()
{
   #pragma clang fp eval_method(source)
  return sizeof(float_t);
}

 It would be as though the user wrote:

   #include "math.h"
   int foo()
   {
  #pragma clang fp eval_method(source)
 return sizeof(float_t);
   }

 where the content of this new math header being:

   #include_next 
   typedef float_t float_t __attribute__((whatever));
   typedef double_t double_t __attribute__((whatever));
>>>
>>> Correct.
>>
>> Right.  To be clear, this is a general thing that we already do to a bunch 
>> of other headers.  It doesn't require any special handling, the compiler's 
>> include directory is just the first entry on the search list for system 
>> headers.
>>
> - We do checks on every typedef declaration.  There's a 
> builtin-identifier trick that we do with library functions that we should 
> be able to generalize to typedefs, so you wouldn't need to actually do 
> string comparisons, you'd just check whether the `IdentifierInfo*` was 
> storing a special ID.  We'd set that up in `initializeBuiltins` at the 
> start of the translation unit, so the overhead would just be that we'd 
> create two extra `IdentifierInfo*`s in every TU.
>
> The builtin ID logic is currently specific to builtin *functions*, and I 
> don't think we'd want to hack typedef names into that.  But the same 
> storage in `IdentifierInfo*` is also used for identifying the ObjC 
> context-sensitive keywords, by just offsetting the builtin IDs by the 
> NUM_OBJC_KEYWORD.  You should be able to generalize that by also 
> introducing a concept of a builtin *type* name, so that e.g. IDs in 
> [0,NUM_OBJC_KEYWORDS) are ObjCKeywordKinds, IDs in [NUM_OBJC_KEYWORDS, 
> NUM_OBJC_KEYWORDS+NUM_BUILTIN_TYPES) are BuiltinTypeKinds (when you 
> subtract NUM_OBJC_KEYWORDS), and IDs in 
> [NUM_OBJC_KEYWORDS+NUM_BUILTIN_TYPES,∞) are builtin function IDs (when 
> you subtract NUM_OBJC_KEYWORDS+NUM_BUILTIN_TYPES).

 Need to look at this more closely to understand what you are suggesting.
>>>
>>> Basically, he's saying that instead of doing a string comparison against 
>>> the name of the typedef, we can ask the typedef for its `IdentifierInfo *` 
>>> for the name and do a pointer comparison against an `IdentiferInfo *` 
>>> that's cached.
>>
>> That's a trick we could do, but I'm actually suggesting a step better than 
>> that.  The way we handle builtin functions is that we have bits in the 
>> `IdentifierInfo` structure saying that the identifier is a builtin name.  
>> Those bits are generally ignored except by a few places in Sema that check 
>> for them during lookup.  We eagerly create those identifiers and set those 
>> bits at the start of the TU.  We could do the same trick for these names, so 
>> that when we're declaring a typedef at global scope we just check whether 
>> the name is special and trigger some special processing only if so.  It 
>> would add a very, very small overhead to processing every typedef 
>> declaration, comparabl

[PATCH] D146885: [clang-tidy][NFC] add debug log when clean empty namespace

2023-03-28 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL requested changes to this revision.
PiotrZSL added a comment.
This revision now requires changes to proceed.

This shouldn't be delivered. Do such tests, locally, instead of committing them.
This change impact clang, and all tools, not only clang-tidy, therfor 
[clang-tidy] prefix is misleading.

Issue related to modernize-concat-nested-namespaces should be fixed by 
clang-tidy itself.
It's visible in AST, so clang-tidy could fix it.

  TranslationUnitDecl
  `-NamespaceDecl  line:1:11 a
`-NamespaceDecl  col:11 b

For me this change should be abandoned.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146885

___
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-03-28 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

In D146973#4227433 , @aaron.ballman 
wrote:

> I am not asking you to implement a library based off another implementation's 
> specification. I am relaying implementation experience with the design you've 
> chosen for your implementation and how well it's worked in other, related 
> projects. Given that two different technologies have both run into this same 
> problem, I think the llvm-libc folks should carefully consider the design 
> decisions here. If it turns out this is the best way forward, that's fine.

Sorry, that was more directed at Johannes, This is definitely a hard problem. 
Each approach has certain benefits, but I think keeping the headers synced like 
we do in OpenMP has mainly worked thus far because we don't have any actual 
implementations of most of it. If we want to provide a library I don't think 
there's a reasonable way to implement it as a unified header unless we control 
the system header as well. I'm hoping that `libc` offers a sufficiently small 
surface that we should be able to provide functionality that's expected for 
both. And in some cases it should be fine to share existing headers, but it 
shouldn't be the expected route it all I'm saying.

> I'm not asking you to copy other libc headers. I'm pointing out that having 
> two separate headers, one for host and one for device, is a recipe for 
> problems in practice because these two will invariably get out of sync in 
> really fascinating ways that are extremely hard for people to debug. But 
> maybe there's a misunderstanding here: I am assuming we consider it to be 
> unsupported to use glibc/musl/etc on the host and llvm-libc on the device, 
> but maybe that's a faulty assumption.

We can't do that for the time being, since LLVM's `libc` is still in 
development. It's not a sufficient replacement for the host `libc` at this 
point. It may be an interesting point to get to in the future, it would make it 
much easier to keep things in sync for sure. It may be easier to stipulate 
something like that with `libc++` when we get to that point since `libc++` is 
more complete as far as I'm aware.


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] D146418: Support for OpenMP 5.0 sec 2.12.7 - Declare Target initializer expressions

2023-03-28 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/Parse/ParseDecl.cpp:2093-2115
+void ParseImplicitDeclareTargetAttr(Decl *TargetDecl) {
+  if (TargetDecl && TargetDecl->hasAttr() &&
+  isa(TargetDecl)) {
+VarDecl *TargetVarDecl = cast(TargetDecl);
+Expr *Ex = TargetVarDecl->getInit()->IgnoreCasts();
+const DeclRefExpr *DeclRef = nullptr;
+if (Ex && isa(Ex) && TargetVarDecl->hasGlobalStorage()) {

RitanyaB wrote:
> ABataev wrote:
> > RitanyaB wrote:
> > > ABataev wrote:
> > > > RitanyaB wrote:
> > > > > ABataev wrote:
> > > > > > It has nothing to do with parsing, sema analysis. Make it part of 
> > > > > > Sema::checkDeclIsAllowedInOpenMPTarget
> > > > > The Declaration in Sema::checkDeclIsAllowedInOpenMPTarget is 
> > > > > incomplete. 
> > > > > 
> > > > > ```
> > > > > VarDecl 0x1582b278  col:7 ptr1 'int **'
> > > > > `-OMPDeclareTargetDeclAttr 0x1582b2e0  Implicit MT_To 
> > > > > DT_Any 1
> > > > >   `-<<>>
> > > > > 
> > > > > ```  
> > > > > At this point, I do not have access to the initializer expression. 
> > > > > Any suggestions? 
> > > > The try to do it ActOnOpenMPDeclareTargetName
> > > In the absence of a declare target clause, this function is not invoked 
> > > (in the examples used above, the function is never called). Do you have 
> > > any suggestions?
> > For such decls use checkDeclIsAllowedInOpenMPTarget
> As mentioned in my previous comment, the Decl in 
> checkDeclIsAllowedInOpenMPTarget is not complete and I don't have access to 
> the initializer expression hence I am unable to move my functionality into 
> checkDeclIsAllowedInOpenMPTarget.
> After ParseDeclarationAfterDeclaratorAndAttributes returns, the Decl is 
> complete and I can process it accordingly. 
For decls, explicitly marked as DeclareTarget, use The try to do it 
ActOnOpenMPDeclareTargetName. For decls, referenced in the initializers, use 
checkDeclIsAllowedInOpenMPTarget.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146418

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


[PATCH] D146971: [Sema] Populate declarations inside TypeLocs for some invalid types

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

LGTM, though the change should come with a release note. Suggestion you can 
take or leave as you see fit: should we turn the places where we removed the 
null pointer check into assertions that the pointer is nonnull? Or are we 
hoping the crash will be sufficient to tell us when we've missed a case?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146971

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


[PATCH] D144862: Include highlighed, include on hover, code lense for used symbols

2023-03-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 509010.
VitaNuo added a comment.

Use vscode command.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144862

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/XRefs.h

Index: clang-tools-extra/clangd/XRefs.h
===
--- clang-tools-extra/clangd/XRefs.h
+++ clang-tools-extra/clangd/XRefs.h
@@ -32,6 +32,8 @@
 namespace clangd {
 class ParsedAST;
 
+std::vector findCodeLens(ParsedAST &AST);
+
 // Describes where a symbol is declared and defined (as far as clangd knows).
 // There are three cases:
 //  - a declaration only, no definition is known (e.g. only header seen)
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.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"
@@ -62,9 +65,11 @@
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
+#include  
 
 namespace clang {
 namespace clangd {
+std::string HelloString = "Hello";
 namespace {
 
 // Returns the single definition of the entity declared by D, if visible.
@@ -74,6 +79,7 @@
 // Kinds of nodes that always return nullptr here will not have definitions
 // reported by locateSymbolAt().
 const NamedDecl *getDefinition(const NamedDecl *D) {
+  std::string AnotherString;
   assert(D);
   // Decl has one definition that we can find.
   if (const auto *TD = dyn_cast(D))
@@ -118,6 +124,7 @@
 // FindSymbols.
 std::optional toLSPLocation(const SymbolLocation &Loc,
   llvm::StringRef TUPath) {
+  std::string ThirdString;
   if (!Loc)
 return std::nullopt;
   auto Uri = URI::parse(Loc.FileURI);
@@ -1213,6 +1220,27 @@
   return std::nullopt;
 }
 
+std::vector
+collectMacroReferences(ParsedAST &AST) {
+  const auto &SM = AST.getSourceManager();
+  //  FIXME: !!this is a hacky way to collect macro references.
+  std::vector Macros;
+  auto &PP = AST.getPreprocessor();
+  for (const syntax::Token &Tok :
+   AST.getTokens().spelledTokens(SM.getMainFileID())) {
+auto Macro = locateMacroAt(Tok, PP);
+if (!Macro)
+  continue;
+if (auto DefLoc = Macro->Info->getDefinitionLoc(); DefLoc.isValid())
+  Macros.push_back(
+  {Tok.location(),
+   include_cleaner::Macro{/*Name=*/PP.getIdentifierInfo(Tok.text(SM)),
+  DefLoc},
+   include_cleaner::RefType::Explicit});
+  }
+  return Macros;
+}
+
 } // namespace
 
 std::vector findDocumentHighlights(ParsedAST &AST,
@@ -1231,11 +1259,96 @@
   DeclRelation::TemplatePattern | DeclRelation::Alias;
   auto TargetDecls =
   targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver());
+
+  const IncludeStructure &Includes = AST.getIncludeStructure();
+  include_cleaner::Includes ConvertedIncludes =
+  convertIncludes(AST.getSourceManager(), Includes.MainFileIncludes);
+  include_cleaner::walkUsed(
+AST.getLocalTopLevelDecls(),
+collectMacroReferences(AST),
+AST.getPragmaIncludes(),
+AST.getSourceManager(),
+[&](const include_cleaner::SymbolReference &Ref,
+llvm::ArrayRef Providers) {
+// std::string SymbolName;
+// switch (Ref.Target.kind()) {
+// case include_cleaner::Symbol::Macro:
+//   break;
+// case include_cleaner::Symbol::Declaration:
+//   SymbolName = static_cast(Ref.Target.declaration()).getNameAsString();
+//   if (SymbolName == "string") {
+// llvm::errs() << "FOUND STRING" << "\n";
+// llvm::errs() << "CUR LOCATION: " << "\n";
+// llvm::errs() << SM.getDecomposedLoc(*CurLoc).second << "\n"; 
+// llvm::errs() << "REF LOCATION: " << "\n";
+// llvm::errs() << SM.getDecomposedLoc(Ref.RefLocation).second << "\n";   
+//   }
+//   break;
+// }
+if (Ref.RefLocation != *CurLoc) {
+  return;  
+}
+llvm::errs() << "GOT PAST THE GUARD" << "\n";
+// the location under cursor corresponds to the current symbo

[PATCH] D146412: [NFC] Fix potential use-after-free in DumpModuleInfoAction::ExecuteAction()

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

In D146412#4223272 , @Fznamznon wrote:

> In D146412#4220021 , @kastiglione 
> wrote:
>
>> I understand the potential for a use after free, since `OutputStream` is a 
>> raw pointer, but I don't understand the fix.
>
> Okay, probably commit message is a little confusing. The potential for a use 
> after free is that `OutputStream` is a raw pointer as you already noted, but 
> it is also accessible outside of `DumpModuleInfoAction::ExecuteAction`. 
> Before the patch there was the case where result of local unique_ptr::get was 
> saved there. When the function is exited, unique_ptr frees the memory it 
> holds, making `OutputStream` poiniting to freed memory. Since `OutputStream` 
> can be easily accessed outside of `DumpModuleInfoAction::ExecuteAction`, 
> hence the potential for use-after-free. I wasn't sure if assigning `nullptr` 
> to `OutputStream` at the end of `DumpModuleInfoAction::ExecuteAction` was a 
> good idea, so I just added code avoiding saving result of unique_ptr::get to 
> `OutputStream` .

Hmmm, but this looks to be the only place `DumpModuleInfoAction` will 
initialize `OutputStream` to a nonnull value, so that seems to be a pretty 
significant change in behavior.

Should `OutputStream` be made into a `shared_ptr` so we can clarify the memory 
ownership instead of leaving it as a raw pointer? That should also address the 
use-after-free.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146412

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


[PATCH] D146922: [clang-tidy] Fix false positve for defaulted move constructor in performance-noexcept-move-constructor

2023-03-28 Thread André Schackier via Phabricator via cfe-commits
AMS21 updated this revision to Diff 509013.
AMS21 added a comment.

Implemented suggested fixes from reviews


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146922

Files:
  clang-tools-extra/clang-tidy/performance/NoexceptMoveConstructorCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance/noexcept-move-constructor-fix.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance/noexcept-move-constructor.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance/noexcept-move-constructor.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance/noexcept-move-constructor.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance/noexcept-move-constructor.cpp
@@ -4,7 +4,7 @@
   A(A &&);
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: move constructors should be marked noexcept [performance-noexcept-move-constructor]
   A &operator=(A &&);
-  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: move assignment operators should
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: move assignment operators should be marked noexcept [performance-noexcept-move-constructor]
 };
 
 struct B {
@@ -13,6 +13,95 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: noexcept specifier on the move constructor evaluates to 'false' [performance-noexcept-move-constructor]
 };
 
+template 
+struct C
+{
+  C(C &&);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: move constructors should be marked noexcept [performance-noexcept-move-constructor]
+  C& operator=(C &&);
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: move assignment operators should be marked noexcept [performance-noexcept-move-constructor]
+};
+
+struct D
+{
+  static constexpr bool kFalse = false;
+  D(D &&) noexcept(kFalse) = default;
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: noexcept specifier on the move constructor evaluates to 'false' [performance-noexcept-move-constructor]
+  D& operator=(D &&) noexcept(kFalse) = default;
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: noexcept specifier on the move assignment operator evaluates to 'false'
+};
+
+template 
+struct E
+{
+  static constexpr bool kFalse = false;
+  E(E &&) noexcept(kFalse);
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: noexcept specifier on the move constructor evaluates to 'false' [performance-noexcept-move-constructor]
+  E& operator=(E &&) noexcept(kFalse);
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: noexcept specifier on the move assignment operator evaluates to 'false'
+};
+
+template 
+struct F
+{
+  static constexpr bool kFalse = false;
+  F(F &&) noexcept(kFalse) = default;
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: noexcept specifier on the move constructor evaluates to 'false' [performance-noexcept-move-constructor]
+  F& operator=(F &&) noexcept(kFalse) = default;
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: noexcept specifier on the move assignment operator evaluates to 'false'
+};
+
+struct Field
+{
+  Field() = default;
+  Field(Field&&) noexcept(false) {
+  }
+  Field& operator=(Field &&) noexcept(false) {
+return *this;
+  }
+};
+
+struct G {
+  G(G &&) = default;
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: move constructors should be marked noexcept [performance-noexcept-move-constructor]
+  G& operator=(G &&) = default;
+  // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: move assignment operators should be marked noexcept [performance-noexcept-move-constructor]
+
+  Field field;
+};
+
+void throwing_function() noexcept(false) {}
+
+struct H {
+  H(H &&) noexcept(noexcept(throwing_function()));
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: noexcept specifier on the move constructor evaluates to 'false' [performance-noexcept-move-constructor]
+  H &operator=(H &&) noexcept(noexcept(throwing_function()));
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: noexcept specifier on the move assignment operator evaluates to 'false'
+};
+
+template 
+struct I {
+  I(I &&) noexcept(noexcept(throwing_function()));
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: noexcept specifier on the move constructor evaluates to 'false' [performance-noexcept-move-constructor]
+  I &operator=(I &&) noexcept(noexcept(throwing_function()));
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: noexcept specifier on the move assignment operator evaluates to 'false'
+};
+
+template  struct TemplatedType {
+  static void f() {}
+};
+
+template <> struct TemplatedType {
+  static void f() noexcept {}
+};
+
+struct J {
+  J(J &&) noexcept(noexcept(TemplatedType::f()));
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: noexcept specifier on the move constructor evaluates to 'false' [performance-noexcept-move-constructor]
+  J &operator=(J &&) noexcept(noexcept(TemplatedType::f()));
+  // CHECK-MESSAGES: :[[@LINE-1]]:31: warning: noexcept specifier on the move assignment operator evaluates to 'false' [performance-noexcept-move-cons

[PATCH] D146995: [clang-format][NFC] Refactor unit tests for "LambdaBodyIndentation: OuterScope" option.

2023-03-28 Thread Jon Phillips via Phabricator via cfe-commits
jp4a50 added a comment.

If you guys are happy with this, could you please merge it for me?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146995

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


[PATCH] D126959: [C++20][Modules] Introduce an implementation module.

2023-03-28 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 509014.
iains added a comment.

rebased, retested.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126959

Files:
  clang/include/clang/Basic/Module.h
  clang/include/clang/Lex/ModuleMap.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaModule.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/CXX/module/basic/basic.def.odr/p4.cppm
  clang/test/CXX/module/basic/basic.link/p2.cppm
  clang/test/CodeGenCXX/module-intializer.cpp

Index: clang/test/CodeGenCXX/module-intializer.cpp
===
--- clang/test/CodeGenCXX/module-intializer.cpp
+++ clang/test/CodeGenCXX/module-intializer.cpp
@@ -18,17 +18,17 @@
 // RUN: -emit-llvm -o - | FileCheck %s --check-prefix=CHECK-P
 
 // RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M.cpp \
-// RUN: -fmodule-file=N.pcm -fmodule-file=O.pcm -fmodule-file=M-part.pcm \
+// RUN: -fmodule-file=N=N.pcm -fmodule-file=O=O.pcm -fmodule-file=M:Part=M-part.pcm \
 // RUN:-emit-module-interface -o M.pcm
 // RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M.pcm -S -emit-llvm \
 // RUN:  -o - | FileCheck %s --check-prefix=CHECK-M
 
 // RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 useM.cpp \
-// RUN: -fmodule-file=M.pcm -S -emit-llvm  -o - \
+// RUN: -fmodule-file=M=M.pcm -S -emit-llvm  -o - \
 // RUN: | FileCheck %s --check-prefix=CHECK-USE
 
 // RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M-impl.cpp \
-// RUN: -fmodule-file=M.pcm -S -emit-llvm  -o - \
+// RUN: -fmodule-file=M=M.pcm -S -emit-llvm  -o - \
 // RUN: | FileCheck %s --check-prefix=CHECK-IMPL
 
 // RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 N.cpp -S -emit-llvm \
@@ -41,7 +41,7 @@
 // RUN:   -o - | FileCheck %s --check-prefix=CHECK-P
 
 // RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M.cpp \
-// RUN:   -fmodule-file=N.pcm -fmodule-file=O.pcm -fmodule-file=M-part.pcm \
+// RUN:   -fmodule-file=N.pcm -fmodule-file=O=O.pcm -fmodule-file=M:Part=M-part.pcm \
 // RUN:   -S -emit-llvm -o - | FileCheck %s --check-prefix=CHECK-M
 
 //--- N-h.h
Index: clang/test/CXX/module/basic/basic.link/p2.cppm
===
--- clang/test/CXX/module/basic/basic.link/p2.cppm
+++ clang/test/CXX/module/basic/basic.link/p2.cppm
@@ -39,19 +39,21 @@
 }
 
 //--- M.cpp
-// expected-no-diagnostics
+
 module M;
 
-// FIXME: Use of internal linkage entities should be rejected.
 void use_from_module_impl() {
   external_linkage_fn();
   module_linkage_fn();
-  internal_linkage_fn();
+  internal_linkage_fn(); // expected-error {{no matching function for call to 'internal_linkage_fn'}}
   (void)external_linkage_class{};
   (void)module_linkage_class{};
-  (void)internal_linkage_class{};
   (void)external_linkage_var;
   (void)module_linkage_var;
+
+  // FIXME: Issue #61427 Internal-linkage declarations in the interface TU
+  // should not be not visible here.
+  (void)internal_linkage_class{};
   (void)internal_linkage_var;
 }
 
Index: clang/test/CXX/module/basic/basic.def.odr/p4.cppm
===
--- clang/test/CXX/module/basic/basic.def.odr/p4.cppm
+++ clang/test/CXX/module/basic/basic.def.odr/p4.cppm
@@ -143,9 +143,6 @@
   (void)&inline_var_exported;
   (void)&const_var_exported;
 
-  // CHECK: define {{.*}}@_ZL26used_static_module_linkagev
-  used_static_module_linkage();
-
   // CHECK: define linkonce_odr {{.*}}@_ZW6Module26used_inline_module_linkagev
   used_inline_module_linkage();
 
@@ -154,8 +151,12 @@
 
   (void)&extern_var_module_linkage;
   (void)&inline_var_module_linkage;
+
+  // FIXME: Issue #61427 Internal-linkage declarations in the interface TU
+  // should not be not visible here.
   (void)&static_var_module_linkage; // FIXME: Should not be visible here.
-  (void)&const_var_module_linkage;
+
+  (void)&const_var_module_linkage; // FIXME: will be visible after P2788R0
 }
 
 //--- user.cpp
@@ -176,5 +177,6 @@
   (void)&inline_var_exported;
   (void)&const_var_exported;
 
+  // Internal-linkage declarations are not visible here.
   // Module-linkage declarations are not visible here.
 }
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -2719,7 +2719,7 @@
   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
-  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Kind
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fix

[clang] 256914b - [AIX] Update release notes regarding -mxcoff-build-id and the profile runtime

2023-03-28 Thread Wael Yehia via cfe-commits

Author: Wael Yehia
Date: 2023-03-28T14:53:12Z
New Revision: 256914bf1c13a7f2dc1343b9761cae15b8b37e00

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

LOG: [AIX] Update release notes regarding -mxcoff-build-id and the profile 
runtime

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
llvm/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 34cfb8e672ef5..aabaab5ca5dc2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -338,6 +338,11 @@ CUDA Support
 
 AIX Support
 ^^^
+- Add an AIX-only link-time option, `-mxcoff-build-id=0xHEXSTRING`, to allow 
users
+  to embed a hex id in their binary such that it's readable by the program 
itself.
+  This option is an alternative to the `--build-id=0xHEXSTRING` GNU linker 
option
+  which is currently not supported by the AIX linker.
+
 
 WebAssembly Support
 ^^^

diff  --git a/llvm/docs/ReleaseNotes.rst b/llvm/docs/ReleaseNotes.rst
index 6f78497644479..3791d5116124e 100644
--- a/llvm/docs/ReleaseNotes.rst
+++ b/llvm/docs/ReleaseNotes.rst
@@ -127,6 +127,8 @@ Changes to the PowerPC Backend
   RO data section. This option should be used with the ``-fdata-sections``
   option, and is not supported with ``-fno-data-sections``. The option is
   only supported on AIX.
+* On AIX, teach the profile runtime to check for a build-id string; such string
+  can be created by the -mxcoff-build-id option.
 
 Changes to the RISC-V Backend
 -



___
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-03-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 509015.
VitaNuo added a comment.

Remove redundant code.


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/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
@@ -5,8 +5,8 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-#include "Annotations.h"
 #include "AST.h"
+#include "Annotations.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "SourceCode.h"
@@ -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;
 }
@@ -1876,8 +1880,8 @@
 ASSERT_GT(A.points().size(), 0u) << Case;
 for (auto Pos : A.points())
   EXPECT_THAT(findType(AST, Pos),
-  ElementsAre(
-sym("Target", HeaderA.range("Target"), HeaderA.range("Target"
+  ElementsAre(sym("Target", HeaderA.range("Target"),
+  HeaderA.range("Target"
   << Case;
   }
 
@@ -1888,11 +1892,12 @@
 TU.Code = A.code().str();
 ParsedAST AST = TU.build();
 
-EXPECT_THAT(findType(AST, A.point()),
-UnorderedElementsAre(
-  sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
-  sym("smart_ptr", HeaderA.range("smart_ptr"), HeaderA.range("smart_ptr"))
-))
+EXPECT_THAT(
+findType(AST, A.point()),
+UnorderedElementsAre(
+sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
+sym("smart_ptr", HeaderA.range("smart_ptr"),
+HeaderA.range("smart_ptr"
 << Case;
   }
 }
@@ -1901,6 +1906,25 @@
   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["private.h"] = guard(R"cpp(
+// IWYU pragma: private, include "public.h"
+int foo(); 
+  )cpp");
+  TU.AdditionalFiles["public.h"] = guard("");
+  TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+namespace std {
+  template
+  class vector{};
+}
+  )cpp");
+  TU.AdditionalFiles["forward.h"] = guard("class Bar;");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
 
   auto AST = TU.build();
   std::vector> ExpectedLocations;
@@ -2293,6 +2317,42 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp",
+
+  R"cpp([[#in^clude "public.h"]]
+#include "private.h"
+int fooVar = [[foo]]();
+  )cpp",
+
+  R"cpp(#include "bar.h"
+#include "for^ward.h"
+Bar *x;
+  )cpp",
+
+  R"cpp([[#include "b^ar.h"]]
+#define DEF(X) const Bar *X
+[[DEF]](a);
+  )cpp",
+
+  R"cpp([[#in^clude "bar.h"]]
+#define BAZ(X) const X x
+BAZ([[Bar]]);
+  )cpp"};
+  for (const char *Test : Tests)
+checkFindRefs(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
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.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 +51,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 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Supp

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

2023-03-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 509017.
VitaNuo added a comment.

Formatting.


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/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
@@ -5,8 +5,8 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-#include "Annotations.h"
 #include "AST.h"
+#include "Annotations.h"
 #include "ParsedAST.h"
 #include "Protocol.h"
 #include "SourceCode.h"
@@ -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;
 }
@@ -1876,8 +1880,8 @@
 ASSERT_GT(A.points().size(), 0u) << Case;
 for (auto Pos : A.points())
   EXPECT_THAT(findType(AST, Pos),
-  ElementsAre(
-sym("Target", HeaderA.range("Target"), HeaderA.range("Target"
+  ElementsAre(sym("Target", HeaderA.range("Target"),
+  HeaderA.range("Target"
   << Case;
   }
 
@@ -1888,11 +1892,12 @@
 TU.Code = A.code().str();
 ParsedAST AST = TU.build();
 
-EXPECT_THAT(findType(AST, A.point()),
-UnorderedElementsAre(
-  sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
-  sym("smart_ptr", HeaderA.range("smart_ptr"), HeaderA.range("smart_ptr"))
-))
+EXPECT_THAT(
+findType(AST, A.point()),
+UnorderedElementsAre(
+sym("Target", HeaderA.range("Target"), HeaderA.range("Target")),
+sym("smart_ptr", HeaderA.range("smart_ptr"),
+HeaderA.range("smart_ptr"
 << Case;
   }
 }
@@ -1901,6 +1906,25 @@
   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["private.h"] = guard(R"cpp(
+// IWYU pragma: private, include "public.h"
+int foo(); 
+  )cpp");
+  TU.AdditionalFiles["public.h"] = guard("");
+  TU.AdditionalFiles["system/vector"] = guard(R"cpp(
+namespace std {
+  template
+  class vector{};
+}
+  )cpp");
+  TU.AdditionalFiles["forward.h"] = guard("class Bar;");
+  TU.ExtraArgs.push_back("-isystem" + testPath("system"));
 
   auto AST = TU.build();
   std::vector> ExpectedLocations;
@@ -2293,6 +2317,42 @@
 checkFindRefs(Test);
 }
 
+TEST(FindReferences, UsedSymbolsFromInclude) {
+  const char *Tests[] = {
+  R"cpp([[#include ^"bar.h"]]
+int fstBar = [[bar1]]();
+int sndBar = [[bar2]]();
+[[Bar]] bar;
+int macroBar = [[BAR]];
+  )cpp",
+
+  R"cpp([[#in^clude ]]
+std::[[vector]] vec;
+  )cpp",
+
+  R"cpp([[#in^clude "public.h"]]
+#include "private.h"
+int fooVar = [[foo]]();
+  )cpp",
+
+  R"cpp(#include "bar.h"
+#include "for^ward.h"
+Bar *x;
+  )cpp",
+
+  R"cpp([[#include "b^ar.h"]]
+#define DEF(X) const Bar *X
+[[DEF]](a);
+  )cpp",
+
+  R"cpp([[#in^clude "bar.h"]]
+#define BAZ(X) const X x
+BAZ([[Bar]]);
+  )cpp"};
+  for (const char *Test : Tests)
+checkFindRefs(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
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.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 +51,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 +65,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ost

[PATCH] D144862: Include highlighed, include on hover, code lense for used symbols

2023-03-28 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 509019.
VitaNuo added a comment.

Remove unrelated code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144862

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/Protocol.cpp
  clang-tools-extra/clangd/Protocol.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/XRefs.h

Index: clang-tools-extra/clangd/XRefs.h
===
--- clang-tools-extra/clangd/XRefs.h
+++ clang-tools-extra/clangd/XRefs.h
@@ -32,6 +32,8 @@
 namespace clangd {
 class ParsedAST;
 
+std::vector findCodeLens(ParsedAST &AST);
+
 // Describes where a symbol is declared and defined (as far as clangd knows).
 // There are three cases:
 //  - a declaration only, no definition is known (e.g. only header seen)
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -10,12 +10,15 @@
 #include "FindSymbols.h"
 #include "FindTarget.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"
@@ -62,9 +65,11 @@
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
+#include  
 
 namespace clang {
 namespace clangd {
+std::string HelloString = "Hello";
 namespace {
 
 // Returns the single definition of the entity declared by D, if visible.
@@ -74,6 +79,7 @@
 // Kinds of nodes that always return nullptr here will not have definitions
 // reported by locateSymbolAt().
 const NamedDecl *getDefinition(const NamedDecl *D) {
+  std::string AnotherString;
   assert(D);
   // Decl has one definition that we can find.
   if (const auto *TD = dyn_cast(D))
@@ -118,6 +124,7 @@
 // FindSymbols.
 std::optional toLSPLocation(const SymbolLocation &Loc,
   llvm::StringRef TUPath) {
+  std::string ThirdString;
   if (!Loc)
 return std::nullopt;
   auto Uri = URI::parse(Loc.FileURI);
@@ -1212,7 +1219,6 @@
   }
   return std::nullopt;
 }
-
 } // namespace
 
 std::vector findDocumentHighlights(ParsedAST &AST,
@@ -1231,6 +1237,7 @@
   DeclRelation::TemplatePattern | DeclRelation::Alias;
   auto TargetDecls =
   targetDecl(N->ASTNode, Relations, AST.getHeuristicResolver());
+
   if (!TargetDecls.empty()) {
 // FIXME: we may get multiple DocumentHighlights with the same location
 // and different kinds, deduplicate them.
@@ -1312,8 +1319,101 @@
 }
 } // namespace
 
+std::vector findCodeLens(ParsedAST &AST) {
+  // TODO(bakalova) find ranges
+  // TODO(bakalova) find used symbols
+
+  std::vector Result;
+  std::vector Includes = AST.getIncludeStructure().MainFileIncludes;
+
+  for (auto Inclusion : Includes) {
+std::set UsedSymbols;
+walkUsed(AST.getLocalTopLevelDecls(),
+collectMacroReferences(AST),
+AST.getPragmaIncludes(),
+AST.getSourceManager(),
+[&](const include_cleaner::SymbolReference &Ref,
+llvm::ArrayRef Providers) {
+
+std::string Name;
+switch(Ref.Target.kind()) {
+   case include_cleaner::Symbol::Declaration:
+Name = cast(Ref.Target.declaration())
+.getDeclName()
+.getAsString();   
+break;
+  case include_cleaner::Symbol::Macro:
+Name = Ref.Target.macro().Name->getName(); 
+break;
+}  
+for (const include_cleaner::Header &H : Providers) {
+  switch (H.kind()) {
+  case include_cleaner::Header::Physical:
+if (H.physical()->tryGetRealPathName().contains(
+llvm::StringRef(Inclusion.Written).trim("\"<>"))) {
+  UsedSymbols.insert(Name);
+}
+break;
+  case include_cleaner::Header::Standard:
+if (Inclusion.Written == H.standard().name()) {
+  UsedSymbols.insert(Name);
+}
+break;
+  // TODO(bakalova) does the verbatim thing include quotes or not?
+  case include_cleaner::Header::Verbatim:
+if (Inclusion.Written == H.verbatim()) {
+  UsedSymbols.insert(Name);
+}
+break;
+  }
+}
+  });
+
+CodeLens Lens;
+Lens.range = clangd::Range{Position{Inclusion.HashLine, 0}, Position{Inclusion.HashLine, 0}};
+Command cmd;
+
+std::vector UsedSymbolsDeduped;
+for (auto Sym : UsedSymbols) {
+  UsedSymbolsDeduped.push_back(Sym);
+}
+
+cmd.title = std::to_string(UsedSymbolsDeduped.size()) + " used symbols";
+   

  1   2   3   >