[PATCH] D92290: [clangd] Factor out the heuristic resolver code into its own class

2021-02-07 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

(This patch should be ready for another round of review.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92290

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


[PATCH] D96245: [clangd] Propagate CodeActions in addition to Fixes for diagnostics

2021-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
Herald added subscribers: usaxena95, arphaman.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Fixes only allow modifications to local file containing the diagnostics,
with CodeActions we'll be able to provide changes that can fix the issue
outside of the local file (e.g. build file/header modificiations).

As an implementation detail, we now covert all the fixes to codeactions
directly at publish time, rather than onCodeAction requests. So this
implies some extra copies on each diag release.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96245

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/Diagnostics.h
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -693,7 +693,8 @@
   // Transform diagnostics and check the results.
   std::vector>> LSPDiags;
   toLSPDiags(D, MainFile, Opts,
- [&](clangd::Diagnostic LSPDiag, ArrayRef Fixes) {
+ [&](clangd::Diagnostic LSPDiag, ArrayRef Fixes,
+ ArrayRef) {
LSPDiags.push_back(
{std::move(LSPDiag),
 std::vector(Fixes.begin(), Fixes.end())});
@@ -712,7 +713,8 @@
   LSPDiags.clear();
   Opts.EmitRelatedLocations = true;
   toLSPDiags(D, MainFile, Opts,
- [&](clangd::Diagnostic LSPDiag, ArrayRef Fixes) {
+ [&](clangd::Diagnostic LSPDiag, ArrayRef Fixes,
+ ArrayRef) {
LSPDiags.push_back(
{std::move(LSPDiag),
 std::vector(Fixes.begin(), Fixes.end())});
@@ -1334,16 +1336,14 @@
   D.InsideMainFile = true;
   N.InsideMainFile = false;
   toLSPDiags(D, {}, Opts,
- [&](clangd::Diagnostic LSPDiag, ArrayRef) {
-   EXPECT_EQ(LSPDiag.range, D.Range);
- });
+ [&](clangd::Diagnostic LSPDiag, ArrayRef,
+ ArrayRef) { EXPECT_EQ(LSPDiag.range, D.Range); });
 
   D.InsideMainFile = false;
   N.InsideMainFile = true;
   toLSPDiags(D, {}, Opts,
- [&](clangd::Diagnostic LSPDiag, ArrayRef) {
-   EXPECT_EQ(LSPDiag.range, N.Range);
- });
+ [&](clangd::Diagnostic LSPDiag, ArrayRef,
+ ArrayRef) { EXPECT_EQ(LSPDiag.range, N.Range); });
 }
 
 } // namespace
Index: clang-tools-extra/clangd/Diagnostics.h
===
--- clang-tools-extra/clangd/Diagnostics.h
+++ clang-tools-extra/clangd/Diagnostics.h
@@ -97,6 +97,7 @@
   std::vector Notes;
   /// *Alternative* fixes for this diagnostic, one should be chosen.
   std::vector Fixes;
+  std::vector Actions;
 };
 llvm::raw_ostream <<(llvm::raw_ostream , const Diag );
 
@@ -107,9 +108,11 @@
 /// separate diagnostics with their corresponding fixits. Notes outside main
 /// file do not have a corresponding LSP diagnostic, but can still be included
 /// as part of their main diagnostic's message.
-void toLSPDiags(
-const Diag , const URIForFile , const ClangdDiagnosticOptions ,
-llvm::function_ref)> OutFn);
+void toLSPDiags(const Diag , const URIForFile ,
+const ClangdDiagnosticOptions ,
+llvm::function_ref,
+llvm::ArrayRef)>
+OutFn);
 
 /// Convert from Fix to LSP CodeAction.
 CodeAction toCodeAction(const Fix , const URIForFile );
Index: clang-tools-extra/clangd/Diagnostics.cpp
===
--- clang-tools-extra/clangd/Diagnostics.cpp
+++ clang-tools-extra/clangd/Diagnostics.cpp
@@ -9,6 +9,7 @@
 #include "Diagnostics.h"
 #include "../clang-tidy/ClangTidyDiagnosticConsumer.h"
 #include "Compiler.h"
+#include "Plugin.h"
 #include "Protocol.h"
 #include "SourceCode.h"
 #include "support/Logger.h"
@@ -403,9 +404,11 @@
   return Result;
 }
 
-void toLSPDiags(
-const Diag , const URIForFile , const ClangdDiagnosticOptions ,
-llvm::function_ref)> OutFn) {
+void toLSPDiags(const Diag , const URIForFile ,
+const ClangdDiagnosticOptions ,
+llvm::function_ref,
+llvm::ArrayRef)>
+OutFn) {
   clangd::Diagnostic Main;
   Main.severity = getSeverity(D.Severity);
 
@@ -437,7 +440,7 @@
 break;
   }
   if (Opts.EmbedFixesInDiagnostics) {
-Main.codeActions.emplace();
+Main.codeActions = D.Actions;
 for (const auto  : D.Fixes)
   Main.codeActions->push_back(toCodeAction(Fix, File));
 if (Main.codeActions->size() == 1)

[PATCH] D96244: [clangd][RFC] Introudce Plugins

2021-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
Herald added subscribers: usaxena95, arphaman, mgorny.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Plugins can be used to augment clangd's behaviours in various features.
Initially it only supports generating extra code actions for diagnostics.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96244

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/Plugin.cpp
  clang-tools-extra/clangd/Plugin.h


Index: clang-tools-extra/clangd/Plugin.h
===
--- /dev/null
+++ clang-tools-extra/clangd/Plugin.h
@@ -0,0 +1,38 @@
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_PLUGIN_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_PLUGIN_H
+#include "Diagnostics.h"
+#include "support/Path.h"
+#include "clang/Basic/Diagnostic.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Registry.h"
+#include 
+
+namespace clang {
+namespace clangd {
+
+/// Plugins enable augmenting clangd's behaviour in various places.
+class Plugin {
+public:
+  virtual ~Plugin() = default;
+
+  /// Identifier for the plugin, should be unique.
+  virtual llvm::StringLiteral id() = 0;
+
+  /// Returns an action that can be invoked to fix the diagnostic.
+  virtual llvm::Optional
+  actOnDiagnostic(DiagnosticsEngine::Level L, const clang::Diagnostic ) {
+return llvm::None;
+  }
+
+  /// Convenience helper to collect fixes from all the plugins.
+  static std::vector collectFixes(DiagnosticsEngine::Level L,
+  const clang::Diagnostic );
+};
+using PluginRegistry = llvm::Registry;
+
+} // namespace clangd
+} // namespace clang
+#endif
Index: clang-tools-extra/clangd/Plugin.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/Plugin.cpp
@@ -0,0 +1,24 @@
+#include "Plugin.h"
+#include "Diagnostics.h"
+#include "Protocol.h"
+#include "clang/Basic/Diagnostic.h"
+#include "llvm/Support/Registry.h"
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+std::vector Plugin::collectFixes(DiagnosticsEngine::Level L,
+ const clang::Diagnostic ) {
+  std::vector Actions;
+  for (const auto  : PluginRegistry::entries()) {
+if (auto Action = Entry.instantiate()->actOnDiagnostic(L, Diag))
+  Actions.emplace_back(std::move(*Action));
+  }
+  return Actions;
+}
+} // namespace clangd
+} // namespace clang
+
+LLVM_INSTANTIATE_REGISTRY(clang::clangd::PluginRegistry);
Index: clang-tools-extra/clangd/CMakeLists.txt
===
--- clang-tools-extra/clangd/CMakeLists.txt
+++ clang-tools-extra/clangd/CMakeLists.txt
@@ -75,6 +75,7 @@
   IncludeFixer.cpp
   JSONTransport.cpp
   PathMapping.cpp
+  Plugin.cpp
   Protocol.cpp
   Quality.cpp
   ParsedAST.cpp


Index: clang-tools-extra/clangd/Plugin.h
===
--- /dev/null
+++ clang-tools-extra/clangd/Plugin.h
@@ -0,0 +1,38 @@
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_PLUGIN_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_PLUGIN_H
+#include "Diagnostics.h"
+#include "support/Path.h"
+#include "clang/Basic/Diagnostic.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Registry.h"
+#include 
+
+namespace clang {
+namespace clangd {
+
+/// Plugins enable augmenting clangd's behaviour in various places.
+class Plugin {
+public:
+  virtual ~Plugin() = default;
+
+  /// Identifier for the plugin, should be unique.
+  virtual llvm::StringLiteral id() = 0;
+
+  /// Returns an action that can be invoked to fix the diagnostic.
+  virtual llvm::Optional
+  actOnDiagnostic(DiagnosticsEngine::Level L, const clang::Diagnostic ) {
+return llvm::None;
+  }
+
+  /// Convenience helper to collect fixes from all the plugins.
+  static std::vector collectFixes(DiagnosticsEngine::Level L,
+  const clang::Diagnostic );
+};
+using PluginRegistry = llvm::Registry;
+
+} // namespace clangd
+} // namespace clang
+#endif
Index: clang-tools-extra/clangd/Plugin.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/Plugin.cpp
@@ -0,0 +1,24 @@
+#include "Plugin.h"
+#include "Diagnostics.h"
+#include "Protocol.h"
+#include "clang/Basic/Diagnostic.h"
+#include "llvm/Support/Registry.h"
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+std::vector Plugin::collectFixes(DiagnosticsEngine::Level L,
+ const clang::Diagnostic ) {
+  std::vector Actions;
+  for (const auto  : PluginRegistry::entries()) {
+if (auto Action 

[PATCH] D68682: format::cleanupAroundReplacements removes whole line when Removals leave previously non-blank line blank

2021-02-07 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc updated this revision to Diff 322033.
poelmanc added a comment.

Update one one comment, hopefully trigger HarborMaster to rerun.


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

https://reviews.llvm.org/D68682

Files:
  clang-tools-extra/clang-tidy/readability/RedundantControlFlowCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-redundant-void-arg.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-control-flow.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-declaration.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-member-init.cpp
  clang-tools-extra/test/clang-tidy/checkers/readability-simplify-bool-expr.cpp
  clang-tools-extra/unittests/clang-change-namespace/ChangeNamespaceTests.cpp
  clang/include/clang/Basic/CharInfo.h
  clang/include/clang/Format/Format.h
  clang/lib/AST/CommentLexer.cpp
  clang/lib/AST/CommentParser.cpp
  clang/lib/Format/Format.cpp
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/CleanupTest.cpp

Index: clang/unittests/Format/CleanupTest.cpp
===
--- clang/unittests/Format/CleanupTest.cpp
+++ clang/unittests/Format/CleanupTest.cpp
@@ -12,6 +12,7 @@
 #include "clang/Tooling/Core/Replacement.h"
 
 #include "gtest/gtest.h"
+#include "llvm/Testing/Support/Annotations.h"
 
 using clang::tooling::ReplacementTest;
 using clang::tooling::toReplacements;
@@ -320,6 +321,11 @@
 return tooling::Replacement(FileName, Offset, Length, Text);
   }
 
+  tooling::Replacement createReplacement(llvm::Annotations::Range Range,
+ StringRef Text) {
+return createReplacement(Range.Begin, Range.End - Range.Begin, Text);
+  }
+
   tooling::Replacement createInsertion(StringRef IncludeDirective) {
 return createReplacement(UINT_MAX, 0, IncludeDirective);
   }
@@ -373,10 +379,12 @@
  "namespace C {\n"
  "namespace D { int i; }\n"
  "inline namespace E { namespace { int y; } }\n"
+ "\n"
  "int x= 0;"
  "}";
-  std::string Expected = "\n\nnamespace C {\n"
- "namespace D { int i; }\n\n"
+  std::string Expected = "\nnamespace C {\n"
+ "namespace D { int i; }\n"
+ "\n"
  "int x= 0;"
  "}";
   tooling::Replacements Replaces =
@@ -386,6 +394,104 @@
   EXPECT_EQ(Expected, formatAndApply(Code, Replaces));
 }
 
+TEST_F(CleanUpReplacementsTest, RemoveLineWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code = "namespace A {$r1[[ // Useless comment]]\n"
+   "  $r2[[int]] $r3[[x]]\t $r4[[=]] $r5[[0;]]\t\n"
+   "  int y\t = 0;$r6[[\t]]\n"
+   "} // namespace A\n";
+  std::string Expected = "namespace A {\n"
+ "  int y\t = 0;\n"
+ "} // namespace A\n";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), ""),
+  createReplacement(Code.range("r5"), ""),
+  createReplacement(Code.range("r6"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, RemoveLinesWhenAllNonWhitespaceRemoved) {
+  llvm::Annotations Code = R"cpp(struct A {
+  A()
+  $r3[[:]] $r1[[f()]]$r2[[,]]
+$r4[[g()]]
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp";
+  std::string Expected = R"cpp(struct A {
+  A()
+  {}
+  int f = 0;
+  int g = 0;
+};)cpp";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), ""),
+  createReplacement(Code.range("r2"), ""),
+  createReplacement(Code.range("r3"), ""),
+  createReplacement(Code.range("r4"), "")});
+
+  EXPECT_EQ(Expected, apply(Code.code(), Replaces));
+}
+
+TEST_F(CleanUpReplacementsTest, KeepLinesWithInsertsOrReplacesEvenIfBlank) {
+  // Not using raw string literals so newlines and spaces are clear and explicit
+  llvm::Annotations Code = "struct A {\n"
+ "  A() {}\n"
+ "$r3[[]]  $r1[[int]] $r2[[f;]]\n" // "  int f;\n"
+ "  \n"
+ "$r4[[  ]]\n"
+ "};";
+  std::string Expected = "struct A {\n"
+ "  A() {}\n"
+ "\n"
+ "\n"
+ "  \n"
+ "\t\n"
+ "};";
+  tooling::Replacements Replaces =
+  toReplacements({createReplacement(Code.range("r1"), "   "),

[PATCH] D68682: format::cleanupAroundReplacements removes whole line when Removals leave previously non-blank line blank

2021-02-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

It looks like premerge tests skipped your last diff with id 321451 
(https://reviews.llvm.org/harbormaster/?after=87950). You can re-trigger by 
uploading a new diff, in the meantime i would also file a bug to 
https://github.com/google/llvm-premerge-checks/issues. mentioning your diff id.


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

https://reviews.llvm.org/D68682

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


[PATCH] D85223: [CUDA][HIP] Support accessing static device variable in host code for -fgpu-rdc

2021-02-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 322021.
yaxunl marked 3 inline comments as done.
yaxunl edited the summary of this revision.
yaxunl added a comment.

Revised by Artem's comments. Use CUID hash as postfix for static variable name.


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

https://reviews.llvm.org/D85223

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/test/CodeGenCUDA/device-var-linkage.cu
  clang/test/CodeGenCUDA/managed-var.cu
  clang/test/CodeGenCUDA/static-device-var-rdc.cu
  clang/test/SemaCUDA/static-device-var.cu

Index: clang/test/SemaCUDA/static-device-var.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/static-device-var.cu
@@ -0,0 +1,37 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang_cc1 -triple nvptx -fcuda-is-device \
+// RUN:-emit-llvm -o - %s -fsyntax-only -verify
+
+// RUN: %clang_cc1 -triple x86_64-gnu-linux \
+// RUN:-emit-llvm -o - %s -fsyntax-only -verify
+
+// expected-no-diagnostics
+
+#include "Inputs/cuda.h"
+
+__device__ void f1() {
+  const static int b = 123;
+  static int a;
+}
+
+__global__ void k1() {
+  const static int b = 123;
+  static int a;
+}
+
+static __device__ int x;
+static __constant__ int y;
+
+__global__ void kernel(int *a) {
+  a[0] = x;
+  a[1] = y;
+}
+
+int* getDeviceSymbol(int *x);
+
+void foo() {
+  getDeviceSymbol();
+  getDeviceSymbol();
+}
Index: clang/test/CodeGenCUDA/static-device-var-rdc.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/static-device-var-rdc.cu
@@ -0,0 +1,89 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -fcuda-is-device \
+// RUN:   -fgpu-rdc -emit-llvm -o - -x hip %s | FileCheck \
+// RUN:   -check-prefixes=DEV,INT-DEV %s
+
+// RUN: %clang_cc1 -triple x86_64-gnu-linux \
+// RUN:   -fgpu-rdc -emit-llvm -o - -x hip %s | FileCheck \
+// RUN:   -check-prefixes=HOST,INT-HOST %s
+
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -fcuda-is-device -cuid=abc \
+// RUN:   -fgpu-rdc -emit-llvm -o - -x hip %s | FileCheck \
+// RUN:   -check-prefixes=DEV,EXT-DEV %s
+
+// RUN: %clang_cc1 -triple x86_64-gnu-linux -cuid=abc \
+// RUN:   -fgpu-rdc -emit-llvm -o - -x hip %s | FileCheck \
+// RUN:   -check-prefixes=HOST,EXT-HOST %s
+
+#include "Inputs/cuda.h"
+
+// Test function scope static device variable, which should not be externalized.
+// DEV-DAG: @_ZZ6kernelPiPPKiE1w = internal addrspace(4) constant i32 1
+
+
+// HOST-DAG: @_ZL1x = internal global i32 undef
+// HOST-DAG: @_ZL1y = internal global i32 undef
+
+// Test normal static device variables
+// INT-DEV-DAG: @_ZL1x = dso_local addrspace(1) externally_initialized global i32 0
+// INT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x\00"
+
+// Test externalized static device variables
+// EXT-DEV-DAG: @_ZL1x.static.[[HASH:b04fd23c98500190]] = dso_local addrspace(1) externally_initialized global i32 0
+// EXT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x.static.[[HASH:b04fd23c98500190]]\00"
+
+static __device__ int x;
+
+// Test static device variables not used by host code should not be externalized
+// DEV-DAG: @_ZL2x2 = internal addrspace(1) global i32 0
+
+static __device__ int x2;
+
+// Test normal static device variables
+// INT-DEV-DAG: @_ZL1y = dso_local addrspace(4) externally_initialized global i32 0
+// INT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y\00"
+
+// Test externalized static device variables
+// EXT-DEV-DAG: @_ZL1y.static.[[HASH]] = dso_local addrspace(4) externally_initialized global i32 0
+// EXT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y.static.[[HASH]]\00"
+
+static __constant__ int y;
+
+// Test static host variable, which should not be externalized nor registered.
+// HOST-DAG: @_ZL1z = internal global i32 0
+// DEV-NOT: @_ZL1z
+static int z;
+
+// Test static device variable in inline function, which should not be
+// externalized nor registered.
+// DEV-DAG: @_ZZ6devfunPPKiE1p = linkonce_odr addrspace(4) constant i32 2, comdat
+
+inline __device__ void devfun(const int ** b) {
+  const static int p = 2;
+  b[0] = 
+}
+
+__global__ void kernel(int *a, const int **b) {
+  const static int w = 1;
+  a[0] = x;
+  a[1] = y;
+  b[0] = 
+  b[1] = 
+  devfun(b);
+}
+
+int* getDeviceSymbol(int *x);
+
+void foo() {
+  getDeviceSymbol();
+  getDeviceSymbol();
+  z = 123;
+}
+
+// HOST: __hipRegisterVar({{.*}}@_ZL1x {{.*}}@[[DEVNAMEX]]
+// HOST: __hipRegisterVar({{.*}}@_ZL1y {{.*}}@[[DEVNAMEY]]
+// HOST-NOT: __hipRegisterVar({{.*}}@_ZL2x2
+// HOST-NOT: __hipRegisterVar({{.*}}@_ZZ6kernelPiPPKiE1w
+// HOST-NOT: __hipRegisterVar({{.*}}@_ZZ6devfunPPKiE1p
Index: clang/test/CodeGenCUDA/managed-var.cu

[PATCH] D85223: [CUDA][HIP] Support accessing static device variable in host code for -fgpu-rdc

2021-02-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 3 inline comments as done.
yaxunl added inline comments.



Comment at: clang/lib/AST/ASTContext.cpp:11446-11447
 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
-  return !getLangOpts().GPURelocatableDeviceCode &&
+  return (!getLangOpts().CUID.empty() ||
+  !getLangOpts().GPURelocatableDeviceCode) &&
  ((D->hasAttr() &&

tra wrote:
> tra wrote:
> > `!(getLangOpts().GPURelocatableDeviceCode && getLangOpts().CUID.empty())`.
> > 
> > Maybe this should be broken down into something easier to read.
> > ```
> >   // Applies only to -fgpu-rdc or when we were given a CUID
> >   if (!getLangOpts().GPURelocatableDeviceCode || 
> > !getLangOpts().CUID.empty()))
> >   return false;
> >   // .. only file-scope static vars...
> >   auto *VD = dyn_cast(D);
> >   if (!(VD && VD->isFileVarDecl() && VD->getStorageClass() == SC_Static))
> >   return false;
> >   // .. with explicit __device__ or __constant__ attributes.
> >   return ((D->hasAttr() && 
> > !D->getAttr()->isImplicit()) ||
> >   (D->hasAttr() 
> > &&!D->getAttr()->isImplicit()));
> >   
> > ```
> BTW, does this mean that we'll externalize & uniquify the vars even w/o 
> `-fgpu-rdc` if CUID is given?
> 
> IMO `-fgpu-rdc` should remain the flag to control whether externalization is 
> needed.
> CUID controls the value of a unique suffix, if we need it, but should not 
> automatically enable externalization.
> 
> 
done



Comment at: clang/lib/AST/ASTContext.cpp:11446-11447
 bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
-  return !getLangOpts().GPURelocatableDeviceCode &&
+  return (!getLangOpts().CUID.empty() ||
+  !getLangOpts().GPURelocatableDeviceCode) &&
  ((D->hasAttr() &&

yaxunl wrote:
> tra wrote:
> > tra wrote:
> > > `!(getLangOpts().GPURelocatableDeviceCode && getLangOpts().CUID.empty())`.
> > > 
> > > Maybe this should be broken down into something easier to read.
> > > ```
> > >   // Applies only to -fgpu-rdc or when we were given a CUID
> > >   if (!getLangOpts().GPURelocatableDeviceCode || 
> > > !getLangOpts().CUID.empty()))
> > >   return false;
> > >   // .. only file-scope static vars...
> > >   auto *VD = dyn_cast(D);
> > >   if (!(VD && VD->isFileVarDecl() && VD->getStorageClass() == SC_Static))
> > >   return false;
> > >   // .. with explicit __device__ or __constant__ attributes.
> > >   return ((D->hasAttr() && 
> > > !D->getAttr()->isImplicit()) ||
> > >   (D->hasAttr() 
> > > &&!D->getAttr()->isImplicit()));
> > >   
> > > ```
> > BTW, does this mean that we'll externalize & uniquify the vars even w/o 
> > `-fgpu-rdc` if CUID is given?
> > 
> > IMO `-fgpu-rdc` should remain the flag to control whether externalization 
> > is needed.
> > CUID controls the value of a unique suffix, if we need it, but should not 
> > automatically enable externalization.
> > 
> > 
> done
mayExternalizeStaticVar returns true does not mean the static var must be 
externalized. mayExternalizeStaticVar only indicates the static var may be 
externalized. It is used to enable checking whether this var is used by host 
code.

For -fno-gpu-rdc, we only externalize a static variable if it is referenced by 
host code. If a static var is referenced by host code, -fno-gpu-rdc will change 
its linkage to external, but does not need to make the symbol unique because 
each TU ends up as a different device binary.



Comment at: clang/lib/CodeGen/CodeGenModule.cpp:2864-2865
+#if 0
+  // We need to decide whether to externalize a static variable after checking
+  // whether it is referenced in host code.
+  if (isa(Global) && getContext().mayExternalizeStaticVar(

tra wrote:
> Is this code needed?
this code is not needed. removed.


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

https://reviews.llvm.org/D85223

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


[PATCH] D95007: [CUDA][HIP] Add -fuse-cuid

2021-02-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 322020.
yaxunl marked an inline comment as done.
yaxunl added a comment.

Revised by Jon and Artem's comments. Removed check of CUID value.


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

https://reviews.llvm.org/D95007

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Action.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Action.cpp
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Driver/hip-cuid.hip

Index: clang/test/Driver/hip-cuid.hip
===
--- /dev/null
+++ clang/test/Driver/hip-cuid.hip
@@ -0,0 +1,130 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// Check invalid -fuse-cuid= option.
+
+// RUN: not %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -fuse-cuid=invalid \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=INVALID %s
+
+// INVALID: invalid value 'invalid' in '-fuse-cuid=invalid'
+
+// Check random CUID generator.
+
+// RUN: %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -fuse-cuid=random \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=COMMON,HEX %s
+
+// Check fixed CUID.
+
+// RUN: %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -cuid=xyz_123 \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=COMMON,FIXED %s
+
+// Check fixed CUID override -fuse-cuid.
+
+// RUN: %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -fuse-cuid=random -cuid=xyz_123 \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=COMMON,FIXED %s
+
+// Check hash CUID generator.
+
+// RUN: %clang -### -x hip \
+// RUN:   -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx900 \
+// RUN:   --offload-arch=gfx906 \
+// RUN:   -c -nogpulib -fuse-cuid=hash \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck -check-prefixes=COMMON,HEX %s
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "amdgcn-amd-amdhsa"
+// COMMON-SAME: "-target-cpu" "gfx900"
+// HEX-SAME: "-cuid=[[CUID:[0-9a-f]+]]"
+// FIXED-SAME: "-cuid=[[CUID:xyz_123]]"
+// COMMON-SAME: "{{.*}}a.cu"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "amdgcn-amd-amdhsa"
+// COMMON-SAME: "-target-cpu" "gfx906"
+// COMMON-SAME: "-cuid=[[CUID]]"
+// COMMON-SAME: "{{.*}}a.cu"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "x86_64-unknown-linux-gnu"
+// COMMON-SAME: "-cuid=[[CUID]]"
+// COMMON-SAME: "{{.*}}a.cu"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "amdgcn-amd-amdhsa"
+// COMMON-SAME: "-target-cpu" "gfx900"
+// HEX-NOT: "-cuid=[[CUID]]"
+// HEX-SAME: "-cuid=[[CUID2:[0-9a-f]+]]"
+// FIXED-SAME: "-cuid=[[CUID2:xyz_123]]"
+// COMMON-SAME: "{{.*}}b.hip"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "amdgcn-amd-amdhsa"
+// COMMON-SAME: "-target-cpu" "gfx906"
+// HEX-NOT: "-cuid=[[CUID]]"
+// COMMON-SAME: "-cuid=[[CUID2]]"
+// COMMON-SAME: "{{.*}}b.hip"
+
+// COMMON: "{{.*}}clang{{.*}}" "-cc1"{{.*}} "-triple" "x86_64-unknown-linux-gnu"
+// HEX-NOT: "-cuid=[[CUID]]"
+// COMMON-SAME: "-cuid=[[CUID2]]"
+// COMMON-SAME: "{{.*}}b.hip"
+
+// Check CUID generated by hash.
+// The same CUID is generated for the same file with the same options.
+
+// RUN: rm -rf %t.out
+
+// RUN: %clang -### -x hip -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx906 -c -nogpulib -fuse-cuid=hash \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu >%t.out 2>&1
+
+// RUN: %clang -### -x hip -target x86_64-unknown-linux-gnu \
+// RUN:   --offload-arch=gfx906 -c -nogpulib -fuse-cuid=hash \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu >>%t.out 2>&1
+
+// RUN: FileCheck %s -check-prefixes=HASH -input-file %t.out
+
+// HASH: "{{.*}}clang{{.*}}" {{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID:[0-9a-f]+]]"
+// HASH: "{{.*}}clang{{.*}}" {{.*}} "-target-cpu" "gfx906" {{.*}}"-cuid=[[CUID]]"
+
+
+// Check CUID generated by hash.
+// Different CUID's are generated for the same file with different options.
+
+// RUN: rm -rf %t.out
+
+// RUN: %clang -### -x hip -target 

[PATCH] D93179: [X86] Convert fmin/fmax _mm_reduce_* intrinsics to emit llvm.reduction intrinsics (PR47506)

2021-02-07 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei added a comment.

In D93179#2547306 , @RKSimon wrote:

> @pengfei I'm sorry I haven't gotten back to looking at this yet - it makes 
> sense to create a patch to revert the fadd/fmul reduction changes for 
> trunk/12.x.

Thanks @RKSimon, I had a try and found maybe we don't need to revert it. See 
D96231 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93179

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


[PATCH] D96231: [X86] Always assign reassoc flag for intrinsics *reduce_add/mul_ps/pd.

2021-02-07 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei created this revision.
pengfei added reviewers: RKSimon, craig.topper, spatel.
pengfei requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Intrinsics *reduce_add/mul_ps/pd have assumption that the elements in
the vector are reassociable. So we need to always assign the reassoc
flag when we call _mm_reduce_* intrinsics.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96231

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Headers/avx512fintrin.h
  clang/test/CodeGen/X86/avx512-reduceIntrin.c

Index: clang/test/CodeGen/X86/avx512-reduceIntrin.c
===
--- clang/test/CodeGen/X86/avx512-reduceIntrin.c
+++ clang/test/CodeGen/X86/avx512-reduceIntrin.c
@@ -115,25 +115,25 @@
 
 double test_mm512_reduce_add_pd(__m512d __W){
 // CHECK-LABEL: @test_mm512_reduce_add_pd(
-// CHECK:call double @llvm.vector.reduce.fadd.v8f64(double 0.00e+00, <8 x double> %{{.*}})
+// CHECK:call reassoc double @llvm.vector.reduce.fadd.v8f64(double 0.00e+00, <8 x double> %{{.*}})
   return _mm512_reduce_add_pd(__W); 
 }
 
 double test_mm512_reduce_mul_pd(__m512d __W){
 // CHECK-LABEL: @test_mm512_reduce_mul_pd(
-// CHECK:call double @llvm.vector.reduce.fmul.v8f64(double 1.00e+00, <8 x double> %{{.*}})
+// CHECK:call reassoc double @llvm.vector.reduce.fmul.v8f64(double 1.00e+00, <8 x double> %{{.*}})
   return _mm512_reduce_mul_pd(__W); 
 }
 
 float test_mm512_reduce_add_ps(__m512 __W){
 // CHECK-LABEL: @test_mm512_reduce_add_ps(
-// CHECK:call float @llvm.vector.reduce.fadd.v16f32(float 0.00e+00, <16 x float> %{{.*}})
+// CHECK:call reassoc float @llvm.vector.reduce.fadd.v16f32(float 0.00e+00, <16 x float> %{{.*}})
   return _mm512_reduce_add_ps(__W); 
 }
 
 float test_mm512_reduce_mul_ps(__m512 __W){
 // CHECK-LABEL: @test_mm512_reduce_mul_ps(
-// CHECK:call float @llvm.vector.reduce.fmul.v16f32(float 1.00e+00, <16 x float> %{{.*}})
+// CHECK:call reassoc float @llvm.vector.reduce.fmul.v16f32(float 1.00e+00, <16 x float> %{{.*}})
   return _mm512_reduce_mul_ps(__W); 
 }
 
@@ -141,7 +141,7 @@
 // CHECK-LABEL: @test_mm512_mask_reduce_add_pd(
 // CHECK:bitcast i8 %{{.*}} to <8 x i1>
 // CHECK:select <8 x i1> %{{.*}}, <8 x double> %{{.*}}, <8 x double> %{{.*}}
-// CHECK:call double @llvm.vector.reduce.fadd.v8f64(double 0.00e+00, <8 x double> %{{.*}})
+// CHECK:call reassoc double @llvm.vector.reduce.fadd.v8f64(double 0.00e+00, <8 x double> %{{.*}})
   return _mm512_mask_reduce_add_pd(__M, __W); 
 }
 
@@ -149,7 +149,7 @@
 // CHECK-LABEL: @test_mm512_mask_reduce_mul_pd(
 // CHECK:bitcast i8 %{{.*}} to <8 x i1>
 // CHECK:select <8 x i1> %{{.*}}, <8 x double> %{{.*}}, <8 x double> %{{.*}}
-// CHECK:call double @llvm.vector.reduce.fmul.v8f64(double 1.00e+00, <8 x double> %{{.*}})
+// CHECK:call reassoc double @llvm.vector.reduce.fmul.v8f64(double 1.00e+00, <8 x double> %{{.*}})
   return _mm512_mask_reduce_mul_pd(__M, __W); 
 }
 
@@ -157,7 +157,7 @@
 // CHECK-LABEL: @test_mm512_mask_reduce_add_ps(
 // CHECK:bitcast i16 %{{.*}} to <16 x i1>
 // CHECK:select <16 x i1> %{{.*}}, <16 x float> {{.*}}, <16 x float> {{.*}}
-// CHECK:call float @llvm.vector.reduce.fadd.v16f32(float 0.00e+00, <16 x float> %{{.*}})
+// CHECK:call reassoc float @llvm.vector.reduce.fadd.v16f32(float 0.00e+00, <16 x float> %{{.*}})
   return _mm512_mask_reduce_add_ps(__M, __W); 
 }
 
@@ -165,6 +165,6 @@
 // CHECK-LABEL: @test_mm512_mask_reduce_mul_ps(
 // CHECK:bitcast i16 %{{.*}} to <16 x i1>
 // CHECK:select <16 x i1> %{{.*}}, <16 x float> {{.*}}, <16 x float> %{{.*}}
-// CHECK:call float @llvm.vector.reduce.fmul.v16f32(float 1.00e+00, <16 x float> %{{.*}})
+// CHECK:call reassoc float @llvm.vector.reduce.fmul.v16f32(float 1.00e+00, <16 x float> %{{.*}})
   return _mm512_mask_reduce_mul_ps(__M, __W); 
 }
Index: clang/lib/Headers/avx512fintrin.h
===
--- clang/lib/Headers/avx512fintrin.h
+++ clang/lib/Headers/avx512fintrin.h
@@ -9300,6 +9300,9 @@
  * computations. In vector-reduction arithmetic, the evaluation off is
  * independent of the order of the input elements of V.
 
+ * For floating points type, we always assume the elements are reassociable even
+ * if -fast-math is off.
+
  * Used bisection method. At each step, we partition the vector with previous
  * step in half, and the operation is performed on its two halves.
  * This takes log2(n) steps where n is the number of elements in the vector.
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -13826,12 +13826,14 @@
   case X86::BI__builtin_ia32_reduce_fadd_ps512: {
 Function *F =
 

[PATCH] D94251: [scan-build-py] Update scan-build-py to allow outputing as SARIF.

2021-02-07 Thread Haowei Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd72859ffa237: [scan-build-py] Update scan-build-py to allow 
outputing as SARIF (authored by Daniel Hwang ar...@google.com, 
committed by haowei).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94251

Files:
  clang/tools/scan-build-py/libscanbuild/analyze.py
  clang/tools/scan-build-py/libscanbuild/arguments.py
  clang/tools/scan-build-py/libscanbuild/report.py
  clang/tools/scan-build-py/tests/unit/test_analyze.py
  clang/tools/scan-build-py/tests/unit/test_report.py

Index: clang/tools/scan-build-py/tests/unit/test_report.py
===
--- clang/tools/scan-build-py/tests/unit/test_report.py
+++ clang/tools/scan-build-py/tests/unit/test_report.py
@@ -3,6 +3,7 @@
 # See https://llvm.org/LICENSE.txt for license information.
 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 
+import json
 import libear
 import libscanbuild.report as sut
 import unittest
@@ -145,3 +146,516 @@
 def test_empty(self):
 self.assertEqual(
 sut.commonprefix([]), '')
+
+class MergeSarifTest(unittest.TestCase):
+
+def test_merging_sarif(self):
+sarif1 = {
+'$schema': 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
+'runs': [
+{
+'artifacts': [
+{
+'length': 100,
+'location': {
+'uri': '//clang/tools/scan-build-py/tests/unit/test_report.py'
+},
+'mimeType': 'text/plain',
+'roles': [
+'resultFile'
+]
+}
+],
+'columnKind': 'unicodeCodePoints',
+'results': [
+{
+'codeFlows': [
+{
+'threadFlows': [
+{
+'locations': [
+{
+'importance': 'important',
+'location': {
+'message': {
+'text': 'test message 1'
+},
+'physicalLocation': {
+'artifactLocation': {
+'index': 0,
+'uri': '//clang/tools/scan-build-py/tests/unit/test_report.py'
+},
+'region': {
+'endColumn': 5,
+'startColumn': 1,
+'startLine': 2
+}
+}
+}
+}
+]
+}
+]
+}
+]
+},
+{
+'codeFlows': [
+{
+'threadFlows': [
+{
+'locations': [
+{
+'importance': 'important',
+'location': {
+'message': {
+'text': 'test message 2'
+},
+'physicalLocation': {
+'artifactLocation': {
+'index': 0,
+  

[clang] d72859f - [scan-build-py] Update scan-build-py to allow outputing as SARIF

2021-02-07 Thread Haowei Wu via cfe-commits

Author: Daniel Hwang
Date: 2021-02-07T18:25:50-08:00
New Revision: d72859ffa237bbb82c1ef7302f2d99534183f8ca

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

LOG: [scan-build-py] Update scan-build-py to allow outputing as SARIF

clang static analysis reports can be generated in html, plist, or sarif
format. This updates scan-build-py to be able to specify SARIF as the
desired output format, as previously it only support plist and html
formats.

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

Added: 


Modified: 
clang/tools/scan-build-py/libscanbuild/analyze.py
clang/tools/scan-build-py/libscanbuild/arguments.py
clang/tools/scan-build-py/libscanbuild/report.py
clang/tools/scan-build-py/tests/unit/test_analyze.py
clang/tools/scan-build-py/tests/unit/test_report.py

Removed: 




diff  --git a/clang/tools/scan-build-py/libscanbuild/analyze.py 
b/clang/tools/scan-build-py/libscanbuild/analyze.py
index a4bb499f86c9..dbe08be9b24a 100644
--- a/clang/tools/scan-build-py/libscanbuild/analyze.py
+++ b/clang/tools/scan-build-py/libscanbuild/analyze.py
@@ -52,7 +52,8 @@ def scan_build():
 
 args = parse_args_for_scan_build()
 # will re-assign the report directory as new output
-with report_directory(args.output, args.keep_empty) as args.output:
+with report_directory(
+args.output, args.keep_empty, args.output_format) as args.output:
 # Run against a build command. there are cases, when analyzer run
 # is not required. But we need to set up everything for the
 # wrappers, because 'configure' needs to capture the CC/CXX values
@@ -79,7 +80,7 @@ def analyze_build():
 
 args = parse_args_for_analyze_build()
 # will re-assign the report directory as new output
-with report_directory(args.output, args.keep_empty) as args.output:
+with report_directory(args.output, args.keep_empty, args.output_format) as 
args.output:
 # Run the analyzer against a compilation db.
 govern_analyzer_runs(args)
 # Cover report generation and bug counting.
@@ -336,7 +337,7 @@ def analyze_compiler_wrapper_impl(result, execution):
 
 
 @contextlib.contextmanager
-def report_directory(hint, keep):
+def report_directory(hint, keep, output_format):
 """ Responsible for the report directory.
 
 hint -- could specify the parent directory of the output directory.
@@ -355,7 +356,11 @@ def report_directory(hint, keep):
 yield name
 finally:
 if os.listdir(name):
-msg = "Run 'scan-view %s' to examine bug reports."
+if output_format != 'sarif':
+# 'scan-view' currently does not support sarif format.
+msg = "Run 'scan-view %s' to examine bug reports."
+else:
+msg = "View result at %s/results-merged.sarif."
 keep = True
 else:
 if keep:
@@ -433,7 +438,7 @@ def wrapper(*args, **kwargs):
   'direct_args',  # arguments from command line
   'force_debug',  # kill non debug macros
   'output_dir',  # where generated report files shall go
-  'output_format',  # it's 'plist', 'html', both or plist-multi-file
+  'output_format',  # it's 'plist', 'html', 'plist-html', 
'plist-multi-file', or 'sarif'
   'output_failures',  # generate crash reports or not
   'ctu'])  # ctu control options
 def run(opts):
@@ -537,6 +542,12 @@ def target():
   dir=opts['output_dir'])
 os.close(handle)
 return name
+elif opts['output_format'] == 'sarif':
+(handle, name) = tempfile.mkstemp(prefix='result-',
+  suffix='.sarif',
+  dir=opts['output_dir'])
+os.close(handle)
+return name
 return opts['output_dir']
 
 try:

diff  --git a/clang/tools/scan-build-py/libscanbuild/arguments.py 
b/clang/tools/scan-build-py/libscanbuild/arguments.py
index e258a4100331..e1d654b331cb 100644
--- a/clang/tools/scan-build-py/libscanbuild/arguments.py
+++ b/clang/tools/scan-build-py/libscanbuild/arguments.py
@@ -244,6 +244,14 @@ def create_analyze_parser(from_build_command):
 action='store_const',
 help="""Cause the results as a set of .plist files with extra
 information on related files.""")
+format_group.add_argument(
+'--sarif',
+'-sarif',
+dest='output_format',
+const='sarif',
+default='html',
+action='store_const',
+help="""Cause the results as a result.sarif file.""")
 
 advanced = parser.add_argument_group('advanced options')
 advanced.add_argument(

diff  --git 

[PATCH] D71726: Let clang atomic builtins fetch add/sub support floating point types

2021-02-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 322005.
yaxunl edited the summary of this revision.
yaxunl added a comment.

Revised by James, Artem, and John's comments.


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

https://reviews.llvm.org/D71726

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TargetInfo.h
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Basic/Targets/AMDGPU.cpp
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/fp-atomic-ops.c
  clang/test/CodeGenCUDA/amdgpu-atomic-ops.cu
  clang/test/CodeGenOpenCL/atomic-ops.cl
  clang/test/Sema/atomic-ops.c
  clang/test/SemaCUDA/amdgpu-atomic-ops.cu
  clang/test/SemaOpenCL/atomic-ops.cl

Index: clang/test/SemaOpenCL/atomic-ops.cl
===
--- clang/test/SemaOpenCL/atomic-ops.cl
+++ clang/test/SemaOpenCL/atomic-ops.cl
@@ -1,10 +1,13 @@
-// RUN: %clang_cc1 %s -cl-std=CL2.0 -verify -fsyntax-only -triple=spir64
-// RUN: %clang_cc1 %s -cl-std=CL2.0 -verify -fsyntax-only -triple=amdgcn-amdhsa-amd-opencl
+// RUN: %clang_cc1 %s -cl-std=CL2.0 -verify=expected,spir \
+// RUN:   -fsyntax-only -triple=spir64
+// RUN: %clang_cc1 %s -cl-std=CL2.0 -verify -fsyntax-only \
+// RUN:   -triple=amdgcn-amd-amdhsa
 
 // Basic parsing/Sema tests for __opencl_atomic_*
 
 #pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable
 #pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable
+#pragma OPENCL EXTENSION cl_khr_fp16 : enable
 
 typedef __INTPTR_TYPE__ intptr_t;
 typedef int int8 __attribute__((ext_vector_type(8)));
@@ -36,7 +39,7 @@
 
 atomic_int gn;
 void f(atomic_int *i, const atomic_int *ci,
-   atomic_intptr_t *p, atomic_float *d,
+   atomic_intptr_t *p, atomic_float *f, atomic_double *d, atomic_half *h, // expected-error {{unknown type name 'atomic_half'}}
int *I, const int *CI,
intptr_t *P, float *D, struct S *s1, struct S *s2,
global atomic_int *i_g, local atomic_int *i_l, private atomic_int *i_p,
@@ -57,37 +60,38 @@
 
   __opencl_atomic_load(i, memory_order_seq_cst, memory_scope_work_group);
   __opencl_atomic_load(p, memory_order_seq_cst, memory_scope_work_group);
-  __opencl_atomic_load(d, memory_order_seq_cst, memory_scope_work_group);
+  __opencl_atomic_load(f, memory_order_seq_cst, memory_scope_work_group);
   __opencl_atomic_load(ci, memory_order_seq_cst, memory_scope_work_group);
   __opencl_atomic_load(i_c, memory_order_seq_cst, memory_scope_work_group); // expected-error {{address argument to atomic operation must be a pointer to non-constant _Atomic type ('__constant atomic_int *' (aka '__constant _Atomic(int) *') invalid)}}
 
   __opencl_atomic_store(i, 1, memory_order_seq_cst, memory_scope_work_group);
   __opencl_atomic_store(p, 1, memory_order_seq_cst, memory_scope_work_group);
-  (int)__opencl_atomic_store(d, 1, memory_order_seq_cst, memory_scope_work_group); // expected-error {{operand of type 'void' where arithmetic or pointer type is required}}
+  (int)__opencl_atomic_store(f, 1, memory_order_seq_cst, memory_scope_work_group); // expected-error {{operand of type 'void' where arithmetic or pointer type is required}}
 
   int exchange_1 = __opencl_atomic_exchange(i, 1, memory_order_seq_cst, memory_scope_work_group);
   int exchange_2 = __opencl_atomic_exchange(I, 1, memory_order_seq_cst, memory_scope_work_group); // expected-error {{address argument to atomic operation must be a pointer to _Atomic}}
 
   __opencl_atomic_fetch_add(i, 1, memory_order_seq_cst, memory_scope_work_group);
   __opencl_atomic_fetch_add(p, 1, memory_order_seq_cst, memory_scope_work_group);
-  __opencl_atomic_fetch_add(d, 1, memory_order_seq_cst, memory_scope_work_group); // expected-error {{address argument to atomic operation must be a pointer to atomic integer or pointer ('__generic atomic_float *' (aka '__generic _Atomic(float) *') invalid)}}
+  __opencl_atomic_fetch_add(f, 1.0f, memory_order_seq_cst, memory_scope_work_group);
+  __opencl_atomic_fetch_add(d, 1.0, memory_order_seq_cst, memory_scope_work_group);
   __opencl_atomic_fetch_and(i, 1, memory_order_seq_cst, memory_scope_work_group);
   __opencl_atomic_fetch_and(p, 1, memory_order_seq_cst, memory_scope_work_group);
-  __opencl_atomic_fetch_and(d, 1, memory_order_seq_cst, memory_scope_work_group); // expected-error {{address argument to atomic operation must be a pointer to atomic integer ('__generic atomic_float *' (aka '__generic _Atomic(float) *') invalid)}}
+  __opencl_atomic_fetch_and(f, 1, memory_order_seq_cst, memory_scope_work_group); // expected-error {{address argument to atomic operation must be a pointer to atomic integer ('__generic atomic_float *' (aka '__generic _Atomic(float) *') invalid)}}
 
   __opencl_atomic_fetch_min(i, 1, memory_order_seq_cst, memory_scope_work_group);
   __opencl_atomic_fetch_max(i, 1, memory_order_seq_cst, memory_scope_work_group);
-  

[PATCH] D71726: Let clang atomic builtins fetch add/sub support floating point types

2021-02-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 2 inline comments as done.
yaxunl added a comment.

In D71726#2537378 , @jyknight wrote:

> In D71726#2537101 , @yaxunl wrote:
>
>> For amdgpu target, we do need diagnose unsupported atomics (not limited to 
>> fp atomics) since we do not support libcall due to ISA level linking not 
>> supported. This is something we cannot fix in a short time and we would 
>> rather diagnose it than confusing the users with missing symbols in lld.
>
> If this is limited simply to not supporting oversized or misaligned atomics, 
> I'd find that a lot less objectionable. At that point you just need a single 
> boolean variable/accessor for whether the target can support atomic library 
> calls. I note that we already have warning messages: 
> warn_atomic_op_misaligned and warn_atomic_op_oversized. Maybe those can just 
> be promoted to errors on AMDGPU.

Good points. Will do.


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

https://reviews.llvm.org/D71726

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


[PATCH] D95771: [clang-tidy] fix modernize-loop-convert to retain needed array-like operator[]

2021-02-07 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D95771#2547467 , @poelmanc wrote:

> Thanks for the commit, and thanks for the heads-up! I've now added the 
> address in my github account.

Its updated now and the commit is linked to your account.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95771

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


[PATCH] D88394: [Driver][M68k] (Patch 8/8) Add driver support for M68k

2021-02-07 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added inline comments.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:380
 ve::getVETargetFeatures(D, Args, Features);
+break;
   }

Unrelated



Comment at: clang/test/Driver/m68k-sub-archs.cpp:1
+// RUN: %clang -### -target m68k-unknown-linux -mcpu=68000 %s 2>&1 | FileCheck 
--check-prefix=CHECK-MX00 %s
+// RUN: %clang -### -target m68k-unknown-linux -mcpu=m68000 %s 2>&1 | 
FileCheck --check-prefix=CHECK-MX00 %s

Why MX00 etc?


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

https://reviews.llvm.org/D88394

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


[PATCH] D88393: [cfe][M68k] (Patch 7/8) Basic Clang support

2021-02-07 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added inline comments.



Comment at: clang/include/clang/Basic/Attr.td:1541
+  // NOTE: If you add any additional spellings, ARMInterrupt's, MipsInterrupt's
+  // and AnyX86Interrupt's spellings must match.
+  let Spellings = [GNU<"interrupt">];

Do you need to add M68kInterrupt to this list, including for all the other 
copies of it?



Comment at: clang/lib/Basic/Targets/M68k.cpp:142
+const char *, TargetInfo::ConstraintInfo ) const {
+  // FIXME: implement
+  switch (*Name) {

This is implemented?



Comment at: clang/lib/Basic/Targets/M68k.cpp:164
+M68kTargetInfo::BuiltinVaListKind M68kTargetInfo::getBuiltinVaListKind() const 
{
+  // FIXME: implement
+  return TargetInfo::CharPtrBuiltinVaList;

Use assert/llvm_unreachable if this is wrong



Comment at: clang/lib/Basic/Targets/M68k.h:57
+
+#endif /* end of include guard: M680X0_H_LTNCIPAD */

(not even the right guard name)


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

https://reviews.llvm.org/D88393

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


[PATCH] D95771: [clang-tidy] fix modernize-loop-convert to retain needed array-like operator[]

2021-02-07 Thread Conrad Poelman via Phabricator via cfe-commits
poelmanc added a comment.

In D95771#2547366 , @njames93 wrote:

> In D95771#2547160 , @poelmanc wrote:
>
>> In D95771#2547102 , @njames93 wrote:
>>
>>> Should this be committed using `poelmanc `?
>>
>> That or `Conrad Poelman ` would be great, thanks.
>
> I committed using the email provided but its not attributed you on github. 
> It's attributed you here though. is that email not linked to your github 
> account?

Thanks for the commit, and thanks for the heads-up! I've now added the address 
in my github account.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95771

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


[PATCH] D96224: [clang-itdy] Simplify virtual near-miss check

2021-02-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire created this revision.
steveire added reviewers: aaron.ballman, njames93.
Herald added a subscriber: nullptr.cpp.
steveire requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Diagnose the problem in templates in the context of the template
declaration instead of in the context of all of the (possibly very many)
template instantiations.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D96224

Files:
  clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
  clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp
@@ -44,9 +44,7 @@
 struct TDerived : TBase {
   virtual void tfunk(T t);
   // Should not apply fix for template.
-  // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: method 'TDerived::tfunk' 
has {{.*}} 'TBase::tfunc'
-  // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: method 'TDerived::tfunk' 
has {{.*}} 'TBase::tfunc'
-  // CHECK-FIXES: virtual void tfunk(T t);
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: method 'TDerived::tfunk' has 
{{.*}} 'TBase::tfunc'
 };
 
 TDerived T1;
Index: clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
@@ -32,6 +32,9 @@
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   /// Check if the given method is possible to be overridden by some other
Index: clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.cpp
@@ -216,10 +216,9 @@
 
 void VirtualNearMissCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
-  cxxMethodDecl(
-  unless(anyOf(isOverride(), isImplicit(), cxxConstructorDecl(),
-   cxxDestructorDecl(), cxxConversionDecl(), isStatic(),
-   isOverloadedOperator(
+  cxxMethodDecl(unless(anyOf(isOverride(), cxxConstructorDecl(),
+ cxxDestructorDecl(), cxxConversionDecl(),
+ isStatic(), isOverloadedOperator(
   .bind("method"),
   this);
 }
@@ -234,7 +233,15 @@
   assert(DerivedRD);
 
   for (const auto  : DerivedRD->bases()) {
-if (const auto *BaseRD = BaseSpec.getType()->getAsCXXRecordDecl()) {
+const auto *BaseRD = BaseSpec.getType()->getAsCXXRecordDecl();
+if (const auto *TST =
+dyn_cast(BaseSpec.getType())) {
+  auto TN = TST->getTemplateName();
+  BaseRD =
+  dyn_cast(TN.getAsTemplateDecl()->getTemplatedDecl());
+}
+
+if (BaseRD) {
   for (const auto *BaseMD : BaseRD->methods()) {
 if (!isPossibleToBeOverridden(BaseMD))
   continue;


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-virtual-near-miss.cpp
@@ -44,9 +44,7 @@
 struct TDerived : TBase {
   virtual void tfunk(T t);
   // Should not apply fix for template.
-  // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: method 'TDerived::tfunk' has {{.*}} 'TBase::tfunc'
-  // CHECK-MESSAGES: :[[@LINE-3]]:3: warning: method 'TDerived::tfunk' has {{.*}} 'TBase::tfunc'
-  // CHECK-FIXES: virtual void tfunk(T t);
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: method 'TDerived::tfunk' has {{.*}} 'TBase::tfunc'
 };
 
 TDerived T1;
Index: clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/VirtualNearMissCheck.h
@@ -32,6 +32,9 @@
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   /// Check if the given method is possible to be overridden by some other
Index: 

[PATCH] D96223: [clang-tidy] Simplify static assert check

2021-02-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire created this revision.
steveire added reviewers: aaron.ballman, njames93.
Herald added subscribers: nullptr.cpp, xazax.hun.
steveire 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/D96223

Files:
  clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
  clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h


Index: clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h
===
--- clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h
+++ clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h
@@ -30,6 +30,9 @@
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   SourceLocation getLastParenLoc(const ASTContext *ASTCtx,
Index: clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
===
--- clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
+++ clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp
@@ -27,48 +27,40 @@
 : ClangTidyCheck(Name, Context) {}
 
 void StaticAssertCheck::registerMatchers(MatchFinder *Finder) {
-  auto NegatedString = unaryOperator(
-  hasOperatorName("!"), 
hasUnaryOperand(ignoringImpCasts(stringLiteral(;
+  auto NegatedString =
+  unaryOperator(hasOperatorName("!"), hasUnaryOperand(stringLiteral()));
   auto IsAlwaysFalse =
   expr(anyOf(cxxBoolLiteral(equals(false)), integerLiteral(equals(0)),
  cxxNullPtrLiteralExpr(), gnuNullExpr(), NegatedString))
   .bind("isAlwaysFalse");
-  auto IsAlwaysFalseWithCast = ignoringParenImpCasts(anyOf(
-  IsAlwaysFalse, cStyleCastExpr(has(ignoringParenImpCasts(IsAlwaysFalse)))
- .bind("castExpr")));
-  auto AssertExprRoot = anyOf(
-  binaryOperator(
-  hasAnyOperatorName("&&", "=="),
-  
hasEitherOperand(ignoringImpCasts(stringLiteral().bind("assertMSG"))),
-  anyOf(binaryOperator(hasEitherOperand(IsAlwaysFalseWithCast)),
-anything()))
-  .bind("assertExprRoot"),
-  IsAlwaysFalse);
+  auto IsAlwaysFalseWithCast =
+  anyOf(IsAlwaysFalse, 
cStyleCastExpr(has(IsAlwaysFalse)).bind("castExpr"));
+  auto AssertExprRoot =
+  anyOf(binaryOperator(
+hasAnyOperatorName("&&", "=="),
+hasEitherOperand(stringLiteral().bind("assertMSG")),
+anyOf(binaryOperator(hasEitherOperand(IsAlwaysFalseWithCast)),
+  anything()))
+.bind("assertExprRoot"),
+IsAlwaysFalse);
   auto NonConstexprFunctionCall =
   callExpr(hasDeclaration(functionDecl(unless(isConstexpr();
   auto AssertCondition =
-  expr(
-  anyOf(expr(ignoringParenCasts(anyOf(
-AssertExprRoot, unaryOperator(hasUnaryOperand(
-
ignoringParenCasts(AssertExprRoot)),
-anything()),
-  unless(findAll(NonConstexprFunctionCall)))
+  expr(anyOf(expr(anyOf(AssertExprRoot,
+unaryOperator(hasUnaryOperand(AssertExprRoot,
+ anything()),
+   unless(findAll(NonConstexprFunctionCall)))
   .bind("condition");
   auto Condition =
-  anyOf(ignoringParenImpCasts(callExpr(
-hasDeclaration(functionDecl(hasName("__builtin_expect"))),
-hasArgument(0, AssertCondition))),
+  anyOf(callExpr(traverse(TK_AsIs, callExpr(hasDeclaration(functionDecl(
+   hasName("__builtin_expect"),
+ hasArgument(0, AssertCondition)),
 AssertCondition);
 
-  Finder->addMatcher(conditionalOperator(hasCondition(Condition),
- unless(isInTemplateInstantiation()))
- .bind("condStmt"),
- this);
-
   Finder->addMatcher(
-  ifStmt(hasCondition(Condition), unless(isInTemplateInstantiation()))
-  .bind("condStmt"),
-  this);
+  conditionalOperator(hasCondition(Condition)).bind("condStmt"), this);
+
+  Finder->addMatcher(ifStmt(hasCondition(Condition)).bind("condStmt"), this);
 }
 
 void StaticAssertCheck::check(const MatchFinder::MatchResult ) {


Index: clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h
===
--- clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h
+++ clang-tools-extra/clang-tidy/misc/StaticAssertCheck.h
@@ -30,6 +30,9 @@
   }
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional 

[PATCH] D96222: [clang-tidy] Simplify redundant smartptr get check

2021-02-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire created this revision.
steveire added reviewers: aaron.ballman, njames93.
Herald added subscribers: nullptr.cpp, xazax.hun.
steveire 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/D96222

Files:
  clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
  clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-smartptr-get.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-redundant-smartptr-get.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-redundant-smartptr-get.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-redundant-smartptr-get.cpp
@@ -168,6 +168,42 @@
   // CHECK-FIXES: if (NULL == x);
 }
 
+template 
+void testTemplate() {
+  T().get()->Do();
+}
+
+template 
+void testTemplate2() {
+  std::unique_ptr up;
+  up.get()->Do();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: redundant get() call
+  // CHECK-FIXES: up->Do();
+}
+
+void instantiate() {
+  testTemplate();
+  testTemplate>();
+  testTemplate();
+
+  testTemplate2();
+}
+
+struct S {
+
+  void foo() {
+m_up.get()->Do();
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant get() call
+// CHECK-FIXES: m_up->Do();
+m_bp.get()->Do();
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: redundant get() call
+// CHECK-FIXES: m_bp->Do();
+  }
+
+  std::unique_ptr m_up;
+  BarPtr m_bp;
+};
+
 #define MACRO(p) p.get()
 
 void Negative() {
Index: clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h
===
--- clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h
+++ clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.h
@@ -35,6 +35,9 @@
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   const bool IgnoreMacros;
Index: clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantSmartptrGetCheck.cpp
@@ -18,15 +18,30 @@
 
 namespace {
 internal::Matcher callToGet(const internal::Matcher ) {
-  return cxxMemberCallExpr(
- on(expr(anyOf(hasType(OnClass),
-   hasType(qualType(
-   pointsTo(decl(OnClass).bind("ptr_to_ptr"))
-.bind("smart_pointer")),
- unless(callee(memberExpr(hasObjectExpression(cxxThisExpr(),
- callee(cxxMethodDecl(
- hasName("get"),
- returns(qualType(pointsTo(type().bind("getType")))
+  return expr(
+ anyOf(cxxMemberCallExpr(
+   on(expr(anyOf(hasType(OnClass),
+ hasType(qualType(pointsTo(
+ decl(OnClass).bind("ptr_to_ptr"))
+  .bind("smart_pointer")),
+   unless(callee(
+   memberExpr(hasObjectExpression(cxxThisExpr(),
+   callee(cxxMethodDecl(hasName("get"),
+returns(qualType(pointsTo(
+type().bind("getType"))),
+   cxxDependentScopeMemberExpr(
+   hasMemberName("get"),
+   hasObjectExpression(
+   expr(hasType(qualType(hasCanonicalType(
+templateSpecializationType(hasDeclaration(
+classTemplateDecl(has(cxxRecordDecl(
+OnClass,
+hasMethod(cxxMethodDecl(
+hasName("get"),
+returns(qualType(
+pointsTo(type().bind(
+"getType")))
+   .bind("smart_pointer")
   .bind("redundant_get");
 }
 
@@ -47,10 +62,9 @@
   const auto Smartptr = anyOf(knownSmartptr(), QuacksLikeASmartptr);
 
   // Catch 'ptr.get()->Foo()'
-  Finder->addMatcher(
-  memberExpr(expr().bind("memberExpr"), isArrow(),
- hasObjectExpression(ignoringImpCasts(callToGet(Smartptr,
-  

[PATCH] D96142: [clang-tidy] Simplify too-small loop variable check

2021-02-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire added a comment.

In D96142#2545078 , @njames93 wrote:

> I'm not sure about this. The warning is good and addresses a real problem.

Well, I've made the diagnostic better anyway.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96142

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


[PATCH] D96142: [clang-tidy] Simplify too-small loop variable check

2021-02-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 321997.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96142

Files:
  clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-too-small-loop-variable.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-too-small-loop-variable.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-too-small-loop-variable.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-too-small-loop-variable.cpp
@@ -65,7 +65,19 @@
 template 
 void doSomething() {
   for (T i = 0; i < size(); ++i) {
-// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: loop variable has narrower type 'short' than iteration's upper bound 'long' [bugprone-too-small-loop-variable]
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: loop variable is template dependent and might be instantiated with a type which is too small.
+  }
+}
+
+template 
+struct Templ {
+};
+
+template 
+void dependentBoundary() {
+  Templ t;
+  for (int i = 0; i < t.size(); ++i) {
+// CHECK-MESSAGES: :[[@LINE-1]]:23: warning: boundary variable is template dependent and might be instantiated with a type which is too large for the loop variable.
   }
 }
 
Index: clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.h
===
--- clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.h
+++ clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.h
@@ -34,6 +34,9 @@
   void storeOptions(ClangTidyOptions::OptionMap ) override;
   void registerMatchers(ast_matchers::MatchFinder *Finder) override;
   void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  llvm::Optional getCheckTraversalKind() const override {
+return TK_IgnoreUnlessSpelledInSource;
+  }
 
 private:
   const unsigned MagnitudeBitsUpperLimit;
Index: clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/TooSmallLoopVariableCheck.cpp
@@ -20,8 +20,6 @@
 llvm::StringLiteral("forLoopName");
 static constexpr llvm::StringLiteral LoopVarName =
 llvm::StringLiteral("loopVar");
-static constexpr llvm::StringLiteral LoopVarCastName =
-llvm::StringLiteral("loopVarCast");
 static constexpr llvm::StringLiteral LoopUpperBoundName =
 llvm::StringLiteral("loopUpperBound");
 static constexpr llvm::StringLiteral LoopIncrementName =
@@ -45,50 +43,38 @@
 /// \endcode
 /// The following string identifiers are bound to these parts of the AST:
 ///   LoopVarName: 'j' (as a VarDecl)
-///   LoopVarCastName: 'j' (after implicit conversion)
 ///   LoopUpperBoundName: '3 + 2' (as an Expr)
 ///   LoopIncrementName: 'k' (as an Expr)
 ///   LoopName: The entire for loop (as a ForStmt)
 ///
 void TooSmallLoopVariableCheck::registerMatchers(MatchFinder *Finder) {
   StatementMatcher LoopVarMatcher =
-  expr(
-  ignoringParenImpCasts(declRefExpr(to(varDecl(hasType(isInteger()))
+  declRefExpr(anyOf(hasType(isInteger()), isTypeDependent()))
   .bind(LoopVarName);
 
-  // We need to catch only those comparisons which contain any integer cast.
-  StatementMatcher LoopVarConversionMatcher = traverse(
-  TK_AsIs, implicitCastExpr(hasImplicitDestinationType(isInteger()),
-has(ignoringParenImpCasts(LoopVarMatcher)))
-   .bind(LoopVarCastName));
-
-  // We are interested in only those cases when the loop bound is a variable
-  // value (not const, enum, etc.).
-  StatementMatcher LoopBoundMatcher =
-  expr(ignoringParenImpCasts(allOf(hasType(isInteger()),
-   unless(integerLiteral()),
-   unless(hasType(isConstQualified())),
-   unless(hasType(enumType())
+  auto LoopBoundMatcher =
+  expr(anyOf(allOf(hasType(isInteger()), unless(integerLiteral()),
+   unless(hasType(isConstQualified())),
+   unless(hasType(enumType(,
+ isTypeDependent()))
   .bind(LoopUpperBoundName);
 
   // We use the loop increment expression only to make sure we found the right
   // loop variable.
-  StatementMatcher IncrementMatcher =
-  expr(ignoringParenImpCasts(hasType(isInteger(.bind(LoopIncrementName);
+  auto IncrementMatcher = expr(anyOf(hasType(isInteger()), isTypeDependent()))
+  .bind(LoopIncrementName);
 
   Finder->addMatcher(
   forStmt(
   hasCondition(anyOf(
-  

[PATCH] D94735: CGDebugInfo CreatedLimitedType: Drop file/line for RecordType with invalid location

2021-02-07 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D94735#2547370 , @jdoerfert wrote:

> In D94735#2546968 , @dblaikie wrote:
>
>> This patch is about a clang synthesized `struct`. 
>> `clang/lib/CodeGen/CGOpenMPRuntime.cpp:3463` has a synthesized `union` 
>> (`distinct !DICompositeType(tag: DW_TAG_union_type, name: "kmp_cmplrdata_t", 
>> size: 64, elements: <0x62b690>)`, which has no filename/line with this 
>> patch). It does not make sense to attach the current filename/line (which 
>> can be entirely irrelevant) to the synthesized `union`. @ABataev @jdoerfert ?
>
> There is no meaningful location for this generated type. Unclear if we should 
> use a filename/line to specify that, e.g. "clang_synthesized:0", or allow it 
> without. Either works for me.

I'd vote in favour of having no location - lots of other types have no location 
(mostly builtin/fundamental types, admittedly) so should generally be fine. 
*fingers crossed*


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94735

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


[PATCH] D94973: [clang][OpenMP] Use OpenMPIRBuilder for workshare loops.

2021-02-07 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

I have a single last comment/request. @jdenny I'll take it you finish the 
review and accept as you see fit.




Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:986
+  if (BodyGenCB)
+BodyGenCB(CL->getBodyIP(), CL->getIndVar());
 

Meinersbur wrote:
> jdoerfert wrote:
> > I'm unsure I understand when it would make sense to not have a body 
> > generator.
> As done by EmitOMPCanonicalLoop, the body code can also added to 
> `CL->getBodyIP()` to the CL returned by this function. Calling the callback 
> is the last action done anyway, using the callback just makes the code harder 
> to understand.
I think in the long run the callbacks will provide more usefulness. Since the 
code generation scope for constructs is then known by the OMPIRBuilder we can 
track the OpenMP context in the OMPIRBuilder including the `construct` traits. 
You think it is worse at the call site to pack the body gen in a lambda?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94973

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


[PATCH] D94735: CGDebugInfo CreatedLimitedType: Drop file/line for RecordType with invalid location

2021-02-07 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

In D94735#2546968 , @dblaikie wrote:

> This patch is about a clang synthesized `struct`. 
> `clang/lib/CodeGen/CGOpenMPRuntime.cpp:3463` has a synthesized `union` 
> (`distinct !DICompositeType(tag: DW_TAG_union_type, name: "kmp_cmplrdata_t", 
> size: 64, elements: <0x62b690>)`, which has no filename/line with this 
> patch). It does not make sense to attach the current filename/line (which can 
> be entirely irrelevant) to the synthesized `union`. @ABataev @jdoerfert ?

There is no meaningful location for this generated type. Unclear if we should 
use a filename/line to specify that, e.g. "clang_synthesized:0", or allow it 
without. Either works for me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94735

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


[PATCH] D92133: [clangd] Cache .clang-tidy files again.

2021-02-07 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Unfortunately this broke the search order for clang-tidy files in root 
directories in favour or subdirectories. This wasn't caught as we didn't have 
tests for this. I've put a fix for this in D96204 
 with appropriate tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92133

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


[PATCH] D95771: [clang-tidy] fix modernize-loop-convert to retain needed array-like operator[]

2021-02-07 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D95771#2547160 , @poelmanc wrote:

> In D95771#2547102 , @njames93 wrote:
>
>> Should this be committed using `poelmanc `?
>
> That or `Conrad Poelman ` would be great, thanks.

I committed using the email provided but its not attributed you on github. It's 
attributed you here though. is that email not linked to your github account?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95771

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


[clang-tools-extra] 5229edd - [clang-tidy] fix modernize-loop-convert to retain needed array-like operator[]

2021-02-07 Thread Nathan James via cfe-commits

Author: poelmanc
Date: 2021-02-07T16:36:34Z
New Revision: 5229edd66742aeed407f774d77d437fa80347ad1

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

LOG: [clang-tidy] fix modernize-loop-convert to retain needed array-like 
operator[]

`modernize-loop-convert` handles //array-like// objects like vectors fairly 
well, but strips slightly too much information from the iteration expression by 
converting:
```
  Vector> X;
  for (int J = 0; J < X[5].size(); ++J)
copyArg(X[5][J]);
```
to
```
  Vector> X;
  for (int J : X) // should be for (int J : X[5])
copyArg(J);
```
The `[5]` is a call to `operator[]` and gets stripped by 
`LoopConvertCheck::getContainerString`. This patch fixes that and adds several 
test cases.

Reviewed By: njames93

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-multidimensional.cpp

Modified: 
clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
index e6b7c1f6025e..ec75be9c5f53 100644
--- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -712,10 +712,11 @@ StringRef LoopConvertCheck::getContainerString(ASTContext 
*Context,
   if (isa(ContainerExpr)) {
 ContainerString = "this";
   } else {
-// For CXXOperatorCallExpr (e.g. vector_ptr->size()), its first argument is
-// the class object (vector_ptr) we are targeting.
+// For CXXOperatorCallExpr such as vector_ptr->size() we want the class
+// object vector_ptr, but for vector[2] we need the whole expression.
 if (const auto* E = dyn_cast(ContainerExpr))
-  ContainerExpr = E->getArg(0);
+  if (E->getOperator() != OO_Subscript)
+ContainerExpr = E->getArg(0);
 ContainerString =
 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(),
ContainerExpr->getSourceRange());

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-multidimensional.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-multidimensional.cpp
new file mode 100644
index ..bffb7f560559
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-multidimensional.cpp
@@ -0,0 +1,79 @@
+// RUN: %check_clang_tidy %s modernize-loop-convert %t
+
+template 
+struct Vector {
+  using iterator = T*;
+  unsigned size() const;
+  const T [](int) const;
+  T [](int);
+  T *begin();
+  T *end();
+  const T *begin() const;
+  const T *end() const;
+};
+
+template 
+void copyArg(T);
+
+class TestArrayOfVector {
+  Vector W[2];
+
+  void foo() const {
+for (int I = 0; I < W[0].size(); ++I) {
+  if (W[0][I])
+copyArg(W[0][I]);
+}
+// CHECK-MESSAGES: :[[@LINE-4]]:5: warning: use range-based for loop
+// CHECK-FIXES: for (int I : W[0]) {
+// CHECK-FIXES-NEXT: if (I)
+// CHECK-FIXES-NEXT: copyArg(I);
+  }
+};
+
+class TestVectorOfVector {
+  Vector> X;
+
+  void foo() const {
+for (int J = 0; J < X[0].size(); ++J) {
+  if (X[0][J])
+copyArg(X[0][J]);
+}
+// CHECK-MESSAGES: :[[@LINE-4]]:5: warning: use range-based for loop
+// CHECK-FIXES: for (int J : X[0]) {
+// CHECK-FIXES-NEXT: if (J)
+// CHECK-FIXES-NEXT: copyArg(J);
+  }
+};
+
+void testVectorOfVectorOfVector() {
+  Vector>> Y;
+  for (int J = 0; J < Y[3].size(); ++J) {
+if (Y[3][J][7])
+  copyArg(Y[3][J][8]);
+  }
+  // CHECK-MESSAGES: :[[@LINE-4]]:3: warning: use range-based for loop
+  // CHECK-FIXES: for (auto & J : Y[3]) {
+  // CHECK-FIXES-NEXT: if (J[7])
+  // CHECK-FIXES-NEXT: copyArg(J[8]);
+
+  for (int J = 0; J < Y[3][4].size(); ++J) {
+if (Y[3][4][J])
+  copyArg(Y[3][4][J]);
+  }
+  // CHECK-MESSAGES: :[[@LINE-4]]:3: warning: use range-based for loop
+  // CHECK-FIXES: for (int J : Y[3][4]) {
+  // CHECK-FIXES-NEXT: if (J)
+  // CHECK-FIXES-NEXT: copyArg(J);
+}
+
+void testVectorOfVectorIterator() {
+  Vector> Z;
+  for (Vector::iterator it = Z[4].begin(); it != Z[4].end();  ++it) {
+if (*it)
+  copyArg(*it);
+  }
+  // CHECK-MESSAGES: :[[@LINE-4]]:3: warning: use range-based for loop
+  // CHECK-FIXES: for (int & it : Z[4]) {
+  // CHECK-FIXES-NEXT: if (it)
+  // CHECK-FIXES-NEXT: copyArg(it);
+}



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


[PATCH] D95771: [clang-tidy] fix modernize-loop-convert to retain needed array-like operator[]

2021-02-07 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5229edd66742: [clang-tidy] fix modernize-loop-convert to 
retain needed array-like operator[] (authored by poelmanc, committed by 
njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95771

Files:
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-multidimensional.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-multidimensional.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-loop-convert-multidimensional.cpp
@@ -0,0 +1,79 @@
+// RUN: %check_clang_tidy %s modernize-loop-convert %t
+
+template 
+struct Vector {
+  using iterator = T*;
+  unsigned size() const;
+  const T [](int) const;
+  T [](int);
+  T *begin();
+  T *end();
+  const T *begin() const;
+  const T *end() const;
+};
+
+template 
+void copyArg(T);
+
+class TestArrayOfVector {
+  Vector W[2];
+
+  void foo() const {
+for (int I = 0; I < W[0].size(); ++I) {
+  if (W[0][I])
+copyArg(W[0][I]);
+}
+// CHECK-MESSAGES: :[[@LINE-4]]:5: warning: use range-based for loop
+// CHECK-FIXES: for (int I : W[0]) {
+// CHECK-FIXES-NEXT: if (I)
+// CHECK-FIXES-NEXT: copyArg(I);
+  }
+};
+
+class TestVectorOfVector {
+  Vector> X;
+
+  void foo() const {
+for (int J = 0; J < X[0].size(); ++J) {
+  if (X[0][J])
+copyArg(X[0][J]);
+}
+// CHECK-MESSAGES: :[[@LINE-4]]:5: warning: use range-based for loop
+// CHECK-FIXES: for (int J : X[0]) {
+// CHECK-FIXES-NEXT: if (J)
+// CHECK-FIXES-NEXT: copyArg(J);
+  }
+};
+
+void testVectorOfVectorOfVector() {
+  Vector>> Y;
+  for (int J = 0; J < Y[3].size(); ++J) {
+if (Y[3][J][7])
+  copyArg(Y[3][J][8]);
+  }
+  // CHECK-MESSAGES: :[[@LINE-4]]:3: warning: use range-based for loop
+  // CHECK-FIXES: for (auto & J : Y[3]) {
+  // CHECK-FIXES-NEXT: if (J[7])
+  // CHECK-FIXES-NEXT: copyArg(J[8]);
+
+  for (int J = 0; J < Y[3][4].size(); ++J) {
+if (Y[3][4][J])
+  copyArg(Y[3][4][J]);
+  }
+  // CHECK-MESSAGES: :[[@LINE-4]]:3: warning: use range-based for loop
+  // CHECK-FIXES: for (int J : Y[3][4]) {
+  // CHECK-FIXES-NEXT: if (J)
+  // CHECK-FIXES-NEXT: copyArg(J);
+}
+
+void testVectorOfVectorIterator() {
+  Vector> Z;
+  for (Vector::iterator it = Z[4].begin(); it != Z[4].end();  ++it) {
+if (*it)
+  copyArg(*it);
+  }
+  // CHECK-MESSAGES: :[[@LINE-4]]:3: warning: use range-based for loop
+  // CHECK-FIXES: for (int & it : Z[4]) {
+  // CHECK-FIXES-NEXT: if (it)
+  // CHECK-FIXES-NEXT: copyArg(it);
+}
Index: clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
@@ -712,10 +712,11 @@
   if (isa(ContainerExpr)) {
 ContainerString = "this";
   } else {
-// For CXXOperatorCallExpr (e.g. vector_ptr->size()), its first argument is
-// the class object (vector_ptr) we are targeting.
+// For CXXOperatorCallExpr such as vector_ptr->size() we want the class
+// object vector_ptr, but for vector[2] we need the whole expression.
 if (const auto* E = dyn_cast(ContainerExpr))
-  ContainerExpr = E->getArg(0);
+  if (E->getOperator() != OO_Subscript)
+ContainerExpr = E->getArg(0);
 ContainerString =
 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(),
ContainerExpr->getSourceRange());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D96114: [ASTMatchers] Fix parent-child traversal between functions and parms

2021-02-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 321991.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96114

Files:
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/lib/AST/ParentMapContext.cpp
  clang/lib/ASTMatchers/ASTMatchFinder.cpp
  clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -3551,6 +3551,14 @@
forFunction(functionDecl(hasName("func13"))),
   langCxx20OrLater()));
 
+  EXPECT_TRUE(
+  matches(Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   parmVarDecl(hasName("d"),
+   hasParent(lambdaExpr(forFunction(
+   functionDecl(hasName("func13"))),
+  langCxx20OrLater()));
+
   EXPECT_TRUE(matches(Code,
   traverse(TK_IgnoreUnlessSpelledInSource,
compoundStmt(hasParent(lambdaExpr(forFunction(
Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2068,6 +2068,41 @@
  Constructor1Arg));
 }
 
+TEST(ASTMatchersTest, has_parmVarDecl) {
+
+  auto Code = R"cpp(
+void f(int ii)
+{
+
+}
+)cpp";
+
+  EXPECT_TRUE(matches(
+  Code,
+  traverse(TK_AsIs,
+   functionDecl(hasName("f"),
+has(typeLoc(has(parmVarDecl(hasName("ii"))),
+  langCxx20OrLater()));
+  EXPECT_TRUE(matches(
+  Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   functionDecl(hasName("f"), has(parmVarDecl(hasName("ii"),
+  langCxx20OrLater()));
+
+  EXPECT_TRUE(
+  matches(Code,
+  traverse(TK_AsIs, parmVarDecl(hasName("ii"),
+hasParent(typeLoc(hasParent(
+functionDecl(hasName("f"))),
+  langCxx20OrLater()));
+  EXPECT_TRUE(
+  matches(Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   parmVarDecl(hasName("ii"),
+   hasParent(functionDecl(hasName("f"),
+  langCxx20OrLater()));
+}
+
 TEST(ASTMatchersTest, NamesMember_CXXDependentScopeMemberExpr) {
 
   // Member functions:
Index: clang/lib/ASTMatchers/ASTMatchFinder.cpp
===
--- clang/lib/ASTMatchers/ASTMatchFinder.cpp
+++ clang/lib/ASTMatchers/ASTMatchFinder.cpp
@@ -143,6 +143,17 @@
 return Matches;
   }
 
+  bool TraverseFunctionHelper(FunctionDecl *FD) {
+if (Finder->isTraversalIgnoringImplicitNodes()) {
+  for (auto *P : FD->parameters()) {
+if (!TraverseDecl(P))
+  return false;
+  }
+}
+return RecursiveASTVisitor::TraverseFunctionHelper(
+FD);
+  }
+
   // The following are overriding methods from the base visitor class.
   // They are public only to allow CRTP to work. They are *not *part
   // of the public API of this class.
Index: clang/lib/AST/ParentMapContext.cpp
===
--- clang/lib/AST/ParentMapContext.cpp
+++ clang/lib/AST/ParentMapContext.cpp
@@ -345,7 +345,7 @@
 class ParentMapContext::ParentMap::ASTVisitor
 : public RecursiveASTVisitor {
 public:
-  ASTVisitor(ParentMap ) : Map(Map) {}
+  ASTVisitor(ParentMap , ASTContext ) : Map(Map), Ctx(Ctx) {}
 
 private:
   friend class RecursiveASTVisitor;
@@ -422,6 +422,19 @@
 );
   }
   bool TraverseTypeLoc(TypeLoc TypeLocNode) {
+if (Ctx.getParentMapContext().getTraversalKind() ==
+TK_IgnoreUnlessSpelledInSource) {
+  if (auto FPTL = TypeLocNode.getAs()) {
+for (unsigned I = 0, E = FPTL.getNumParams(); I != E; ++I) {
+  if (auto *P = FPTL.getParam(I)) {
+if (!TraverseDecl(P))
+  return false;
+  }
+}
+return true;
+  }
+}
+
 return TraverseNode(
 TypeLocNode, DynTypedNode::create(TypeLocNode),
 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
@@ -446,11 +459,12 @@
   }
 
   ParentMap 
+  ASTContext 
   llvm::SmallVector ParentStack;
 };
 
 ParentMapContext::ParentMap::ParentMap(ASTContext ) {
-  ASTVisitor(*this).TraverseAST(Ctx);
+  ASTVisitor(*this, Ctx).TraverseAST(Ctx);
 }
 
 DynTypedNodeList ParentMapContext::getParents(const DynTypedNode ) {
Index: 

[PATCH] D96113: [ASTMatchers] Fix hasParent while ignoring unwritten nodes

2021-02-07 Thread Stephen Kelly via Phabricator via cfe-commits
steveire updated this revision to Diff 321990.
steveire added a comment.

Update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D96113

Files:
  clang/include/clang/AST/ParentMapContext.h
  clang/lib/AST/ParentMapContext.cpp
  clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Index: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
@@ -2933,6 +2933,37 @@
 EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
 EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
   }
+  {
+auto M = ifStmt(hasParent(compoundStmt(hasParent(cxxForRangeStmt();
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = cxxForRangeStmt(
+has(varDecl(hasName("i"), hasParent(cxxForRangeStmt();
+EXPECT_FALSE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = cxxForRangeStmt(hasDescendant(varDecl(
+hasName("i"), hasParent(declStmt(hasParent(cxxForRangeStmt()));
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+  {
+auto M = cxxForRangeStmt(hasRangeInit(declRefExpr(
+to(varDecl(hasName("arr"))), hasParent(cxxForRangeStmt();
+EXPECT_FALSE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_TRUE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
+
+  {
+auto M = cxxForRangeStmt(hasRangeInit(declRefExpr(
+to(varDecl(hasName("arr"))), hasParent(varDecl(hasParent(declStmt(
+ hasParent(cxxForRangeStmt();
+EXPECT_TRUE(matches(Code, traverse(TK_AsIs, M)));
+EXPECT_FALSE(matches(Code, traverse(TK_IgnoreUnlessSpelledInSource, M)));
+  }
 
   Code = R"cpp(
   struct Range {
@@ -3035,6 +3066,15 @@
 matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
  true, {"-std=c++20"}));
   }
+  {
+auto M = cxxForRangeStmt(hasInitStatement(declStmt(
+hasSingleDecl(varDecl(hasName("a"))), hasParent(cxxForRangeStmt();
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_AsIs, M), true, {"-std=c++20"}));
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+ true, {"-std=c++20"}));
+  }
 
   Code = R"cpp(
   struct Range {
@@ -3511,6 +3551,20 @@
forFunction(functionDecl(hasName("func13"))),
   langCxx20OrLater()));
 
+  EXPECT_TRUE(matches(Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   compoundStmt(hasParent(lambdaExpr(forFunction(
+   functionDecl(hasName("func13"))),
+  langCxx20OrLater()));
+
+  EXPECT_TRUE(matches(
+  Code,
+  traverse(TK_IgnoreUnlessSpelledInSource,
+   templateTypeParmDecl(hasName("TemplateType"),
+hasParent(lambdaExpr(forFunction(
+functionDecl(hasName("func14"))),
+  langCxx20OrLater()));
+
   EXPECT_TRUE(matches(
   Code,
   traverse(TK_IgnoreUnlessSpelledInSource,
@@ -3635,6 +3689,16 @@
 matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
  true, {"-std=c++20"}));
   }
+  {
+auto M = cxxRewrittenBinaryOperator(
+hasLHS(expr(hasParent(cxxRewrittenBinaryOperator(,
+hasRHS(expr(hasParent(cxxRewrittenBinaryOperator();
+EXPECT_FALSE(
+matchesConditionally(Code, traverse(TK_AsIs, M), true, {"-std=c++20"}));
+EXPECT_TRUE(
+matchesConditionally(Code, traverse(TK_IgnoreUnlessSpelledInSource, M),
+ true, {"-std=c++20"}));
+  }
   {
 EXPECT_TRUE(matchesConditionally(
 Code,
Index: clang/lib/AST/ParentMapContext.cpp
===
--- clang/lib/AST/ParentMapContext.cpp
+++ clang/lib/AST/ParentMapContext.cpp
@@ -49,7 +49,17 @@
   return N;
 }
 
+template 
+std::tuple
+matchParents(const DynTypedNodeList ,
+ ParentMapContext::ParentMap *ParentMap);
+
+template  struct MatchParents;
+
 class ParentMapContext::ParentMap {
+
+  template  friend struct ::MatchParents;
+
   /// Contains parents of a node.
   using ParentVector = llvm::SmallVector;
 
@@ -117,11 +127,75 @@
 if (Node.getNodeKind().hasPointerIdentity()) {
   auto ParentList =
   getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
- 

[clang] ddca007 - Add code complete support for mapAnyOf

2021-02-07 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-07T16:03:05Z
New Revision: ddca007a291b0e224fe5a492ae8d78c6a933b4fe

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

LOG: Add code complete support for mapAnyOf

Added: 


Modified: 
clang/lib/ASTMatchers/Dynamic/Registry.cpp
clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index ef5fd64a36667..4300eb8d8b983 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -656,20 +656,40 @@ Registry::getMatcherCompletions(ArrayRef 
AcceptedTypes) {
 bool IsPolymorphic = Matcher.isPolymorphic();
 std::vector> ArgsKinds(NumArgs);
 unsigned MaxSpecificity = 0;
+bool NodeArgs = false;
 for (const ArgKind& Kind : AcceptedTypes) {
-  if (Kind.getArgKind() != Kind.AK_Matcher)
+  if (Kind.getArgKind() != Kind.AK_Matcher &&
+  Kind.getArgKind() != Kind.AK_Node) {
 continue;
-  unsigned Specificity;
-  ASTNodeKind LeastDerivedKind;
-  if (Matcher.isConvertibleTo(Kind.getMatcherKind(), ,
-  )) {
-if (MaxSpecificity < Specificity)
-  MaxSpecificity = Specificity;
-RetKinds.insert(LeastDerivedKind);
-for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
-  Matcher.getArgKinds(Kind.getMatcherKind(), Arg, ArgsKinds[Arg]);
-if (IsPolymorphic)
-  break;
+  }
+
+  if (Kind.getArgKind() == Kind.AK_Node) {
+NodeArgs = true;
+unsigned Specificity;
+ASTNodeKind LeastDerivedKind;
+if (Matcher.isConvertibleTo(Kind.getNodeKind(), ,
+)) {
+  if (MaxSpecificity < Specificity)
+MaxSpecificity = Specificity;
+  RetKinds.insert(LeastDerivedKind);
+  for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
+Matcher.getArgKinds(Kind.getNodeKind(), Arg, ArgsKinds[Arg]);
+  if (IsPolymorphic)
+break;
+}
+  } else {
+unsigned Specificity;
+ASTNodeKind LeastDerivedKind;
+if (Matcher.isConvertibleTo(Kind.getMatcherKind(), ,
+)) {
+  if (MaxSpecificity < Specificity)
+MaxSpecificity = Specificity;
+  RetKinds.insert(LeastDerivedKind);
+  for (unsigned Arg = 0; Arg != NumArgs; ++Arg)
+Matcher.getArgKinds(Kind.getMatcherKind(), Arg, ArgsKinds[Arg]);
+  if (IsPolymorphic)
+break;
+}
   }
 }
 
@@ -677,42 +697,49 @@ Registry::getMatcherCompletions(ArrayRef 
AcceptedTypes) {
   std::string Decl;
   llvm::raw_string_ostream OS(Decl);
 
-  if (IsPolymorphic) {
-OS << "Matcher " << Name << "(Matcher";
+  std::string TypedText = std::string(Name);
+
+  if (NodeArgs) {
+OS << Name;
   } else {
-OS << "Matcher<" << RetKinds << "> " << Name << "(";
-for (const std::vector  : ArgsKinds) {
-  if ( != [0])
-OS << ", ";
-
-  bool FirstArgKind = true;
-  std::set MatcherKinds;
-  // Two steps. First all non-matchers, then matchers only.
-  for (const ArgKind  : Arg) {
-if (AK.getArgKind() == ArgKind::AK_Matcher) {
-  MatcherKinds.insert(AK.getMatcherKind());
-} else {
+
+if (IsPolymorphic) {
+  OS << "Matcher " << Name << "(Matcher";
+} else {
+  OS << "Matcher<" << RetKinds << "> " << Name << "(";
+  for (const std::vector  : ArgsKinds) {
+if ( != [0])
+  OS << ", ";
+
+bool FirstArgKind = true;
+std::set MatcherKinds;
+// Two steps. First all non-matchers, then matchers only.
+for (const ArgKind  : Arg) {
+  if (AK.getArgKind() == ArgKind::AK_Matcher) {
+MatcherKinds.insert(AK.getMatcherKind());
+  } else {
+if (!FirstArgKind)
+  OS << "|";
+FirstArgKind = false;
+OS << AK.asString();
+  }
+}
+if (!MatcherKinds.empty()) {
   if (!FirstArgKind) OS << "|";
-  FirstArgKind = false;
-  OS << AK.asString();
+  OS << "Matcher<" << MatcherKinds << ">";
 }
   }
-  if (!MatcherKinds.empty()) {
-if (!FirstArgKind) OS << "|";
-OS << "Matcher<" << MatcherKinds << ">";
-  }
 }
+if (Matcher.isVariadic())
+  OS << "...";
+OS << ")";
+
+TypedText += "(";
+if (ArgsKinds.empty())
+ 

[PATCH] D94880: Add clang-query support for mapAnyOf

2021-02-07 Thread Stephen Kelly 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 rG04b69d9a6013: Add clang-query support for mapAnyOf (authored 
by stephenkelly).

Changed prior to commit:
  https://reviews.llvm.org/D94880?vs=320774=321989#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94880

Files:
  clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
  clang/include/clang/ASTMatchers/Dynamic/Parser.h
  clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
  clang/lib/ASTMatchers/Dynamic/Parser.cpp
  clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp

Index: clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
===
--- clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
+++ clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp
@@ -32,6 +32,17 @@
 return M.getID().second;
   }
 
+  bool isBuilderMatcher(MatcherCtor) const override { return false; }
+
+  ASTNodeKind nodeMatcherType(MatcherCtor) const override { return {}; }
+
+  internal::MatcherDescriptorPtr
+  buildMatcherCtor(MatcherCtor, SourceRange NameRange,
+   ArrayRef Args,
+   Diagnostics *Error) const override {
+return internal::MatcherDescriptorPtr{nullptr};
+  }
+
   void parse(StringRef Code) {
 Diagnostics Error;
 VariantValue Value;
@@ -329,7 +340,7 @@
 "1:5: Invalid token <(> found when looking for a value.",
 ParseWithError("Foo(("));
   EXPECT_EQ("1:7: Expected end of code.", ParseWithError("expr()a"));
-  EXPECT_EQ("1:11: Malformed bind() expression.",
+  EXPECT_EQ("1:11: Period not followed by valid chained call.",
 ParseWithError("isArrow().biind"));
   EXPECT_EQ("1:15: Malformed bind() expression.",
 ParseWithError("isArrow().bind"));
@@ -340,6 +351,20 @@
   EXPECT_EQ("1:1: Error building matcher isArrow.\n"
 "1:1: Matcher does not support binding.",
 ParseWithError("isArrow().bind(\"foo\")"));
+  EXPECT_EQ("1:1: Error building matcher isArrow.\n"
+"1:11: Matcher does not support with call.",
+ParseWithError("isArrow().with"));
+  EXPECT_EQ(
+  "1:22: Error parsing matcher. Found token  while looking for '('.",
+  ParseWithError("mapAnyOf(ifStmt).with"));
+  EXPECT_EQ(
+  "1:22: Error parsing matcher. Found end-of-code while looking for ')'.",
+  ParseWithError("mapAnyOf(ifStmt).with("));
+  EXPECT_EQ("1:1: Failed to build matcher: mapAnyOf.",
+ParseWithError("mapAnyOf()"));
+  EXPECT_EQ("1:1: Error parsing argument 1 for matcher mapAnyOf.\n1:1: Failed "
+"to build matcher: mapAnyOf.",
+ParseWithError("mapAnyOf(\"foo\")"));
   EXPECT_EQ("Input value has unresolved overloaded type: "
 "Matcher",
 ParseMatcherWithError("hasBody(stmt())"));
@@ -470,7 +495,8 @@
 )matcher";
 M = Parser::parseMatcherExpression(Code, nullptr, , );
 EXPECT_FALSE(M.hasValue());
-EXPECT_EQ("1:11: Malformed bind() expression.", Error.toStringFull());
+EXPECT_EQ("1:11: Period not followed by valid chained call.",
+  Error.toStringFull());
   }
 
   {
Index: clang/lib/ASTMatchers/Dynamic/Parser.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Parser.cpp
+++ clang/lib/ASTMatchers/Dynamic/Parser.cpp
@@ -52,6 +52,7 @@
 
   /// Some known identifiers.
   static const char* const ID_Bind;
+  static const char *const ID_With;
 
   TokenInfo() = default;
 
@@ -62,6 +63,7 @@
 };
 
 const char* const Parser::TokenInfo::ID_Bind = "bind";
+const char *const Parser::TokenInfo::ID_With = "with";
 
 /// Simple tokenizer for the parser.
 class Parser::CodeTokenizer {
@@ -367,14 +369,26 @@
 
   std::string BindID;
   Tokenizer->consumeNextToken();
-  TokenInfo BindToken = Tokenizer->consumeNextToken();
-  if (BindToken.Kind == TokenInfo::TK_CodeCompletion) {
-addCompletion(BindToken, MatcherCompletion("bind(\"", "bind", 1));
+  TokenInfo ChainCallToken = Tokenizer->consumeNextToken();
+  if (ChainCallToken.Kind == TokenInfo::TK_CodeCompletion) {
+addCompletion(ChainCallToken, MatcherCompletion("bind(\"", "bind", 1));
 return false;
   }
-  if (BindToken.Kind != TokenInfo::TK_Ident ||
-BindToken.Text != TokenInfo::ID_Bind) {
-Error->addError(BindToken.Range, Error->ET_ParserMalformedBindExpr);
+
+  if (ChainCallToken.Kind != TokenInfo::TK_Ident ||
+  (ChainCallToken.Text != TokenInfo::ID_Bind &&
+   ChainCallToken.Text != TokenInfo::ID_With)) {
+Error->addError(ChainCallToken.Range,
+Error->ET_ParserMalformedChainedExpr);
+return false;
+  }
+  if (ChainCallToken.Text == TokenInfo::ID_With) {
+
+Diagnostics::Context 

[clang] 04b69d9 - Add clang-query support for mapAnyOf

2021-02-07 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-07T15:40:15Z
New Revision: 04b69d9a6013cbc39321452fa09e24fed4c98bc7

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

LOG: Add clang-query support for mapAnyOf

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

Added: 


Modified: 
clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
clang/include/clang/ASTMatchers/Dynamic/Parser.h
clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
clang/lib/ASTMatchers/Dynamic/Parser.cpp
clang/unittests/ASTMatchers/Dynamic/ParserTest.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h 
b/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
index f095dcdd60b0..10625311c1a5 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Diagnostics.h
@@ -66,6 +66,8 @@ class Diagnostics {
 ET_RegistryAmbiguousOverload = 5,
 ET_RegistryValueNotFound = 6,
 ET_RegistryUnknownEnumWithReplace = 7,
+ET_RegistryNonNodeMatcher = 8,
+ET_RegistryMatcherNoWithSupport = 9,
 
 ET_ParserStringError = 100,
 ET_ParserNoOpenParen = 101,
@@ -77,7 +79,9 @@ class Diagnostics {
 ET_ParserMalformedBindExpr = 107,
 ET_ParserTrailingCode = 108,
 ET_ParserNumberError = 109,
-ET_ParserOverloadedType = 110
+ET_ParserOverloadedType = 110,
+ET_ParserMalformedChainedExpr = 111,
+ET_ParserFailedToBuildMatcher = 112
   };
 
   /// Helper stream class.

diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Parser.h 
b/clang/include/clang/ASTMatchers/Dynamic/Parser.h
index 384e88ff5edf..af370d83782a 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Parser.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Parser.h
@@ -100,6 +100,14 @@ class Parser {
 virtual llvm::Optional
 lookupMatcherCtor(StringRef MatcherName) = 0;
 
+virtual bool isBuilderMatcher(MatcherCtor) const = 0;
+
+virtual ASTNodeKind nodeMatcherType(MatcherCtor) const = 0;
+
+virtual internal::MatcherDescriptorPtr
+buildMatcherCtor(MatcherCtor, SourceRange NameRange,
+ ArrayRef Args, Diagnostics *Error) const = 0;
+
 /// Compute the list of completion types for \p Context.
 ///
 /// Each element of \p Context represents a matcher invocation, going from
@@ -142,6 +150,15 @@ class Parser {
 std::vector getAcceptedCompletionTypes(
 llvm::ArrayRef> Context) override;
 
+bool isBuilderMatcher(MatcherCtor Ctor) const override;
+
+ASTNodeKind nodeMatcherType(MatcherCtor) const override;
+
+internal::MatcherDescriptorPtr
+buildMatcherCtor(MatcherCtor, SourceRange NameRange,
+ ArrayRef Args,
+ Diagnostics *Error) const override;
+
 std::vector
 getMatcherCompletions(llvm::ArrayRef AcceptedTypes) override;
   };
@@ -233,6 +250,8 @@ class Parser {
 
   bool parseBindID(std::string );
   bool parseExpressionImpl(VariantValue *Value);
+  bool parseMatcherBuilder(MatcherCtor Ctor, const TokenInfo ,
+   const TokenInfo , VariantValue *Value);
   bool parseMatcherExpressionImpl(const TokenInfo ,
   const TokenInfo ,
   llvm::Optional Ctor,

diff  --git a/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp 
b/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
index 88c2279afb2e..ba2f49e6b623 100644
--- a/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Diagnostics.cpp
@@ -100,6 +100,10 @@ static StringRef 
errorTypeToFormatString(Diagnostics::ErrorType Type) {
 return "Value not found: $0";
   case Diagnostics::ET_RegistryUnknownEnumWithReplace:
 return "Unknown value '$1' for arg $0; did you mean '$2'";
+  case Diagnostics::ET_RegistryNonNodeMatcher:
+return "Matcher not a node matcher: $0";
+  case Diagnostics::ET_RegistryMatcherNoWithSupport:
+return "Matcher does not support with call.";
 
   case Diagnostics::ET_ParserStringError:
 return "Error parsing string token: <$0>";
@@ -123,6 +127,10 @@ static StringRef 
errorTypeToFormatString(Diagnostics::ErrorType Type) {
 return "Error parsing numeric literal: <$0>";
   case Diagnostics::ET_ParserOverloadedType:
 return "Input value has unresolved overloaded type: $0";
+  case Diagnostics::ET_ParserMalformedChainedExpr:
+return "Period not followed by valid chained call.";
+  case Diagnostics::ET_ParserFailedToBuildMatcher:
+return "Failed to build matcher: $0.";
 
   case Diagnostics::ET_None:
 return "";

diff  --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp 
b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
index efe581284fb9..c6a77bb6c2e0 100644
--- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp
+++ 

[clang] 816cc43 - [ASTMatchers] Extract parsing of bind token from the bind id

2021-02-07 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-07T15:40:15Z
New Revision: 816cc432812724627835e66ed94a20a2478edef8

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

LOG: [ASTMatchers] Extract parsing of bind token from the bind id

This will be extended to be able to parse "with" for mapAnyOf in
addition to "bind".

Added: 


Modified: 
clang/lib/ASTMatchers/Dynamic/Parser.cpp

Removed: 




diff  --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp 
b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
index 7715e2a17799..efe581284fb9 100644
--- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
@@ -366,6 +366,17 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue 
*Value) {
   }
 
   std::string BindID;
+  Tokenizer->consumeNextToken();
+  TokenInfo BindToken = Tokenizer->consumeNextToken();
+  if (BindToken.Kind == TokenInfo::TK_CodeCompletion) {
+addCompletion(BindToken, MatcherCompletion("bind(\"", "bind", 1));
+return false;
+  }
+  if (BindToken.Kind != TokenInfo::TK_Ident ||
+BindToken.Text != TokenInfo::ID_Bind) {
+Error->addError(BindToken.Range, Error->ET_ParserMalformedBindExpr);
+return false;
+  }
   if (!parseBindID(BindID))
 return false;
 
@@ -420,26 +431,13 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue 
*Value) {
 }
 
 bool Parser::parseBindID(std::string ) {
-  // Parse .bind("foo")
-  assert(Tokenizer->peekNextToken().Kind == TokenInfo::TK_Period);
-  Tokenizer->consumeNextToken(); // consume the period.
-  const TokenInfo BindToken = Tokenizer->consumeNextToken();
-  if (BindToken.Kind == TokenInfo::TK_CodeCompletion) {
-addCompletion(BindToken, MatcherCompletion("bind(\"", "bind", 1));
-return false;
-  }
-
+  // Parse the parenthesized argument to .bind("foo")
   const TokenInfo OpenToken = Tokenizer->consumeNextToken();
   const TokenInfo IDToken = Tokenizer->consumeNextTokenIgnoreNewlines();
   const TokenInfo CloseToken = Tokenizer->consumeNextTokenIgnoreNewlines();
 
   // TODO: We could use 
diff erent error codes for each/some to be more
   //   explicit about the syntax error.
-  if (BindToken.Kind != TokenInfo::TK_Ident ||
-  BindToken.Text != TokenInfo::ID_Bind) {
-Error->addError(BindToken.Range, Error->ET_ParserMalformedBindExpr);
-return false;
-  }
   if (OpenToken.Kind != TokenInfo::TK_OpenParen) {
 Error->addError(OpenToken.Range, Error->ET_ParserMalformedBindExpr);
 return false;
@@ -518,6 +516,17 @@ bool Parser::parseMatcherExpressionImpl(const TokenInfo 
,
 
   std::string BindID;
   if (Tokenizer->peekNextToken().Kind == TokenInfo::TK_Period) {
+Tokenizer->consumeNextToken();
+TokenInfo BindToken = Tokenizer->consumeNextToken();
+if (BindToken.Kind == TokenInfo::TK_CodeCompletion) {
+  addCompletion(BindToken, MatcherCompletion("bind(\"", "bind", 1));
+  return false;
+}
+if (BindToken.Kind != TokenInfo::TK_Ident ||
+  BindToken.Text != TokenInfo::ID_Bind) {
+  Error->addError(BindToken.Range, Error->ET_ParserMalformedBindExpr);
+  return false;
+}
 if (!parseBindID(BindID))
   return false;
   }



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


[clang] 8021078 - [ASTMatchers] Change internal method API

2021-02-07 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-07T15:37:35Z
New Revision: 8021078bc993073d703b91eae8f9b9ed8de478dc

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

LOG: [ASTMatchers] Change internal method API

This will make it possible to parse matchers built dynamically.

Added: 


Modified: 
clang/include/clang/ASTMatchers/Dynamic/Parser.h
clang/lib/ASTMatchers/Dynamic/Parser.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Parser.h 
b/clang/include/clang/ASTMatchers/Dynamic/Parser.h
index 70bbe816accd..384e88ff5edf 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Parser.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Parser.h
@@ -234,6 +234,8 @@ class Parser {
   bool parseBindID(std::string );
   bool parseExpressionImpl(VariantValue *Value);
   bool parseMatcherExpressionImpl(const TokenInfo ,
+  const TokenInfo ,
+  llvm::Optional Ctor,
   VariantValue *Value);
   bool parseIdentifierPrefixImpl(VariantValue *Value);
 

diff  --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp 
b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
index a0037549ca61..7715e2a17799 100644
--- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
@@ -405,8 +405,18 @@ bool Parser::parseIdentifierPrefixImpl(VariantValue 
*Value) {
 
   Tokenizer->SkipNewlines();
 
+  assert(NameToken.Kind == TokenInfo::TK_Ident);
+  TokenInfo OpenToken = Tokenizer->consumeNextToken();
+  if (OpenToken.Kind != TokenInfo::TK_OpenParen) {
+Error->addError(OpenToken.Range, Error->ET_ParserNoOpenParen)
+<< OpenToken.Text;
+return false;
+  }
+
+  llvm::Optional Ctor = S->lookupMatcherCtor(NameToken.Text);
+
   // Parse as a matcher expression.
-  return parseMatcherExpressionImpl(NameToken, Value);
+  return parseMatcherExpressionImpl(NameToken, OpenToken, Ctor, Value);
 }
 
 bool Parser::parseBindID(std::string ) {
@@ -451,17 +461,9 @@ bool Parser::parseBindID(std::string ) {
 ///   If the input is malformed, or some argument has an error, it
 ///   returns \c false.
 bool Parser::parseMatcherExpressionImpl(const TokenInfo ,
+const TokenInfo ,
+llvm::Optional Ctor,
 VariantValue *Value) {
-  assert(NameToken.Kind == TokenInfo::TK_Ident);
-  const TokenInfo OpenToken = Tokenizer->consumeNextToken();
-  if (OpenToken.Kind != TokenInfo::TK_OpenParen) {
-Error->addError(OpenToken.Range, Error->ET_ParserNoOpenParen)
-<< OpenToken.Text;
-return false;
-  }
-
-  llvm::Optional Ctor = S->lookupMatcherCtor(NameToken.Text);
-
   if (!Ctor) {
 Error->addError(NameToken.Range, Error->ET_RegistryMatcherNotFound)
 << NameToken.Text;



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


[clang] 45e210d - [ASTMatchers] Make it possible to build mapAnyOf through the registry

2021-02-07 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-07T15:36:15Z
New Revision: 45e210dbebfae916b213e52be15c276032aeb60d

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

LOG: [ASTMatchers] Make it possible to build mapAnyOf through the registry

Added: 


Modified: 
clang/include/clang/ASTMatchers/Dynamic/Registry.h
clang/lib/ASTMatchers/Dynamic/Marshallers.h
clang/lib/ASTMatchers/Dynamic/Registry.cpp
clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Registry.h 
b/clang/include/clang/ASTMatchers/Dynamic/Registry.h
index 9ce77c33d6d8..f91f5fe01c4e 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Registry.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Registry.h
@@ -33,6 +33,23 @@ namespace internal {
 
 class MatcherDescriptor;
 
+/// A smart (owning) pointer for MatcherDescriptor. We can't use unique_ptr
+/// because MatcherDescriptor is forward declared
+class MatcherDescriptorPtr {
+public:
+  explicit MatcherDescriptorPtr(MatcherDescriptor *);
+  ~MatcherDescriptorPtr();
+  MatcherDescriptorPtr(MatcherDescriptorPtr &&) = default;
+  MatcherDescriptorPtr =(MatcherDescriptorPtr &&) = default;
+  MatcherDescriptorPtr(const MatcherDescriptorPtr &) = delete;
+  MatcherDescriptorPtr =(const MatcherDescriptorPtr &) = delete;
+
+  MatcherDescriptor *get() { return Ptr; }
+
+private:
+  MatcherDescriptor *Ptr;
+};
+
 } // namespace internal
 
 using MatcherCtor = const internal::MatcherDescriptor *;
@@ -68,6 +85,12 @@ class Registry {
 
   static ASTNodeKind nodeMatcherType(MatcherCtor);
 
+  static bool isBuilderMatcher(MatcherCtor Ctor);
+
+  static internal::MatcherDescriptorPtr
+  buildMatcherCtor(MatcherCtor, SourceRange NameRange,
+   ArrayRef Args, Diagnostics *Error);
+
   /// Look up a matcher in the registry by name,
   ///
   /// \return An opaque value which may be used to refer to the matcher

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
index 71d7443c91ca..3ffa0d6af217 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
@@ -311,6 +311,14 @@ class MatcherDescriptor {
 
   virtual ASTNodeKind nodeMatcherType() const { return ASTNodeKind(); }
 
+  virtual bool isBuilderMatcher() const { return false; }
+
+  virtual std::unique_ptr
+  buildMatcherCtor(SourceRange NameRange, ArrayRef Args,
+   Diagnostics *Error) const {
+return {};
+  }
+
   /// Returns whether the matcher is variadic. Variadic matchers can take any
   /// number of arguments, but they must be of the same type.
   virtual bool isVariadic() const = 0;
@@ -996,6 +1004,62 @@ class MapAnyOfMatcherDescriptor : public 
MatcherDescriptor {
   }
 };
 
+class MapAnyOfBuilderDescriptor : public MatcherDescriptor {
+public:
+  VariantMatcher create(SourceRange, ArrayRef,
+Diagnostics *) const override {
+return {};
+  }
+
+  bool isBuilderMatcher() const override { return true; }
+
+  std::unique_ptr
+  buildMatcherCtor(SourceRange, ArrayRef Args,
+   Diagnostics *) const override {
+
+std::vector NodeKinds;
+for (auto Arg : Args) {
+  if (!Arg.Value.isNodeKind())
+return {};
+  NodeKinds.push_back(Arg.Value.getNodeKind());
+}
+
+if (NodeKinds.empty())
+  return {};
+
+ASTNodeKind CladeNodeKind = NodeKinds.front().getCladeKind();
+
+for (auto NK : NodeKinds)
+{
+  if (!NK.getCladeKind().isSame(CladeNodeKind))
+return {};
+}
+
+return std::make_unique(CladeNodeKind,
+   NodeKinds);
+  }
+
+  bool isVariadic() const override { return true; }
+
+  unsigned getNumArgs() const override { return 0; }
+
+  void getArgKinds(ASTNodeKind ThisKind, unsigned,
+   std::vector ) const override {
+ArgKinds.push_back(ArgKind::MakeNodeArg(ThisKind));
+return;
+  }
+  bool isConvertibleTo(ASTNodeKind Kind, unsigned *Specificity = nullptr,
+   ASTNodeKind *LeastDerivedKind = nullptr) const override 
{
+if (Specificity)
+  *Specificity = 1;
+if (LeastDerivedKind)
+  *LeastDerivedKind = Kind;
+return true;
+  }
+
+  bool isPolymorphic() const override { return false; }
+};
+
 /// Helper functions to select the appropriate marshaller functions.
 /// They detect the number of arguments, arguments types and return type.
 

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 908a9ee8ae62..ef5fd64a3666 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -102,6 +102,9 @@ 

[PATCH] D93800: [clangd] Add caching behaviour for clang-format config

2021-02-07 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 321988.
njames93 added a comment.

Add unittests for provider.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93800

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/Compiler.h
  clang-tools-extra/clangd/FormatProvider.cpp
  clang-tools-extra/clangd/FormatProvider.h
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/Hover.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/FormatTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TestTU.h

Index: clang-tools-extra/clangd/unittests/TestTU.h
===
--- clang-tools-extra/clangd/unittests/TestTU.h
+++ clang-tools-extra/clangd/unittests/TestTU.h
@@ -19,6 +19,7 @@
 
 #include "../TidyProvider.h"
 #include "Compiler.h"
+#include "FormatProvider.h"
 #include "ParsedAST.h"
 #include "TestFS.h"
 #include "index/Index.h"
@@ -60,6 +61,8 @@
   std::vector ExtraArgs;
 
   TidyProvider ClangTidyProvider = {};
+
+  mutable FormatProvider ClangFormatProvider = formatFallbackProvider;
   // Index to use when building AST.
   const SymbolIndex *ExternalIndex = nullptr;
 
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -9,6 +9,7 @@
 #include "TestTU.h"
 #include "Compiler.h"
 #include "Diagnostics.h"
+#include "FormatProvider.h"
 #include "TestFS.h"
 #include "index/FileIndex.h"
 #include "index/MemIndex.h"
@@ -61,6 +62,9 @@
   Inputs.Opts = ParseOptions();
   if (ClangTidyProvider)
 Inputs.ClangTidyProvider = ClangTidyProvider;
+  ClangFormatProvider =
+  getClangFormatProvider(FS, format::DefaultFallbackStyle);
+  Inputs.ClangFormatProvider = ClangFormatProvider;
   Inputs.Index = ExternalIndex;
   return Inputs;
 }
Index: clang-tools-extra/clangd/unittests/FormatTests.cpp
===
--- clang-tools-extra/clangd/unittests/FormatTests.cpp
+++ clang-tools-extra/clangd/unittests/FormatTests.cpp
@@ -303,6 +303,30 @@
 )cpp");
 }
 
+TEST(FormatProvider, NestedDirectories) {
+  MockFS FS;
+  FS.Files[testPath("project/.clang-format")] = R"yaml(
+  BasedOnStyle: llvm
+)yaml";
+  FS.Files[testPath("project/test/.clang-format")] = R"yaml(
+  BasedOnStyle: llvm
+  ColumnLimit: 0
+)yaml";
+
+  auto Provider = getClangFormatProvider(FS, "google");
+  auto LLVMStyle = format::getLLVMStyle(format::FormatStyle::LK_Cpp);
+
+  EXPECT_EQ(*Provider(testPath("project/File.cpp"), ""), LLVMStyle);
+
+  LLVMStyle.ColumnLimit = 0U;
+  EXPECT_EQ(*Provider(testPath("project/test/File.cpp"), ""), LLVMStyle);
+
+  // This shouldn't find a config file and instead fallback to using google
+  // style.
+  EXPECT_EQ(*Provider(testPath("File.cpp"), ""),
+format::getGoogleStyle(format::FormatStyle::LK_Cpp));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -11,6 +11,7 @@
 #include "ClangdServer.h"
 #include "CodeComplete.h"
 #include "Compiler.h"
+#include "FormatProvider.h"
 #include "Matchers.h"
 #include "Protocol.h"
 #include "Quality.h"
@@ -154,6 +155,7 @@
   MockFS FS;
   Annotations Test(Text);
   ParseInputs ParseInput{tooling::CompileCommand(), , Test.code().str()};
+  ParseInput.ClangFormatProvider = formatFallbackProvider;
   return codeComplete(FilePath, Test.point(), /*Preamble=*/nullptr, ParseInput,
   Opts);
 }
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -9,6 +9,7 @@
 #include "ClangdLSPServer.h"
 #include "CodeComplete.h"
 #include "Features.inc"
+#include "FormatProvider.h"
 #include "PathMapping.h"
 #include "Protocol.h"
 #include "TidyProvider.h"
@@ -841,6 +842,9 @@
 ClangTidyOptProvider = combine(std::move(Providers));
 Opts.ClangTidyProvider = ClangTidyOptProvider;
   }
+  FormatProvider ClangFormatOptProvider =
+  getClangFormatProvider(TFS, FallbackStyle);
+  Opts.ClangFormatProvider = ClangFormatOptProvider;
   

[clang] d3bccdc - [ASTMatchers ]Make MatcherDescriptors indicate the node type they match

2021-02-07 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-07T15:13:28Z
New Revision: d3bccdcd50e392469c5d115eda29a308914e19ae

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

LOG: [ASTMatchers ]Make MatcherDescriptors indicate the node type they match

Added: 


Modified: 
clang/include/clang/ASTMatchers/Dynamic/Registry.h
clang/lib/ASTMatchers/Dynamic/Marshallers.h
clang/lib/ASTMatchers/Dynamic/Registry.cpp
clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/Registry.h 
b/clang/include/clang/ASTMatchers/Dynamic/Registry.h
index 215206b2f50c..9ce77c33d6d8 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/Registry.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/Registry.h
@@ -66,6 +66,8 @@ class Registry {
 public:
   Registry() = delete;
 
+  static ASTNodeKind nodeMatcherType(MatcherCtor);
+
   /// Look up a matcher in the registry by name,
   ///
   /// \return An opaque value which may be used to refer to the matcher

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
index 411062392dad..71d7443c91ca 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
@@ -309,6 +309,8 @@ class MatcherDescriptor {
 ArrayRef Args,
 Diagnostics *Error) const = 0;
 
+  virtual ASTNodeKind nodeMatcherType() const { return ASTNodeKind(); }
+
   /// Returns whether the matcher is variadic. Variadic matchers can take any
   /// number of arguments, but they must be of the same type.
   virtual bool isVariadic() const = 0;
@@ -576,6 +578,8 @@ class VariadicFuncMatcherDescriptor : public 
MatcherDescriptor {
   LeastDerivedKind);
   }
 
+  ASTNodeKind nodeMatcherType() const override { return RetKinds[0]; }
+
 private:
   const RunFunc Func;
   const std::string MatcherName;
@@ -611,6 +615,8 @@ class DynCastAllOfMatcherDescriptor : public 
VariadicFuncMatcherDescriptor {
 }
   }
 
+  ASTNodeKind nodeMatcherType() const override { return DerivedKind; }
+
 private:
   const ASTNodeKind DerivedKind;
 };

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 0887eb7e0881..908a9ee8ae62 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -562,6 +562,10 @@ RegistryMaps::~RegistryMaps() = default;
 
 static llvm::ManagedStatic RegistryData;
 
+ASTNodeKind Registry::nodeMatcherType(MatcherCtor Ctor) {
+  return Ctor->nodeMatcherType();
+}
+
 // static
 llvm::Optional Registry::lookupMatcherCtor(StringRef MatcherName) 
{
   auto it = RegistryData->constructors().find(MatcherName);

diff  --git a/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp 
b/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
index 7d6c51f965ec..386fd523bb24 100644
--- a/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
+++ b/clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp
@@ -497,6 +497,12 @@ TEST_F(RegistryTest, Completion) {
   "Matcher 
isSameOrDerivedFrom(string|Matcher)"));
 }
 
+TEST_F(RegistryTest, NodeType) {
+  
EXPECT_TRUE(Registry::nodeMatcherType(*lookupMatcherCtor("callExpr")).isSame(ASTNodeKind::getFromNodeKind()));
+  EXPECT_TRUE(Registry::nodeMatcherType(*lookupMatcherCtor("has")).isNone());
+  EXPECT_TRUE(Registry::nodeMatcherType(*lookupMatcherCtor("allOf")).isNone());
+}
+
 TEST_F(RegistryTest, HasArgs) {
   Matcher Value = constructMatcher(
   "decl", constructMatcher("hasAttr", StringRef("attr::WarnUnused")))



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


[clang] e12d827 - Make it possible to store NodeKinds in ArgKind

2021-02-07 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-07T14:00:45Z
New Revision: e12d8279915c323f3727085ccfd0f2c54ad82bdd

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

LOG: Make it possible to store NodeKinds in ArgKind

Added: 


Modified: 
clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
clang/lib/ASTMatchers/Dynamic/VariantValue.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h 
b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
index abfb29707924..5b3f8a7ca5eb 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
@@ -35,6 +35,7 @@ class ArgKind {
  public:
   enum Kind {
 AK_Matcher,
+AK_Node,
 AK_Boolean,
 AK_Double,
 AK_Unsigned,
@@ -48,11 +49,19 @@ class ArgKind {
 return ArgKind{AK_Matcher, MatcherKind};
   }
 
+  static ArgKind MakeNodeArg(ASTNodeKind MatcherKind) {
+return ArgKind{AK_Node, MatcherKind};
+  }
+
   Kind getArgKind() const { return K; }
   ASTNodeKind getMatcherKind() const {
 assert(K == AK_Matcher);
 return NodeKind;
   }
+  ASTNodeKind getNodeKind() const {
+assert(K == AK_Node);
+return NodeKind;
+  }
 
   /// Determines if this type can be converted to \p To.
   ///
@@ -63,7 +72,8 @@ class ArgKind {
   bool isConvertibleTo(ArgKind To, unsigned *Specificity) const;
 
   bool operator<(const ArgKind ) const {
-if (K == AK_Matcher && Other.K == AK_Matcher)
+if ((K == AK_Matcher && Other.K == AK_Matcher) ||
+(K == AK_Node && Other.K == AK_Node))
   return NodeKind < Other.NodeKind;
 return K < Other.K;
   }

diff  --git a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp 
b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
index d367ad0e3233..813eb1597756 100644
--- a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
@@ -23,6 +23,8 @@ std::string ArgKind::asString() const {
   switch (getArgKind()) {
   case AK_Matcher:
 return (Twine("Matcher<") + NodeKind.asStringRef() + ">").str();
+  case AK_Node:
+return NodeKind.asStringRef().str();
   case AK_Boolean:
 return "boolean";
   case AK_Double:
@@ -38,7 +40,7 @@ std::string ArgKind::asString() const {
 bool ArgKind::isConvertibleTo(ArgKind To, unsigned *Specificity) const {
   if (K != To.K)
 return false;
-  if (K != AK_Matcher) {
+  if (K != AK_Matcher && K != AK_Node) {
 if (Specificity)
   *Specificity = 1;
 return true;
@@ -443,6 +445,11 @@ bool VariantValue::isConvertibleTo(ArgKind Kind, unsigned 
*Specificity) const {
 *Specificity = 1;
 return true;
 
+  case ArgKind::AK_Node:
+if (!isNodeKind())
+  return false;
+return getMatcher().isConvertibleTo(Kind.getNodeKind(), Specificity);
+
   case ArgKind::AK_Matcher:
 if (!isMatcher())
   return false;



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


[clang] 79fedad - [ASTMatchers] Add static constructor for ArgKinds of Matchers

2021-02-07 Thread Stephen Kelly via cfe-commits

Author: Stephen Kelly
Date: 2021-02-07T13:43:04Z
New Revision: 79fedadd6af84701e8c873c8d7b507e323d15a5e

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

LOG: [ASTMatchers] Add static constructor for ArgKinds of Matchers

It will soon be possible to store a node kind in an ArgKind, which will
also be contructed with an ASTNodeKind.  The desired Kind must be
expicit.

Added: 


Modified: 
clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
clang/lib/ASTMatchers/Dynamic/Marshallers.h
clang/lib/ASTMatchers/Dynamic/Registry.cpp
clang/lib/ASTMatchers/Dynamic/VariantValue.cpp

Removed: 




diff  --git a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h 
b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
index fa033f49bc90..abfb29707924 100644
--- a/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
+++ b/clang/include/clang/ASTMatchers/Dynamic/VariantValue.h
@@ -44,12 +44,14 @@ class ArgKind {
   ArgKind(Kind K) : K(K) { assert(K != AK_Matcher); }
 
   /// Constructor for matcher types.
-  ArgKind(ASTNodeKind MatcherKind) : K(AK_Matcher), MatcherKind(MatcherKind) {}
+  static ArgKind MakeMatcherArg(ASTNodeKind MatcherKind) {
+return ArgKind{AK_Matcher, MatcherKind};
+  }
 
   Kind getArgKind() const { return K; }
   ASTNodeKind getMatcherKind() const {
 assert(K == AK_Matcher);
-return MatcherKind;
+return NodeKind;
   }
 
   /// Determines if this type can be converted to \p To.
@@ -62,7 +64,7 @@ class ArgKind {
 
   bool operator<(const ArgKind ) const {
 if (K == AK_Matcher && Other.K == AK_Matcher)
-  return MatcherKind < Other.MatcherKind;
+  return NodeKind < Other.NodeKind;
 return K < Other.K;
   }
 
@@ -70,8 +72,9 @@ class ArgKind {
   std::string asString() const;
 
 private:
+  ArgKind(Kind K, ASTNodeKind NK) : K(K), NodeKind(NK) {}
   Kind K;
-  ASTNodeKind MatcherKind;
+  ASTNodeKind NodeKind;
 };
 
 using ast_matchers::internal::DynTypedMatcher;

diff  --git a/clang/lib/ASTMatchers/Dynamic/Marshallers.h 
b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
index 690b52162e2b..411062392dad 100644
--- a/clang/lib/ASTMatchers/Dynamic/Marshallers.h
+++ b/clang/lib/ASTMatchers/Dynamic/Marshallers.h
@@ -93,7 +93,7 @@ template  struct 
ArgTypeTraits> {
   }
 
   static ArgKind getKind() {
-return ArgKind(ASTNodeKind::getFromNodeKind());
+return ArgKind::MakeMatcherArg(ASTNodeKind::getFromNodeKind());
   }
 
   static llvm::Optional getBestGuess(const VariantValue &) {
@@ -343,7 +343,8 @@ inline bool isRetKindConvertibleTo(ArrayRef 
RetKinds,
ASTNodeKind Kind, unsigned *Specificity,
ASTNodeKind *LeastDerivedKind) {
   for (const ASTNodeKind  : RetKinds) {
-if (ArgKind(NodeKind).isConvertibleTo(Kind, Specificity)) {
+if (ArgKind::MakeMatcherArg(NodeKind).isConvertibleTo(
+ArgKind::MakeMatcherArg(Kind), Specificity)) {
   if (LeastDerivedKind)
 *LeastDerivedKind = NodeKind;
   return true;
@@ -904,7 +905,7 @@ class VariadicOperatorMatcherDescriptor : public 
MatcherDescriptor {
 
   void getArgKinds(ASTNodeKind ThisKind, unsigned ArgNo,
std::vector ) const override {
-Kinds.push_back(ThisKind);
+Kinds.push_back(ArgKind::MakeMatcherArg(ThisKind));
   }
 
   bool isConvertibleTo(ASTNodeKind Kind, unsigned *Specificity,
@@ -976,7 +977,7 @@ class MapAnyOfMatcherDescriptor : public MatcherDescriptor {
 
   void getArgKinds(ASTNodeKind ThisKind, unsigned,
std::vector ) const override {
-Kinds.push_back(ThisKind);
+Kinds.push_back(ArgKind::MakeMatcherArg(ThisKind));
   }
 
   bool isConvertibleTo(ASTNodeKind Kind, unsigned *Specificity,

diff  --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 775f51b419a1..0887eb7e0881 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -599,7 +599,10 @@ std::vector Registry::getAcceptedCompletionTypes(
 
   // Starting with the above seed of acceptable top-level matcher types, 
compute
   // the acceptable type set for the argument indicated by each context 
element.
-  std::set TypeSet(std::begin(InitialTypes), std::end(InitialTypes));
+  std::set TypeSet;
+  for (auto IT : InitialTypes) {
+TypeSet.insert(ArgKind::MakeMatcherArg(IT));
+  }
   for (const auto  : Context) {
 MatcherCtor Ctor = CtxEntry.first;
 unsigned ArgNumber = CtxEntry.second;

diff  --git a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp 
b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
index d1ecb1e00b91..d367ad0e3233 100644
--- a/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/VariantValue.cpp
@@ -22,7 

[PATCH] D93179: [X86] Convert fmin/fmax _mm_reduce_* intrinsics to emit llvm.reduction intrinsics (PR47506)

2021-02-07 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

@pengfei I'm sorry I haven't gotten back to looking at this yet - it makes 
sense to create a patch to revert the fadd/fmul reduction changes for 
trunk/12.x.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93179

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


[PATCH] D95877: [analyzer] Fix static_cast on pointer-to-member handling

2021-02-07 Thread Deep Majumder via Phabricator via cfe-commits
RedDocMD added a comment.

@vsavchenko are there some more changes you want done?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D95877

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