Re: [PATCH] [scan-build] Add an option to skip overriding CC and CXX make vars

2018-01-19 Thread Paul Fertser via cfe-commits
Hello Jonathan,

On Mon, Jan 15, 2018 at 08:36:03AM -0700, Jonathan Roelofs wrote:
> LGTM. Would you like me to commit it for you?

Yes, please, commit this patch with my next html documentation patch
squashed into it, and also please commit the ccc-analyzer patch and
close the related ticket as I do not have any permissions.

-- 
Be free, use free (http://www.gnu.org/philosophy/free-sw.html) software!
mailto:fercer...@gmail.com
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42074: [clangd] Collect enum constants in SymbolCollector

2018-01-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 130568.
hokein marked an inline comment as done.
hokein added a comment.

Update comment.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42074

Files:
  clangd/index/SymbolCollector.cpp
  unittests/clangd/SymbolCollectorTests.cpp


Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -161,6 +161,43 @@
QName("foo::baz")}));
 }
 
+TEST_F(SymbolCollectorTest, IncludeEnums) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+enum {
+  Red
+};
+enum Color {
+  Green
+};
+enum class Color2 {
+  Yellow // ignore
+};
+namespace ns {
+enum {
+  Black
+};
+}
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Red"), QName("Color"),
+QName("Green"), QName("Color2"),
+QName("ns"),
+QName("ns::Black")));
+}
+
+TEST_F(SymbolCollectorTest, IgnoreNamelessSymbols) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+struct {
+  int a;
+} Foo;
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("Foo")));
+}
+
 TEST_F(SymbolCollectorTest, IgnoreSymbolsInMainFile) {
   CollectorOpts.IndexMainFiles = false;
   const std::string Header = R"(
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -71,6 +71,10 @@
   using namespace clang::ast_matchers;
   if (ND->isImplicit())
 return true;
+  // Skip anonymous declarations, e.g (anonymous enum/class/struct).
+  if (ND->getDeclName().isEmpty())
+return true;
+
   // FIXME: figure out a way to handle internal linkage symbols (e.g. static
   // variables, function) defined in the .cc files. Also we skip the symbols
   // in anonymous namespace as the qualifier names of these symbols are like
@@ -82,12 +86,18 @@
   if (ND->isInAnonymousNamespace())
 return true;
 
-  // We only want symbols in namespaces or translation unit scopes (e.g. no
-  // class members).
-  if (match(decl(allOf(
-Opts.IndexMainFiles ? decl()
-: decl(unless(isExpansionInMainFile())),
-hasDeclContext(anyOf(namespaceDecl(), 
translationUnitDecl(),
+  // We only want:
+  //   * symbols in namespaces or translation unit scopes (e.g. no class
+  // members)
+  //   * enum constants in unscoped enum decl (e.g. "red" in "enum {red};")
+  auto InTopLevelScope =
+  hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
+  if (match(decl(allOf(Opts.IndexMainFiles
+   ? decl()
+   : decl(unless(isExpansionInMainFile())),
+   anyOf(InTopLevelScope,
+ hasDeclContext(enumDecl(InTopLevelScope,
+ unless(isScoped())),
 *ND, *ASTCtx)
   .empty())
 return true;


Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -161,6 +161,43 @@
QName("foo::baz")}));
 }
 
+TEST_F(SymbolCollectorTest, IncludeEnums) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+enum {
+  Red
+};
+enum Color {
+  Green
+};
+enum class Color2 {
+  Yellow // ignore
+};
+namespace ns {
+enum {
+  Black
+};
+}
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Red"), QName("Color"),
+QName("Green"), QName("Color2"),
+QName("ns"),
+QName("ns::Black")));
+}
+
+TEST_F(SymbolCollectorTest, IgnoreNamelessSymbols) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+struct {
+  int a;
+} Foo;
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("Foo")));
+}
+
 TEST_F(SymbolCollectorTest, IgnoreSymbolsInMainFile) {
   CollectorOpts.IndexMainFiles = false;
   const std::string Header = R"(
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -71,6 +71,10 @@
   using namespace clang::ast_matchers;
   if (ND->isImpl

[PATCH] D42261: [clang-tidy objc-property-declaration] New option AdditionalAcronyms

2018-01-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tidy/objc/PropertyDeclarationCheck.h:38
 const std::vector SpecialAcronyms;
+const std::vector AdditionalAcronyms;
 };

nit: code indent



Comment at: docs/clang-tidy/checks/objc-property-declaration.rst:47
+
+.. option:: AdditionalAcronyms
+

It seems to me the `Acronyms` and `AdditionalAcronyms` play most same role 
here. 

If we want to keep the long default list, how about using a bool flag 
`IncludeDefaultList` + the existing `Acronyms` option?

* if `IncludeDefaultList` is on, the acronyms will be "default" + "Acronyms".
* if `IncludeDefaultList` is off, the acronyms will be only "Acronyms".


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42261



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


[clang-tools-extra] r322929 - [clangd] Collect enum constants in SymbolCollector

2018-01-19 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Fri Jan 19 01:35:55 2018
New Revision: 322929

URL: http://llvm.org/viewvc/llvm-project?rev=322929&view=rev
Log:
[clangd] Collect enum constants in SymbolCollector

Summary:
* ignore nameless symbols
* include enum constant declarataion

Reviewers: ilya-biryukov, jkorous-apple

Reviewed By: ilya-biryukov

Subscribers: ioeric, cfe-commits, klimek

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

Modified:
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=322929&r1=322928&r2=322929&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Fri Jan 19 
01:35:55 2018
@@ -71,6 +71,10 @@ bool shouldFilterDecl(const NamedDecl *N
   using namespace clang::ast_matchers;
   if (ND->isImplicit())
 return true;
+  // Skip anonymous declarations, e.g (anonymous enum/class/struct).
+  if (ND->getDeclName().isEmpty())
+return true;
+
   // FIXME: figure out a way to handle internal linkage symbols (e.g. static
   // variables, function) defined in the .cc files. Also we skip the symbols
   // in anonymous namespace as the qualifier names of these symbols are like
@@ -82,12 +86,18 @@ bool shouldFilterDecl(const NamedDecl *N
   if (ND->isInAnonymousNamespace())
 return true;
 
-  // We only want symbols in namespaces or translation unit scopes (e.g. no
-  // class members).
-  if (match(decl(allOf(
-Opts.IndexMainFiles ? decl()
-: decl(unless(isExpansionInMainFile())),
-hasDeclContext(anyOf(namespaceDecl(), 
translationUnitDecl(),
+  // We only want:
+  //   * symbols in namespaces or translation unit scopes (e.g. no class
+  // members)
+  //   * enum constants in unscoped enum decl (e.g. "red" in "enum {red};")
+  auto InTopLevelScope =
+  hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
+  if (match(decl(allOf(Opts.IndexMainFiles
+   ? decl()
+   : decl(unless(isExpansionInMainFile())),
+   anyOf(InTopLevelScope,
+ hasDeclContext(enumDecl(InTopLevelScope,
+ unless(isScoped())),
 *ND, *ASTCtx)
   .empty())
 return true;

Modified: clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp?rev=322929&r1=322928&r2=322929&view=diff
==
--- clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp Fri Jan 
19 01:35:55 2018
@@ -161,6 +161,43 @@ TEST_F(SymbolCollectorTest, CollectSymbo
QName("foo::baz")}));
 }
 
+TEST_F(SymbolCollectorTest, IncludeEnums) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+enum {
+  Red
+};
+enum Color {
+  Green
+};
+enum class Color2 {
+  Yellow // ignore
+};
+namespace ns {
+enum {
+  Black
+};
+}
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Red"), QName("Color"),
+QName("Green"), QName("Color2"),
+QName("ns"),
+QName("ns::Black")));
+}
+
+TEST_F(SymbolCollectorTest, IgnoreNamelessSymbols) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+struct {
+  int a;
+} Foo;
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("Foo")));
+}
+
 TEST_F(SymbolCollectorTest, IgnoreSymbolsInMainFile) {
   CollectorOpts.IndexMainFiles = false;
   const std::string Header = R"(


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


[PATCH] D42074: [clangd] Collect enum constants in SymbolCollector

2018-01-19 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL322929: [clangd] Collect enum constants in SymbolCollector 
(authored by hokein, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42074

Files:
  clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
  clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp


Index: clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
@@ -161,6 +161,43 @@
QName("foo::baz")}));
 }
 
+TEST_F(SymbolCollectorTest, IncludeEnums) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+enum {
+  Red
+};
+enum Color {
+  Green
+};
+enum class Color2 {
+  Yellow // ignore
+};
+namespace ns {
+enum {
+  Black
+};
+}
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Red"), QName("Color"),
+QName("Green"), QName("Color2"),
+QName("ns"),
+QName("ns::Black")));
+}
+
+TEST_F(SymbolCollectorTest, IgnoreNamelessSymbols) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+struct {
+  int a;
+} Foo;
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("Foo")));
+}
+
 TEST_F(SymbolCollectorTest, IgnoreSymbolsInMainFile) {
   CollectorOpts.IndexMainFiles = false;
   const std::string Header = R"(
Index: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
@@ -71,6 +71,10 @@
   using namespace clang::ast_matchers;
   if (ND->isImplicit())
 return true;
+  // Skip anonymous declarations, e.g (anonymous enum/class/struct).
+  if (ND->getDeclName().isEmpty())
+return true;
+
   // FIXME: figure out a way to handle internal linkage symbols (e.g. static
   // variables, function) defined in the .cc files. Also we skip the symbols
   // in anonymous namespace as the qualifier names of these symbols are like
@@ -82,12 +86,18 @@
   if (ND->isInAnonymousNamespace())
 return true;
 
-  // We only want symbols in namespaces or translation unit scopes (e.g. no
-  // class members).
-  if (match(decl(allOf(
-Opts.IndexMainFiles ? decl()
-: decl(unless(isExpansionInMainFile())),
-hasDeclContext(anyOf(namespaceDecl(), 
translationUnitDecl(),
+  // We only want:
+  //   * symbols in namespaces or translation unit scopes (e.g. no class
+  // members)
+  //   * enum constants in unscoped enum decl (e.g. "red" in "enum {red};")
+  auto InTopLevelScope =
+  hasDeclContext(anyOf(namespaceDecl(), translationUnitDecl()));
+  if (match(decl(allOf(Opts.IndexMainFiles
+   ? decl()
+   : decl(unless(isExpansionInMainFile())),
+   anyOf(InTopLevelScope,
+ hasDeclContext(enumDecl(InTopLevelScope,
+ unless(isScoped())),
 *ND, *ASTCtx)
   .empty())
 return true;


Index: clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp
@@ -161,6 +161,43 @@
QName("foo::baz")}));
 }
 
+TEST_F(SymbolCollectorTest, IncludeEnums) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+enum {
+  Red
+};
+enum Color {
+  Green
+};
+enum class Color2 {
+  Yellow // ignore
+};
+namespace ns {
+enum {
+  Black
+};
+}
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols, UnorderedElementsAre(QName("Red"), QName("Color"),
+QName("Green"), QName("Color2"),
+QName("ns"),
+QName("ns::Black")));
+}
+
+TEST_F(SymbolCollectorTest, IgnoreNamelessSymbols) {
+  CollectorOpts.IndexMainFiles = false;
+  const std::string Header = R"(
+struct {
+  int a;
+} Foo;
+  )";
+  runSymbolCollector(Header, /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(QName("Foo")));
+}
+
 TEST_F(SymbolCollectorTest, IgnoreSy

[PATCH] D41852: [clang-tidy] Don't generate fix for argument constructed from std::initializer_list.

2018-01-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: test/clang-tidy/Inputs/modernize-smart-ptr/initializer_list.h:30
   vector(initializer_list<_E> init);
+  ~vector();
 };

ilya-biryukov wrote:
> hokein wrote:
> > ilya-biryukov wrote:
> > > Why do we need to add this destructor in this patch?
> > Yeah, we do need it to reproduce the issue in real world. The AST is 
> > different with/without the destructor.
> Because without destructor `CXXBindTemporaryExpr` does not show up?
Yes.


Repository:
  rL LLVM

https://reviews.llvm.org/D41852



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


Re: r322901 - Remove TautologicalInRangeCompare from Extra and TautologicalCompare.

2018-01-19 Thread Hans Wennborg via cfe-commits
Merged to 6.0 in r322931.

On Thu, Jan 18, 2018 at 10:40 PM, Nico Weber via cfe-commits
 wrote:
> Author: nico
> Date: Thu Jan 18 13:40:27 2018
> New Revision: 322901
>
> URL: http://llvm.org/viewvc/llvm-project?rev=322901&view=rev
> Log:
> Remove TautologicalInRangeCompare from Extra and TautologicalCompare.
>
> This removes the following (already default-off) warnings from -Wextra:
>   -Wtautological-type-limit-compare,
>   -Wtautological-unsigned-zero-compare
>   -Wtautological-unsigned-enum-zero-compare
>
> On the thread "[cfe-dev] -Wtautological-constant-compare issues", clang
> code owners Richard Smith, John McCall, and Reid Kleckner as well as
> libc++ code owner Marshall Clow stated that these new warnings are not
> yet ready for prime time and shouldn't be part of -Wextra.
>
> Furthermore, Vedant Kumar (Apple), Peter Hosek (Fuchsia), and me (Chromium)
> expressed the same concerns (Vedant on that thread, Peter on
> https://reviews.llvm.org/D39462, me on https://reviews.llvm.org/D41512).
>
> So remove them from -Wextra, and remove TautologicalInRangeCompare from
> TautologicalCompare too until they're usable with real-world code.
>
> Modified:
> cfe/trunk/include/clang/Basic/DiagnosticGroups.td
> cfe/trunk/test/Sema/tautological-constant-compare.c
>
> Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=322901&r1=322900&r2=322901&view=diff
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Thu Jan 18 13:40:27 2018
> @@ -444,8 +444,7 @@ def TautologicalInRangeCompare : DiagGro
>  
> TautologicalUnsignedEnumZeroCompare]>;
>  def TautologicalOutOfRangeCompare : 
> DiagGroup<"tautological-constant-out-of-range-compare">;
>  def TautologicalConstantCompare : DiagGroup<"tautological-constant-compare",
> -[TautologicalInRangeCompare,
> - TautologicalOutOfRangeCompare]>;
> +[TautologicalOutOfRangeCompare]>;
>  def TautologicalPointerCompare : DiagGroup<"tautological-pointer-compare">;
>  def TautologicalOverlapCompare : DiagGroup<"tautological-overlap-compare">;
>  def TautologicalUndefinedCompare : 
> DiagGroup<"tautological-undefined-compare">;
> @@ -719,7 +718,6 @@ def IntToPointerCast : DiagGroup<"int-to
>  def Move : DiagGroup<"move", [PessimizingMove, RedundantMove, SelfMove]>;
>
>  def Extra : DiagGroup<"extra", [
> -TautologicalInRangeCompare,
>  MissingFieldInitializers,
>  IgnoredQualifiers,
>  InitializerOverrides,
>
> Modified: cfe/trunk/test/Sema/tautological-constant-compare.c
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/tautological-constant-compare.c?rev=322901&r1=322900&r2=322901&view=diff
> ==
> --- cfe/trunk/test/Sema/tautological-constant-compare.c (original)
> +++ cfe/trunk/test/Sema/tautological-constant-compare.c Thu Jan 18 13:40:27 
> 2018
> @@ -2,8 +2,8 @@
>  // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only 
> -Wtautological-constant-in-range-compare -DTEST -verify -x c++ %s
>  // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only 
> -Wtautological-type-limit-compare -DTEST -verify %s
>  // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only 
> -Wtautological-type-limit-compare -DTEST -verify -x c++ %s
> -// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only -Wextra 
> -Wno-sign-compare -DTEST -verify %s
> -// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only -Wextra 
> -Wno-sign-compare -DTEST -verify -x c++ %s
> +// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only -Wextra 
> -Wno-sign-compare -verify %s
> +// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only -Wextra 
> -Wno-sign-compare -verify -x c++ %s
>  // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only -Wall -verify %s
>  // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only -Wall -verify -x 
> c++ %s
>  // RUN: %clang_cc1 -triple x86_64-linux-gnu -fsyntax-only -verify %s
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41947: Provide default virtual filesystem argument to ClangTool constructor

2018-01-19 Thread Vladimir Plyashkun via Phabricator via cfe-commits
vladimir.plyashkun updated this revision to Diff 130573.
vladimir.plyashkun added a comment.

Fixed comment


Repository:
  rC Clang

https://reviews.llvm.org/D41947

Files:
  include/clang/Tooling/Tooling.h
  lib/Tooling/Tooling.cpp
  unittests/Tooling/ToolingTest.cpp


Index: unittests/Tooling/ToolingTest.cpp
===
--- unittests/Tooling/ToolingTest.cpp
+++ unittests/Tooling/ToolingTest.cpp
@@ -402,6 +402,24 @@
   EXPECT_FALSE(Found);
 }
 
+TEST(ClangToolTest, BaseVirtualFileSystemUsage) {
+  FixedCompilationDatabase Compilations("/", std::vector());
+  llvm::IntrusiveRefCntPtr OverlayFileSystem(
+  new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
+  llvm::IntrusiveRefCntPtr InMemoryFileSystem(
+  new vfs::InMemoryFileSystem);
+  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
+
+  InMemoryFileSystem->addFile(
+  "a.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}"));
+
+  ClangTool Tool(Compilations, std::vector(1, "a.cpp"),
+ std::make_shared(), 
OverlayFileSystem);
+  std::unique_ptr Action(
+  newFrontendActionFactory());
+  EXPECT_EQ(0, Tool.run(Action.get()));
+}
+
 // Check getClangStripDependencyFileAdjuster doesn't strip args after -MD/-MMD.
 TEST(ClangToolTest, StripDependencyFileAdjuster) {
   FixedCompilationDatabase Compilations("/", {"-MD", "-c", "-MMD", "-w"});
Index: lib/Tooling/Tooling.cpp
===
--- lib/Tooling/Tooling.cpp
+++ lib/Tooling/Tooling.cpp
@@ -328,10 +328,11 @@
 
 ClangTool::ClangTool(const CompilationDatabase &Compilations,
  ArrayRef SourcePaths,
- std::shared_ptr PCHContainerOps)
+ std::shared_ptr PCHContainerOps,
+ IntrusiveRefCntPtr BaseFS)
 : Compilations(Compilations), SourcePaths(SourcePaths),
   PCHContainerOps(std::move(PCHContainerOps)),
-  OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
+  OverlayFileSystem(new vfs::OverlayFileSystem(BaseFS)),
   InMemoryFileSystem(new vfs::InMemoryFileSystem),
   Files(new FileManager(FileSystemOptions(), OverlayFileSystem)),
   DiagConsumer(nullptr) {
Index: include/clang/Tooling/Tooling.h
===
--- include/clang/Tooling/Tooling.h
+++ include/clang/Tooling/Tooling.h
@@ -296,10 +296,14 @@
   ///not found in Compilations, it is skipped.
   /// \param PCHContainerOps The PCHContainerOperations for loading and 
creating
   /// clang modules.
+  /// \param BaseFS VFS used for all underlying file accesses 
+  ///when running the tool.
   ClangTool(const CompilationDatabase &Compilations,
 ArrayRef SourcePaths,
 std::shared_ptr PCHContainerOps =
-std::make_shared());
+std::make_shared(),
+IntrusiveRefCntPtr BaseFS = 
+vfs::getRealFileSystem());
 
   ~ClangTool();
 


Index: unittests/Tooling/ToolingTest.cpp
===
--- unittests/Tooling/ToolingTest.cpp
+++ unittests/Tooling/ToolingTest.cpp
@@ -402,6 +402,24 @@
   EXPECT_FALSE(Found);
 }
 
+TEST(ClangToolTest, BaseVirtualFileSystemUsage) {
+  FixedCompilationDatabase Compilations("/", std::vector());
+  llvm::IntrusiveRefCntPtr OverlayFileSystem(
+  new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
+  llvm::IntrusiveRefCntPtr InMemoryFileSystem(
+  new vfs::InMemoryFileSystem);
+  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
+
+  InMemoryFileSystem->addFile(
+  "a.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}"));
+
+  ClangTool Tool(Compilations, std::vector(1, "a.cpp"),
+ std::make_shared(), OverlayFileSystem);
+  std::unique_ptr Action(
+  newFrontendActionFactory());
+  EXPECT_EQ(0, Tool.run(Action.get()));
+}
+
 // Check getClangStripDependencyFileAdjuster doesn't strip args after -MD/-MMD.
 TEST(ClangToolTest, StripDependencyFileAdjuster) {
   FixedCompilationDatabase Compilations("/", {"-MD", "-c", "-MMD", "-w"});
Index: lib/Tooling/Tooling.cpp
===
--- lib/Tooling/Tooling.cpp
+++ lib/Tooling/Tooling.cpp
@@ -328,10 +328,11 @@
 
 ClangTool::ClangTool(const CompilationDatabase &Compilations,
  ArrayRef SourcePaths,
- std::shared_ptr PCHContainerOps)
+ std::shared_ptr PCHContainerOps,
+ IntrusiveRefCntPtr BaseFS)
 : Compilations(Compilations), SourcePaths(SourcePaths),
   PCHContainerOps(std::move(PCHContainerOps)),
-  OverlayFileSystem(new vfs::OverlayFileSystem(vfs::getRealFileSystem())),
+  OverlayFileSystem(new vfs::OverlayFileSystem(BaseFS)),
   InMemoryFileSystem(new vfs::InMemoryFileSystem),
   Files(new FileManager(FileSystemOptions(), Overl

[PATCH] D41852: [clang-tidy] Don't generate fix for argument constructed from std::initializer_list.

2018-01-19 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: test/clang-tidy/Inputs/modernize-smart-ptr/initializer_list.h:30
   vector(initializer_list<_E> init);
+  ~vector();
 };

hokein wrote:
> ilya-biryukov wrote:
> > hokein wrote:
> > > ilya-biryukov wrote:
> > > > Why do we need to add this destructor in this patch?
> > > Yeah, we do need it to reproduce the issue in real world. The AST is 
> > > different with/without the destructor.
> > Because without destructor `CXXBindTemporaryExpr` does not show up?
> Yes.
Thanks for explaining clang's AST to me :-)


Repository:
  rL LLVM

https://reviews.llvm.org/D41852



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


[PATCH] D42073: [clangd] Query all visible scopes based on all visible using-namespace declarationsand containing namespace for global qualified code completion.

2018-01-19 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/CodeComplete.cpp:270
+  /// namespace scopes which are visible to the qualified-id completion token.
+  std::vector Scopes;
+};

sammccall wrote:
> ilya-biryukov wrote:
> > sammccall wrote:
> > > Just to check, if the user types:
> > > "vec" --> None
> > > "::vec" --> {""}
> > > "std::vec" --> {"std"}
> > > "using namespace std; vec" --> None
> > > "using namespace std; ::vec" --> {"", "std"}
> > > 
> > > is this right?
> > I think the idea was to have (I only highlight the differences):
> > "vec" --> {""}
> > "using namespace std; vec" --> {"", "std"}
> > 
> > @hokein , or am I getting it wrong?
> You're probably right, just want to be sure we're talking about the same 
> thing.
> 
> There's two layers here: the context detected from sema, and what we're going 
> to send the index. The layering is more relevant now that more of this moves 
> out of clangd.
> 
> for "vec", we should be sending {""} to the index for now, and later move 
> towards doing global completion.
> But if possible the detection code should report None, and the query-index 
> code should translate it - there's no reason the detection code needs to be 
> wrong just because clangd can't do qualifier insertion/smart ranking/etc.
> 
> That said, per our discussion this morning, the detected state shouldn't 
> really be Optional>, but rather struct { vector 
> AccessibleScope, optional UnresolvedQualifier } or something like 
> that...
- Totally agree, this patch only fills the `vector AccessibleScope` 
field, and `optional UnresolvedQualifier` could be added in the 
follow-up patch when it's actually handled.
- It still makes sense to have `optional` to distinguish cases 
when clang did not run the lookup during completion and the scopes were not set 
(i.e. completion inside macros, etc.)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42073



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


[PATCH] D41535: Add -vfsoverlay option for Clang-Tidy

2018-01-19 Thread Vladimir Plyashkun via Phabricator via cfe-commits
vladimir.plyashkun updated this revision to Diff 130578.
vladimir.plyashkun added a comment.

Fixed code review remarks.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41535

Files:
  clang-tidy/ClangTidy.cpp
  clang-tidy/ClangTidy.h
  clang-tidy/tool/ClangTidyMain.cpp

Index: clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tidy/tool/ClangTidyMain.cpp
@@ -209,6 +209,12 @@
cl::init(false),
cl::cat(ClangTidyCategory));
 
+static cl::opt VfsOverlay("vfsoverlay", cl::desc(R"(
+Overlay the virtual filesystem described by file over the real file system.
+)"),
+   cl::value_desc("filename"),
+   cl::cat(ClangTidyCategory));
+
 namespace clang {
 namespace tidy {
 
@@ -330,6 +336,29 @@
 OverrideOptions);
 }
 
+llvm::IntrusiveRefCntPtr
+getVfsOverlayFromFile(const std::string &OverlayFile) {
+  llvm::IntrusiveRefCntPtr OverlayFS(
+  new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
+  llvm::ErrorOr> Buffer =
+  OverlayFS->getBufferForFile(OverlayFile);
+  if (!Buffer) {
+llvm::errs() << "Error: virtual filesystem overlay file '" << OverlayFile
+ << "' not found.\n";
+return nullptr;
+  }
+
+  IntrusiveRefCntPtr FS = vfs::getVFSFromYAML(
+  std::move(Buffer.get()), /*DiagHandler*/ nullptr, OverlayFile);
+  if (!FS.get()) {
+llvm::errs() << "Error: invalid virtual filesystem overlay file '"
+ << OverlayFile << "'.\n";
+return nullptr;
+  }
+  OverlayFS->pushOverlay(FS);
+  return OverlayFS;
+}
+
 static int clangTidyMain(int argc, const char **argv) {
   CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
 cl::ZeroOrMore);
@@ -401,6 +430,12 @@
 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
 return 0;
   }
+  llvm::IntrusiveRefCntPtr BaseFS(
+  VfsOverlay.empty() ? vfs::getRealFileSystem()
+ : getVfsOverlayFromFile(VfsOverlay));
+  if (!BaseFS) {
+return 1;
+  }
 
   ProfileData Profile;
 
@@ -410,7 +445,7 @@
 
   ClangTidyContext Context(std::move(OwningOptionsProvider));
   runClangTidy(Context, OptionsParser.getCompilations(), PathList,
-   EnableCheckProfile ? &Profile : nullptr);
+   BaseFS, EnableCheckProfile ? &Profile : nullptr);
   ArrayRef Errors = Context.getErrors();
   bool FoundErrors =
   std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
@@ -422,7 +457,7 @@
   unsigned WErrorCount = 0;
 
   // -fix-errors implies -fix.
-  handleErrors(Context, (FixErrors || Fix) && !DisableFixes, WErrorCount);
+  handleErrors(Context, (FixErrors || Fix) && !DisableFixes, WErrorCount, BaseFS);
 
   if (!ExportFixes.empty() && !Errors.empty()) {
 std::error_code EC;
Index: clang-tidy/ClangTidy.h
===
--- clang-tidy/ClangTidy.h
+++ clang-tidy/ClangTidy.h
@@ -227,6 +227,7 @@
 void runClangTidy(clang::tidy::ClangTidyContext &Context,
   const tooling::CompilationDatabase &Compilations,
   ArrayRef InputFiles,
+  llvm::IntrusiveRefCntPtr BaseFS,
   ProfileData *Profile = nullptr);
 
 // FIXME: This interface will need to be significantly extended to be useful.
@@ -236,7 +237,8 @@
 /// Errors containing fixes are automatically applied and reformatted. If no
 /// clang-format configuration file is found, the given \P FormatStyle is used.
 void handleErrors(ClangTidyContext &Context, bool Fix,
-  unsigned &WarningsAsErrorsCount);
+  unsigned &WarningsAsErrorsCount,
+  llvm::IntrusiveRefCntPtr BaseFS);
 
 /// \brief Serializes replacements into YAML and writes them to the specified
 /// output stream.
Index: clang-tidy/ClangTidy.cpp
===
--- clang-tidy/ClangTidy.cpp
+++ clang-tidy/ClangTidy.cpp
@@ -89,8 +89,10 @@
 
 class ErrorReporter {
 public:
-  ErrorReporter(ClangTidyContext &Context, bool ApplyFixes)
-  : Files(FileSystemOptions()), DiagOpts(new DiagnosticOptions()),
+  ErrorReporter(ClangTidyContext &Context, bool ApplyFixes,
+llvm::IntrusiveRefCntPtr BaseFS)
+  : Files(FileSystemOptions(), BaseFS), 
+DiagOpts(new DiagnosticOptions()),
 DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts)),
 Diags(IntrusiveRefCntPtr(new DiagnosticIDs), &*DiagOpts,
   DiagPrinter),
@@ -474,8 +476,11 @@
 
 void runClangTidy(clang::tidy::ClangTidyContext &Context,
   const CompilationDatabase &Compilations,
-  ArrayRef InputFiles, ProfileData *Profile) {
-  ClangTool Tool(Compilations, InputFiles);
+  

Re: r316268 - [Sema] Fixes for enum handling for tautological comparison diagnostics

2018-01-19 Thread Roman Lebedev via cfe-commits
On Fri, Jan 19, 2018 at 2:22 AM, Alex L  wrote:
> Hi Roman,
Hi.

> This commit has caused a regression in LLVM 6 which now triggers
> -Wsign-compare for typeof(enum) and typeof(enumConstant).
Interesting, first impression is that it appears to be a false-positive.

> I filed
> https://bugs.llvm.org/show_bug.cgi?id=36008. Could you please take a look at
> it?
Will do, thanks.

> Thanks,
> Alex
Roman.

> On 21 October 2017 at 09:44, Roman Lebedev via cfe-commits
>  wrote:
>>
>> Author: lebedevri
>> Date: Sat Oct 21 09:44:03 2017
>> New Revision: 316268
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=316268&view=rev
>> Log:
>> [Sema] Fixes for enum handling for tautological comparison diagnostics
>>
>> Summary:
>> As Mattias Eriksson has reported in PR35009, in C, for enums, the
>> underlying type should
>> be used when checking for the tautological comparison, unlike C++, where
>> the enumerator
>> values define the value range. So if not in CPlusPlus mode, use the enum
>> underlying type.
>>
>> Also, i have discovered a problem (a crash) when evaluating
>> tautological-ness of the following comparison:
>> ```
>> enum A { A_a = 0 };
>> if (a < 0) // expected-warning {{comparison of unsigned enum expression <
>> 0 is always false}}
>> return 0;
>> ```
>> This affects both the C and C++, but after the first fix, only C++ code
>> was affected.
>> That was also fixed, while preserving (i think?) the proper diagnostic
>> output.
>>
>> And while there, attempt to enhance the test coverage.
>> Yes, some tests got moved around, sorry about that :)
>>
>> Fixes PR35009
>>
>> Reviewers: aaron.ballman, rsmith, rjmccall
>>
>> Reviewed By: aaron.ballman
>>
>> Subscribers: Rakete, efriedma, materi, cfe-commits
>>
>> Tags: #clang
>>
>> Differential Revision: https://reviews.llvm.org/D39122
>>
>> Added:
>> cfe/trunk/test/Sema/outof-range-enum-constant-compare.c
>> cfe/trunk/test/Sema/tautological-constant-enum-compare.c
>> Modified:
>> cfe/trunk/lib/Sema/SemaChecking.cpp
>> cfe/trunk/test/Sema/tautological-unsigned-enum-zero-compare.c
>> cfe/trunk/test/Sema/tautological-unsigned-enum-zero-compare.cpp
>>
>> Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=316268&r1=316267&r2=316268&view=diff
>>
>> ==
>> --- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaChecking.cpp Sat Oct 21 09:44:03 2017
>> @@ -8181,8 +8181,12 @@ struct IntRange {
>>  if (const AtomicType *AT = dyn_cast(T))
>>T = AT->getValueType().getTypePtr();
>>
>> -// For enum types, use the known bit width of the enumerators.
>> -if (const EnumType *ET = dyn_cast(T)) {
>> +if (!C.getLangOpts().CPlusPlus) {
>> +  // For enum types in C code, use the underlying datatype.
>> +  if (const EnumType *ET = dyn_cast(T))
>> +T =
>> ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
>> +} else if (const EnumType *ET = dyn_cast(T)) {
>> +  // For enum types in C++, use the known bit width of the
>> enumerators.
>>EnumDecl *Enum = ET->getDecl();
>>// In C++11, enums without definitions can have an explicitly
>> specified
>>// underlying type.  Use this type to compute the range.
>> @@ -8584,8 +8588,10 @@ bool isNonBooleanUnsignedValue(Expr *E)
>>  }
>>
>>  enum class LimitType {
>> -  Max, // e.g. 32767 for short
>> -  Min  // e.g. -32768 for short
>> +  Max = 1U << 0U,  // e.g. 32767 for short
>> +  Min = 1U << 1U,  // e.g. -32768 for short
>> +  Both = Max | Min // When the value is both the Min and the Max limit at
>> the
>> +   // same time; e.g. in C++, A::a in enum A { a = 0 };
>>  };
>>
>>  /// Checks whether Expr 'Constant' may be the
>> @@ -8608,6 +8614,10 @@ llvm::Optional IsTypeLimit(Se
>>
>>IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
>>
>> +  // Special-case for C++ for enum with one enumerator with value of 0.
>> +  if (OtherRange.Width == 0)
>> +return Value == 0 ? LimitType::Both : llvm::Optional();
>> +
>>if (llvm::APSInt::isSameValue(
>>llvm::APSInt::getMaxValue(OtherRange.Width,
>>  OtherT->isUnsignedIntegerType()),
>> @@ -8620,7 +8630,7 @@ llvm::Optional IsTypeLimit(Se
>>Value))
>>  return LimitType::Min;
>>
>> -  return llvm::Optional();
>> +  return llvm::None;
>>  }
>>
>>  bool HasEnumType(Expr *E) {
>> @@ -8655,9 +8665,12 @@ bool CheckTautologicalComparison(Sema &S
>>
>>bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant;
>>bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE);
>> -  bool ResultWhenConstNeOther =
>> -  ConstIsLowerBound ^ (ValueType == LimitType::Max);
>> -  if (ResultWhenConstEqualsOther != ResultWhenConstNeOther)
>> +  if (ValueType != LimitType::Both) {
>> +bool ResultWhenConstNeOther =

[PATCH] D41992: [libcxx] Avoid spurious construction of valarray elements

2018-01-19 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki added a comment.

ping


https://reviews.llvm.org/D41992



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


[PATCH] D42291: [libcxx] Correctly handle invalid regex character class names

2018-01-19 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki created this revision.
miyuki added reviewers: EricWF, mclow.lists.

Currently when a regular expression contains an invalid character
class name std::regex constructors throw an std::regex_error with
std::regex_constants::error_brack code.

This patch changes the code to std::regex_constants::error_ctype and
adds a test.


https://reviews.llvm.org/D42291

Files:
  include/regex
  test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp


Index: test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
===
--- /dev/null
+++ test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
@@ -0,0 +1,37 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: libcpp-no-exceptions
+// 
+
+// template > class 
basic_regex;
+
+// template 
+//basic_regex(const basic_string& s);
+
+#include 
+#include 
+#include "test_macros.h"
+
+static bool error_ctype_thrown(const char *pat)
+{
+bool result = false;
+try {
+std::regex re(pat);
+} catch (const std::regex_error &ex) {
+result = (ex.code() == std::regex_constants::error_ctype);
+}
+return result;
+}
+
+int main()
+{
+assert(error_ctype_thrown("[[::]]"));
+assert(error_ctype_thrown("[[:error:]]"));
+}
Index: include/regex
===
--- include/regex
+++ include/regex
@@ -4013,7 +4013,7 @@
 char_class_type __class_type =
 __traits_.lookup_classname(__first, __temp, __flags_ & icase);
 if (__class_type == 0)
-__throw_regex_error();
+__throw_regex_error();
 __ml->__add_class(__class_type);
 __first = _VSTD::next(__temp, 2);
 return __first;


Index: test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
===
--- /dev/null
+++ test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp
@@ -0,0 +1,37 @@
+//===--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source Licenses. See LICENSE.TXT for details.
+//
+//===--===//
+
+// UNSUPPORTED: libcpp-no-exceptions
+// 
+
+// template > class basic_regex;
+
+// template 
+//basic_regex(const basic_string& s);
+
+#include 
+#include 
+#include "test_macros.h"
+
+static bool error_ctype_thrown(const char *pat)
+{
+bool result = false;
+try {
+std::regex re(pat);
+} catch (const std::regex_error &ex) {
+result = (ex.code() == std::regex_constants::error_ctype);
+}
+return result;
+}
+
+int main()
+{
+assert(error_ctype_thrown("[[::]]"));
+assert(error_ctype_thrown("[[:error:]]"));
+}
Index: include/regex
===
--- include/regex
+++ include/regex
@@ -4013,7 +4013,7 @@
 char_class_type __class_type =
 __traits_.lookup_classname(__first, __temp, __flags_ & icase);
 if (__class_type == 0)
-__throw_regex_error();
+__throw_regex_error();
 __ml->__add_class(__class_type);
 __first = _VSTD::next(__temp, 2);
 return __first;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D39050: Add index-while-building support to Clang

2018-01-19 Thread Eric Liu via Phabricator via cfe-commits
ioeric accepted this revision.
ioeric added a comment.
This revision is now accepted and ready to land.

Nice! Thanks for making the refactoring and adding tests! I think this is good 
to go now.

I'm not very familiar with code outside of the index library (Driver, Basic 
etc), but the changes seem reasonable to me. Feel free to get another pair of 
eyes for them ;)




Comment at: include/clang/Index/RecordingAction.h:42
+std::unique_ptr
+createIndexDataRecordingAction(RecordingOptions RecordOpts,
+   std::unique_ptr WrappedAction);

Add a FIXME that this is not implemented yet.



Comment at: lib/Index/IndexingAction.cpp:758
+
+  class IndexUnitDataRecorder : public IndexUnitDataConsumer {
+  public:

nathawes wrote:
> ioeric wrote:
> > I think the inheritance of `IndexUnitDataConsumer`  and the creation of 
> > factory should be in user code (e.g. implementation for on-disk 
> > persist-index-data should come from the compiler invocation code 
> > `ExecuteCompilerInvocation.cpp` or at least a separate file in the library 
> > that compiler invocation can use), and the user should only use 
> > `createUnitIndexingAction` by providing a factory.  Currently, 
> > `createUnitIndexingAction` and `createIndexDataRecordingAction` are mostly 
> > identical except for the code that implements `IndexUnitDataConsumer ` and 
> > creates the factory.
> > 
> > The current `createIndexDataRecordingAction` would probably only used by 
> > the compiler invocation, and we can keep the generalized 
> > `createUnitIndexingAction` in the public APIs.
> `IndexUnitDataRecorder` here is just a stub I added when I split the patch up 
> – the follow-up revision has it in a separate file. I'll move the separate 
> files to this patch and stub out the method bodies with TODOs instead.
> 
> I've made `createIndexDataRecordingAction` call `createUnitIndexingAction` to 
> remove the duplication, and pulled it, `RecordingOptions` and 
> `getRecordingOptionsFromFrontendOptions` to a new header 
> (`RecordingAction.h`) that `ExecuteComilerInvocation.cpp` uses. Does that 
> sound ok?
Sounds good. Thanks for the explanation! 


https://reviews.llvm.org/D39050



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


[PATCH] D42187: [clang-format] Adds a canonical delimiter to raw string formatting

2018-01-19 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 130587.
krasimir marked an inline comment as done.
krasimir added a comment.

- Add a comment about std::string


Repository:
  rC Clang

https://reviews.llvm.org/D42187

Files:
  docs/ClangFormatStyleOptions.rst
  include/clang/Format/Format.h
  lib/Format/ContinuationIndenter.cpp
  lib/Format/Format.cpp
  unittests/Format/FormatTest.cpp
  unittests/Format/FormatTestRawStrings.cpp

Index: unittests/Format/FormatTestRawStrings.cpp
===
--- unittests/Format/FormatTestRawStrings.cpp
+++ unittests/Format/FormatTestRawStrings.cpp
@@ -66,30 +66,41 @@
 FormatStyle Style = getLLVMStyle();
 Style.ColumnLimit = ColumnLimit;
 Style.RawStringFormats = {
-{/*Language=*/FormatStyle::LK_TextProto,
- /*Delimiters=*/{"pb"},
- /*EnclosingFunctions=*/{},
- /*BasedOnStyle=*/"google"},
+{
+/*Language=*/FormatStyle::LK_TextProto,
+/*Delimiters=*/{"pb"},
+/*EnclosingFunctions=*/{},
+/*CanonicalDelimiter=*/"",
+/*BasedOnStyle=*/"google",
+},
 };
 return Style;
   }
 
   FormatStyle getRawStringLLVMCppStyleBasedOn(std::string BasedOnStyle) {
 FormatStyle Style = getLLVMStyle();
 Style.RawStringFormats = {
-{/*Language=*/FormatStyle::LK_Cpp,
- /*Delimiters=*/{"cpp"},
- /*EnclosingFunctions=*/{}, BasedOnStyle},
+{
+/*Language=*/FormatStyle::LK_Cpp,
+/*Delimiters=*/{"cpp"},
+/*EnclosingFunctions=*/{},
+/*CanonicalDelimiter=*/"",
+BasedOnStyle,
+},
 };
 return Style;
   }
 
   FormatStyle getRawStringGoogleCppStyleBasedOn(std::string BasedOnStyle) {
 FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
 Style.RawStringFormats = {
-{/*Language=*/FormatStyle::LK_Cpp,
- /*Delimiters=*/{"cpp"},
- /*EnclosingFunctions=*/{}, BasedOnStyle},
+{
+/*Language=*/FormatStyle::LK_Cpp,
+/*Delimiters=*/{"cpp"},
+/*EnclosingFunctions=*/{},
+/*CanonicalDelimiter=*/"",
+BasedOnStyle,
+},
 };
 return Style;
   }
@@ -131,7 +142,13 @@
   EXPECT_EQ(0, parseConfiguration("---\n"
   "Language: Cpp\n"
   "BasedOnStyle: Google", &Style).value());
-  Style.RawStringFormats = {{FormatStyle::LK_Cpp, {"cpp"}, {}, "llvm"}};
+  Style.RawStringFormats = {{
+  FormatStyle::LK_Cpp,
+  {"cpp"},
+  {},
+  /*CanonicalDelimiter=*/"",
+  /*BasedOnStyle=*/"llvm",
+  }};
   expect_eq(R"test(int* i = R"cpp(int* j = 0;)cpp";)test",
 format(R"test(int * i = R"cpp(int * j = 0;)cpp";)test", Style));
 }
@@ -752,6 +769,18 @@
Style));
 }
 
+TEST_F(FormatTestRawStrings, UpdatesToCanonicalDelimiters) {
+  FormatStyle Style = getRawStringPbStyleWithColumns(25);
+  Style.RawStringFormats[0].CanonicalDelimiter = "proto";
+  expect_eq(R"test(a = R"proto(key: value)proto";)test",
+format(R"test(a = R"pb(key:value)pb";)test", Style));
+
+  // Don't update to canonical delimiter if it occurs as a raw string suffix in
+  // the raw string content.
+  expect_eq(R"test(a = R"pb(key: ")proto")pb";)test",
+format(R"test(a = R"pb(key:")proto")pb";)test", Style));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang
Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -10412,13 +10412,15 @@
   FormatStyle::LK_TextProto,
   {"pb", "proto"},
   {"PARSE_TEXT_PROTO"},
+  /*CanonicalDelimiter=*/"",
   "llvm",
   },
   {
   FormatStyle::LK_Cpp,
   {"cc", "cpp"},
   {"C_CODEBLOCK", "CPPEVAL"},
-  "",
+  /*CanonicalDelimiter=*/"cc",
+  /*BasedOnStyle=*/"",
   },
   };
 
@@ -10436,7 +10438,8 @@
   "  - 'cpp'\n"
   "EnclosingFunctions:\n"
   "  - 'C_CODEBLOCK'\n"
-  "  - 'CPPEVAL'\n",
+  "  - 'CPPEVAL'\n"
+  "CanonicalDelimiter: 'cc'",
   RawStringFormats, ExpectedRawStringFormats);
 }
 
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -470,6 +470,7 @@
 IO.mapOptional("Language", Format.Language);
 IO.mapOptional("Delimiters", Format.Delimiters);
 IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
+IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
 IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
   }
 };
@@ -724,6 +725,7 @@
"PARSE_TEXT_PROTO",
"ParseTextProto",
},
+  /*C

[PATCH] D42187: [clang-format] Adds a canonical delimiter to raw string formatting

2018-01-19 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir added inline comments.



Comment at: lib/Format/ContinuationIndenter.cpp:1336
+  unsigned OldSuffixSize = 2 + OldDelimiter.size();
+  std::string RawText =
+  Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize);

bkramer wrote:
> Can this be a StringRef? Can RawText outlive the Current token?
Nice catch! The reformatting code creates a virtual source code environment 
which expects a null-terminated string. Added a comment why this is necessary.


Repository:
  rC Clang

https://reviews.llvm.org/D42187



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


[PATCH] D41535: Add -vfsoverlay option for Clang-Tidy

2018-01-19 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Just a few more NITs and we're good to go




Comment at: clang-tidy/tool/ClangTidyMain.cpp:347
+llvm::errs() << "Error: virtual filesystem overlay file '" << OverlayFile
+ << "' not found.\n";
+return nullptr;

We should probably print the error message (in addition to "not found", we 
could have permission errors, etc.)
`Buffer.getError().message()` would give a more informative message.



Comment at: clang-tidy/tool/ClangTidyMain.cpp:353
+  std::move(Buffer.get()), /*DiagHandler*/ nullptr, OverlayFile);
+  if (!FS.get()) {
+llvm::errs() << "Error: invalid virtual filesystem overlay file '"

NIT: `if (!FS)` is equivalent, but less typing



Comment at: clang-tidy/tool/ClangTidyMain.cpp:437
+  if (!BaseFS) {
+return 1;
+  }

NIT:  remove braces around a single-statement return.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41535



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


[PATCH] D41535: Add -vfsoverlay option for Clang-Tidy

2018-01-19 Thread Vladimir Plyashkun via Phabricator via cfe-commits
vladimir.plyashkun updated this revision to Diff 130589.
vladimir.plyashkun added a comment.

Some more nits were fixed.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41535

Files:
  clang-tidy/ClangTidy.cpp
  clang-tidy/ClangTidy.h
  clang-tidy/tool/ClangTidyMain.cpp

Index: clang-tidy/tool/ClangTidyMain.cpp
===
--- clang-tidy/tool/ClangTidyMain.cpp
+++ clang-tidy/tool/ClangTidyMain.cpp
@@ -209,6 +209,12 @@
cl::init(false),
cl::cat(ClangTidyCategory));
 
+static cl::opt VfsOverlay("vfsoverlay", cl::desc(R"(
+Overlay the virtual filesystem described by file over the real file system.
+)"),
+   cl::value_desc("filename"),
+   cl::cat(ClangTidyCategory));
+
 namespace clang {
 namespace tidy {
 
@@ -330,6 +336,29 @@
 OverrideOptions);
 }
 
+llvm::IntrusiveRefCntPtr
+getVfsOverlayFromFile(const std::string &OverlayFile) {
+  llvm::IntrusiveRefCntPtr OverlayFS(
+  new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
+  llvm::ErrorOr> Buffer =
+  OverlayFS->getBufferForFile(OverlayFile);
+  if (!Buffer) {
+llvm::errs() << "Can't load virtual filesystem overlay file: '"
+ << OverlayFile << "' " << Buffer.getError().message() << ".\n";
+return nullptr;
+  }
+
+  IntrusiveRefCntPtr FS = vfs::getVFSFromYAML(
+  std::move(Buffer.get()), /*DiagHandler*/ nullptr, OverlayFile);
+  if (!FS) {
+llvm::errs() << "Error: invalid virtual filesystem overlay file '"
+ << OverlayFile << "'.\n";
+return nullptr;
+  }
+  OverlayFS->pushOverlay(FS);
+  return OverlayFS;
+}
+
 static int clangTidyMain(int argc, const char **argv) {
   CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
 cl::ZeroOrMore);
@@ -401,6 +430,11 @@
 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
 return 0;
   }
+  llvm::IntrusiveRefCntPtr BaseFS(
+  VfsOverlay.empty() ? vfs::getRealFileSystem()
+ : getVfsOverlayFromFile(VfsOverlay));
+  if (!BaseFS)
+return 1;
 
   ProfileData Profile;
 
@@ -410,7 +444,7 @@
 
   ClangTidyContext Context(std::move(OwningOptionsProvider));
   runClangTidy(Context, OptionsParser.getCompilations(), PathList,
-   EnableCheckProfile ? &Profile : nullptr);
+   BaseFS, EnableCheckProfile ? &Profile : nullptr);
   ArrayRef Errors = Context.getErrors();
   bool FoundErrors =
   std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
@@ -422,7 +456,7 @@
   unsigned WErrorCount = 0;
 
   // -fix-errors implies -fix.
-  handleErrors(Context, (FixErrors || Fix) && !DisableFixes, WErrorCount);
+  handleErrors(Context, (FixErrors || Fix) && !DisableFixes, WErrorCount, BaseFS);
 
   if (!ExportFixes.empty() && !Errors.empty()) {
 std::error_code EC;
Index: clang-tidy/ClangTidy.h
===
--- clang-tidy/ClangTidy.h
+++ clang-tidy/ClangTidy.h
@@ -227,6 +227,7 @@
 void runClangTidy(clang::tidy::ClangTidyContext &Context,
   const tooling::CompilationDatabase &Compilations,
   ArrayRef InputFiles,
+  llvm::IntrusiveRefCntPtr BaseFS,
   ProfileData *Profile = nullptr);
 
 // FIXME: This interface will need to be significantly extended to be useful.
@@ -236,7 +237,8 @@
 /// Errors containing fixes are automatically applied and reformatted. If no
 /// clang-format configuration file is found, the given \P FormatStyle is used.
 void handleErrors(ClangTidyContext &Context, bool Fix,
-  unsigned &WarningsAsErrorsCount);
+  unsigned &WarningsAsErrorsCount,
+  llvm::IntrusiveRefCntPtr BaseFS);
 
 /// \brief Serializes replacements into YAML and writes them to the specified
 /// output stream.
Index: clang-tidy/ClangTidy.cpp
===
--- clang-tidy/ClangTidy.cpp
+++ clang-tidy/ClangTidy.cpp
@@ -89,8 +89,10 @@
 
 class ErrorReporter {
 public:
-  ErrorReporter(ClangTidyContext &Context, bool ApplyFixes)
-  : Files(FileSystemOptions()), DiagOpts(new DiagnosticOptions()),
+  ErrorReporter(ClangTidyContext &Context, bool ApplyFixes,
+llvm::IntrusiveRefCntPtr BaseFS)
+  : Files(FileSystemOptions(), BaseFS), 
+DiagOpts(new DiagnosticOptions()),
 DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts)),
 Diags(IntrusiveRefCntPtr(new DiagnosticIDs), &*DiagOpts,
   DiagPrinter),
@@ -474,8 +476,11 @@
 
 void runClangTidy(clang::tidy::ClangTidyContext &Context,
   const CompilationDatabase &Compilations,
-  ArrayRef InputFiles, ProfileData *Profile) {
-  ClangTool Tool(Compilations, InputFil

[PATCH] D39053: [Bitfield] Add more cases to making the bitfield a separate location

2018-01-19 Thread Petar Jovanovic via Phabricator via cfe-commits
petarj added a comment.

This sounds as a valid improvement. Can we have this code committed?


https://reviews.llvm.org/D39053



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


[PATCH] D42272: [X86] Add rdpid command line option and intrinsics.

2018-01-19 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: lib/Headers/immintrin.h:251
+#if !defined(_MSC_VER) || __has_feature(modules) || defined(__RDPID__)
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__, 
__target__("rdpid")))
+_rdpid_u32(void) {

Doxygen comment?


https://reviews.llvm.org/D42272



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


[PATCH] D40580: [clang-tidy] Adding Fuchsia checker for multiple inheritance

2018-01-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM aside from a few small nits.




Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp:85
+void MultipleInheritanceCheck::registerMatchers(MatchFinder *Finder) {
+  // Match declarations which have bases.
+  Finder->addMatcher(cxxRecordDecl(hasBases()).bind("decl"), this);

No need to register the matchers for languages other than C++.



Comment at: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp:113-114
+  diag(D->getLocStart(),
+   "inheriting mulitple classes which aren't "
+   "pure virtual is discouraged");
+}

s/which/that


https://reviews.llvm.org/D40580



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


[PATCH] D42181: [clangd] Merge index-provided completions with those from Sema.

2018-01-19 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

LGTM




Comment at: clangd/CodeComplete.cpp:743
+  int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
+  bool Incomplete = false;
+  llvm::Optional Filter; // Initialized once Sema runs.

`InComplete` can probably be output variable of `queryIndex` and `addCandidate` 
instead of a state?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42181



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


[PATCH] D42213: [ASTMatchers] [NFC] Fix code examples

2018-01-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

The documentation needs to be regenerated for this patch. One thing that seems 
to be inconsistent is with the "what gets matched" messages is that sometimes 
it includes extra adornments like curly braces and other times it does not. It 
might be good to pick a style and try to be more consistent with it.




Comment at: include/clang/ASTMatchers/ASTMatchers.h:1792
 /// switchStmt()
-///   matches 'switch(a)'.
+///   matches 'switch(a) {'.
 extern const internal::VariadicDynCastAllOfMatcher 
switchStmt;

I don't think this adds clarity.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:1841
 /// cxxCatchStmt()
-///   matches 'catch(int i)'
+///   matches 'catch(int i) {}'
 extern const internal::VariadicDynCastAllOfMatcher

I don't think this adds clarity.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:1851
 /// cxxTryStmt()
-///   matches 'try {}'
+///   matches 'try {} catch(int i) {}'
 extern const internal::VariadicDynCastAllOfMatcher 
cxxTryStmt;

I think this adds confusion.


Repository:
  rC Clang

https://reviews.llvm.org/D42213



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


[PATCH] D42273: Add hasTrailingReturn AST matcher

2018-01-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:5902
+AST_MATCHER(FunctionDecl, hasTrailingReturn) {
+  return Node.getType()->castAs()->hasTrailingReturn();
+}

I think this may cause failed assertions on code like `void f();` when compiled 
in C mode because that `FunctionDecl` should have a type of 
`FunctionNoProtoType`. You should use `getAs()` and test for 
null.



Comment at: unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp:2121
+  functionDecl(hasTrailingReturn(;
+  EXPECT_TRUE(notMatches("int X() {};", functionDecl(hasTrailingReturn(;
+}

Spurious semicolon in the test.


https://reviews.llvm.org/D42273



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


[PATCH] D42181: [clangd] Merge index-provided completions with those from Sema.

2018-01-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

looks good to me too, just a few nits.




Comment at: clangd/CodeComplete.cpp:308
+return None;
+  }
+}

add `return None` to make compiler happier? I think it might trigger 
-Wreturn-type warning.



Comment at: clangd/CodeComplete.cpp:341
+  CodeCompletionContext CCContext;
+  Sema *Sema = nullptr; // The Sema that created the results.
+

I'd suggesting rename the variable `Sema` to another name, since `Sema` is 
already a class name (although naming is hard).



Comment at: clangd/CodeComplete.cpp:845
+for (const auto &IndexResult : IndexResults) {
+  if (UsedIndexResults.count(&IndexResult))
+continue;

consider using `llvm::set_difference` here?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42181



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


[PATCH] D42181: [clangd] Merge index-provided completions with those from Sema.

2018-01-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Oops, I forgot to submit comments with my last update.
I don't think there's anything surprising so I'll land this, but let me know if 
you want any changes!




Comment at: clangd/CodeComplete.cpp:339
+  std::vector Results;
+  CodeCompletionContext CCContext;
+  Sema *Sema = nullptr; // The Sema that created the results.

ioeric wrote:
> It seems that `CCContext` can change  during `ProcessCodeCompleteResults`. 
> It's unclear what the implication is for `codeCompletionString` at the end. 
This function is only ever called once, but this isn't documented anywhere :-\
Added an assert.



Comment at: clangd/CodeComplete.cpp:734
+// Now we have the needed context to query the index.
+// FIXME: we shouldn't query the index if the scope is e.g. class members.
+// FIXME: in addition to querying for extra/overlapping symbols, we should

ioeric wrote:
> I think we already only query namespace scopes now?
Nope, we never check the completion context kind, and I think I've seen cases 
where we end up completing when it's inappropriate.

Fixed this (see the new `allowIndex()` check) and removed the fixme.



Comment at: clangd/CodeComplete.cpp:747
+  // FIXME(ioeric): add scopes based on using directives and enclosing ns.
+  if (auto SS = Recorder->CCContext.getCXXScopeSpecifier())
+Req.Scopes = {getSpecifiedScope(*Recorder->Sema, **SS).forIndex()};

ioeric wrote:
> As discussed offline, we want to defer unqualified completion support (IIRC?) 
> until we have enough information about visible scopes (i.e. after D42073).
Done - we now complete only symbols in the global scope.
I added two FIXMEs describing how we can progressively make this better over 
time. Do they match your understanding?



Comment at: clangd/CodeComplete.cpp:782
+  // For Sema results, we build the CCS here, where we have the arenas.
+  auto *CCS =
+  Candidate.first.SemaResult

ioeric wrote:
> It would be a bit more natural if the decision of building CCS is hidden in 
> the candidate. Maybe pass in a callback for creating CCS from a sema result 
> and let candidate decide whether to create CCS or not? This would also get 
> rid of the constraint for `build`.
I agree, but trying this out I found it equally hard to read, and not as 
decoupled as I'd hope.
So as discussed offline, sticking with the ugly-and-direct approach :-)



Comment at: clangd/CodeComplete.cpp:743
+  int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
+  bool Incomplete = false;
+  llvm::Optional Filter; // Initialized once Sema runs.

ioeric wrote:
> `InComplete` can probably be output variable of `queryIndex` and 
> `addCandidate` instead of a state?
Certainly it can (it needs to be an out-param, because these functions already 
have primary return values). Just as these could all be free functions :-)

I tried it out - I find the out-params are a bit messy/hard to read, and they'd 
need to be added to `mergeResults`, `queryIndex` and `addCandidate`. It adds 
quite a lot of noise, and I'm not sure on balance emphasizing the flow of 
IsIncomplete is worth obscuring the flow of the results themselves. If you 
disagree, let me know (or just change it!)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42181



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


[PATCH] D41539: [CodeGen] Decorate aggregate accesses with TBAA tags

2018-01-19 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev updated this revision to Diff 130599.
kosarev added a comment.

- Supported propagation of TBAA info for aggregate transfers.
- Added tests on copying of `may_alias` aggregates.


https://reviews.llvm.org/D41539

Files:
  lib/CodeGen/CGAtomic.cpp
  lib/CodeGen/CGCall.cpp
  lib/CodeGen/CGClass.cpp
  lib/CodeGen/CGExprAgg.cpp
  lib/CodeGen/CGExprCXX.cpp
  lib/CodeGen/CGObjC.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGStmt.cpp
  lib/CodeGen/CGStmtOpenMP.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/CodeGenModule.h
  lib/CodeGen/CodeGenTBAA.cpp
  lib/CodeGen/CodeGenTBAA.h
  lib/CodeGen/ItaniumCXXABI.cpp
  test/CodeGen/tbaa-struct.cpp

Index: test/CodeGen/tbaa-struct.cpp
===
--- test/CodeGen/tbaa-struct.cpp
+++ test/CodeGen/tbaa-struct.cpp
@@ -1,75 +1,122 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -o - -O1 %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -emit-llvm -o - -O1 %s | \
+// RUN: FileCheck -check-prefixes=CHECK,CHECK-OLD %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -new-struct-path-tbaa \
+// RUN: -emit-llvm -o - -O1 %s | \
+// RUN: FileCheck -check-prefixes=CHECK,CHECK-NEW %s
 //
-// Check that we generate !tbaa.struct metadata for struct copies.
+// Check that we generate TBAA metadata for struct copies correctly.
+
 struct A {
   short s;
   int i;
   char c;
   int j;
 };
 
-void copy(struct A *a, struct A *b) {
-  *a = *b;
-}
+typedef A __attribute__((may_alias)) AA;
 
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 16, i32 4, i1 false), !tbaa.struct [[TS:!.*]]
+void copy(A *a1, A *a2) {
+// CHECK-LABEL: _Z4copyP1AS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_A:![0-9]*]]
+  *a1 = *a2;
+}
 
 struct B {
-  char c1;
-  struct A a;
-  int ii;
+  char c;
+  A a;
+  int i;
 };
 
-void copy2(struct B *a, struct B *b) {
-  *a = *b;
+void copy2(B *b1, B *b2) {
+// CHECK-LABEL: _Z5copy2P1BS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS2:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_B:![0-9]*]]
+  *b1 = *b2;
 }
 
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 24, i32 4, i1 false), !tbaa.struct [[TS2:!.*]]
+struct S {
+  _Complex char cc;
+  _Complex int ci;
+};
 
-typedef _Complex int T2;
-typedef _Complex char T5;
-typedef _Complex int T7;
-typedef struct T4 { T5 field0; T7 field1; } T4;
-typedef union T1 { T2 field0; T4 field1; } T1;
+union U {
+  _Complex int ci;
+  S s;
+};
 
-void copy3 (T1 *a, T1 *b) {
-  *a = *b;
+void copy3(U *u1, U *u2) {
+// CHECK-LABEL: _Z5copy3P1US0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS3:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_U:![0-9]*]]
+  *u1 = *u2;
 }
 
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 12, i32 4, i1 false), !tbaa.struct [[TS3:!.*]]
-
 // Make sure that zero-length bitfield works.
-#define ATTR __attribute__ ((ms_struct))
-struct five {
+struct C {
   char a;
-  int :0;/* ignored; prior field is not a bitfield. */
+  int : 0;  // Shall not be ignored; see r185018.
   char b;
   char c;
-} ATTR;
-void copy4(struct five *a, struct five *b) {
-  *a = *b;
+} __attribute__((ms_struct));
+
+void copy4(C *c1, C *c2) {
+// CHECK-LABEL: _Z5copy4P1CS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS4:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_C:![0-9]*]]
+  *c1 = *c2;
 }
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 3, i32 1, i1 false), !tbaa.struct [[TS4:!.*]]
 
-struct six {
+struct D {
   char a;
-  int :0;
+  int : 0;
   char b;
   char c;
 };
-void copy5(struct six *a, struct six *b) {
-  *a = *b;
+
+void copy5(D *d1, D *d2) {
+// CHECK-LABEL: _Z5copy5P1DS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS5:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_D:![0-9]*]]
+  *d1 = *d2;
+}
+
+void copy6(AA *a1, A *a2) {
+// CHECK-LABEL: _Z5copy6P1AS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_char:![0-9]*]]
+  *a1 = *a2;
+}
+
+void copy7(A *a1, AA *a2) {
+// CHECK-LABEL: _Z5copy7P1AS0_
+// CHECK-OLD: call void @llvm.memcpy{{.*}}, !tbaa.struct [[TS:!.*]]
+// CHECK-NEW: call void @llvm.memcpy{{.*}}, !tbaa [[TAG_char]]
+  *a1 = *a2;
 }
-// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %{{.*}}, i8* %{{.*}}, i64 6, i32 1, i1 false), !tbaa.struct [[TS5:!.*]]
 
-// CHECK: [[TS]] = !{i64 0, i64 2, !{{.*}}, i64 4, i64 4, !{{.*}}, i64 8, i64 1, !{{.*}}, i64 12, i64 4, !{{.*}}}
-// CHECK: [[CHAR:!.*]] = !{!"omnipotent char", !{{.*}}}
-// CHECK: [[TAG_INT:!.*]] = !{[[INT:!.*]], [[INT]], i64 0}
-// CHECK: [[INT]] = !{!"int", [[CHAR]]
-// CHECK: [[TAG_CHAR:!.*]] = !{[[CHAR]], 

[PATCH] D42181: [clangd] Merge index-provided completions with those from Sema.

2018-01-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 2 inline comments as done.
sammccall added inline comments.



Comment at: clangd/CodeComplete.cpp:308
+return None;
+  }
+}

hokein wrote:
> add `return None` to make compiler happier? I think it might trigger 
> -Wreturn-type warning.
added llvm_unreachable.



Comment at: clangd/CodeComplete.cpp:845
+for (const auto &IndexResult : IndexResults) {
+  if (UsedIndexResults.count(&IndexResult))
+continue;

hokein wrote:
> consider using `llvm::set_difference` here?
The value type is different: Symbol vs Symbol*


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42181



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


[PATCH] D42298: [clang-format] Fix shortening blocks in macros causing merged next line

2018-01-19 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir created this revision.
krasimir added a reviewer: bkramer.
Herald added a subscriber: klimek.

This patch addresses bug 36002, where a combination of options causes the line
following a short block in macro to be merged with that macro.


Repository:
  rC Clang

https://reviews.llvm.org/D42298

Files:
  lib/Format/UnwrappedLineFormatter.cpp
  unittests/Format/FormatTest.cpp


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -495,6 +495,7 @@
"};",
AllowSimpleBracedStatements);
 
+
   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = false;
   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
   verifyFormat("if (true) {\n"
@@ -588,6 +589,23 @@
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+  FormatStyle Style = getLLVMStyleWithColumns(60);
+  Style.AllowShortBlocksOnASingleLine = true;
+  Style.AllowShortIfStatementsOnASingleLine = true;
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  EXPECT_EQ("#define A  \\\n"
+"  if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+"  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
+"X;",
+format("#define A \\\n"
+   "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+   "  RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+   "   }\n"
+   "X;",
+   Style));
+}
+
 TEST_F(FormatTest, ParseIfElse) {
   verifyFormat("if (true)\n"
"  if (true)\n"
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -304,9 +304,15 @@
 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
 I != AnnotatedLines.begin() &&
 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
-  return Style.AllowShortBlocksOnASingleLine
- ? tryMergeSimpleBlock(I - 1, E, Limit)
- : 0;
+  unsigned MergedLines = 0;
+  if (Style.AllowShortBlocksOnASingleLine) {
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first  merged line
+// since we are merging starting from I.
+if (MergedLines > 0)
+  --MergedLines;
+  }
+  return MergedLines;
 }
 // Try to merge a block with left brace wrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -495,6 +495,7 @@
"};",
AllowSimpleBracedStatements);
 
+
   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = false;
   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
   verifyFormat("if (true) {\n"
@@ -588,6 +589,23 @@
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+  FormatStyle Style = getLLVMStyleWithColumns(60);
+  Style.AllowShortBlocksOnASingleLine = true;
+  Style.AllowShortIfStatementsOnASingleLine = true;
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  EXPECT_EQ("#define A  \\\n"
+"  if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+"  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
+"X;",
+format("#define A \\\n"
+   "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+   "  RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+   "   }\n"
+   "X;",
+   Style));
+}
+
 TEST_F(FormatTest, ParseIfElse) {
   verifyFormat("if (true)\n"
"  if (true)\n"
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -304,9 +304,15 @@
 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
 I != AnnotatedLines.begin() &&
 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
-  return Style.AllowShortBlocksOnASingleLine
- ? tryMergeSimpleBlock(I - 1, E, Limit)
- : 0;
+  unsigned MergedLines = 0;
+  if (Style.AllowShortBlocksOnASingleLine) {
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first  merged line
+// since we ar

[clang-tools-extra] r322945 - [clangd] Merge index-provided completions with those from Sema.

2018-01-19 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Jan 19 06:34:02 2018
New Revision: 322945

URL: http://llvm.org/viewvc/llvm-project?rev=322945&view=rev
Log:
[clangd] Merge index-provided completions with those from Sema.

Summary:
 - we match on USR, and do a field-by-field merge if both have results
 - scoring is post-merge, with both sets of information available
   (for now, sema priority is used if available, static score for index results)
 - limit is applied to the complete result set (previously index ignored limit)
 - CompletionItem is only produces for the returned results
 - If the user doesn't type a scope, we send the global scope for completion
   (we can improve this after D42073)

Reviewers: ioeric

Subscribers: klimek, ilya-biryukov, mgrang, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/FuzzyMatch.h
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=322945&r1=322944&r2=322945&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Fri Jan 19 06:34:02 2018
@@ -22,6 +22,7 @@
 #include "index/Index.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendActions.h"
+#include "clang/Index/USRGeneration.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "clang/Sema/Sema.h"
 #include "llvm/Support/Format.h"
@@ -185,48 +186,53 @@ getOptionalParameters(const CodeCompleti
   return Result;
 }
 
-/// A scored code completion result.
+// Produces an integer that sorts in the same order as F.
+// That is: a < b <==> encodeFloat(a) < encodeFloat(b).
+uint32_t encodeFloat(float F) {
+  static_assert(std::numeric_limits::is_iec559, "");
+  static_assert(sizeof(float) == sizeof(uint32_t), "");
+  constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
+
+  // Get the bits of the float. Endianness is the same as for integers.
+  uint32_t U;
+  memcpy(&U, &F, sizeof(float));
+  // IEEE 754 floats compare like sign-magnitude integers.
+  if (U & TopBit)// Negative float.
+return 0 - U;// Map onto the low half of integers, order reversed.
+  return U + TopBit; // Positive floats map onto the high half of integers.
+}
+
+// Returns a string that sorts in the same order as (-Score, Name), for LSP.
+std::string sortText(float Score, llvm::StringRef Name) {
+  // We convert -Score to an integer, and hex-encode for readability.
+  // Example: [0.5, "foo"] -> "4100foo"
+  std::string S;
+  llvm::raw_string_ostream OS(S);
+  write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
+/*Width=*/2 * sizeof(Score));
+  OS << Name;
+  OS.flush();
+  return S;
+}
+
+/// A code completion result, in clang-native form.
 /// It may be promoted to a CompletionItem if it's among the top-ranked 
results.
-///
-/// We score candidates by multiplying the symbolScore ("quality" of the 
result)
-/// with the filterScore (how well it matched the query).
-/// This is sensitive to the distribution of both component scores!
 struct CompletionCandidate {
-  CompletionCandidate(CodeCompletionResult &Result, float FilterScore)
-  : Result(&Result) {
-Scores.symbolScore = score(Result);  // Higher is better.
-Scores.filterScore = FilterScore;// 0-1, higher is better.
-Scores.finalScore = Scores.symbolScore * Scores.filterScore;
-  }
-
-  CodeCompletionResult *Result;
-  CompletionItemScores Scores;
-
-  // Comparison reflects rank: better candidates are smaller.
-  bool operator<(const CompletionCandidate &C) const {
-if (Scores.finalScore != C.Scores.finalScore)
-  return Scores.finalScore > C.Scores.finalScore;
-return *Result < *C.Result;
-  }
-
-  // Returns a string that sorts in the same order as operator<, for LSP.
-  // Conceptually, this is [-Score, Name]. We convert -Score to an integer, and
-  // hex-encode it for readability. Example: [0.5, "foo"] -> "4100foo"
-  std::string sortText() const {
-std::string S, NameStorage;
-llvm::raw_string_ostream OS(S);
-write_hex(OS, encodeFloat(-Scores.finalScore), llvm::HexPrintStyle::Lower,
-  /*Width=*/2 * sizeof(Scores.finalScore));
-OS << Result->getOrderedName(NameStorage);
-return OS.str();
-  }
+  llvm::StringRef Name; // Used for filtering and sorting.
+  // We may have a result from Sema, from the index, or both.
+  const CodeCompletionResult *SemaResult = nullptr;
+  const Symbol *IndexResult = nullptr;
+
+  // Computes the "symbol quality" score for this completion. Higher is better.
+  float score() const {
+// For now we just use the Sema priority, mapping it onto a 0-1 interval.
+if (!SemaResult) // FIXME(sammccall): better scoring fo

[PATCH] D42298: [clang-format] Fix shortening blocks in macros causing merged next line

2018-01-19 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 130604.
krasimir added a comment.

- Remove added newline


Repository:
  rC Clang

https://reviews.llvm.org/D42298

Files:
  lib/Format/UnwrappedLineFormatter.cpp
  unittests/Format/FormatTest.cpp


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -588,6 +588,23 @@
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+  FormatStyle Style = getLLVMStyleWithColumns(60);
+  Style.AllowShortBlocksOnASingleLine = true;
+  Style.AllowShortIfStatementsOnASingleLine = true;
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  EXPECT_EQ("#define A  \\\n"
+"  if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+"  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
+"X;",
+format("#define A \\\n"
+   "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+   "  RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+   "   }\n"
+   "X;",
+   Style));
+}
+
 TEST_F(FormatTest, ParseIfElse) {
   verifyFormat("if (true)\n"
"  if (true)\n"
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -304,9 +304,15 @@
 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
 I != AnnotatedLines.begin() &&
 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
-  return Style.AllowShortBlocksOnASingleLine
- ? tryMergeSimpleBlock(I - 1, E, Limit)
- : 0;
+  unsigned MergedLines = 0;
+  if (Style.AllowShortBlocksOnASingleLine) {
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first  merged line
+// since we are merging starting from I.
+if (MergedLines > 0)
+  --MergedLines;
+  }
+  return MergedLines;
 }
 // Try to merge a block with left brace wrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -588,6 +588,23 @@
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+  FormatStyle Style = getLLVMStyleWithColumns(60);
+  Style.AllowShortBlocksOnASingleLine = true;
+  Style.AllowShortIfStatementsOnASingleLine = true;
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  EXPECT_EQ("#define A  \\\n"
+"  if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+"  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
+"X;",
+format("#define A \\\n"
+   "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+   "  RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+   "   }\n"
+   "X;",
+   Style));
+}
+
 TEST_F(FormatTest, ParseIfElse) {
   verifyFormat("if (true)\n"
"  if (true)\n"
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -304,9 +304,15 @@
 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
 I != AnnotatedLines.begin() &&
 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
-  return Style.AllowShortBlocksOnASingleLine
- ? tryMergeSimpleBlock(I - 1, E, Limit)
- : 0;
+  unsigned MergedLines = 0;
+  if (Style.AllowShortBlocksOnASingleLine) {
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first  merged line
+// since we are merging starting from I.
+if (MergedLines > 0)
+  --MergedLines;
+  }
+  return MergedLines;
 }
 // Try to merge a block with left brace wrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42181: [clangd] Merge index-provided completions with those from Sema.

2018-01-19 Thread Sam McCall via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rL322945: [clangd] Merge index-provided completions with those 
from Sema. (authored by sammccall, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42181?vs=130440&id=130606#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42181

Files:
  clang-tools-extra/trunk/clangd/CodeComplete.cpp
  clang-tools-extra/trunk/clangd/FuzzyMatch.h
  clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp

Index: clang-tools-extra/trunk/clangd/FuzzyMatch.h
===
--- clang-tools-extra/trunk/clangd/FuzzyMatch.h
+++ clang-tools-extra/trunk/clangd/FuzzyMatch.h
@@ -35,7 +35,8 @@
   // Characters beyond MaxWord are ignored.
   llvm::Optional match(llvm::StringRef Word);
 
-  bool empty() { return PatN == 0; }
+  llvm::StringRef pattern() const { return llvm::StringRef(Pat, PatN); }
+  bool empty() const { return PatN == 0; }
 
   // Dump internal state from the last match() to the stream, for debugging.
   // Returns the pattern with [] around matched characters, e.g.
Index: clang-tools-extra/trunk/clangd/CodeComplete.cpp
===
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp
@@ -22,6 +22,7 @@
 #include "index/Index.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendActions.h"
+#include "clang/Index/USRGeneration.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "clang/Sema/Sema.h"
 #include "llvm/Support/Format.h"
@@ -185,48 +186,53 @@
   return Result;
 }
 
-/// A scored code completion result.
+// Produces an integer that sorts in the same order as F.
+// That is: a < b <==> encodeFloat(a) < encodeFloat(b).
+uint32_t encodeFloat(float F) {
+  static_assert(std::numeric_limits::is_iec559, "");
+  static_assert(sizeof(float) == sizeof(uint32_t), "");
+  constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
+
+  // Get the bits of the float. Endianness is the same as for integers.
+  uint32_t U;
+  memcpy(&U, &F, sizeof(float));
+  // IEEE 754 floats compare like sign-magnitude integers.
+  if (U & TopBit)// Negative float.
+return 0 - U;// Map onto the low half of integers, order reversed.
+  return U + TopBit; // Positive floats map onto the high half of integers.
+}
+
+// Returns a string that sorts in the same order as (-Score, Name), for LSP.
+std::string sortText(float Score, llvm::StringRef Name) {
+  // We convert -Score to an integer, and hex-encode for readability.
+  // Example: [0.5, "foo"] -> "4100foo"
+  std::string S;
+  llvm::raw_string_ostream OS(S);
+  write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
+/*Width=*/2 * sizeof(Score));
+  OS << Name;
+  OS.flush();
+  return S;
+}
+
+/// A code completion result, in clang-native form.
 /// It may be promoted to a CompletionItem if it's among the top-ranked results.
-///
-/// We score candidates by multiplying the symbolScore ("quality" of the result)
-/// with the filterScore (how well it matched the query).
-/// This is sensitive to the distribution of both component scores!
 struct CompletionCandidate {
-  CompletionCandidate(CodeCompletionResult &Result, float FilterScore)
-  : Result(&Result) {
-Scores.symbolScore = score(Result);  // Higher is better.
-Scores.filterScore = FilterScore;// 0-1, higher is better.
-Scores.finalScore = Scores.symbolScore * Scores.filterScore;
-  }
-
-  CodeCompletionResult *Result;
-  CompletionItemScores Scores;
-
-  // Comparison reflects rank: better candidates are smaller.
-  bool operator<(const CompletionCandidate &C) const {
-if (Scores.finalScore != C.Scores.finalScore)
-  return Scores.finalScore > C.Scores.finalScore;
-return *Result < *C.Result;
-  }
-
-  // Returns a string that sorts in the same order as operator<, for LSP.
-  // Conceptually, this is [-Score, Name]. We convert -Score to an integer, and
-  // hex-encode it for readability. Example: [0.5, "foo"] -> "4100foo"
-  std::string sortText() const {
-std::string S, NameStorage;
-llvm::raw_string_ostream OS(S);
-write_hex(OS, encodeFloat(-Scores.finalScore), llvm::HexPrintStyle::Lower,
-  /*Width=*/2 * sizeof(Scores.finalScore));
-OS << Result->getOrderedName(NameStorage);
-return OS.str();
-  }
+  llvm::StringRef Name; // Used for filtering and sorting.
+  // We may have a result from Sema, from the index, or both.
+  const CodeCompletionResult *SemaResult = nullptr;
+  const Symbol *IndexResult = nullptr;
+
+  // Computes the "symbol quality" score for this completion. Higher is better.
+  float score() const {
+// For now we just use the Sema priority

[PATCH] D42181: [clangd] Merge index-provided completions with those from Sema.

2018-01-19 Thread Sam McCall via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE322945: [clangd] Merge index-provided completions with 
those from Sema. (authored by sammccall, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42181?vs=130440&id=130607#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42181

Files:
  clangd/CodeComplete.cpp
  clangd/FuzzyMatch.h
  unittests/clangd/CodeCompleteTests.cpp

Index: clangd/FuzzyMatch.h
===
--- clangd/FuzzyMatch.h
+++ clangd/FuzzyMatch.h
@@ -35,7 +35,8 @@
   // Characters beyond MaxWord are ignored.
   llvm::Optional match(llvm::StringRef Word);
 
-  bool empty() { return PatN == 0; }
+  llvm::StringRef pattern() const { return llvm::StringRef(Pat, PatN); }
+  bool empty() const { return PatN == 0; }
 
   // Dump internal state from the last match() to the stream, for debugging.
   // Returns the pattern with [] around matched characters, e.g.
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -22,6 +22,7 @@
 #include "index/Index.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendActions.h"
+#include "clang/Index/USRGeneration.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "clang/Sema/Sema.h"
 #include "llvm/Support/Format.h"
@@ -185,48 +186,53 @@
   return Result;
 }
 
-/// A scored code completion result.
+// Produces an integer that sorts in the same order as F.
+// That is: a < b <==> encodeFloat(a) < encodeFloat(b).
+uint32_t encodeFloat(float F) {
+  static_assert(std::numeric_limits::is_iec559, "");
+  static_assert(sizeof(float) == sizeof(uint32_t), "");
+  constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
+
+  // Get the bits of the float. Endianness is the same as for integers.
+  uint32_t U;
+  memcpy(&U, &F, sizeof(float));
+  // IEEE 754 floats compare like sign-magnitude integers.
+  if (U & TopBit)// Negative float.
+return 0 - U;// Map onto the low half of integers, order reversed.
+  return U + TopBit; // Positive floats map onto the high half of integers.
+}
+
+// Returns a string that sorts in the same order as (-Score, Name), for LSP.
+std::string sortText(float Score, llvm::StringRef Name) {
+  // We convert -Score to an integer, and hex-encode for readability.
+  // Example: [0.5, "foo"] -> "4100foo"
+  std::string S;
+  llvm::raw_string_ostream OS(S);
+  write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
+/*Width=*/2 * sizeof(Score));
+  OS << Name;
+  OS.flush();
+  return S;
+}
+
+/// A code completion result, in clang-native form.
 /// It may be promoted to a CompletionItem if it's among the top-ranked results.
-///
-/// We score candidates by multiplying the symbolScore ("quality" of the result)
-/// with the filterScore (how well it matched the query).
-/// This is sensitive to the distribution of both component scores!
 struct CompletionCandidate {
-  CompletionCandidate(CodeCompletionResult &Result, float FilterScore)
-  : Result(&Result) {
-Scores.symbolScore = score(Result);  // Higher is better.
-Scores.filterScore = FilterScore;// 0-1, higher is better.
-Scores.finalScore = Scores.symbolScore * Scores.filterScore;
-  }
-
-  CodeCompletionResult *Result;
-  CompletionItemScores Scores;
-
-  // Comparison reflects rank: better candidates are smaller.
-  bool operator<(const CompletionCandidate &C) const {
-if (Scores.finalScore != C.Scores.finalScore)
-  return Scores.finalScore > C.Scores.finalScore;
-return *Result < *C.Result;
-  }
-
-  // Returns a string that sorts in the same order as operator<, for LSP.
-  // Conceptually, this is [-Score, Name]. We convert -Score to an integer, and
-  // hex-encode it for readability. Example: [0.5, "foo"] -> "4100foo"
-  std::string sortText() const {
-std::string S, NameStorage;
-llvm::raw_string_ostream OS(S);
-write_hex(OS, encodeFloat(-Scores.finalScore), llvm::HexPrintStyle::Lower,
-  /*Width=*/2 * sizeof(Scores.finalScore));
-OS << Result->getOrderedName(NameStorage);
-return OS.str();
-  }
+  llvm::StringRef Name; // Used for filtering and sorting.
+  // We may have a result from Sema, from the index, or both.
+  const CodeCompletionResult *SemaResult = nullptr;
+  const Symbol *IndexResult = nullptr;
+
+  // Computes the "symbol quality" score for this completion. Higher is better.
+  float score() const {
+// For now we just use the Sema priority, mapping it onto a 0-1 interval.
+if (!SemaResult) // FIXME(sammccall): better scoring for index results.
+  return 0.3;// fixed mediocre score for index-only results.
 
-private:
-  static float score(const CodeCompletionResult &Result) {
 // Priority 80 is a really bad score.
-  

[PATCH] D42298: [clang-format] Fix shortening blocks in macros causing merged next line

2018-01-19 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir updated this revision to Diff 130609.
krasimir added a comment.

- Remove double whitespace


Repository:
  rC Clang

https://reviews.llvm.org/D42298

Files:
  lib/Format/UnwrappedLineFormatter.cpp
  unittests/Format/FormatTest.cpp


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -588,6 +588,23 @@
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+  FormatStyle Style = getLLVMStyleWithColumns(60);
+  Style.AllowShortBlocksOnASingleLine = true;
+  Style.AllowShortIfStatementsOnASingleLine = true;
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  EXPECT_EQ("#define A  \\\n"
+"  if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+"  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
+"X;",
+format("#define A \\\n"
+   "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+   "  RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+   "   }\n"
+   "X;",
+   Style));
+}
+
 TEST_F(FormatTest, ParseIfElse) {
   verifyFormat("if (true)\n"
"  if (true)\n"
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -304,9 +304,15 @@
 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
 I != AnnotatedLines.begin() &&
 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
-  return Style.AllowShortBlocksOnASingleLine
- ? tryMergeSimpleBlock(I - 1, E, Limit)
- : 0;
+  unsigned MergedLines = 0;
+  if (Style.AllowShortBlocksOnASingleLine) {
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first merged line
+// since we are merging starting from I.
+if (MergedLines > 0)
+  --MergedLines;
+  }
+  return MergedLines;
 }
 // Try to merge a block with left brace wrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {


Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -588,6 +588,23 @@
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+  FormatStyle Style = getLLVMStyleWithColumns(60);
+  Style.AllowShortBlocksOnASingleLine = true;
+  Style.AllowShortIfStatementsOnASingleLine = true;
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  EXPECT_EQ("#define A  \\\n"
+"  if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+"  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
+"X;",
+format("#define A \\\n"
+   "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+   "  RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+   "   }\n"
+   "X;",
+   Style));
+}
+
 TEST_F(FormatTest, ParseIfElse) {
   verifyFormat("if (true)\n"
"  if (true)\n"
Index: lib/Format/UnwrappedLineFormatter.cpp
===
--- lib/Format/UnwrappedLineFormatter.cpp
+++ lib/Format/UnwrappedLineFormatter.cpp
@@ -304,9 +304,15 @@
 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
 I != AnnotatedLines.begin() &&
 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
-  return Style.AllowShortBlocksOnASingleLine
- ? tryMergeSimpleBlock(I - 1, E, Limit)
- : 0;
+  unsigned MergedLines = 0;
+  if (Style.AllowShortBlocksOnASingleLine) {
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first merged line
+// since we are merging starting from I.
+if (MergedLines > 0)
+  --MergedLines;
+  }
+  return MergedLines;
 }
 // Try to merge a block with left brace wrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42298: [clang-format] Fix shortening blocks in macros causing merged next line

2018-01-19 Thread Benjamin Kramer via Phabricator via cfe-commits
bkramer accepted this revision.
bkramer added a comment.
This revision is now accepted and ready to land.

lgtm




Comment at: lib/Format/UnwrappedLineFormatter.cpp:310
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first  merged line
+// since we are merging starting from I.

double space in comment


Repository:
  rC Clang

https://reviews.llvm.org/D42298



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


[PATCH] D42300: [Analyzer] Add PreStmt and PostStmt callbacks for OffsetOfExpr

2018-01-19 Thread Henry Wong via Phabricator via cfe-commits
MTC created this revision.
MTC added reviewers: NoQ, a.sidorin, dcoughlin.
Herald added subscribers: cfe-commits, szepet, xazax.hun.

PreStmt and PostStmt callbacks for OffsetOfExpr are necessary to implement 
`Cert ARR39-C: Do not add or subtract a scaled integer to a pointer`. And 
should I define the `offsetof` macro in 
`clang/test/Analysis/Inputs/system-header-simulator.h`? Or, like 
`clang/test/Analysis/malloc-sizeof.c`, use `#include `?


Repository:
  rC Clang

https://reviews.llvm.org/D42300

Files:
  lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  test/Analysis/offsetofexpr-callback.c


Index: test/Analysis/offsetofexpr-callback.c
===
--- /dev/null
+++ test/Analysis/offsetofexpr-callback.c
@@ -0,0 +1,15 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.AnalysisOrder 
-analyzer-config 
debug.AnalysisOrder:PreStmtOffsetOfExpr=true,debug.AnalysisOrder:PostStmtOffsetOfExpr=true
 %s 2>&1 | FileCheck %s
+
+#include 
+
+struct S {
+char c;
+double d;
+};
+
+void test() {
+  offsetof(struct S, c);
+}
+
+// CHECK: PreStmt
+// CHECK-NEXT: PostStmt
Index: lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1488,12 +1488,21 @@
   Bldr.addNodes(Dst);
   break;
 
-case Stmt::OffsetOfExprClass:
+case Stmt::OffsetOfExprClass: {
   Bldr.takeNodes(Pred);
-  VisitOffsetOfExpr(cast(S), Pred, Dst);
+  ExplodedNodeSet PreVisit;
+  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
+
+  ExplodedNodeSet PostVisit;
+  for (ExplodedNodeSet::iterator i = PreVisit.begin(), e = PreVisit.end();
+   i != e; ++i) {
+VisitOffsetOfExpr(cast(S), *i, PostVisit);
+  }
+
+  getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
   Bldr.addNodes(Dst);
   break;
-
+}
 case Stmt::UnaryExprOrTypeTraitExprClass:
   Bldr.takeNodes(Pred);
   VisitUnaryExprOrTypeTraitExpr(cast(S),
Index: lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
+++ lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
@@ -33,6 +33,8 @@
  check::PostStmt,
  check::PreStmt,
  check::PostStmt,
+ check::PreStmt,
+ check::PostStmt,
  check::PreCall,
  check::PostCall,
  check::NewAllocator,
@@ -89,6 +91,16 @@
   llvm::errs() << "PostStmt\n";
   }
 
+  void checkPreStmt(const OffsetOfExpr *OOE, CheckerContext &C) const {
+if (isCallbackEnabled(C, "PreStmtOffsetOfExpr"))
+  llvm::errs() << "PreStmt\n";
+  }
+
+  void checkPostStmt(const OffsetOfExpr *OOE, CheckerContext &C) const {
+if (isCallbackEnabled(C, "PostStmtOffsetOfExpr"))
+  llvm::errs() << "PostStmt\n";
+  }
+
   void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
 if (isCallbackEnabled(C, "PreCall")) {
   llvm::errs() << "PreCall";


Index: test/Analysis/offsetofexpr-callback.c
===
--- /dev/null
+++ test/Analysis/offsetofexpr-callback.c
@@ -0,0 +1,15 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.AnalysisOrder -analyzer-config debug.AnalysisOrder:PreStmtOffsetOfExpr=true,debug.AnalysisOrder:PostStmtOffsetOfExpr=true %s 2>&1 | FileCheck %s
+
+#include 
+
+struct S {
+char c;
+double d;
+};
+
+void test() {
+  offsetof(struct S, c);
+}
+
+// CHECK: PreStmt
+// CHECK-NEXT: PostStmt
Index: lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1488,12 +1488,21 @@
   Bldr.addNodes(Dst);
   break;
 
-case Stmt::OffsetOfExprClass:
+case Stmt::OffsetOfExprClass: {
   Bldr.takeNodes(Pred);
-  VisitOffsetOfExpr(cast(S), Pred, Dst);
+  ExplodedNodeSet PreVisit;
+  getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
+
+  ExplodedNodeSet PostVisit;
+  for (ExplodedNodeSet::iterator i = PreVisit.begin(), e = PreVisit.end();
+   i != e; ++i) {
+VisitOffsetOfExpr(cast(S), *i, PostVisit);
+  }
+
+  getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
   Bldr.addNodes(Dst);
   break;
-
+}
 case Stmt::UnaryExprOrTypeTraitExprClass:
   Bldr.takeNodes(Pred);
   VisitUnaryExprOrTypeTraitExpr(cast(S),
Index: lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/AnalysisOrderChecker.cpp
+++ l

[clang-tools-extra] r322949 - [clangd] Fix memcpy(?, null, 0) UB by switching to std::copy

2018-01-19 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Jan 19 07:03:49 2018
New Revision: 322949

URL: http://llvm.org/viewvc/llvm-project?rev=322949&view=rev
Log:
[clangd] Fix memcpy(?, null, 0) UB by switching to std::copy

Modified:
clang-tools-extra/trunk/clangd/FuzzyMatch.cpp

Modified: clang-tools-extra/trunk/clangd/FuzzyMatch.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FuzzyMatch.cpp?rev=322949&r1=322948&r2=322949&view=diff
==
--- clang-tools-extra/trunk/clangd/FuzzyMatch.cpp (original)
+++ clang-tools-extra/trunk/clangd/FuzzyMatch.cpp Fri Jan 19 07:03:49 2018
@@ -76,7 +76,7 @@ static constexpr int PerfectBonus = 3; /
 FuzzyMatcher::FuzzyMatcher(StringRef Pattern)
 : PatN(std::min(MaxPat, Pattern.size())), CaseSensitive(false),
   ScoreScale(PatN ? float{1} / (PerfectBonus * PatN) : 0), WordN(0) {
-  memcpy(Pat, Pattern.data(), PatN);
+  std::copy(Pattern.begin(), Pattern.begin() + PatN, Pat);
   for (int I = 0; I < PatN; ++I) {
 LowPat[I] = lower(Pat[I]);
 CaseSensitive |= LowPat[I] != Pat[I];
@@ -200,7 +200,7 @@ bool FuzzyMatcher::init(StringRef NewWor
   WordN = std::min(MaxWord, NewWord.size());
   if (PatN > WordN)
 return false;
-  memcpy(Word, NewWord.data(), WordN);
+  std::copy(NewWord.begin(), NewWord.begin() + WordN, Word);
   if (PatN == 0)
 return true;
   for (int I = 0; I < WordN; ++I)


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


[PATCH] D40481: [libclang] Fix cursors for arguments of Subscript and Call operators

2018-01-19 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik added a comment.

Ping!


https://reviews.llvm.org/D40481



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


r322950 - [CodeGenCXX] annotate a GEP to a derived class with 'inbounds' (PR35909)

2018-01-19 Thread Sanjay Patel via cfe-commits
Author: spatel
Date: Fri Jan 19 07:14:51 2018
New Revision: 322950

URL: http://llvm.org/viewvc/llvm-project?rev=322950&view=rev
Log:
[CodeGenCXX] annotate a GEP to a derived class with 'inbounds' (PR35909)

The standard says:
[expr.static.cast] p11: "If the prvalue of type “pointer to cv1 B” points to a 
B 
that is actually a subobject of an object of type D, the resulting pointer 
points 
to the enclosing object of type D. Otherwise, the behavior is undefined."

Therefore, the GEP must be inbounds.

This should solve the failure to optimize away a null check shown in PR35909:
https://bugs.llvm.org/show_bug.cgi?id=35909 

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

Added:
cfe/trunk/test/CodeGenCXX/derived-cast.cpp
Modified:
cfe/trunk/lib/CodeGen/CGClass.cpp
cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp

Modified: cfe/trunk/lib/CodeGen/CGClass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGClass.cpp?rev=322950&r1=322949&r2=322950&view=diff
==
--- cfe/trunk/lib/CodeGen/CGClass.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGClass.cpp Fri Jan 19 07:14:51 2018
@@ -406,8 +406,8 @@ CodeGenFunction::GetAddressOfDerivedClas
 
   // Apply the offset.
   llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
-  Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
-"sub.ptr");
+  Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
+"sub.ptr");
 
   // Just cast.
   Value = Builder.CreateBitCast(Value, DerivedPtrTy);

Modified: cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp?rev=322950&r1=322949&r2=322950&view=diff
==
--- cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp Fri Jan 19 07:14:51 2018
@@ -371,7 +371,7 @@ class C : public A, public B // align=16
 void downcast_pointer(B *b) {
   (void) static_cast(b);
   // Alignment check from EmitTypeCheck(TCK_DowncastPointer, ...)
-  // CHECK: [[SUB:%[.a-z0-9]*]] = getelementptr i8, i8* {{.*}}, i64 -16
+  // CHECK: [[SUB:%[.a-z0-9]*]] = getelementptr inbounds i8, i8* {{.*}}, i64 
-16
   // CHECK-NEXT: [[C:%.+]] = bitcast i8* [[SUB]] to %class.C*
   // null check goes here
   // CHECK: [[FROM_PHI:%.+]] = phi %class.C* [ [[C]], {{.*}} ], {{.*}}
@@ -388,7 +388,7 @@ void downcast_pointer(B *b) {
 void downcast_reference(B &b) {
   (void) static_cast(b);
   // Alignment check from EmitTypeCheck(TCK_DowncastReference, ...)
-  // CHECK:  [[SUB:%[.a-z0-9]*]] = getelementptr i8, i8* {{.*}}, i64 -16
+  // CHECK:  [[SUB:%[.a-z0-9]*]] = getelementptr inbounds i8, i8* {{.*}}, 
i64 -16
   // CHECK-NEXT: [[C:%.+]] = bitcast i8* [[SUB]] to %class.C*
   // Objectsize check goes here
   // CHECK:  [[C_INT:%.+]] = ptrtoint %class.C* [[C]] to i64

Added: cfe/trunk/test/CodeGenCXX/derived-cast.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/derived-cast.cpp?rev=322950&view=auto
==
--- cfe/trunk/test/CodeGenCXX/derived-cast.cpp (added)
+++ cfe/trunk/test/CodeGenCXX/derived-cast.cpp Fri Jan 19 07:14:51 2018
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm %s -o - | 
FileCheck %s
+
+class A {
+int a;
+};
+
+class B {
+int b;
+public:
+A *getAsA();
+};
+
+class X : public A, public B {
+int x;
+};
+
+// PR35909 - https://bugs.llvm.org/show_bug.cgi?id=35909
+
+A *B::getAsA() {
+  return static_cast(this);
+
+  // CHECK-LABEL: define %class.A* @_ZN1B6getAsAEv
+  // CHECK: %[[THIS:.*]] = load %class.B*, %class.B**
+  // CHECK-NEXT: %[[BC:.*]] = bitcast %class.B* %[[THIS]] to i8*
+  // CHECK-NEXT: getelementptr inbounds i8, i8* %[[BC]], i64 -4
+}
+


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


[PATCH] D42249: [CodeGenCXX] annotate a GEP to a derived class with 'inbounds' (PR35909)

2018-01-19 Thread Sanjay Patel via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL322950: [CodeGenCXX] annotate a GEP to a derived class with 
'inbounds' (PR35909) (authored by spatel, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42249?vs=130488&id=130616#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42249

Files:
  cfe/trunk/lib/CodeGen/CGClass.cpp
  cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
  cfe/trunk/test/CodeGenCXX/derived-cast.cpp


Index: cfe/trunk/test/CodeGenCXX/derived-cast.cpp
===
--- cfe/trunk/test/CodeGenCXX/derived-cast.cpp
+++ cfe/trunk/test/CodeGenCXX/derived-cast.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm %s -o - | 
FileCheck %s
+
+class A {
+int a;
+};
+
+class B {
+int b;
+public:
+A *getAsA();
+};
+
+class X : public A, public B {
+int x;
+};
+
+// PR35909 - https://bugs.llvm.org/show_bug.cgi?id=35909
+
+A *B::getAsA() {
+  return static_cast(this);
+
+  // CHECK-LABEL: define %class.A* @_ZN1B6getAsAEv
+  // CHECK: %[[THIS:.*]] = load %class.B*, %class.B**
+  // CHECK-NEXT: %[[BC:.*]] = bitcast %class.B* %[[THIS]] to i8*
+  // CHECK-NEXT: getelementptr inbounds i8, i8* %[[BC]], i64 -4
+}
+
Index: cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
===
--- cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
+++ cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
@@ -371,7 +371,7 @@
 void downcast_pointer(B *b) {
   (void) static_cast(b);
   // Alignment check from EmitTypeCheck(TCK_DowncastPointer, ...)
-  // CHECK: [[SUB:%[.a-z0-9]*]] = getelementptr i8, i8* {{.*}}, i64 -16
+  // CHECK: [[SUB:%[.a-z0-9]*]] = getelementptr inbounds i8, i8* {{.*}}, i64 
-16
   // CHECK-NEXT: [[C:%.+]] = bitcast i8* [[SUB]] to %class.C*
   // null check goes here
   // CHECK: [[FROM_PHI:%.+]] = phi %class.C* [ [[C]], {{.*}} ], {{.*}}
@@ -388,7 +388,7 @@
 void downcast_reference(B &b) {
   (void) static_cast(b);
   // Alignment check from EmitTypeCheck(TCK_DowncastReference, ...)
-  // CHECK:  [[SUB:%[.a-z0-9]*]] = getelementptr i8, i8* {{.*}}, i64 -16
+  // CHECK:  [[SUB:%[.a-z0-9]*]] = getelementptr inbounds i8, i8* {{.*}}, 
i64 -16
   // CHECK-NEXT: [[C:%.+]] = bitcast i8* [[SUB]] to %class.C*
   // Objectsize check goes here
   // CHECK:  [[C_INT:%.+]] = ptrtoint %class.C* [[C]] to i64
Index: cfe/trunk/lib/CodeGen/CGClass.cpp
===
--- cfe/trunk/lib/CodeGen/CGClass.cpp
+++ cfe/trunk/lib/CodeGen/CGClass.cpp
@@ -406,8 +406,8 @@
 
   // Apply the offset.
   llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
-  Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
-"sub.ptr");
+  Value = Builder.CreateInBoundsGEP(Value, Builder.CreateNeg(NonVirtualOffset),
+"sub.ptr");
 
   // Just cast.
   Value = Builder.CreateBitCast(Value, DerivedPtrTy);


Index: cfe/trunk/test/CodeGenCXX/derived-cast.cpp
===
--- cfe/trunk/test/CodeGenCXX/derived-cast.cpp
+++ cfe/trunk/test/CodeGenCXX/derived-cast.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s
+
+class A {
+int a;
+};
+
+class B {
+int b;
+public:
+A *getAsA();
+};
+
+class X : public A, public B {
+int x;
+};
+
+// PR35909 - https://bugs.llvm.org/show_bug.cgi?id=35909
+
+A *B::getAsA() {
+  return static_cast(this);
+
+  // CHECK-LABEL: define %class.A* @_ZN1B6getAsAEv
+  // CHECK: %[[THIS:.*]] = load %class.B*, %class.B**
+  // CHECK-NEXT: %[[BC:.*]] = bitcast %class.B* %[[THIS]] to i8*
+  // CHECK-NEXT: getelementptr inbounds i8, i8* %[[BC]], i64 -4
+}
+
Index: cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
===
--- cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
+++ cfe/trunk/test/CodeGenCXX/catch-undef-behavior.cpp
@@ -371,7 +371,7 @@
 void downcast_pointer(B *b) {
   (void) static_cast(b);
   // Alignment check from EmitTypeCheck(TCK_DowncastPointer, ...)
-  // CHECK: [[SUB:%[.a-z0-9]*]] = getelementptr i8, i8* {{.*}}, i64 -16
+  // CHECK: [[SUB:%[.a-z0-9]*]] = getelementptr inbounds i8, i8* {{.*}}, i64 -16
   // CHECK-NEXT: [[C:%.+]] = bitcast i8* [[SUB]] to %class.C*
   // null check goes here
   // CHECK: [[FROM_PHI:%.+]] = phi %class.C* [ [[C]], {{.*}} ], {{.*}}
@@ -388,7 +388,7 @@
 void downcast_reference(B &b) {
   (void) static_cast(b);
   // Alignment check from EmitTypeCheck(TCK_DowncastReference, ...)
-  // CHECK:  [[SUB:%[.a-z0-9]*]] = getelementptr i8, i8* {{.*}}, i64 -16
+  // CHECK:  [[SUB:%[.a-z0-9]*]] = getelementptr inbounds i8, i8* {{.*}}, i64 -16
   // CHECK-NEXT: [[C:%.+]] = bitcast i

[PATCH] D42099: [libclang] Add missing CINDEX_LINKAGE

2018-01-19 Thread Nikolai Kosjar via Phabricator via cfe-commits
nik added a comment.

Hmm, nothing changed. So how to get rid of this correctly. Is "Abandon 
Revision" the right thing to do?


Repository:
  rC Clang

https://reviews.llvm.org/D42099



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


[PATCH] D42300: [Analyzer] Add PreStmt and PostStmt callbacks for OffsetOfExpr

2018-01-19 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

Hello Henry,

The patch looks reasonable. I think it can be landed after comments are 
resolved.




Comment at: lib/StaticAnalyzer/Core/ExprEngine.cpp:1497
+  ExplodedNodeSet PostVisit;
+  for (ExplodedNodeSet::iterator i = PreVisit.begin(), e = PreVisit.end();
+   i != e; ++i) {

Could you C++11-fy this loop?



Comment at: test/Analysis/offsetofexpr-callback.c:3
+
+#include 
+

Answering your question, we should put the declaration into 
system-header-simulator.h.



Comment at: test/Analysis/offsetofexpr-callback.c:7
+char c;
+double d;
+};

This decl seems unused. Should we remove it?


Repository:
  rC Clang

https://reviews.llvm.org/D42300



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


[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 130618.
hokein marked 4 inline comments as done.
hokein added a comment.

- Rebase the patch to latest
- Update the patch based on the offline discussion

Updating D42073: [clangd] Query all visible scopes based on all visible 
using-namespace declarations


and containing namespace for global qualified code completion.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42073

Files:
  clangd/CodeComplete.cpp
  unittests/clangd/CodeCompleteTests.cpp

Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -58,6 +58,7 @@
 using ::testing::ElementsAre;
 using ::testing::Not;
 using ::testing::UnorderedElementsAre;
+using ::testing::Field;
 
 class IgnoreDiagnostics : public DiagnosticsConsumer {
   void
@@ -676,6 +677,123 @@
   EXPECT_EQ(1, Results.activeParameter);
 }
 
+class IndexRequestCollector : public SymbolIndex {
+public:
+  bool
+  fuzzyFind(const Context &Ctx, const FuzzyFindRequest &Req,
+llvm::function_ref Callback) const override {
+Requests.push_back(Req);
+return false;
+  }
+
+  const std::vector allRequests() const { return Requests; }
+
+private:
+  mutable std::vector Requests;
+};
+
+TEST(CompletionTest, UnqualifiedIdQuery) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+
+  auto Results = completions(R"cpp(
+ namespace std {}
+ using namespace std;
+ namespace ns {
+ void f() {
+   vec^
+ }
+ }
+  )cpp", {}, Opts);
+
+  EXPECT_THAT(Requests.allRequests(),
+  ElementsAre(Field(&FuzzyFindRequest::Scopes,
+UnorderedElementsAre("", "ns", "std";
+}
+
+TEST(CompletionTest, ResolvedQualifiedIdQuery) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+
+  auto Results = completions(R"cpp(
+ namespace ns1 {}
+ namespace ns2 {} // ignore
+ namespace ns3 { namespace nns3 {} }
+ namespace foo {
+ using namespace ns1;
+ using namespace ns3::nns3;
+ }
+ namespace ns {
+ void f() {
+   foo::^
+ }
+ }
+  )cpp", {}, Opts);
+
+  EXPECT_THAT(
+  Requests.allRequests(),
+  ElementsAre(Field(&FuzzyFindRequest::Scopes,
+UnorderedElementsAre("foo", "ns1", "ns3::nns3";
+}
+
+TEST(CompletionTest, UnresolvedQualifierIdQuery) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+
+  auto Results = completions(R"cpp(
+  namespace a {}
+  using namespace a;
+  namespace ns {
+  void f() {
+  bar::^
+  }
+  } // namespace ns
+  )cpp", {}, Opts);
+
+  EXPECT_THAT(Requests.allRequests(),
+  ElementsAre(Field(&FuzzyFindRequest::Scopes,
+UnorderedElementsAre("bar";
+}
+
+TEST(CompletionTest, EmptyQualifiedQuery) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+
+  auto Results = completions(R"cpp(
+  namespace ns {
+  void f() {
+  ^
+  }
+  } // namespace ns
+  )cpp", {}, Opts);
+
+  EXPECT_THAT(Requests.allRequests(),
+  ElementsAre(Field(&FuzzyFindRequest::Scopes,
+UnorderedElementsAre("", "ns";
+}
+
+TEST(CompletionTest, GlobalQualifiedQuery) {
+  clangd::CodeCompleteOptions Opts;
+  IndexRequestCollector Requests;
+  Opts.Index = &Requests;
+
+  auto Results = completions(R"cpp(
+  namespace ns {
+  void f() {
+  ::^
+  }
+  } // namespace ns
+  )cpp", {}, Opts);
+
+  EXPECT_THAT(
+  Requests.allRequests(),
+  ElementsAre(Field(&FuzzyFindRequest::Scopes, UnorderedElementsAre("";
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -309,20 +309,52 @@
   llvm_unreachable("unknown CodeCompletionResult kind");
 }
 
-/// \brief Information about the scope specifier in the qualified-id code
-/// completion (e.g. "ns::ab?").
-struct SpecifiedScope {
-  /// The scope specifier as written. For example, for completion "ns::ab?", the
-  /// written scope specifier is "ns".
-  std::string Written;
-  // If this scope specifier is recognized in Sema (e.g. as a namespace
-  // context), this will be set to the fully qualfied name of the corresponding
-  // context.
-  std::string Resolved;
-
-  llvm::StringRef forIndex() {
-llvm::StringRef Chosen = Resolved.empty() ? Written : Resolved;
-return Chosen.trim(':');
+StringRef normalizeScope(StringRef Q) {
+  return Q.trim(':');
+}
+
+/// \brief Scopes being queried in indexes for the qualified-id code completion
+/// (e.g. "ns::a

[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-19 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clangd/CodeComplete.cpp:270
+  /// namespace scopes which are visible to the qualified-id completion token.
+  std::vector Scopes;
+};

ilya-biryukov wrote:
> sammccall wrote:
> > ilya-biryukov wrote:
> > > sammccall wrote:
> > > > Just to check, if the user types:
> > > > "vec" --> None
> > > > "::vec" --> {""}
> > > > "std::vec" --> {"std"}
> > > > "using namespace std; vec" --> None
> > > > "using namespace std; ::vec" --> {"", "std"}
> > > > 
> > > > is this right?
> > > I think the idea was to have (I only highlight the differences):
> > > "vec" --> {""}
> > > "using namespace std; vec" --> {"", "std"}
> > > 
> > > @hokein , or am I getting it wrong?
> > You're probably right, just want to be sure we're talking about the same 
> > thing.
> > 
> > There's two layers here: the context detected from sema, and what we're 
> > going to send the index. The layering is more relevant now that more of 
> > this moves out of clangd.
> > 
> > for "vec", we should be sending {""} to the index for now, and later move 
> > towards doing global completion.
> > But if possible the detection code should report None, and the query-index 
> > code should translate it - there's no reason the detection code needs to be 
> > wrong just because clangd can't do qualifier insertion/smart ranking/etc.
> > 
> > That said, per our discussion this morning, the detected state shouldn't 
> > really be Optional>, but rather struct { vector 
> > AccessibleScope, optional UnresolvedQualifier } or something like 
> > that...
> - Totally agree, this patch only fills the `vector AccessibleScope` 
> field, and `optional UnresolvedQualifier` could be added in the 
> follow-up patch when it's actually handled.
> - It still makes sense to have `optional` to distinguish cases 
> when clang did not run the lookup during completion and the scopes were not 
> set (i.e. completion inside macros, etc.)
@ilya-biryukov your are right. 

Based on our discussion last morning, the accessible scopes:

  //   qualified completion
  //   "::vec" => {"::"}
  //   "using namespace std; ::vec^" => {"::", "std"}
  //   "namespace ns {using namespace std;} ns::^" => {"ns", "std"}
  //   "std::vec^" => {"::"}  // unresolved "std::"
  //
  //   unqualified completion
  //   "vec^" => {"::"}
  //   "using namespace std; vec^" => {"::", "std"}
  //   "using namespace std; namespace ns { vec^ }" => {"ns", "std", "::"}


With rL322945, now it is sensible to include all (qualified/unqualified 
completion) in this patch.



Comment at: clangd/CodeComplete.cpp:658
+VisibleNamespaceFinder Finder;
+S.LookupVisibleDecls(QCC.ClosestScope,
+ clang::Sema::LookupNameKind::LookupOrdinaryName,

sammccall wrote:
> you need to set loadexternal to false to avoid deserializing the whole 
> preamble.
> Ilya says this is going to get merged with lookup during code-completion, 
> which would be nice :-)
not needed now as we don't do lookup manually in clangd.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42073



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


[PATCH] D41946: [clangd] Add support for different file URI schemas.

2018-01-19 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 130621.
ioeric marked 14 inline comments as done.
ioeric added a comment.

- Address review comments


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41946

Files:
  clangd/CMakeLists.txt
  clangd/URI.cpp
  clangd/URI.h
  unittests/clangd/CMakeLists.txt
  unittests/clangd/URITests.cpp

Index: unittests/clangd/URITests.cpp
===
--- /dev/null
+++ unittests/clangd/URITests.cpp
@@ -0,0 +1,176 @@
+//===-- URITests.cpp  -*- C++ -*---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "URI.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+using ::testing::AllOf;
+
+MATCHER_P(Scheme, S, "") { return arg.scheme() == S; }
+MATCHER_P(Authority, A, "") { return arg.authority() == A; }
+MATCHER_P(Body, B, "") { return arg.body() == B; }
+
+std::string decodeOrDie(llvm::StringRef S) {
+  auto D = percentDecode(S);
+  if (!D)
+llvm_unreachable(llvm::toString(D.takeError()).c_str());
+  return *D;
+}
+
+TEST(PercentEncodingTest, Encode) {
+  EXPECT_EQ(percentEncode("a/b/c"), "a/b/c");
+  EXPECT_EQ(percentEncode("a!b;c~"), "a%21b%3bc~");
+}
+
+TEST(PercentEncodingTest, Decode) {
+  EXPECT_EQ(decodeOrDie("a/b/c"), "a/b/c");
+  EXPECT_EQ(decodeOrDie("a%21b%3ac~"), "a!b:c~");
+}
+
+// Assume all files in the schema have a "test-root/" root directory, and the
+// schema path is the relative path to the root directory.
+// So the schema of "/some-dir/test-root/x/y/z" is "test:x/y/z".
+class TestScheme : public URIScheme {
+public:
+  static const char *Scheme;
+
+  static const char *TestRoot;
+
+  llvm::Expected
+  getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
+  llvm::StringRef HintPath) const override {
+auto Pos = HintPath.find(TestRoot);
+assert(Pos != llvm::StringRef::npos);
+return (HintPath.substr(0, Pos + llvm::StringRef(TestRoot).size()) + Body)
+.str();
+  }
+
+  llvm::Expected
+  uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
+auto Pos = AbsolutePath.find(TestRoot);
+assert(Pos != llvm::StringRef::npos);
+return (llvm::Twine(Scheme) + ":" +
+AbsolutePath.substr(Pos + Pos + llvm::StringRef(TestRoot).size()))
+.str();
+  }
+};
+
+const char *TestScheme::Scheme = "test";
+const char *TestScheme::TestRoot = "/test-root/";
+
+static URISchemeRegistry::Add X(TestScheme::Scheme, "Test schema");
+
+std::string createOrDie(llvm::StringRef AbsolutePath,
+llvm::StringRef Scheme = "file") {
+  auto Uri = FileURI::create(AbsolutePath, Scheme);
+  if (!Uri)
+llvm_unreachable(llvm::toString(Uri.takeError()).c_str());
+  return *Uri;
+}
+
+FileURI parseOrDie(llvm::StringRef Uri) {
+  auto U = FileURI::parse(Uri);
+  if (!U)
+llvm_unreachable(llvm::toString(U.takeError()).c_str());
+  return *U;
+}
+
+std::string resolveOrDie(const FileURI &U, llvm::StringRef HintPath = "") {
+  auto Path = FileURI::resolve(U, HintPath);
+  if (!Path)
+llvm_unreachable(llvm::toString(Path.takeError()).c_str());
+  return *Path;
+}
+
+TEST(URITest, Create) {
+  EXPECT_THAT(createOrDie("/x/y/z"), "file:///x/y/z");
+  EXPECT_THAT(createOrDie("/(x)/y/\\ z"), "file:///%28x%29/y/%5c%20z");
+}
+
+TEST(URITest, FailedCreate) {
+  auto Uri = FileURI::create("/x/y/z", "no");
+  EXPECT_FALSE(static_cast(Uri));
+  llvm::consumeError(Uri.takeError());
+
+  // Path has to be absolute.
+  Uri = FileURI::create("x/y/z");
+  EXPECT_FALSE(static_cast(Uri));
+  llvm::consumeError(Uri.takeError());
+}
+
+TEST(URITest, Parse) {
+  EXPECT_THAT(parseOrDie("file://auth/x/y/z"),
+  AllOf(Scheme("file"), Authority("auth"), Body("/x/y/z")));
+
+  EXPECT_THAT(parseOrDie("file://au%3dth/%28x%29/y/%5c%20z"),
+  AllOf(Scheme("file"), Authority("au=th"), Body("/(x)/y/\\ z")));
+
+  EXPECT_THAT(parseOrDie("file:///%28x%29/y/%5c%20z"),
+  AllOf(Scheme("file"), Authority(""), Body("/(x)/y/\\ z")));
+  EXPECT_THAT(parseOrDie("file:///x/y/z"),
+  AllOf(Scheme("file"), Authority(""), Body("/x/y/z")));
+}
+
+TEST(URITest, ParseFailed) {
+  auto FailedParse = [](llvm::StringRef U) {
+auto URI = FileURI::parse(U);
+if (!URI) {
+  llvm::consumeError(URI.takeError());
+  return true;
+}
+return false;
+  };
+
+  // Expect ':' in URI.
+  EXPECT_TRUE(FailedParse("file//x/y/z"));
+  // Expect two bytes after %.
+  EXPECT_TRUE(FailedParse("file:///x/y/z%2"));
+  // Empty.
+  EXPECT_TRUE(FailedParse(""));
+  EXPECT_TRUE(FailedParse(":/a/b/c"));
+  EXPECT_TRUE(FailedParse("s:"));
+  // Incomplete.
+  EXPECT_TRUE(FailedParse("x:"));
+  

[PATCH] D41946: [clangd] Add support for different file URI schemas.

2018-01-19 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clangd/URI.cpp:43
+  Body.consume_front("/");
+return llvm::sys::path::convert_to_slash(Body);
+  }

sammccall wrote:
> Don't you want the opposite here, convert from unix to native?
Ah, right!



Comment at: clangd/URI.cpp:57
+  Body = "/";
+Body += path::convert_to_slash(AbsolutePath, path::Style::posix);
+return (llvm::Twine(Scheme) + ":" + percentEncode(Body)).str();

sammccall wrote:
> conversely, here you want native (which is the default)
Don't we still need to convert \ to / on windows?



Comment at: clangd/URI.h:29
+  llvm::StringRef scheme() const { return Scheme; }
+  /// \brief Returns decoded authority.
+  llvm::StringRef authority() const { return Authority; }

sammccall wrote:
> e.g. "//reviews.llvm.org"
I think authority doesn't include leading "//"? 



Comment at: clangd/URI.h:76
+  /// \brief Returns the absolute path of the file corresponding to the URI 
body
+  /// in the file system. \p CurrentFile is the file from which the request is
+  /// issued. This is needed because the same URI in different workspace may

sammccall wrote:
> I think "the file from which the request is issued" is overly-specified (and 
> a little unclear).
> 
> For instance, consider this workflow:
>  vim $projectroot
>  go to symbol -> "MyClass" (from global index)
> Now we're trying to navigate to "monorepo://proj/myclass.h", but we don't 
> have a "current file" to use as a hint. $projectroot would probably do 
> nicely, and is available to clangd.
> 
> So maybe `llvm::StringRef HintPath`- "A related path, such as the current 
> file or working directory, which can help disambiguate when the same file 
> exists in many workspaces".
Makes sense. Thanks for the suggestion!



Comment at: clangd/URI.h:90
+/// - All other characters are escaped.
+std::string percentEncode(llvm::StringRef Content);
+

sammccall wrote:
> this seems easy enough to test via uri::create rather than exposing it 
> publicly, but up to you.
I think this would also be useful for other scheme extensions. 


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41946



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


[PATCH] D41946: [clangd] Add support for different file URI schemas.

2018-01-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clangd/URI.cpp:94
+
+std::vector createEncodeMap() {
+  std::vector Result(128, "");

Performance doesn't really matter here, but it looks like this is intended to 
save time by precomputing, and I don't think it's any faster than the direct 
version of `percentEncode` which might be easier to read:

  for (unsigned char C : Content)
if (shouldEscape(C))
  OS << '%' << format_hex_no_prefix(C, 2);
else
  OS << C;

where shouldEscape just does some range checks.
(the "unsigned" is important!)



Comment at: clangd/URI.cpp:95
+std::vector createEncodeMap() {
+  std::vector Result(128, "");
+  for (char C : Unreserved)

128 should be 256, right?



Comment at: clangd/URI.cpp:123
+}
+if (I + 1 == E || I + 2 == E)
+  return make_string_error("Expect two characters after '%' sign: 
Content");

most implementations seem to just treat treat the % as literal in this case, 
e.g. "%41%" -> "A%", which makes this function unable to fail, which simplifies 
`parse()` a bit



Comment at: clangd/URI.cpp:125
+  return make_string_error("Expect two characters after '%' sign: 
Content");
+char Buf[3];
+Buf[0] = *(++I);

alternatively, using more llvm and less std:

  if (*I == '%' && I + 2 < Content.end()
&& isHexDigit(*(I+1)) && isHexDigit(*(I+2)) {
Result.push_back(hexFromNibbles(*(I+1), *(I+2)));
I += 2;
  } else
Result.push_back(*I);
  



Comment at: clangd/URI.cpp:136
+  FileURI U;
+  llvm::StringRef OrigUri = Uri;
+

nit: i'd probably prefer to keep "uri" referring to the whole URI, and call the 
one you mutate something else



Comment at: clangd/URI.cpp:138
+
+  auto Pos = Uri.find(':');
+  if (Pos == llvm::StringRef::npos)

consider StringRef::split which avoids some index arithmetic:

  pair SchemeSplit = Uri.split(':');
  if (SchemeSplit.second == "")
return error
  U.Scheme = percentDecode(SchemeSplit.first);
  // then SchemeSplit.second contains the rest



Comment at: clangd/URI.cpp:149
+Pos = Uri.find('/');
+if (Pos == llvm::StringRef::npos)
+  return make_string_error("Expect '/' after a URI authority: " + OrigUri);

this is e.g. `http://llvm.org`
This is valid: scheme = 'http', authority = 'llvm.org', path = ''.
(Wikipedia is wrong, but the RFC covers this)



Comment at: clangd/URI.cpp:155
+  return Decoded.takeError();
+if (Decoded->empty())
+  return make_string_error(

this is e.g. `file:///foo/bar`, which is definitely valid!
scheme = 'file', authority = '', path = '/foo/bar'

(we should have a test for this one!)



Comment at: clangd/URI.cpp:168
+  if (U.Scheme.empty() || U.Body.empty())
+return make_string_error("Scheme and body must be provided in URI: " +
+ OrigUri);

body may be empty. (`http://llvm.org` again)



Comment at: unittests/clangd/URITests.cpp:115
+
+TEST(URITest, Parse) {
+  EXPECT_THAT(parseOrDie("file://auth//x/y/z"),

please include some typical examples:

"file:///etc/passwd"
"file:///c:/windows/system32/"
"http://llvm.org";
"urn:isbn:0451450523"



Comment at: unittests/clangd/URITests.cpp:117
+  EXPECT_THAT(parseOrDie("file://auth//x/y/z"),
+  AllOf(Scheme("file"), Authority("auth"), Body("/x/y/z")));
+

the body should be "//x/y/z" here - the / that terminates the authority is part 
of the path.
(This is a valid URI, but not a typical example)



Comment at: unittests/clangd/URITests.cpp:143
+  EXPECT_TRUE(FailedParse(":/a/b/c"));
+  EXPECT_TRUE(FailedParse("s:"));
+  // Incomplete.

this is the same as the next one



Comment at: unittests/clangd/URITests.cpp:144
+  EXPECT_TRUE(FailedParse("s:"));
+  // Incomplete.
+  EXPECT_TRUE(FailedParse("x:"));

these are both valid



Comment at: unittests/clangd/URITests.cpp:148
+  // Empty authority.
+  EXPECT_TRUE(FailedParse("file:x/y/z"));
+}

this is valid, authority may be empty


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41946



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


r322954 - [clang-format] Fix shortening blocks in macros causing merged next line

2018-01-19 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Fri Jan 19 08:12:37 2018
New Revision: 322954

URL: http://llvm.org/viewvc/llvm-project?rev=322954&view=rev
Log:
[clang-format] Fix shortening blocks in macros causing merged next line

Summary:
This patch addresses bug 36002, where a combination of options causes the line
following a short block in macro to be merged with that macro.

Reviewers: bkramer

Reviewed By: bkramer

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp?rev=322954&r1=322953&r2=322954&view=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp Fri Jan 19 08:12:37 2018
@@ -304,9 +304,15 @@ private:
 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
 I != AnnotatedLines.begin() &&
 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
-  return Style.AllowShortBlocksOnASingleLine
- ? tryMergeSimpleBlock(I - 1, E, Limit)
- : 0;
+  unsigned MergedLines = 0;
+  if (Style.AllowShortBlocksOnASingleLine) {
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first merged line
+// since we are merging starting from I.
+if (MergedLines > 0)
+  --MergedLines;
+  }
+  return MergedLines;
 }
 // Try to merge a block with left brace wrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=322954&r1=322953&r2=322954&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Fri Jan 19 08:12:37 2018
@@ -588,6 +588,23 @@ TEST_F(FormatTest, FormatShortBracedStat
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+  FormatStyle Style = getLLVMStyleWithColumns(60);
+  Style.AllowShortBlocksOnASingleLine = true;
+  Style.AllowShortIfStatementsOnASingleLine = true;
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  EXPECT_EQ("#define A  \\\n"
+"  if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+"  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
+"X;",
+format("#define A \\\n"
+   "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+   "  RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+   "   }\n"
+   "X;",
+   Style));
+}
+
 TEST_F(FormatTest, ParseIfElse) {
   verifyFormat("if (true)\n"
"  if (true)\n"


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


[PATCH] D42298: [clang-format] Fix shortening blocks in macros causing merged next line

2018-01-19 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL322954: [clang-format] Fix shortening blocks in macros 
causing merged next line (authored by krasimir, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42298

Files:
  cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
  cfe/trunk/unittests/Format/FormatTest.cpp


Index: cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
===
--- cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
+++ cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
@@ -304,9 +304,15 @@
 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
 I != AnnotatedLines.begin() &&
 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
-  return Style.AllowShortBlocksOnASingleLine
- ? tryMergeSimpleBlock(I - 1, E, Limit)
- : 0;
+  unsigned MergedLines = 0;
+  if (Style.AllowShortBlocksOnASingleLine) {
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first merged line
+// since we are merging starting from I.
+if (MergedLines > 0)
+  --MergedLines;
+  }
+  return MergedLines;
 }
 // Try to merge a block with left brace wrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -588,6 +588,23 @@
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+  FormatStyle Style = getLLVMStyleWithColumns(60);
+  Style.AllowShortBlocksOnASingleLine = true;
+  Style.AllowShortIfStatementsOnASingleLine = true;
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  EXPECT_EQ("#define A  \\\n"
+"  if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+"  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
+"X;",
+format("#define A \\\n"
+   "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+   "  RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+   "   }\n"
+   "X;",
+   Style));
+}
+
 TEST_F(FormatTest, ParseIfElse) {
   verifyFormat("if (true)\n"
"  if (true)\n"


Index: cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
===
--- cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
+++ cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
@@ -304,9 +304,15 @@
 if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
 I != AnnotatedLines.begin() &&
 I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
-  return Style.AllowShortBlocksOnASingleLine
- ? tryMergeSimpleBlock(I - 1, E, Limit)
- : 0;
+  unsigned MergedLines = 0;
+  if (Style.AllowShortBlocksOnASingleLine) {
+MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
+// If we managed to merge the block, discard the first merged line
+// since we are merging starting from I.
+if (MergedLines > 0)
+  --MergedLines;
+  }
+  return MergedLines;
 }
 // Try to merge a block with left brace wrapped that wasn't yet covered
 if (TheLine->Last->is(tok::l_brace)) {
Index: cfe/trunk/unittests/Format/FormatTest.cpp
===
--- cfe/trunk/unittests/Format/FormatTest.cpp
+++ cfe/trunk/unittests/Format/FormatTest.cpp
@@ -588,6 +588,23 @@
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
+  FormatStyle Style = getLLVMStyleWithColumns(60);
+  Style.AllowShortBlocksOnASingleLine = true;
+  Style.AllowShortIfStatementsOnASingleLine = true;
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  EXPECT_EQ("#define A  \\\n"
+"  if (HANDLEwernufrnuLwrmviferuvnierv) \\\n"
+"  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
+"X;",
+format("#define A \\\n"
+   "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
+   "  RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
+   "   }\n"
+   "X;",
+   Style));
+}
+
 TEST_F(FormatTest, ParseIfElse) {
   verifyFormat("if (true)\n"
"  if (true)\n"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mai

[PATCH] D42301: [ASTImporter] Support LambdaExprs and improve template support

2018-01-19 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin created this revision.
a.sidorin added reviewers: xazax.hun, szepet, jingham.
a.sidorin added a project: clang.
Herald added subscribers: rnkovacs, kristof.beyls, aemerson.

Also, a number of style and bug fixes was done:

- ASTImporterTest: added sanity check for source node
- ExternalASTMerger: better lookup for template specializations
- ASTImporter: don't add templated declarations into DeclContext
- ASTImporter: introduce a helper, ImportTemplateArgumentListInfo getting 
SourceLocations
- ASTImporter: proper set ParmVarDecls for imported FunctionProtoTypeLoc


Repository:
  rC Clang

https://reviews.llvm.org/D42301

Files:
  lib/AST/ASTImporter.cpp
  lib/AST/ASTStructuralEquivalence.cpp
  lib/AST/ExternalASTMerger.cpp
  test/ASTMerge/class-template/Inputs/class-template1.cpp
  test/ASTMerge/class-template/Inputs/class-template2.cpp
  test/ASTMerge/class-template/test.cpp
  test/ASTMerge/exprs-cpp/Inputs/exprs3.cpp
  test/ASTMerge/exprs-cpp/test.cpp
  test/ASTMerge/function-cpp/Inputs/function-1.cpp
  test/ASTMerge/function-cpp/test.cpp
  test/Import/template-specialization/Inputs/T.cpp
  test/Import/template-specialization/test.cpp
  unittests/AST/ASTImporterTest.cpp

Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -11,9 +11,9 @@
 //
 //===--===//
 
+#include "MatchVerifier.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ASTImporter.h"
-#include "MatchVerifier.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Tooling/Tooling.h"
@@ -99,7 +99,11 @@
   if (FoundDecls.size() != 1)
 return testing::AssertionFailure() << "Multiple declarations were found!";
 
-  auto Imported = Importer.Import(*FoundDecls.begin());
+  // Sanity check: the node being imported should match in the same way as
+  // the result node.
+  EXPECT_TRUE(Verifier.match(FoundDecls.front(), AMatcher));
+
+  auto Imported = Importer.Import(FoundDecls.front());
   if (!Imported)
 return testing::AssertionFailure() << "Import failed, nullptr returned!";
 
@@ -624,7 +628,7 @@
 TEST(ImportDecl, ImportUsingDecl) {
   MatchVerifier Verifier;
   testImport("namespace foo { int bar; }"
- "int declToImport(){ using foo::bar; }",
+ "void declToImport() { using foo::bar; }",
  Lang_CXX, "", Lang_CXX, Verifier,
  functionDecl(
has(
@@ -665,22 +669,22 @@
  "}"
  "void instantiate() { declToImport(); }",
  Lang_CXX, "", Lang_CXX, Verifier,
- functionTemplateDecl(has(functionDecl(has(
- compoundStmt(has(unresolvedLookupExpr(;
+ functionTemplateDecl(has(functionDecl(
+ has(compoundStmt(has(unresolvedLookupExpr(;
 }
 
 TEST(ImportExpr, ImportCXXUnresolvedConstructExpr) {
   MatchVerifier Verifier;
-  testImport("template  class C { T t; };"
+  testImport("template  struct C { T t; };"
  "template  void declToImport() {"
  "  C d;"
  "  d.t = T();"
  "}"
  "void instantiate() { declToImport(); }",
  Lang_CXX, "", Lang_CXX, Verifier,
  functionTemplateDecl(has(functionDecl(has(compoundStmt(has(
  binaryOperator(has(cxxUnresolvedConstructExpr());
-  testImport("template  class C { T t; };"
+  testImport("template  struct C { T t; };"
  "template  void declToImport() {"
  "  C d;"
  "  (&d)->t = T();"
@@ -691,5 +695,22 @@
  binaryOperator(has(cxxUnresolvedConstructExpr());
 }
 
+/// Check that function "declToImport()" (which is the templated function
+/// for corresponding FunctionTemplateDecl) is not added into DeclContext.
+/// Same for class template declarations.
+TEST(ImportDecl, ImportTemplatedDeclForTemplate) {
+  MatchVerifier Verifier;
+  testImport("template  void declToImport() { T a = 1; }"
+ "void instantiate() { declToImport(); }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ functionTemplateDecl(hasAncestor(translationUnitDecl(
+ unless(has(functionDecl(hasName("declToImport";
+  testImport("template  struct declToImport { T t; };"
+ "void instantiate() { declToImport(); }",
+ Lang_CXX, "", Lang_CXX, Verifier,
+ classTemplateDecl(hasAncestor(translationUnitDecl(
+ unless(has(cxxRecordDecl(hasName("declToImport";
+}
+
 } // end namespace ast_matchers
 } // end namespace clang
Index: test/Import/template-specialization/test.cpp
===
--- test/Import/template-specialization/test.cpp
+++ test/Import/template-specialization/test.cpp
@@ -1,7 +1,10 @@

[PATCH] D41535: Add -vfsoverlay option for Clang-Tidy

2018-01-19 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

This looks good, but we should add a test.
Should've noticed that before, sorry for the slowing this down a bit more. 
After the test is there, I'm happy to commit this change for you.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41535



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


r322956 - [clang-format] Adds a canonical delimiter to raw string formatting

2018-01-19 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Fri Jan 19 08:18:47 2018
New Revision: 322956

URL: http://llvm.org/viewvc/llvm-project?rev=322956&view=rev
Log:
[clang-format] Adds a canonical delimiter to raw string formatting

Summary:
This patch adds canonical delimiter support to the raw string formatting.
This allows matching delimiters to be updated to the canonical one.

Reviewers: bkramer

Reviewed By: bkramer

Subscribers: klimek, cfe-commits

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

Modified:
cfe/trunk/docs/ClangFormatStyleOptions.rst
cfe/trunk/include/clang/Format/Format.h
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTest.cpp
cfe/trunk/unittests/Format/FormatTestRawStrings.cpp

Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=322956&r1=322955&r2=322956&view=diff
==
--- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
+++ cfe/trunk/docs/ClangFormatStyleOptions.rst Fri Jan 19 08:18:47 2018
@@ -1590,6 +1590,9 @@ the configuration (without a prefix: ``A
   precedence over a matching enclosing function name for determining the
   language of the raw string contents.
 
+  If a canonical delimiter is specified, occurences of other delimiters for
+  the same language will be updated to the canonical if possible.
+
   There should be at most one specification per language and each delimiter
   and enclosing function should not occur in multiple specifications.
 
@@ -1610,6 +1613,7 @@ the configuration (without a prefix: ``A
 - 'cc'
 - 'cpp'
   BasedOnStyle: llvm
+  CanonicalDelimiter: 'cc'
 
 **ReflowComments** (``bool``)
   If ``true``, clang-format will attempt to re-flow comments.

Modified: cfe/trunk/include/clang/Format/Format.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=322956&r1=322955&r2=322956&view=diff
==
--- cfe/trunk/include/clang/Format/Format.h (original)
+++ cfe/trunk/include/clang/Format/Format.h Fri Jan 19 08:18:47 2018
@@ -1369,6 +1369,8 @@ struct FormatStyle {
 std::vector Delimiters;
 /// \brief A list of enclosing function names that match this language.
 std::vector EnclosingFunctions;
+/// \brief The canonical delimiter for this language.
+std::string CanonicalDelimiter;
 /// \brief The style name on which this raw string format is based on.
 /// If not specified, the raw string format is based on the style that this
 /// format is based on.
@@ -1376,6 +1378,7 @@ struct FormatStyle {
 bool operator==(const RawStringFormat &Other) const {
   return Language == Other.Language && Delimiters == Other.Delimiters &&
  EnclosingFunctions == Other.EnclosingFunctions &&
+ CanonicalDelimiter == Other.CanonicalDelimiter &&
  BasedOnStyle == Other.BasedOnStyle;
 }
   };
@@ -1392,6 +1395,9 @@ struct FormatStyle {
   /// precedence over a matching enclosing function name for determining the
   /// language of the raw string contents.
   ///
+  /// If a canonical delimiter is specified, occurences of other delimiters for
+  /// the same language will be updated to the canonical if possible.
+  ///
   /// There should be at most one specification per language and each delimiter
   /// and enclosing function should not occur in multiple specifications.
   ///
@@ -1410,6 +1416,7 @@ struct FormatStyle {
   ///   - 'cc'
   ///   - 'cpp'
   /// BasedOnStyle: llvm
+  /// CanonicalDelimiter: 'cc'
   /// \endcode
   std::vector RawStringFormats;
 

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=322956&r1=322955&r2=322956&view=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Fri Jan 19 08:18:47 2018
@@ -102,6 +102,18 @@ static llvm::Optional getRawS
   return Delimiter;
 }
 
+// Returns the canonical delimiter for \p Language, or the empty string if no
+// canonical delimiter is specified.
+static StringRef
+getCanonicalRawStringDelimiter(const FormatStyle &Style,
+   FormatStyle::LanguageKind Language) {
+  for (const auto &Format : Style.RawStringFormats) {
+if (Format.Language == Language)
+  return StringRef(Format.CanonicalDelimiter);
+  }
+  return "";
+}
+
 RawStringFormatStyleManager::RawStringFormatStyleManager(
 const FormatStyle &CodeStyle) {
   for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
@@ -1312,14 +1324,32 @@ unsigned ContinuationIndenter::reformatR
 const FormatToken &Cu

[PATCH] D42187: [clang-format] Adds a canonical delimiter to raw string formatting

2018-01-19 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC322956: [clang-format] Adds a canonical delimiter to raw 
string formatting (authored by krasimir, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42187?vs=130587&id=130626#toc

Repository:
  rC Clang

https://reviews.llvm.org/D42187

Files:
  docs/ClangFormatStyleOptions.rst
  include/clang/Format/Format.h
  lib/Format/ContinuationIndenter.cpp
  lib/Format/Format.cpp
  unittests/Format/FormatTest.cpp
  unittests/Format/FormatTestRawStrings.cpp

Index: docs/ClangFormatStyleOptions.rst
===
--- docs/ClangFormatStyleOptions.rst
+++ docs/ClangFormatStyleOptions.rst
@@ -1590,6 +1590,9 @@
   precedence over a matching enclosing function name for determining the
   language of the raw string contents.
 
+  If a canonical delimiter is specified, occurences of other delimiters for
+  the same language will be updated to the canonical if possible.
+
   There should be at most one specification per language and each delimiter
   and enclosing function should not occur in multiple specifications.
 
@@ -1610,6 +1613,7 @@
 - 'cc'
 - 'cpp'
   BasedOnStyle: llvm
+  CanonicalDelimiter: 'cc'
 
 **ReflowComments** (``bool``)
   If ``true``, clang-format will attempt to re-flow comments.
Index: include/clang/Format/Format.h
===
--- include/clang/Format/Format.h
+++ include/clang/Format/Format.h
@@ -1369,13 +1369,16 @@
 std::vector Delimiters;
 /// \brief A list of enclosing function names that match this language.
 std::vector EnclosingFunctions;
+/// \brief The canonical delimiter for this language.
+std::string CanonicalDelimiter;
 /// \brief The style name on which this raw string format is based on.
 /// If not specified, the raw string format is based on the style that this
 /// format is based on.
 std::string BasedOnStyle;
 bool operator==(const RawStringFormat &Other) const {
   return Language == Other.Language && Delimiters == Other.Delimiters &&
  EnclosingFunctions == Other.EnclosingFunctions &&
+ CanonicalDelimiter == Other.CanonicalDelimiter &&
  BasedOnStyle == Other.BasedOnStyle;
 }
   };
@@ -1392,6 +1395,9 @@
   /// precedence over a matching enclosing function name for determining the
   /// language of the raw string contents.
   ///
+  /// If a canonical delimiter is specified, occurences of other delimiters for
+  /// the same language will be updated to the canonical if possible.
+  ///
   /// There should be at most one specification per language and each delimiter
   /// and enclosing function should not occur in multiple specifications.
   ///
@@ -1410,6 +1416,7 @@
   ///   - 'cc'
   ///   - 'cpp'
   /// BasedOnStyle: llvm
+  /// CanonicalDelimiter: 'cc'
   /// \endcode
   std::vector RawStringFormats;
 
Index: lib/Format/ContinuationIndenter.cpp
===
--- lib/Format/ContinuationIndenter.cpp
+++ lib/Format/ContinuationIndenter.cpp
@@ -102,6 +102,18 @@
   return Delimiter;
 }
 
+// Returns the canonical delimiter for \p Language, or the empty string if no
+// canonical delimiter is specified.
+static StringRef
+getCanonicalRawStringDelimiter(const FormatStyle &Style,
+   FormatStyle::LanguageKind Language) {
+  for (const auto &Format : Style.RawStringFormats) {
+if (Format.Language == Language)
+  return StringRef(Format.CanonicalDelimiter);
+  }
+  return "";
+}
+
 RawStringFormatStyleManager::RawStringFormatStyleManager(
 const FormatStyle &CodeStyle) {
   for (const auto &RawStringFormat : CodeStyle.RawStringFormats) {
@@ -1312,14 +1324,32 @@
 const FormatToken &Current, LineState &State,
 const FormatStyle &RawStringStyle, bool DryRun) {
   unsigned StartColumn = State.Column - Current.ColumnWidth;
-  auto Delimiter = *getRawStringDelimiter(Current.TokenText);
+  StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
+  StringRef NewDelimiter =
+  getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
+  if (NewDelimiter.empty() || OldDelimiter.empty())
+NewDelimiter = OldDelimiter;
   // The text of a raw string is between the leading 'R"delimiter(' and the
   // trailing 'delimiter)"'.
-  unsigned PrefixSize = 3 + Delimiter.size();
-  unsigned SuffixSize = 2 + Delimiter.size();
+  unsigned OldPrefixSize = 3 + OldDelimiter.size();
+  unsigned OldSuffixSize = 2 + OldDelimiter.size();
+  // We create a virtual text environment which expects a null-terminated
+  // string, so we cannot use StringRef.
+  std::string RawText =
+  Current.TokenText.substr(OldPrefixSize).drop_back(OldSuffixSize);
+  if (NewDelimiter != OldDelimiter) {
+// Don't update to the canonica

Re: [PATCH] [scan-build] Add an option to skip overriding CC and CXX make vars

2018-01-19 Thread Jon Roelofs via cfe-commits
Sorry, I forgot to commit this before heading off on vacation. I'll be back
on monday.


Jon

On Fri, Jan 19, 2018 at 1:53 AM, Paul Fertser  wrote:

> Hello Jonathan,
>
> On Mon, Jan 15, 2018 at 08:36:03AM -0700, Jonathan Roelofs wrote:
> > LGTM. Would you like me to commit it for you?
>
> Yes, please, commit this patch with my next html documentation patch
> squashed into it, and also please commit the ccc-analyzer patch and
> close the related ticket as I do not have any permissions.
>
> --
> Be free, use free (http://www.gnu.org/philosophy/free-sw.html) software!
> mailto:fercer...@gmail.com
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41946: [clangd] Add support for different file URI schemas.

2018-01-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Sorry, our comments crossed...




Comment at: clangd/URI.cpp:57
+  Body = "/";
+Body += path::convert_to_slash(AbsolutePath, path::Style::posix);
+return (llvm::Twine(Scheme) + ":" + percentEncode(Body)).str();

ioeric wrote:
> sammccall wrote:
> > conversely, here you want native (which is the default)
> Don't we still need to convert \ to / on windows?
yes. `convert_to_slash(path, style)` assumes that `path` is in `style`.

`convert_to_slash("c:\\foo.txt", windows)` --> "c:/foo.txt"
`convert_to_slash("c:\\foo.txt", posix)` --> "c:\\foo.txt" (because that's a 
perfectly valid filename on a posix system! well, apart from the colon)
`convert_to_slash("c:\\foo.txt", native)` --> "c:/foo.txt" if the host is 
windows, "c:\\foo.txt" if the host is windows (this is what you want)




Comment at: clangd/URI.h:29
+  llvm::StringRef scheme() const { return Scheme; }
+  /// \brief Returns decoded authority.
+  llvm::StringRef authority() const { return Authority; }

ioeric wrote:
> sammccall wrote:
> > e.g. "//reviews.llvm.org"
> I think authority doesn't include leading "//"? 
You're right! my mistake.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D41946



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


r322967 - [WebAssembly] Add target flags for sign-ext opcodes.

2018-01-19 Thread Dan Gohman via cfe-commits
Author: djg
Date: Fri Jan 19 09:16:32 2018
New Revision: 322967

URL: http://llvm.org/viewvc/llvm-project?rev=322967&view=rev
Log:
[WebAssembly] Add target flags for sign-ext opcodes.

Add -msign-ext and -mno-sign-ext to control the new sign-ext target
feature.

Modified:
cfe/trunk/docs/ClangCommandLineReference.rst
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Basic/Targets/WebAssembly.cpp
cfe/trunk/lib/Basic/Targets/WebAssembly.h

Modified: cfe/trunk/docs/ClangCommandLineReference.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangCommandLineReference.rst?rev=322967&r1=322966&r2=322967&view=diff
==
--- cfe/trunk/docs/ClangCommandLineReference.rst (original)
+++ cfe/trunk/docs/ClangCommandLineReference.rst Fri Jan 19 09:16:32 2018
@@ -2320,6 +2320,8 @@ WebAssembly
 ---
 .. option:: -mnontrapping-fptoint, -mno-nontrapping-fptoint
 
+.. option:: -msign-ext, -mno-sign-ext
+
 .. option:: -msimd128, -mno-simd128
 
 X86

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=322967&r1=322966&r2=322967&view=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Fri Jan 19 09:16:32 2018
@@ -1870,6 +1870,8 @@ def msimd128 : Flag<["-"], "msimd128">,
 def mno_simd128 : Flag<["-"], "mno-simd128">, Group;
 def mnontrapping_fptoint : Flag<["-"], "mnontrapping-fptoint">, 
Group;
 def mno_nontrapping_fptoint : Flag<["-"], "mno-nontrapping-fptoint">, 
Group;
+def msign_ext : Flag<["-"], "msign-ext">, Group;
+def mno_sign_ext : Flag<["-"], "mno-sign-ext">, Group;
 
 def mamdgpu_debugger_abi : Joined<["-"], "mamdgpu-debugger-abi=">,
   Flags<[HelpHidden]>,

Modified: cfe/trunk/lib/Basic/Targets/WebAssembly.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/WebAssembly.cpp?rev=322967&r1=322966&r2=322967&view=diff
==
--- cfe/trunk/lib/Basic/Targets/WebAssembly.cpp (original)
+++ cfe/trunk/lib/Basic/Targets/WebAssembly.cpp Fri Jan 19 09:16:32 2018
@@ -33,6 +33,7 @@ bool WebAssemblyTargetInfo::hasFeature(S
   return llvm::StringSwitch(Feature)
   .Case("simd128", SIMDLevel >= SIMD128)
   .Case("nontrapping-fptoint", HasNontrappingFPToInt)
+  .Case("sign-ext", HasSignExt)
   .Default(false);
 }
 
@@ -70,6 +71,14 @@ bool WebAssemblyTargetInfo::handleTarget
   HasNontrappingFPToInt = false;
   continue;
 }
+if (Feature == "+sign-ext") {
+  HasSignExt = true;
+  continue;
+}
+if (Feature == "-sign-ext") {
+  HasSignExt = false;
+  continue;
+}
 
 Diags.Report(diag::err_opt_not_valid_with_opt)
 << Feature << "-target-feature";

Modified: cfe/trunk/lib/Basic/Targets/WebAssembly.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/WebAssembly.h?rev=322967&r1=322966&r2=322967&view=diff
==
--- cfe/trunk/lib/Basic/Targets/WebAssembly.h (original)
+++ cfe/trunk/lib/Basic/Targets/WebAssembly.h Fri Jan 19 09:16:32 2018
@@ -31,10 +31,12 @@ class LLVM_LIBRARY_VISIBILITY WebAssembl
   } SIMDLevel;
 
   bool HasNontrappingFPToInt;
+  bool HasSignExt;
 
 public:
   explicit WebAssemblyTargetInfo(const llvm::Triple &T, const TargetOptions &)
-  : TargetInfo(T), SIMDLevel(NoSIMD), HasNontrappingFPToInt(false) {
+  : TargetInfo(T), SIMDLevel(NoSIMD), HasNontrappingFPToInt(false),
+HasSignExt(false) {
 NoAsmVariants = true;
 SuitableAlign = 128;
 LargeArrayMinWidth = 128;
@@ -60,6 +62,7 @@ private:
 if (CPU == "bleeding-edge") {
   Features["simd128"] = true;
   Features["nontrapping-fptoint"] = true;
+  Features["sign-ext"] = true;
 }
 return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
   }


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


[libcxx] r322970 - More P0202 constexpr-ifying in . This commit handles 'transform'.

2018-01-19 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Fri Jan 19 09:45:39 2018
New Revision: 322970

URL: http://llvm.org/viewvc/llvm-project?rev=322970&view=rev
Log:
More P0202 constexpr-ifying in . This commit handles 'transform'.

Modified:
libcxx/trunk/include/algorithm

libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/binary_transform.pass.cpp

libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/unary_transform.pass.cpp

Modified: libcxx/trunk/include/algorithm
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/algorithm?rev=322970&r1=322969&r2=322970&view=diff
==
--- libcxx/trunk/include/algorithm (original)
+++ libcxx/trunk/include/algorithm Fri Jan 19 09:45:39 2018
@@ -193,11 +193,11 @@ template 
-OutputIterator
+constexpr OutputIterator  // constexpr in C++20
 transform(InputIterator first, InputIterator last, OutputIterator result, 
UnaryOperation op);
 
 template 
-OutputIterator
+constexpr OutputIterator  // constexpr in C++20
 transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 
first2,
   OutputIterator result, BinaryOperation binary_op);
 
@@ -1946,7 +1946,7 @@ move_backward(_BidirectionalIterator1 __
 // transform
 
 template 
-inline _LIBCPP_INLINE_VISIBILITY
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
 _OutputIterator
 transform(_InputIterator __first, _InputIterator __last, _OutputIterator 
__result, _UnaryOperation __op)
 {
@@ -1956,7 +1956,7 @@ transform(_InputIterator __first, _Input
 }
 
 template 
-inline _LIBCPP_INLINE_VISIBILITY
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
 _OutputIterator
 transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 
__first2,
   _OutputIterator __result, _BinaryOperation __binary_op)

Modified: 
libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/binary_transform.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/binary_transform.pass.cpp?rev=322970&r1=322969&r2=322970&view=diff
==
--- 
libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/binary_transform.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/binary_transform.pass.cpp
 Fri Jan 19 09:45:39 2018
@@ -12,15 +12,34 @@
 // template BinaryOp>
 //   requires OutputIterator && 
CopyConstructible
-// OutIter
+// constexpr OutIter  // constexpr after C++17
 // transform(InIter1 first1, InIter1 last1, InIter2 first2, OutIter result, 
BinaryOp binary_op);
 
 #include 
 #include 
 #include 
 
+#include "test_macros.h"
 #include "test_iterators.h"
 
+#if TEST_STD_VER > 17
+TEST_CONSTEXPR bool test_constexpr() {
+const int ia[] = {1, 3, 6, 7};
+const int ib[] = {2, 4, 7, 8};
+  int ic[] = {0, 0, 0, 0, 0}; // one bigger
+const int expected[] = {3, 7, 13, 15};
+
+auto it = std::transform(std::begin(ia), std::end(ia), 
+ std::begin(ib), std::begin(ic), std::plus());
+
+return it == (std::begin(ic) + std::size(ia))
+&& *it == 0 // don't overwrite the last value in the output array
+&& std::equal(std::begin(expected), std::end(expected), 
std::begin(ic), it)
+;
+}
+#endif
+
+
 template
 void
 test()
@@ -214,4 +233,8 @@ int main()
 test >();
 test >();
 test();
+
+#if TEST_STD_VER > 17
+static_assert(test_constexpr());
+#endif
 }

Modified: 
libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/unary_transform.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/unary_transform.pass.cpp?rev=322970&r1=322969&r2=322970&view=diff
==
--- 
libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/unary_transform.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.transform/unary_transform.pass.cpp
 Fri Jan 19 09:45:39 2018
@@ -12,16 +12,34 @@
 // template Op>
 //   requires OutputIterator && CopyConstructible
-//   OutIter
+// constexpr OutIter  // constexpr after C++17
 //   transform(InIter first, InIter last, OutIter result, Op op);
 
 #include 
 #include 
 #include 
 
+#include "test_macros.h"
 #include "test_iterators.h"
 
-int plusOne(int v) { return v + 1; }
+TEST_CONSTEXPR int plusOne(int v) { return v + 1; }
+
+
+#if TEST_STD_VER > 17
+TEST_CONSTEXPR bool test_constexpr() {
+int ia[] = {1, 3, 6, 7};
+int ib[] = {0, 0, 0, 0, 0}; // one bigger
+const int expected[] = {2, 4, 7, 8};
+
+auto it = std::transform(std::begin(ia), std::end(ia), std::begin(ib), 
plusOne);
+
+return it == (std::begin(i

[PATCH] D41829: [cmake] Add cache file to bootstrap linux cross compile on Darwin.

2018-01-19 Thread Don Hinton via Phabricator via cfe-commits
hintonda updated this revision to Diff 130638.
hintonda edited the summary of this revision.
hintonda added a comment.

- Also pass LLVM_CONFIG_EXE.
- Add llvm-objcopy, and make sure that is stage2 cache file is passed,


Repository:
  rC Clang

https://reviews.llvm.org/D41829

Files:
  cmake/caches/Linux.cmake

Index: cmake/caches/Linux.cmake
===
--- /dev/null
+++ cmake/caches/Linux.cmake
@@ -0,0 +1,96 @@
+# This file is primarily for cross compiling clang+llvm, et al, for
+# Linux on Darwin, and can be invoked like this:
+#
+#  cmake -GNinja -DBOOTSTRAP_CMAKE_SYSROOT= [OPTIONS] \
+#-C /cmake/caches/Linux.cmake ../llvm
+#
+#  Use "BOOTSTRAP_" prefix to pass options to stage2, e.g.,
+#  "-DBOOTSTRAP_CMAKE_BUILD_TYPE=Release", and
+#  "-DSTAGE2_CACHE_FILE=" to specify a stage2 cache file.
+#
+
+
+if(NOT DEFINED BOOTSTRAP_CMAKE_SYSROOT)
+  message(FATAL_ERROR "Missing required argument -DBOOTSTRAP_CMAKE_SYSROOT=.")
+endif()
+
+# FIXME: Default to Linux, but should this be required?
+if(NOT DEFINED BOOTSTRAP_CMAKE_SYSTEM_NAME)
+  set(BOOTSTRAP_CMAKE_SYSTEM_NAME Linux CACHE STRING "")
+endif()
+
+# FIXME:  Should this default be based on BOOTSTRAP_CMAKE_SYSTEM_NAME?
+if(NOT DEFINED BOOTSTRAP_LLVM_DEFAULT_BOOTSTRAP_TRIPLE)
+  set(BOOTSTRAP_LLVM_DEFAULT_BOOTSTRAP_TRIPLE "x86_64-unknown-linux-gnu")
+endif()
+
+if(NOT DEFINED BOOTSTRAP_GCC_INSTALL_PREFIX)
+  # Force clang to look for gcc at runtime -- otherwise it will
+  # default to 4.2.1.
+  set(BOOTSTRAP_GCC_INSTALL_PREFIX "/usr" CACHE STRING "")
+endif()
+
+# Allow user to pass a custom stage2 cache file.
+if(DEFINED STAGE2_CACHE_FILE)
+  if(NOT IS_ABSOLUTE ${STAGE2_CACHE_FILE})
+message(SEND_ERROR "STAGE2_CACHE_FILE [${STAGE2_CACHE_FILE}] must be an absolute path.")
+  endif()
+  if(NOT EXISTS ${STAGE2_CACHE_FILE})
+message(SEND_ERROR "STAGE2_CACHE_FILE [${STAGE2_CACHE_FILE}] does not exist.")
+  endif()
+  list(APPEND EXTRA_ARGS -C${STAGE2_CACHE_FILE})
+endif()
+
+list(APPEND EXTRA_ARGS
+  -DCMAKE_C_COMPILER_TARGET=${BOOTSTRAP_LLVM_DEFAULT_BOOTSTRAP_TRIPLE}
+  -DCMAKE_CXX_COMPILER_TARGET=${BOOTSTRAP_LLVM_DEFAULT_BOOTSTRAP_TRIPLE}
+  -DCMAKE_ASM_COMPILER_TARGET=${BOOTSTRAP_LLVM_DEFAULT_BOOTSTRAP_TRIPLE}
+
+  # Adjust the default behaviour of the FIND_XXX() commands to only
+  # search for headers and libraries in the
+  # CMAKE_SYSROOT/CMAKE_FIND_ROOT_PATH, and always search for programs
+  # in the host system.  These all default to BOTH.
+  -DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER
+  -DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY
+  -DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY
+  )
+
+set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
+set(CMAKE_BUILD_TYPE RELEASE CACHE STRING "")
+set(LLVM_ENABLE_ASSERTIONS ON CACHE BOOL "")
+
+set(LLVM_INCLUDE_DOCS OFF CACHE BOOL "")
+set(LLVM_INCLUDE_EXAMPLES OFF CACHE BOOL "")
+set(LLVM_INCLUDE_RUNTIMES OFF CACHE BOOL "")
+set(LLVM_INCLUDE_TESTS OFF CACHE BOOL "")
+set(LLVM_INCLUDE_UTILS OFF CACHE BOOL "")
+set(CLANG_BUILD_TOOLS OFF CACHE BOOL "")
+set(CLANG_ENABLE_ARCMT OFF CACHE BOOL "")
+set(CLANG_ENABLE_STATIC_ANALYZER OFF CACHE BOOL "")
+
+# FIXME: Is there a better way to specify this? i.e., target is elf,
+# but host isn't.
+if(CMAKE_HOST_APPLE)
+  # Make sure at least clang and lld are included.
+  set(LLVM_ENABLE_PROJECTS ${LLVM_ENABLE_PROJECTS} clang lld CACHE STRING "")
+
+  # Passing -fuse-ld=lld is hard for cmake to handle correctly, so
+  # make lld the default linker.
+  set(CLANG_DEFAULT_LINKER lld CACHE STRING "")
+
+  set(CLANG_DEFAULT_OBJCOPY llvm-objcopy CACHE STRING "")
+
+  list(APPEND EXTRA_ARGS
+-DLLVM_ENABLE_LLD=ON
+-DCMAKE_AR=${CMAKE_BINARY_DIR}/bin/llvm-ar
+-DCMAKE_OBJCOPY=${CMAKE_BINARY_DIR}/bin/llvm-objcopy
+-DCMAKE_RANLIB=${CMAKE_BINARY_DIR}/bin/llvm-ranlib
+-DCLANG_TABLEGEN=${CMAKE_BINARY_DIR}/bin/clang-tblgen
+-DLLVM_TABLEGEN=${CMAKE_BINARY_DIR}/bin/llvm-tblgen
+-DLLVM_CONFIG_EXE=${CMAKE_BINARY_DIR}/bin/llvm-config
+)
+
+endif()
+
+set(CLANG_ENABLE_BOOTSTRAP ON CACHE BOOL "")
+set(CLANG_BOOTSTRAP_CMAKE_ARGS ${EXTRA_ARGS} CACHE STRING "")
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42213: [ASTMatchers] [NFC] Fix code examples

2018-01-19 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 130644.
MaskRay added a comment.

Revert some changes to address comments


Repository:
  rC Clang

https://reviews.llvm.org/D42213

Files:
  include/clang/ASTMatchers/ASTMatchers.h

Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -800,7 +800,7 @@
 ///   A b;
 ///   A c;
 ///
-///   template f() {};
+///   template void f() {};
 ///   void func() { f(); };
 /// \endcode
 /// classTemplateSpecializationDecl(hasTemplateArgument(
@@ -880,12 +880,12 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
-///   struct B { B* next; };
+///   struct B { int next; };
+///   template struct A {};
 ///   A<&B::next> a;
 /// \endcode
 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
-/// refersToDeclaration(fieldDecl(hasName("next"
+/// refersToDeclaration(fieldDecl(hasName("next")
 ///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
 /// \c B::next
 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
@@ -899,8 +899,8 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
-///   struct B { B* next; };
+///   struct B { int next; };
+///   template struct A {};
 ///   A<&B::next> a;
 /// \endcode
 /// templateSpecializationType(hasAnyTemplateArgument(
@@ -917,7 +917,7 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
+///   template struct C {};
 ///   C<42> c;
 /// \endcode
 /// classTemplateSpecializationDecl(
@@ -932,7 +932,7 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
+///   template struct C {};
 ///   C<42> c;
 /// \endcode
 /// classTemplateSpecializationDecl(
@@ -953,7 +953,7 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
+///   template struct C {};
 ///   C<42> c;
 /// \endcode
 /// classTemplateSpecializationDecl(
@@ -1523,12 +1523,12 @@
 /// \code
 ///   T u(f());
 ///   g(f());
-/// \endcode
-/// but does not match
-/// \code
-///   f();
 ///   f().func();
 /// \endcode
+/// but does not match
+/// \code
+///   f();
+/// \endcode
 extern const internal::VariadicDynCastAllOfMatcher
 materializeTemporaryExpr;
@@ -1799,7 +1799,7 @@
 ///   switch(a) { case 42: break; default: break; }
 /// \endcode
 /// switchCase()
-///   matches 'case 42: break;' and 'default: break;'.
+///   matches 'case 42:' and 'default:'.
 extern const internal::VariadicDynCastAllOfMatcher switchCase;
 
 /// \brief Matches case statements inside switch statements.
@@ -1809,7 +1809,7 @@
 ///   switch(a) { case 42: break; default: break; }
 /// \endcode
 /// caseStmt()
-///   matches 'case 42: break;'.
+///   matches 'case 42:'.
 extern const internal::VariadicDynCastAllOfMatcher caseStmt;
 
 /// \brief Matches default statements inside switch statements.
@@ -1819,13 +1819,13 @@
 ///   switch(a) { case 42: break; default: break; }
 /// \endcode
 /// defaultStmt()
-///   matches 'default: break;'.
+///   matches 'default:'.
 extern const internal::VariadicDynCastAllOfMatcher
 defaultStmt;
 
 /// \brief Matches compound statements.
 ///
-/// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
+/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
 /// \code
 ///   for (;;) {{}}
 /// \endcode
@@ -2502,11 +2502,12 @@
 /// \brief Matches AST nodes that have child AST nodes that match the
 /// provided matcher.
 ///
-/// Example matches X, Y
+/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
 ///   (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
 /// \code
-///   class X {};  // Matches X, because X::X is a class of name X inside X.
-///   class Y { class X {}; };
+///   class X {};
+///   class Y { class X {}; };  // Matches Y, because Y::X is a class of name X
+/// // inside Y.
 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
 /// \endcode
 ///
@@ -2522,11 +2523,12 @@
 /// \brief Matches AST nodes that have descendant AST nodes that match the
 /// provided matcher.
 ///
-/// Example matches X, A, B, C
+/// Example matches X, A, A::X, B, B::C, B::C::X
 ///   (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")
 /// \code
-///   class X {};  // Matches X, because X::X is a class of name X inside X.
-///   class A { class X {}; };
+///   class X {};
+///   class A { class X {}; };  // Matches A, because A::X is a class of name
+/// // X inside A.
 ///   class B { class C { class X {}; }; };
 /// \endcode
 ///
@@ -2681,7 +2683,7 @@
 ///   (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))
 /// \code
 ///   class Y { public: void x(); };
-///   void z() { Y y; y.x(); }",
+///   void z() { Y y; y.x(); }
 /// \endcode
 ///
 /// FIXME: Overload to allow directly matching types?
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cf

[PATCH] D42232: [cmake] Also pass CMAKE_ASM_COMPILER_ID to next stage when bootstrapping

2018-01-19 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd accepted this revision.
compnerd added a comment.
This revision is now accepted and ready to land.

Took a bit of reading to realize that the compiler is being set to clang, and 
therefore `CMAKE_ASM_COMPILER_ID` should be `Clang`.


Repository:
  rC Clang

https://reviews.llvm.org/D42232



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


[libcxx] r322975 - More P0202 constexpr-ifying in . This commit handles replace/replace_if/replace_copy/replace_copy_if.

2018-01-19 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Fri Jan 19 10:07:29 2018
New Revision: 322975

URL: http://llvm.org/viewvc/llvm-project?rev=322975&view=rev
Log:
More P0202 constexpr-ifying in . This commit handles 
replace/replace_if/replace_copy/replace_copy_if.

Modified:
libcxx/trunk/include/algorithm

libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.replace/replace.pass.cpp

libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.replace/replace_copy.pass.cpp

libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.replace/replace_copy_if.pass.cpp

libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.replace/replace_if.pass.cpp

Modified: libcxx/trunk/include/algorithm
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/algorithm?rev=322975&r1=322974&r2=322975&view=diff
==
--- libcxx/trunk/include/algorithm (original)
+++ libcxx/trunk/include/algorithm Fri Jan 19 10:07:29 2018
@@ -202,20 +202,20 @@ template 
-void
+constexpr void  // constexpr in C++20
 replace(ForwardIterator first, ForwardIterator last, const T& old_value, 
const T& new_value);
 
 template 
-void
+constexpr void  // constexpr in C++20
 replace_if(ForwardIterator first, ForwardIterator last, Predicate pred, 
const T& new_value);
 
 template 
-OutputIterator
+constexpr OutputIterator  // constexpr in C++20
 replace_copy(InputIterator first, InputIterator last, OutputIterator 
result,
  const T& old_value, const T& new_value);
 
 template 
-OutputIterator
+constexpr OutputIterator  // constexpr in C++20
 replace_copy_if(InputIterator first, InputIterator last, OutputIterator 
result, Predicate pred, const T& new_value);
 
 template 
@@ -1461,9 +1461,9 @@ __is_permutation(_ForwardIterator1 __fir
 if (!__pred(*__first1, *__first2))
 break;
 if (__first1 == __last1)
-   return __first2 == __last2;
+return __first2 == __last2;
 else if (__first2 == __last2)
-   return false;
+return false;
 
 typedef typename iterator_traits<_ForwardIterator1>::difference_type _D1;
 _D1 __l1 = _VSTD::distance(__first1, __last1);
@@ -1969,7 +1969,7 @@ transform(_InputIterator1 __first1, _Inp
 // replace
 
 template 
-inline _LIBCPP_INLINE_VISIBILITY
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
 void
 replace(_ForwardIterator __first, _ForwardIterator __last, const _Tp& 
__old_value, const _Tp& __new_value)
 {
@@ -1981,7 +1981,7 @@ replace(_ForwardIterator __first, _Forwa
 // replace_if
 
 template 
-inline _LIBCPP_INLINE_VISIBILITY
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
 void
 replace_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate 
__pred, const _Tp& __new_value)
 {
@@ -1993,7 +1993,7 @@ replace_if(_ForwardIterator __first, _Fo
 // replace_copy
 
 template 
-inline _LIBCPP_INLINE_VISIBILITY
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
 _OutputIterator
 replace_copy(_InputIterator __first, _InputIterator __last, _OutputIterator 
__result,
  const _Tp& __old_value, const _Tp& __new_value)
@@ -2009,7 +2009,7 @@ replace_copy(_InputIterator __first, _In
 // replace_copy_if
 
 template 
-inline _LIBCPP_INLINE_VISIBILITY
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
 _OutputIterator
 replace_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator 
__result,
 _Predicate __pred, const _Tp& __new_value)

Modified: 
libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.replace/replace.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.replace/replace.pass.cpp?rev=322975&r1=322974&r2=322975&view=diff
==
--- 
libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.replace/replace.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/algorithms/alg.modifying.operations/alg.replace/replace.pass.cpp
 Fri Jan 19 10:07:29 2018
@@ -13,14 +13,27 @@
 //   requires OutputIterator
 // && OutputIterator
 // && HasEqualTo
-//   void
+//   constexpr void  // constexpr after C++17
 //   replace(Iter first, Iter last, const T& old_value, const T& new_value);
 
 #include 
 #include 
 
+#include "test_macros.h"
 #include "test_iterators.h"
 
+
+#if TEST_STD_VER > 17
+TEST_CONSTEXPR bool test_constexpr() {
+  int ia[]   = {0, 1, 2, 3, 4};
+const int expected[] = {0, 1, 5, 3, 4};
+
+std::replace(std::begin(ia), std::end(ia), 2, 5);
+return std::equal(std::begin(ia), std::end(ia), std::begin(expected), 
std::end(expected))
+;
+}
+#endif
+
 template 
 void
 test()
@@ -41,4 +54,8 @@ int main()
 test >();
 test >();
 test();
+
+#if TEST_STD_VER > 17
+static_assert(test_constexpr());
+#endi

[PATCH] D42213: [ASTMatchers] [NFC] Fix code examples

2018-01-19 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In https://reviews.llvm.org/D42213#981700, @aaron.ballman wrote:

> The documentation needs to be regenerated for this patch. One thing that 
> seems to be inconsistent is with the "what gets matched" messages is that 
> sometimes it includes extra adornments like curly braces and other times it 
> does not. It might be good to pick a style and try to be more consistent with 
> it.


Do I need to do anything to re-generate the doc and check it into this 
revision? If so, can you show me the Doxygen generation instruction?

Reverted some changes as they may cause confusion which are pointed by you.


Repository:
  rC Clang

https://reviews.llvm.org/D42213



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


[PATCH] D41623: [cmake] [libcxxabi] Fix path problems when cross compiling.

2018-01-19 Thread Don Hinton via Phabricator via cfe-commits
hintonda added a comment.

Unless there's any further comment, I plan to commit these patches tomorrow.


Repository:
  rCXXA libc++abi

https://reviews.llvm.org/D41623



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


[PATCH] D42276: [Driver] Add an -fexperimental-isel driver option to enable/disable GlobalISel

2018-01-19 Thread Quentin Colombet via Phabricator via cfe-commits
qcolombet added inline comments.



Comment at: lib/Driver/ToolChains/Clang.cpp:4699
+else
+  CmdArgs.push_back("-global-isel=0");
+  }

I think that it would be useful to also set -global-isel-abort=2, so that users 
can report problem early.

What do you think?





Comment at: lib/Driver/ToolChains/Clang.cpp:4699
+else
+  CmdArgs.push_back("-global-isel=0");
+  }

qcolombet wrote:
> I think that it would be useful to also set -global-isel-abort=2, so that 
> users can report problem early.
> 
> What do you think?
> 
> 
Should we have some kind of "target validation"?
What I'd like to avoid is people trying the new allocator on unsupported target 
(as in the GISel base classes are not present) that would just crash the 
compiler.

Alternatively, we could fix the backend to fallback gracefully/abort properly 
in those situation.
Right now I believe we would get a segfault on RegisterBankInfo or something 
along those lines.


Repository:
  rC Clang

https://reviews.llvm.org/D42276



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


[PATCH] D42232: [cmake] Also pass CMAKE_ASM_COMPILER_ID to next stage when bootstrapping

2018-01-19 Thread Don Hinton via Phabricator via cfe-commits
hintonda added a comment.

In https://reviews.llvm.org/D42232#982043, @compnerd wrote:

> Took a bit of reading to realize that the compiler is being set to clang, and 
> therefore `CMAKE_ASM_COMPILER_ID` should be `Clang`.


Thanks, I'll add that to the commit message.


Repository:
  rC Clang

https://reviews.llvm.org/D42232



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


[PATCH] D42261: [clang-tidy objc-property-declaration] New option AdditionalAcronyms

2018-01-19 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added a comment.

Thanks, fixed.




Comment at: clang-tidy/objc/PropertyDeclarationCheck.h:38
 const std::vector SpecialAcronyms;
+const std::vector AdditionalAcronyms;
 };

hokein wrote:
> nit: code indent
Ah, the previous one was wrong, I see. Fixed both.



Comment at: docs/clang-tidy/checks/objc-property-declaration.rst:45
+
+   If set, replaces the default list. (If you want to append to the default 
list, set AdditionalAcronyms instead.)
+

Eugene.Zelenko wrote:
> Please limit string length to 80 symbols.
Thanks, fixed.



Comment at: docs/clang-tidy/checks/objc-property-declaration.rst:47
+
+.. option:: AdditionalAcronyms
+

hokein wrote:
> It seems to me the `Acronyms` and `AdditionalAcronyms` play most same role 
> here. 
> 
> If we want to keep the long default list, how about using a bool flag 
> `IncludeDefaultList` + the existing `Acronyms` option?
> 
> * if `IncludeDefaultList` is on, the acronyms will be "default" + "Acronyms".
> * if `IncludeDefaultList` is off, the acronyms will be only "Acronyms".
I think most people will want the "include default + add more" option. My goal 
was to make that possible, which is why I added the new `AdditionalAcronyms` 
option.

I agree the idea of a setting to control including the default list is nice, 
but I feel that should be on by default, since most users will want that.

If we add `IncludeDefaultList`, it should need to be on by default. That would 
break backwards compatibility for existing users. Do we think that's okay?

I'm assuming not a lot of people use this check yet, but I have no way of 
knowing that.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42261



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


[PATCH] D42261: [clang-tidy objc-property-declaration] New option AdditionalAcronyms

2018-01-19 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 130657.
benhamilton marked 2 inline comments as done.
benhamilton added a comment.

- Switch to IncludeDefaultAcronyms option (defaults to 1).
- Use array for default acronyms, since we no longer need to parse it.
- Don't regex-escape default acronyms, since we control them.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42261

Files:
  clang-tidy/objc/PropertyDeclarationCheck.cpp
  clang-tidy/objc/PropertyDeclarationCheck.h
  docs/clang-tidy/checks/objc-property-declaration.rst
  test/clang-tidy/objc-property-declaration-additional.m
  test/clang-tidy/objc-property-declaration-custom.m

Index: test/clang-tidy/objc-property-declaration-custom.m
===
--- test/clang-tidy/objc-property-declaration-custom.m
+++ test/clang-tidy/objc-property-declaration-custom.m
@@ -1,6 +1,7 @@
 // RUN: %check_clang_tidy %s objc-property-declaration %t \
 // RUN: -config='{CheckOptions: \
-// RUN:  [{key: objc-property-declaration.Acronyms, value: "ABC;TGIF"}]}' \
+// RUN:  [{key: objc-property-declaration.Acronyms, value: "ABC;TGIF"}, \
+// RUN:   {key: objc-property-declaration.IncludeDefaultAcronyms, value: 0}]}' \
 // RUN: --
 @class NSString;
 
@@ -11,4 +12,6 @@
 @property(assign, nonatomic) int ABCCustomPrefix;
 @property(strong, nonatomic) NSString *ABC_custom_prefix;
 // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: property name 'ABC_custom_prefix' should use lowerCamelCase style, according to the Apple Coding Guidelines [objc-property-declaration]
+@property(assign, nonatomic) int GIFIgnoreStandardAcronym;
+// CHECK-MESSAGES: :[[@LINE-1]]:34: warning: property name 'GIFIgnoreStandardAcronym' should use lowerCamelCase style, according to the Apple Coding Guidelines [objc-property-declaration]
 @end
Index: test/clang-tidy/objc-property-declaration-additional.m
===
--- test/clang-tidy/objc-property-declaration-additional.m
+++ test/clang-tidy/objc-property-declaration-additional.m
@@ -11,4 +11,5 @@
 @property(assign, nonatomic) int ABCCustomPrefix;
 @property(strong, nonatomic) NSString *ABC_custom_prefix;
 // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: property name 'ABC_custom_prefix' should use lowerCamelCase style, according to the Apple Coding Guidelines [objc-property-declaration]
+@property(assign, nonatomic) int GIFShouldIncludeStandardAcronym;
 @end
Index: docs/clang-tidy/checks/objc-property-declaration.rst
===
--- docs/clang-tidy/checks/objc-property-declaration.rst
+++ docs/clang-tidy/checks/objc-property-declaration.rst
@@ -37,7 +37,25 @@
 
 .. option:: Acronyms
 
-   Semicolon-separated list of acronyms that can be used as a prefix
+   Semicolon-separated list of custom acronyms that can be used as a prefix
or a suffix of property names.
 
-   If unset, defaults to "ACL;API;ARGB;ASCII;BGRA;CMYK;DNS;FPS;FTP;GIF;GPS;HD;HDR;HTML;HTTP;HTTPS;HUD;ID;JPG;JS;LAN;LZW;MDNS;MIDI;OS;PDF;PIN;PNG;POI;PSTN;PTR;QA;QOS;RGB;RGBA;RGBX;ROM;RPC;RTF;RTL;SDK;SSO;TCP;TIFF;TTS;UI;URI;URL;VC;VOIP;VPN;VR;WAN;XML".
+   By default, appends to the list of default acronyms (
+   ``IncludeDefaultAcronyms`` set to ``1``).
+   If ``IncludeDefaultAcronyms`` is set to ``0``, instead replaces the
+   default list of acronyms.
+
+.. option:: IncludeDefaultAcronyms
+
+   Integer value (defaults to ``1``) to control whether the default
+   acronyms are included in the list of acronyms.
+
+   If set to ``1``, the value in ``Acronyms`` is appended to the
+   default list of acronyms:
+
+   ``ACL;API;ARGB;ASCII;BGRA;CMYK;DNS;FPS;FTP;GIF;GPS;HD;HDR;HTML;HTTP;HTTPS;
+HUD;ID;JPG;JS;LAN;LZW;MDNS;MIDI;OS;PDF;PIN;PNG;POI;PSTN;PTR;QA;QOS;RGB;RGBA;
+RGBX;ROM;RPC;RTF;RTL;SDK;SSO;TCP;TIFF;TTS;UI;URI;URL;VC;VOIP;VPN;VR;WAN;XML``.
+
+   If set to ``0``, the value in ``Acronyms`` replaces the default list
+   of acronyms.
Index: clang-tidy/objc/PropertyDeclarationCheck.h
===
--- clang-tidy/objc/PropertyDeclarationCheck.h
+++ clang-tidy/objc/PropertyDeclarationCheck.h
@@ -34,7 +34,8 @@
   void storeOptions(ClangTidyOptions::OptionMap &Options) override;
 
 private:
-const std::vector SpecialAcronyms;
+  const std::vector SpecialAcronyms;
+  const bool IncludeDefaultAcronyms;
 };
 
 } // namespace objc
Index: clang-tidy/objc/PropertyDeclarationCheck.cpp
===
--- clang-tidy/objc/PropertyDeclarationCheck.cpp
+++ clang-tidy/objc/PropertyDeclarationCheck.cpp
@@ -11,6 +11,7 @@
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Regex.h"
 #include 
@@ -26,61 +27,62 @@
 /// https://developer.apple.com/library/content/documentation/Cocoa/Conc

r322977 - [cmake] Also pass CMAKE_ASM_COMPILER_ID to next stage when bootstrapping

2018-01-19 Thread Don Hinton via cfe-commits
Author: dhinton
Date: Fri Jan 19 10:31:12 2018
New Revision: 322977

URL: http://llvm.org/viewvc/llvm-project?rev=322977&view=rev
Log:
[cmake] Also pass CMAKE_ASM_COMPILER_ID to next stage when bootstrapping

Summary:
When setting CMAKE_ASM_COMPILER=clang, we also need to set
CMAKE_ASM_COMPILER_ID=Clang.

This is needed because cmake won't set CMAKE_ASM_COMPILER_ID if
CMAKE_ASM_COMPILER is already set.

Without CMAKE_ASM_COMPILER_ID, cmake can't set
CMAKE_ASM_COMPILER_OPTIONS_TARGET either, which means
CMAKE_ASM_COMPILER_TARGET is ignored, causing cross compiling to fail,
i.e., `--target=${CMAKE_ASM_COMPILER_TARGET}` isn't passed.

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

Modified:
cfe/trunk/CMakeLists.txt

Modified: cfe/trunk/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/CMakeLists.txt?rev=322977&r1=322976&r2=322977&view=diff
==
--- cfe/trunk/CMakeLists.txt (original)
+++ cfe/trunk/CMakeLists.txt Fri Jan 19 10:31:12 2018
@@ -624,7 +624,8 @@ if (CLANG_ENABLE_BOOTSTRAP)
   set(COMPILER_OPTIONS
 -DCMAKE_CXX_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${CXX_COMPILER}
 -DCMAKE_C_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${C_COMPILER}
--DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${C_COMPILER})
+-DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${C_COMPILER}
+-DCMAKE_ASM_COMPILER_ID=Clang)
 
   if(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED)
 add_dependencies(clang-bootstrap-deps llvm-profdata)


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


[PATCH] D42307: [OpenCL][6.0.0 Release] Release notes for OpenCL in Clang

2018-01-19 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia created this revision.
Anastasia added reviewers: yaxunl, bader, hans.

https://reviews.llvm.org/D42307

Files:
  docs/ReleaseNotes.rst


Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -204,7 +204,46 @@
 OpenCL C Language Changes in Clang
 --
 
-...
+- Added subgroup builtins to enqueue kernel support.
+- Added CL2.0 atomics as Clang builtins that now accept
+  an additional memory scope parameter propagated to atomic IR instructions
+  (this is to align with the corresponding change in LLVM IR) (see `spec 
s6.13.11.4
+`_).
+
+- Miscellaneous fixes in the CL header.
+
+- Allow per target selection of address space during CodeGen of certain OpenCL 
types.
+  Default target implementation is provided mimicking old behavior.
+
+- Macro ``__IMAGE_SUPPORT__`` is now automatically added (as per `spec s6.10
+`_).
+
+- Added ``cl_intel_subgroups`` and ``cl_intel_subgroups_short`` extensions.
+
+- All function calls are marked by the convergent attribute
+  
(https://clang.llvm.org/docs/AttributeReference.html#convergent-clang-convergent)
+  to prevent optimizations that break SPMD program semantics. This will be 
removed
+  by LLVM passes if it can be proved that the function does not use convergent
+  operations.
+
+- Create a kernel wrapper for enqueued blocks, which simplifies enqueue 
support by
+  providing common functionality.
+
+- Added private address space explicitly in AST and refactored address space 
support
+  with several simplifications and bug fixes (llvm.org/pr33419 and 
llvm.org/pr33420).
+
+- OpenCL now allows functions with empty parameters to be treated as if they 
had a
+  void parameter list (inspired from C++ support). OpenCL C spec update to 
follow.
+
+- General miscellaneous refactoring and cleanup of blocks support for OpenCL to
+  remove unused parts inherited from Objective C implementation.
+
+- Miscellaneous improvements in vector diagnostics.
+
+- Added half float load and store builtins without enabling half as a legal 
type
+  (``__builtin_store_half for double``, ``__builtin_store_halff`` for double,
+  ``__builtin_load_half for double``, ``__builtin_load_halff`` for float).
+
 
 OpenMP Support in Clang
 --


Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -204,7 +204,46 @@
 OpenCL C Language Changes in Clang
 --
 
-...
+- Added subgroup builtins to enqueue kernel support.
+- Added CL2.0 atomics as Clang builtins that now accept
+  an additional memory scope parameter propagated to atomic IR instructions
+  (this is to align with the corresponding change in LLVM IR) (see `spec s6.13.11.4
+`_).
+
+- Miscellaneous fixes in the CL header.
+
+- Allow per target selection of address space during CodeGen of certain OpenCL types.
+  Default target implementation is provided mimicking old behavior.
+
+- Macro ``__IMAGE_SUPPORT__`` is now automatically added (as per `spec s6.10
+`_).
+
+- Added ``cl_intel_subgroups`` and ``cl_intel_subgroups_short`` extensions.
+
+- All function calls are marked by the convergent attribute
+  (https://clang.llvm.org/docs/AttributeReference.html#convergent-clang-convergent)
+  to prevent optimizations that break SPMD program semantics. This will be removed
+  by LLVM passes if it can be proved that the function does not use convergent
+  operations.
+
+- Create a kernel wrapper for enqueued blocks, which simplifies enqueue support by
+  providing common functionality.
+
+- Added private address space explicitly in AST and refactored address space support
+  with several simplifications and bug fixes (llvm.org/pr33419 and llvm.org/pr33420).
+
+- OpenCL now allows functions with empty parameters to be treated as if they had a
+  void parameter list (inspired from C++ support). OpenCL C spec update to follow.
+
+- General miscellaneous refactoring and cleanup of blocks support for OpenCL to
+  remove unused parts inherited from Objective C implementation.
+
+- Miscellaneous improvements in vector diagnostics.
+
+- Added half float load and store builtins without enabling half as a legal type
+  (``__builtin_store_half for double``, ``__builtin_store_halff`` for double,
+  ``__builtin_load_half for double``, ``__builtin_load_halff`` for float).
+
 
 OpenMP Support in Clang
 --
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-comm

[PATCH] D42261: [clang-tidy objc-property-declaration] New option IncludeDefaultAcronyms

2018-01-19 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton updated this revision to Diff 130661.
benhamilton added a comment.

- Remove debugging code


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42261

Files:
  clang-tidy/objc/PropertyDeclarationCheck.cpp
  clang-tidy/objc/PropertyDeclarationCheck.h
  docs/clang-tidy/checks/objc-property-declaration.rst
  test/clang-tidy/objc-property-declaration-additional.m
  test/clang-tidy/objc-property-declaration-custom.m

Index: test/clang-tidy/objc-property-declaration-custom.m
===
--- test/clang-tidy/objc-property-declaration-custom.m
+++ test/clang-tidy/objc-property-declaration-custom.m
@@ -1,6 +1,7 @@
 // RUN: %check_clang_tidy %s objc-property-declaration %t \
 // RUN: -config='{CheckOptions: \
-// RUN:  [{key: objc-property-declaration.Acronyms, value: "ABC;TGIF"}]}' \
+// RUN:  [{key: objc-property-declaration.Acronyms, value: "ABC;TGIF"}, \
+// RUN:   {key: objc-property-declaration.IncludeDefaultAcronyms, value: 0}]}' \
 // RUN: --
 @class NSString;
 
@@ -11,4 +12,6 @@
 @property(assign, nonatomic) int ABCCustomPrefix;
 @property(strong, nonatomic) NSString *ABC_custom_prefix;
 // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: property name 'ABC_custom_prefix' should use lowerCamelCase style, according to the Apple Coding Guidelines [objc-property-declaration]
+@property(assign, nonatomic) int GIFIgnoreStandardAcronym;
+// CHECK-MESSAGES: :[[@LINE-1]]:34: warning: property name 'GIFIgnoreStandardAcronym' should use lowerCamelCase style, according to the Apple Coding Guidelines [objc-property-declaration]
 @end
Index: test/clang-tidy/objc-property-declaration-additional.m
===
--- test/clang-tidy/objc-property-declaration-additional.m
+++ test/clang-tidy/objc-property-declaration-additional.m
@@ -11,4 +11,5 @@
 @property(assign, nonatomic) int ABCCustomPrefix;
 @property(strong, nonatomic) NSString *ABC_custom_prefix;
 // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: property name 'ABC_custom_prefix' should use lowerCamelCase style, according to the Apple Coding Guidelines [objc-property-declaration]
+@property(assign, nonatomic) int GIFShouldIncludeStandardAcronym;
 @end
Index: docs/clang-tidy/checks/objc-property-declaration.rst
===
--- docs/clang-tidy/checks/objc-property-declaration.rst
+++ docs/clang-tidy/checks/objc-property-declaration.rst
@@ -37,7 +37,25 @@
 
 .. option:: Acronyms
 
-   Semicolon-separated list of acronyms that can be used as a prefix
+   Semicolon-separated list of custom acronyms that can be used as a prefix
or a suffix of property names.
 
-   If unset, defaults to "ACL;API;ARGB;ASCII;BGRA;CMYK;DNS;FPS;FTP;GIF;GPS;HD;HDR;HTML;HTTP;HTTPS;HUD;ID;JPG;JS;LAN;LZW;MDNS;MIDI;OS;PDF;PIN;PNG;POI;PSTN;PTR;QA;QOS;RGB;RGBA;RGBX;ROM;RPC;RTF;RTL;SDK;SSO;TCP;TIFF;TTS;UI;URI;URL;VC;VOIP;VPN;VR;WAN;XML".
+   By default, appends to the list of default acronyms (
+   ``IncludeDefaultAcronyms`` set to ``1``).
+   If ``IncludeDefaultAcronyms`` is set to ``0``, instead replaces the
+   default list of acronyms.
+
+.. option:: IncludeDefaultAcronyms
+
+   Integer value (defaults to ``1``) to control whether the default
+   acronyms are included in the list of acronyms.
+
+   If set to ``1``, the value in ``Acronyms`` is appended to the
+   default list of acronyms:
+
+   ``ACL;API;ARGB;ASCII;BGRA;CMYK;DNS;FPS;FTP;GIF;GPS;HD;HDR;HTML;HTTP;HTTPS;
+HUD;ID;JPG;JS;LAN;LZW;MDNS;MIDI;OS;PDF;PIN;PNG;POI;PSTN;PTR;QA;QOS;RGB;RGBA;
+RGBX;ROM;RPC;RTF;RTL;SDK;SSO;TCP;TIFF;TTS;UI;URI;URL;VC;VOIP;VPN;VR;WAN;XML``.
+
+   If set to ``0``, the value in ``Acronyms`` replaces the default list
+   of acronyms.
Index: clang-tidy/objc/PropertyDeclarationCheck.h
===
--- clang-tidy/objc/PropertyDeclarationCheck.h
+++ clang-tidy/objc/PropertyDeclarationCheck.h
@@ -34,7 +34,8 @@
   void storeOptions(ClangTidyOptions::OptionMap &Options) override;
 
 private:
-const std::vector SpecialAcronyms;
+  const std::vector SpecialAcronyms;
+  const bool IncludeDefaultAcronyms;
 };
 
 } // namespace objc
Index: clang-tidy/objc/PropertyDeclarationCheck.cpp
===
--- clang-tidy/objc/PropertyDeclarationCheck.cpp
+++ clang-tidy/objc/PropertyDeclarationCheck.cpp
@@ -11,6 +11,7 @@
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Regex.h"
 #include 
@@ -26,61 +27,62 @@
 /// https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/APIAbbreviations.html#//apple_ref/doc/uid/20001285-BCIHCGAE
 ///
 /// Keep this list sorted.
-constexpr char DefaultSpecialAcronyms[] =
-"ACL;"
-"API;"
-"ARGB;"
-"AS

[PATCH] D42232: [cmake] Also pass CMAKE_ASM_COMPILER_ID to next stage when bootstrapping

2018-01-19 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL322977: [cmake] Also pass CMAKE_ASM_COMPILER_ID to next 
stage when bootstrapping (authored by dhinton, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42232

Files:
  cfe/trunk/CMakeLists.txt


Index: cfe/trunk/CMakeLists.txt
===
--- cfe/trunk/CMakeLists.txt
+++ cfe/trunk/CMakeLists.txt
@@ -624,7 +624,8 @@
   set(COMPILER_OPTIONS
 -DCMAKE_CXX_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${CXX_COMPILER}
 -DCMAKE_C_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${C_COMPILER}
--DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${C_COMPILER})
+-DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${C_COMPILER}
+-DCMAKE_ASM_COMPILER_ID=Clang)
 
   if(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED)
 add_dependencies(clang-bootstrap-deps llvm-profdata)


Index: cfe/trunk/CMakeLists.txt
===
--- cfe/trunk/CMakeLists.txt
+++ cfe/trunk/CMakeLists.txt
@@ -624,7 +624,8 @@
   set(COMPILER_OPTIONS
 -DCMAKE_CXX_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${CXX_COMPILER}
 -DCMAKE_C_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${C_COMPILER}
--DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${C_COMPILER})
+-DCMAKE_ASM_COMPILER=${LLVM_RUNTIME_OUTPUT_INTDIR}/${C_COMPILER}
+-DCMAKE_ASM_COMPILER_ID=Clang)
 
   if(BOOTSTRAP_LLVM_BUILD_INSTRUMENTED)
 add_dependencies(clang-bootstrap-deps llvm-profdata)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libclc] r322979 - tan: Port from amd_builtins

2018-01-19 Thread Jan Vesely via cfe-commits
Author: jvesely
Date: Fri Jan 19 10:57:19 2018
New Revision: 322979

URL: http://llvm.org/viewvc/llvm-project?rev=322979&view=rev
Log:
tan: Port from amd_builtins

v2: fixup constant precision
Passes piglit on turks and carrizo.
Passes CTS on carrizo
Fixes half_tan to pass CTS on carrizo

Acked-By: Aaron Watry 
Tested-By: Aaron Watry 
Signed-off-by: Jan Vesely 

Added:
libclc/trunk/generic/include/math/clc_tan.h
libclc/trunk/generic/lib/math/clc_sw_unary.inc
libclc/trunk/generic/lib/math/clc_tan.cl
Removed:
libclc/trunk/generic/lib/math/tan.inc
Modified:
libclc/trunk/generic/lib/SOURCES
libclc/trunk/generic/lib/math/sincosD_piby4.h
libclc/trunk/generic/lib/math/sincos_helpers.cl
libclc/trunk/generic/lib/math/sincos_helpers.h
libclc/trunk/generic/lib/math/tan.cl

Added: libclc/trunk/generic/include/math/clc_tan.h
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/math/clc_tan.h?rev=322979&view=auto
==
--- libclc/trunk/generic/include/math/clc_tan.h (added)
+++ libclc/trunk/generic/include/math/clc_tan.h Fri Jan 19 10:57:19 2018
@@ -0,0 +1,5 @@
+#define __CLC_FUNCTION __clc_tan
+#define __CLC_BODY 
+#include 
+#undef __CLC_BODY
+#undef __CLC_FUNCTION

Modified: libclc/trunk/generic/lib/SOURCES
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/SOURCES?rev=322979&r1=322978&r2=322979&view=diff
==
--- libclc/trunk/generic/lib/SOURCES (original)
+++ libclc/trunk/generic/lib/SOURCES Fri Jan 19 10:57:19 2018
@@ -164,6 +164,7 @@ math/sinh.cl
 math/sinpi.cl
 math/clc_sqrt.cl
 math/sqrt.cl
+math/clc_tan.cl
 math/tan.cl
 math/tanh.cl
 math/tgamma.cl

Added: libclc/trunk/generic/lib/math/clc_sw_unary.inc
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/clc_sw_unary.inc?rev=322979&view=auto
==
--- libclc/trunk/generic/lib/math/clc_sw_unary.inc (added)
+++ libclc/trunk/generic/lib/math/clc_sw_unary.inc Fri Jan 19 10:57:19 2018
@@ -0,0 +1,9 @@
+#include 
+
+#define __CLC_SW_FUNC(x) __CLC_CONCAT(__clc_, x)
+
+_CLC_OVERLOAD _CLC_DEF __CLC_GENTYPE __CLC_FUNC(__CLC_GENTYPE x) {
+  return __CLC_SW_FUNC(__CLC_FUNC)(x);
+}
+
+#undef __CLC_SW_FUNC

Added: libclc/trunk/generic/lib/math/clc_tan.cl
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/clc_tan.cl?rev=322979&view=auto
==
--- libclc/trunk/generic/lib/math/clc_tan.cl (added)
+++ libclc/trunk/generic/lib/math/clc_tan.cl Fri Jan 19 10:57:19 2018
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2014 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to 
deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#include 
+
+#include "math.h"
+#include "sincos_helpers.h"
+#include "../clcmacro.h"
+#include "tables.h"
+
+_CLC_DEF _CLC_OVERLOAD float __clc_tan(float x)
+{
+int ix = as_int(x);
+int ax = ix & 0x7fff;
+float dx = as_float(ax);
+
+float r0, r1;
+int regn = __clc_argReductionS(&r0, &r1, dx);
+
+float t = __clc_tanf_piby4(r0 + r1, regn);
+t = as_float(as_int(t) ^ (ix ^ ax));
+
+t = ax >= PINFBITPATT_SP32 ? as_float(QNANBITPATT_SP32) : t;
+//Take care of subnormals
+t = (x == 0.0f) ? x : t;
+return t;
+}
+_CLC_UNARY_VECTORIZE(_CLC_DEF _CLC_OVERLOAD, float, __clc_tan, float);
+
+#ifdef cl_khr_fp64
+#include "sincosD_piby4.h"
+
+_CLC_DEF _CLC_OVERLOAD double __clc_tan(double x)
+{
+double y = fabs(x);
+
+double r, rr;
+int regn;
+
+if (y < 0x1.0p+30)
+__clc_remainder_piby2_medium(y, &r, &rr, ®n);
+else
+__clc_remainder_piby2_large(y, &r, &rr, ®n);
+
+double2 tt = __clc_tan_piby4(r, rr);
+
+int2 t = as_int2(regn & 1 ? tt.y : tt.x);
+t.hi ^= (x < 0.0) << 31;
+
+return isnan(x)

[libclc] r322980 - tanpi: Port from amd_builtins

2018-01-19 Thread Jan Vesely via cfe-commits
Author: jvesely
Date: Fri Jan 19 10:57:22 2018
New Revision: 322980

URL: http://llvm.org/viewvc/llvm-project?rev=322980&view=rev
Log:
tanpi: Port from amd_builtins

Passes piglit on turks and carrizo.
Passes CTS on carrizo.

Acked-By: Aaron Watry 
Tested-By: Aaron Watry 
Signed-off-by: Jan Vesely 

Added:
libclc/trunk/generic/include/clc/math/tanpi.h
libclc/trunk/generic/include/math/clc_tanpi.h
libclc/trunk/generic/lib/math/clc_tanpi.cl
libclc/trunk/generic/lib/math/tanpi.cl
Modified:
libclc/trunk/generic/include/clc/clc.h
libclc/trunk/generic/lib/SOURCES

Modified: libclc/trunk/generic/include/clc/clc.h
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/clc/clc.h?rev=322980&r1=322979&r2=322980&view=diff
==
--- libclc/trunk/generic/include/clc/clc.h (original)
+++ libclc/trunk/generic/include/clc/clc.h Fri Jan 19 10:57:22 2018
@@ -111,6 +111,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 

Added: libclc/trunk/generic/include/clc/math/tanpi.h
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/clc/math/tanpi.h?rev=322980&view=auto
==
--- libclc/trunk/generic/include/clc/math/tanpi.h (added)
+++ libclc/trunk/generic/include/clc/math/tanpi.h Fri Jan 19 10:57:22 2018
@@ -0,0 +1,7 @@
+#define __CLC_BODY 
+#define __CLC_FUNCTION tanpi
+
+#include 
+
+#undef __CLC_BODY
+#undef __CLC_FUNCTION

Added: libclc/trunk/generic/include/math/clc_tanpi.h
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/include/math/clc_tanpi.h?rev=322980&view=auto
==
--- libclc/trunk/generic/include/math/clc_tanpi.h (added)
+++ libclc/trunk/generic/include/math/clc_tanpi.h Fri Jan 19 10:57:22 2018
@@ -0,0 +1,5 @@
+#define __CLC_FUNCTION __clc_tanpi
+#define __CLC_BODY 
+#include 
+#undef __CLC_BODY
+#undef __CLC_FUNCTION

Modified: libclc/trunk/generic/lib/SOURCES
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/SOURCES?rev=322980&r1=322979&r2=322980&view=diff
==
--- libclc/trunk/generic/lib/SOURCES (original)
+++ libclc/trunk/generic/lib/SOURCES Fri Jan 19 10:57:22 2018
@@ -167,6 +167,8 @@ math/sqrt.cl
 math/clc_tan.cl
 math/tan.cl
 math/tanh.cl
+math/clc_tanpi.cl
+math/tanpi.cl
 math/tgamma.cl
 misc/shuffle.cl
 misc/shuffle2.cl

Added: libclc/trunk/generic/lib/math/clc_tanpi.cl
URL: 
http://llvm.org/viewvc/llvm-project/libclc/trunk/generic/lib/math/clc_tanpi.cl?rev=322980&view=auto
==
--- libclc/trunk/generic/lib/math/clc_tanpi.cl (added)
+++ libclc/trunk/generic/lib/math/clc_tanpi.cl Fri Jan 19 10:57:22 2018
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2014 Advanced Micro Devices, Inc.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to 
deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+#include 
+
+#include "math.h"
+#include "sincos_helpers.h"
+#include "../clcmacro.h"
+#include "tables.h"
+
+_CLC_DEF _CLC_OVERLOAD float __clc_tanpi(float x)
+{
+int ix = as_int(x);
+int xsgn = ix & 0x8000;
+int xnsgn = xsgn ^ 0x8000;
+ix ^= xsgn;
+float ax = as_float(ix);
+int iax = (int)ax;
+float r = ax - iax;
+int xodd = xsgn ^ (iax & 0x1 ? 0x8000 : 0);
+
+// Initialize with return for +-Inf and NaN
+int ir = 0x7fc0;
+
+// 2^24 <= |x| < Inf, the result is always even integer
+ir = ix < 0x7f80 ? xsgn : ir;
+
+// 2^23 <= |x| < 2^24, the result is always integer
+ir = ix < 0x4b80 ? xodd : ir;
+
+// 0x1.0p-7 <= |x| < 2^23, result depends on which 0.25 interval
+
+// r < 1.0
+float a = 1.0f - r;
+int e = 0;
+int s = xnsgn;
+
+// r <= 0.75
+int c = r <= 0.75f;
+a = c ? 

[PATCH] D42213: [ASTMatchers] [NFC] Fix code examples

2018-01-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In https://reviews.llvm.org/D42213#982047, @MaskRay wrote:

> In https://reviews.llvm.org/D42213#981700, @aaron.ballman wrote:
>
> > The documentation needs to be regenerated for this patch. One thing that 
> > seems to be inconsistent is with the "what gets matched" messages is that 
> > sometimes it includes extra adornments like curly braces and other times it 
> > does not. It might be good to pick a style and try to be more consistent 
> > with it.
>
>
> Do I need to do anything to re-generate the doc and check it into this 
> revision? If so, can you show me the Doxygen generation instruction?


Yes, the documentation for this is something that has to be generated manually. 
You should just have to execute clang/docs/tools/dump_ast_matchers.py to 
regenerate the documentation.

> Reverted some changes as they may cause confusion which are pointed by you.

Thanks! I found one more minor nit with some example code, but this basically 
looks good aside from the documentation bit.




Comment at: include/clang/ASTMatchers/ASTMatchers.h:803
 ///
-///   template f() {};
+///   template void f() {};
 ///   void func() { f(); };

Spurious semi-colon in the declaration.


Repository:
  rC Clang

https://reviews.llvm.org/D42213



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


[PATCH] D41623: [cmake] [libcxxabi] Fix path problems when cross compiling.

2018-01-19 Thread Petr Hosek via Phabricator via cfe-commits
phosek added a comment.

Isn't `NO_DEFAULT_PATH` more appropriate here? That's what libc++ uses as well.


Repository:
  rCXXA libc++abi

https://reviews.llvm.org/D41623



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


[PATCH] D42300: [Analyzer] Add PreStmt and PostStmt callbacks for OffsetOfExpr

2018-01-19 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

The patch seems correct, but i suspect that your overall approach to the 
checker you're trying to make is not ideal. `offsetof` returns a concrete value 
(because, well, symbolic `offsetof`s are not yet supported in the analyzer), 
and even if you see the concrete value, you'd be unable to track it, because 
when you get another concrete value with the same integer inside, you won't be 
able to easily figure out if its the same value or a different value. My 
intuition suggests that this checker shouldn't be path-sensitive; our 
path-sensitive analysis does very little to help you with this particular 
checker, and you might end up with a much easier and more reliable checker if 
you turn it into a simple AST visitor or an AST matcher. Just a heads up.


Repository:
  rC Clang

https://reviews.llvm.org/D42300



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


[PATCH] D42073: [clangd] Use accessible scopes to query indexes for global code completion.

2018-01-19 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

I think this mostly does the right thing, but I find some of the code 
structure/description confusing.
I might have made misguided comments, happy to sit down together and work this 
out :-)




Comment at: clangd/CodeComplete.cpp:316
+
+/// \brief Scopes being queried in indexes for the qualified-id code completion
+/// (e.g. "ns::ab^").

This comment is a bit confusing.
If this struct is trying to model "what we're going to  query the index for" 
then it's not needed - just use vector.
If it's trying to model the context of the identifier we're completing, then 
this comment is inaccurate and should be something like `The namespace context 
of the partial identifier we're trying to complete.`
Then add something like `We use this when querying the index for more results.`



Comment at: clangd/CodeComplete.cpp:316
+
+/// \brief Scopes being queried in indexes for the qualified-id code completion
+/// (e.g. "ns::ab^").

sammccall wrote:
> This comment is a bit confusing.
> If this struct is trying to model "what we're going to  query the index for" 
> then it's not needed - just use vector.
> If it's trying to model the context of the identifier we're completing, then 
> this comment is inaccurate and should be something like `The namespace 
> context of the partial identifier we're trying to complete.`
> Then add something like `We use this when querying the index for more 
> results.`
nit: avoid \brief where possible - the first sentence is used by default.



Comment at: clangd/CodeComplete.cpp:319
+//
+// FIXME: we might want to make Sema code completion smarter on handling
+// unresolved qualified-id completion.

it's not totally clear to me whether you're talking about *our* sema-based 
results, or the sema infrastructure we're using, or it's a mistake and you mean 
our index code completion.

Maybe just:
  // FIXME: When we resolve part of a scope chain (e.g. 
"known::unknown::ident"), we should
  // expand the known part rather than treating the whole thing as unknown.
I think this should go in the implementation, rather than the type comment.



Comment at: clangd/CodeComplete.cpp:327-328
+// way is to return an unresolved qualifier "ns1::ns2" with all scopes that are
+// accessible in "foo".
+struct QualifiedScopes {
+  // All scopes that are accessible in the completion scope qualifier.

Hmm, you're renamed this from `SpecifiedScope` to `QualifiedScope`. I don't 
understand this name, can you explain what it means?
(SpecifiedScope refers to the scope that the *user* specified when typing)



Comment at: clangd/CodeComplete.cpp:329
+struct QualifiedScopes {
+  // All scopes that are accessible in the completion scope qualifier.
+  //

This is a bit hard to parse, and doesn't seem to describe the "unresolved by 
sema" case in a meaningful way.

What about:
  The scopes we should look in, determined by Sema.
  If the qualifier was fully resolved, we should look for completions in these 
scopes.
  If there is an unresolved part of the qualifier, it should be resolved within 
these scopes.
That way we describe what we aim to do (which is pretty simple), and we can 
document deviations with FIXMEs.



Comment at: clangd/CodeComplete.cpp:334
+  //   scopes (namespace) in the resolved qualifier;
+  //   * unresolved by Sema, global namespace "::" is the only accessible 
scope.
+  //

for this case: why not "the containing namespace and all accessible 
namespaces"? You've implemented that below, and it seems like the right thing 
to do here.




Comment at: clangd/CodeComplete.cpp:340
+  //   "namespace ns {using namespace std;} ns::^" => {"ns", "std"}
+  //   "std::vec^" => {"::"}  // unresolved "std::"
+  std::vector AccessibleScopes;

you seem to have a comment-in-a-comment here.
nit: please line up the => so it forms a table.

I'd like to see an example `"namespace ns { vec^ }" => {"ns", ""}
(I know it's not what the code currently does, but IMO it should!)



Comment at: clangd/CodeComplete.cpp:342
+  std::vector AccessibleScopes;
+  // The scope qualifier that is not resolved in Sema, it is the user-written
+  // qualifiers.

This is ambiguous, does it mean `The suffix of the user-writter qualifiers that 
Sema didn't resolve` or `The full scope qualifier as typed by the user`?
(I'm hoping the former, but not sure).



Comment at: clangd/CodeComplete.cpp:346
+
+  std::vector forIndex() {
+std::vector Results;

this needs a new name. Previously it described one scope, and was being 
formatted to match the index representation.
Now it contains logic to determine the index query, so maybe 
`scopesForIndexQuery()`?



Comment at: clangd/CodeComplete.cpp:348
+std::vecto

[PATCH] D42272: [X86] Add rdpid command line option and intrinsics.

2018-01-19 Thread Craig Topper via Phabricator via cfe-commits
craig.topper updated this revision to Diff 130670.
craig.topper added a comment.

Add doxygen comment


https://reviews.llvm.org/D42272

Files:
  include/clang/Basic/BuiltinsX86.def
  include/clang/Driver/Options.td
  lib/Basic/Targets/X86.cpp
  lib/Basic/Targets/X86.h
  lib/Headers/immintrin.h
  test/CodeGen/rdpid-builtins.c
  test/Driver/x86-target-features.c
  test/Preprocessor/predefined-arch-macros.c
  test/Preprocessor/x86_target_features.c

Index: test/Preprocessor/x86_target_features.c
===
--- test/Preprocessor/x86_target_features.c
+++ test/Preprocessor/x86_target_features.c
@@ -436,3 +436,6 @@
 // VPCLMULQDQNOPCLMUL-NOT: #define __PCLMUL__ 1
 // VPCLMULQDQNOPCLMUL-NOT: #define __VPCLMULQDQ__ 1
 
+// RUN: %clang -target i386-unknown-unknown -march=atom -mrdpid -x c -E -dM -o - %s | FileCheck -match-full-lines --check-prefix=RDPID %s
+
+// RDPID: #define __RDPID__ 1
Index: test/Preprocessor/predefined-arch-macros.c
===
--- test/Preprocessor/predefined-arch-macros.c
+++ test/Preprocessor/predefined-arch-macros.c
@@ -1086,6 +1086,7 @@
 // CHECK_ICL_M32: #define __PKU__ 1
 // CHECK_ICL_M32: #define __POPCNT__ 1
 // CHECK_ICL_M32: #define __PRFCHW__ 1
+// CHECK_ICL_M32: #define __RDPID__ 1
 // CHECK_ICL_M32: #define __RDRND__ 1
 // CHECK_ICL_M32: #define __RDSEED__ 1
 // CHECK_ICL_M32: #define __RTM__ 1
@@ -1141,6 +1142,7 @@
 // CHECK_ICL_M64: #define __PKU__ 1
 // CHECK_ICL_M64: #define __POPCNT__ 1
 // CHECK_ICL_M64: #define __PRFCHW__ 1
+// CHECK_ICL_M64: #define __RDPID__ 1
 // CHECK_ICL_M64: #define __RDRND__ 1
 // CHECK_ICL_M64: #define __RDSEED__ 1
 // CHECK_ICL_M64: #define __RTM__ 1
Index: test/Driver/x86-target-features.c
===
--- test/Driver/x86-target-features.c
+++ test/Driver/x86-target-features.c
@@ -125,3 +125,7 @@
 // VBMI2: "-target-feature" "+avx512vbmi2"
 // NO-VBMI2: "-target-feature" "-avx512vbmi2"
 
+// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mrdpid %s -### -o %t.o 2>&1 | FileCheck -check-prefix=RDPID %s
+// RUN: %clang -target i386-unknown-linux-gnu -march=i386 -mno-rdpid %s -### -o %t.o 2>&1 | FileCheck -check-prefix=NO-RDPID %s
+// RDPID: "-target-feature" "+rdpid"
+// NO-RDPID: "-target-feature" "-rdpid"
Index: test/CodeGen/rdpid-builtins.c
===
--- /dev/null
+++ test/CodeGen/rdpid-builtins.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -ffreestanding -triple x86_64-unknown-unknown -target-feature +rdpid -emit-llvm -o - %s | FileCheck %s
+
+
+#include 
+
+unsigned int test_rdpid_u32(void) {
+// CHECK-LABEL: @test_rdpid_u32
+// CHECK: call i32 @llvm.x86.rdpid
+  return _rdpid_u32();
+}
Index: lib/Headers/immintrin.h
===
--- lib/Headers/immintrin.h
+++ lib/Headers/immintrin.h
@@ -247,6 +247,18 @@
 #include 
 #endif
 
+#if !defined(_MSC_VER) || __has_feature(modules) || defined(__RDPID__)
+/// \brief Returns the value of the IA32_TSC_AUX MSR (0xc103).
+///
+/// \headerfile 
+///
+/// This intrinsic corresponds to the  RDPID  instruction.
+static __inline__ unsigned int __attribute__((__always_inline__, __nodebug__, __target__("rdpid")))
+_rdpid_u32(void) {
+  return __builtin_ia32_rdpid();
+}
+#endif // __RDPID__
+
 #if !defined(_MSC_VER) || __has_feature(modules) || defined(__RDRND__)
 static __inline__ int __attribute__((__always_inline__, __nodebug__, __target__("rdrnd")))
 _rdrand16_step(unsigned short *__p)
Index: lib/Basic/Targets/X86.h
===
--- lib/Basic/Targets/X86.h
+++ lib/Basic/Targets/X86.h
@@ -96,6 +96,7 @@
   bool HasCLWB = false;
   bool HasMOVBE = false;
   bool HasPREFETCHWT1 = false;
+  bool HasRDPID = false;
 
   /// \brief Enumeration of all of the X86 CPUs supported by Clang.
   ///
Index: lib/Basic/Targets/X86.cpp
===
--- lib/Basic/Targets/X86.cpp
+++ lib/Basic/Targets/X86.cpp
@@ -160,6 +160,7 @@
 setFeatureEnabledImpl(Features, "avx512vnni", true);
 setFeatureEnabledImpl(Features, "avx512vbmi2", true);
 setFeatureEnabledImpl(Features, "avx512vpopcntdq", true);
+setFeatureEnabledImpl(Features, "rdpid", true);
 LLVM_FALLTHROUGH;
   case CK_Cannonlake:
 setFeatureEnabledImpl(Features, "avx512ifma", true);
@@ -784,6 +785,8 @@
   HasPREFETCHWT1 = true;
 } else if (Feature == "+clzero") {
   HasCLZERO = true;
+} else if (Feature == "+rdpid") {
+  HasRDPID = true;
 }
 
 X86SSEEnum Level = llvm::StringSwitch(Feature)
@@ -1125,6 +1128,8 @@
 Builder.defineMacro("__PREFETCHWT1__");
   if (HasCLZERO)
 Builder.defineMacro("__CLZERO__");
+  if (HasRDPID)
+Builder.defineMacro("__RDPID__");
 
   // Each case falls through to the previous one here.
   switch (SS

r322982 - [X86] Add goldmont to test/Driver/x86-march.c

2018-01-19 Thread Craig Topper via cfe-commits
Author: ctopper
Date: Fri Jan 19 11:43:36 2018
New Revision: 322982

URL: http://llvm.org/viewvc/llvm-project?rev=322982&view=rev
Log:
[X86] Add goldmont to test/Driver/x86-march.c

Modified:
cfe/trunk/test/Driver/x86-march.c

Modified: cfe/trunk/test/Driver/x86-march.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/x86-march.c?rev=322982&r1=322981&r2=322982&view=diff
==
--- cfe/trunk/test/Driver/x86-march.c (original)
+++ cfe/trunk/test/Driver/x86-march.c Fri Jan 19 11:43:36 2018
@@ -76,6 +76,10 @@
 // RUN:   | FileCheck %s -check-prefix=silvermont
 // silvermont: "-target-cpu" "silvermont"
 //
+// RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=goldmont 2>&1 \
+// RUN:   | FileCheck %s -check-prefix=goldmont
+// goldmont: "-target-cpu" "goldmont"
+//
 // RUN: %clang -target x86_64-unknown-unknown -c -### %s -march=k8 2>&1 \
 // RUN:   | FileCheck %s -check-prefix=k8
 // k8: "-target-cpu" "k8"


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


[PATCH] D42273: Add hasTrailingReturn AST matcher

2018-01-19 Thread Julie Hockett via Phabricator via cfe-commits
juliehockett updated this revision to Diff 130671.
juliehockett marked 2 inline comments as done.
juliehockett added a comment.

Updating matcher and fixing semicolons


https://reviews.llvm.org/D42273

Files:
  docs/LibASTMatchersReference.html
  include/clang/ASTMatchers/ASTMatchers.h
  lib/ASTMatchers/Dynamic/Registry.cpp
  unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp


Index: unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2112,5 +2112,15 @@
   EXPECT_TRUE(notMatches("enum X {};", enumDecl(isScoped(;
 }
 
+TEST(HasTrailingReturn, MatchesTrailingReturn) {
+  EXPECT_TRUE(matches("auto Y() -> int {}",
+  functionDecl(hasTrailingReturn(;
+  EXPECT_TRUE(matches(
+  "auto lambda2 = [](double x, double y) -> double {return x + y;};",
+  functionDecl(hasTrailingReturn(;
+  EXPECT_TRUE(notMatches("int X() {}", functionDecl(hasTrailingReturn(;
+  EXPECT_TRUE(notMatches("void X();", functionDecl(hasTrailingReturn(;
+}
+
 } // namespace ast_matchers
 } // namespace clang
Index: lib/ASTMatchers/Dynamic/Registry.cpp
===
--- lib/ASTMatchers/Dynamic/Registry.cpp
+++ lib/ASTMatchers/Dynamic/Registry.cpp
@@ -296,6 +296,7 @@
   REGISTER_MATCHER(hasTemplateArgument);
   REGISTER_MATCHER(hasThen);
   REGISTER_MATCHER(hasThreadStorageDuration);
+  REGISTER_MATCHER(hasTrailingReturn);
   REGISTER_MATCHER(hasTrueExpression);
   REGISTER_MATCHER(hasTypeLoc);
   REGISTER_MATCHER(hasUnaryOperand);
Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -5891,6 +5891,19 @@
   return Node.isScoped();
 }
 
+/// \brief Matches a function declared with a trailing return type.
+///
+/// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
+/// \code
+/// int X() {};
+/// auto Y() -> int {};
+/// \endcode
+AST_MATCHER(FunctionDecl, hasTrailingReturn) {
+  if (const auto *F = Node.getType()->getAs())
+return F->hasTrailingReturn();
+  return false;
+}
+
 } // namespace ast_matchers
 } // namespace clang
 
Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -2749,6 +2749,15 @@
 
 
 
+MatcherFunctionDecl>hasTrailingReturn
+Matches a 
function declared with a trailing return type.
+
+Example matches Y (matcher = functionDecl(hasTrailingReturn()))
+int X() {};
+auto Y() -> int {};
+
+
+
 MatcherFunctionDecl>isConstexpr
 Matches constexpr 
variable and function declarations.
 


Index: unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2112,5 +2112,15 @@
   EXPECT_TRUE(notMatches("enum X {};", enumDecl(isScoped(;
 }
 
+TEST(HasTrailingReturn, MatchesTrailingReturn) {
+  EXPECT_TRUE(matches("auto Y() -> int {}",
+  functionDecl(hasTrailingReturn(;
+  EXPECT_TRUE(matches(
+  "auto lambda2 = [](double x, double y) -> double {return x + y;};",
+  functionDecl(hasTrailingReturn(;
+  EXPECT_TRUE(notMatches("int X() {}", functionDecl(hasTrailingReturn(;
+  EXPECT_TRUE(notMatches("void X();", functionDecl(hasTrailingReturn(;
+}
+
 } // namespace ast_matchers
 } // namespace clang
Index: lib/ASTMatchers/Dynamic/Registry.cpp
===
--- lib/ASTMatchers/Dynamic/Registry.cpp
+++ lib/ASTMatchers/Dynamic/Registry.cpp
@@ -296,6 +296,7 @@
   REGISTER_MATCHER(hasTemplateArgument);
   REGISTER_MATCHER(hasThen);
   REGISTER_MATCHER(hasThreadStorageDuration);
+  REGISTER_MATCHER(hasTrailingReturn);
   REGISTER_MATCHER(hasTrueExpression);
   REGISTER_MATCHER(hasTypeLoc);
   REGISTER_MATCHER(hasUnaryOperand);
Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -5891,6 +5891,19 @@
   return Node.isScoped();
 }
 
+/// \brief Matches a function declared with a trailing return type.
+///
+/// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
+/// \code
+/// int X() {};
+/// auto Y() -> int {};
+/// \endcode
+AST_MATCHER(FunctionDecl, hasTrailingReturn) {
+  if (const auto *F = Node.getType()->getAs())
+return F->hasTrailingReturn();
+  return false;
+}
+
 } // namespace ast_matc

[PATCH] D42310: Formalize FreeBSD support of compiler rt

2018-01-19 Thread Tom Rix via Phabricator via cfe-commits
trixirt created this revision.
trixirt added reviewers: emaste, filcab, rsmith.
Herald added subscribers: cfe-commits, krytarowski.

FreeBSD's libgcc and libgcc_p are symlinks to libcompiler_rt and 
libcompiler_rt_p
Start using the compiler rt libs directly.


Repository:
  rC Clang

https://reviews.llvm.org/D42310

Files:
  lib/Driver/ToolChains/CommonArgs.cpp
  lib/Driver/ToolChains/FreeBSD.cpp
  lib/Driver/ToolChains/FreeBSD.h
  test/Driver/freebsd.c

Index: test/Driver/freebsd.c
===
--- test/Driver/freebsd.c
+++ test/Driver/freebsd.c
@@ -4,23 +4,38 @@
 // RUN:   | FileCheck --check-prefix=CHECK-ARM64 %s
 // CHECK-ARM64: "-cc1" "-triple" "aarch64-pc-freebsd11"
 // CHECK-ARM64: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]"
-// CHECK-ARM64: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "{{.*}}crtend.o" "{{.*}}crtn.o"
+// CHECK-ARM64: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lcompiler_rt" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lcompiler_rt" "--as-needed" "-lgcc_s" "--no-as-needed" "{{.*}}crtend.o" "{{.*}}crtn.o"
+// RUN: %clang -no-canonical-prefixes \
+// RUN:   -target aarch64-pc-freebsd11 %s  \
+// RUN:   --sysroot=%S/Inputs/basic_freebsd64_tree -### -pg 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-ARM64_PG %s
+// CHECK-ARM64_PG: "-cc1" "-triple" "aarch64-pc-freebsd11"
+// CHECK-ARM64_PG: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]"
+// CHECK-ARM64_PG: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lcompiler_rt_p" "-lgcc_eh_p" "-lc_p" "-lcompiler_rt_p" "-lgcc_eh_p" "{{.*}}crtend.o" "{{.*}}crtn.o"
+//
+// RUN: %clang -no-canonical-prefixes \
+// RUN:   -target aarch64-pc-freebsd11 %s  \
+// RUN:   --sysroot=%S/Inputs/basic_freebsd64_tree -### -pg -static 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-ARM64_PG_STATIC %s
+// CHECK-ARM64_PG_STATIC: "-cc1" "-triple" "aarch64-pc-freebsd11"
+// CHECK-ARM64_PG_STATIC: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]"
+// CHECK-ARM64_PG_STATIC: "--eh-frame-hdr" "-Bstatic" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbeginT.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lcompiler_rt_p" "-lgcc_eh" "-lc_p" "-lcompiler_rt_p" "-lgcc_eh" "{{.*}}crtend.o" "{{.*}}crtn.o"
 //
 // RUN: %clang -no-canonical-prefixes \
 // RUN:   -target powerpc-pc-freebsd8 %s\
 // RUN:   --sysroot=%S/Inputs/basic_freebsd_tree -### 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPC %s
 // CHECK-PPC: "-cc1" "-triple" "powerpc-pc-freebsd8"
 // CHECK-PPC: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]"
-// CHECK-PPC: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "{{.*}}crtend.o" "{{.*}}crtn.o"
+// CHECK-PPC: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lcompiler_rt" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lcompiler_rt" "--as-needed" "-lgcc_s" "--no-as-needed" "{{.*}}crtend.o" "{{.*}}crtn.o"
 //
 // RUN: %clang -no-canonical-prefixes \
 // RUN:   -target powerpc64-pc-freebsd8 %s  \
 // RUN:   --sysroot=%S/Inputs/basic_freebsd64_tree -### 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PPC64 %s
 // CHECK-PPC64: "-cc1" "-triple" "powerpc64-pc-freebsd8"
 // CHECK-PPC64: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]"
-// CHECK-PPC64: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "{{.*}}crtend.o" "{{.*}}crtn.o"
+// CHECK-PPC64: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lcompiler_rt" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lcompiler_rt" "--as-needed" "-lgcc_s" "--no-as-needed" "{{.*}}crtend.o" "{{.*}}crtn.o"
 //
 //
 // Check that -m32 properly adjusts the toolchain flags.
Index: lib/Driver/ToolChains/FreeBSD.h
===
--- lib/Driver/ToolChains/FreeBSD.h
+++ lib/Driver/ToolChains/FreeBSD.h
@@ -74,7 +74,7 @@
   // Until dtrace (via CTF) and LLDB can deal with distributed debug info,
   // FreeBSD defaults to standalone/full de

[PATCH] D42213: [ASTMatchers] [NFC] Fix code examples

2018-01-19 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 130672.
MaskRay added a comment.

Address comment


Repository:
  rC Clang

https://reviews.llvm.org/D42213

Files:
  include/clang/ASTMatchers/ASTMatchers.h

Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -800,7 +800,7 @@
 ///   A b;
 ///   A c;
 ///
-///   template f() {};
+///   template void f() {}
 ///   void func() { f(); };
 /// \endcode
 /// classTemplateSpecializationDecl(hasTemplateArgument(
@@ -880,12 +880,12 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
-///   struct B { B* next; };
+///   struct B { int next; };
+///   template struct A {};
 ///   A<&B::next> a;
 /// \endcode
 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
-/// refersToDeclaration(fieldDecl(hasName("next"
+/// refersToDeclaration(fieldDecl(hasName("next")
 ///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
 /// \c B::next
 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
@@ -899,8 +899,8 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
-///   struct B { B* next; };
+///   struct B { int next; };
+///   template struct A {};
 ///   A<&B::next> a;
 /// \endcode
 /// templateSpecializationType(hasAnyTemplateArgument(
@@ -917,7 +917,7 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
+///   template struct C {};
 ///   C<42> c;
 /// \endcode
 /// classTemplateSpecializationDecl(
@@ -932,7 +932,7 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
+///   template struct C {};
 ///   C<42> c;
 /// \endcode
 /// classTemplateSpecializationDecl(
@@ -953,7 +953,7 @@
 ///
 /// Given
 /// \code
-///   template struct A {};
+///   template struct C {};
 ///   C<42> c;
 /// \endcode
 /// classTemplateSpecializationDecl(
@@ -1523,12 +1523,12 @@
 /// \code
 ///   T u(f());
 ///   g(f());
-/// \endcode
-/// but does not match
-/// \code
-///   f();
 ///   f().func();
 /// \endcode
+/// but does not match
+/// \code
+///   f();
+/// \endcode
 extern const internal::VariadicDynCastAllOfMatcher
 materializeTemporaryExpr;
@@ -1799,7 +1799,7 @@
 ///   switch(a) { case 42: break; default: break; }
 /// \endcode
 /// switchCase()
-///   matches 'case 42: break;' and 'default: break;'.
+///   matches 'case 42:' and 'default:'.
 extern const internal::VariadicDynCastAllOfMatcher switchCase;
 
 /// \brief Matches case statements inside switch statements.
@@ -1809,7 +1809,7 @@
 ///   switch(a) { case 42: break; default: break; }
 /// \endcode
 /// caseStmt()
-///   matches 'case 42: break;'.
+///   matches 'case 42:'.
 extern const internal::VariadicDynCastAllOfMatcher caseStmt;
 
 /// \brief Matches default statements inside switch statements.
@@ -1819,13 +1819,13 @@
 ///   switch(a) { case 42: break; default: break; }
 /// \endcode
 /// defaultStmt()
-///   matches 'default: break;'.
+///   matches 'default:'.
 extern const internal::VariadicDynCastAllOfMatcher
 defaultStmt;
 
 /// \brief Matches compound statements.
 ///
-/// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
+/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
 /// \code
 ///   for (;;) {{}}
 /// \endcode
@@ -2502,11 +2502,12 @@
 /// \brief Matches AST nodes that have child AST nodes that match the
 /// provided matcher.
 ///
-/// Example matches X, Y
+/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
 ///   (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
 /// \code
-///   class X {};  // Matches X, because X::X is a class of name X inside X.
-///   class Y { class X {}; };
+///   class X {};
+///   class Y { class X {}; };  // Matches Y, because Y::X is a class of name X
+/// // inside Y.
 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
 /// \endcode
 ///
@@ -2522,11 +2523,12 @@
 /// \brief Matches AST nodes that have descendant AST nodes that match the
 /// provided matcher.
 ///
-/// Example matches X, A, B, C
+/// Example matches X, A, A::X, B, B::C, B::C::X
 ///   (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")
 /// \code
-///   class X {};  // Matches X, because X::X is a class of name X inside X.
-///   class A { class X {}; };
+///   class X {};
+///   class A { class X {}; };  // Matches A, because A::X is a class of name
+/// // X inside A.
 ///   class B { class C { class X {}; }; };
 /// \endcode
 ///
@@ -2681,7 +2683,7 @@
 ///   (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))
 /// \code
 ///   class Y { public: void x(); };
-///   void z() { Y y; y.x(); }",
+///   void z() { Y y; y.x(); }
 /// \endcode
 ///
 /// FIXME: Overload to allow directly matching types?
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42273: Add hasTrailingReturn AST matcher

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

LGTM with a minor commenting/documentation nit.




Comment at: include/clang/ASTMatchers/ASTMatchers.h:5898
+/// \code
+/// int X() {};
+/// auto Y() -> int {};

Sorry for not noticing this earlier -- spurious semicolon here (don't forget to 
regenerate the docs too).


https://reviews.llvm.org/D42273



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


[PATCH] D42273: Add hasTrailingReturn AST matcher

2018-01-19 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: include/clang/ASTMatchers/ASTMatchers.h:5904
+return F->hasTrailingReturn();
+  return false;
+}

There are no negative tests in the unittest that cover this false path.


https://reviews.llvm.org/D42273



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


[PATCH] D42213: [ASTMatchers] [NFC] Fix code examples

2018-01-19 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

I am also not sure about this function:  line 3548

  /// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a
  /// specific parameter count.
  ///
  /// Given
  /// \code
  ///   void f(int i) {}
  ///   void g(int i, int j) {}
  ///   void h(int i, int j);
  ///   void j(int i);
  ///   void k(int x, int y, int z, ...);
  /// \endcode
  /// functionDecl(parameterCountIs(2))
  ///   matches void g(int i, int j) {}
  /// functionProtoType(parameterCountIs(2))
  ///   matches void h(int i, int j)
  /// functionProtoType(parameterCountIs(3))
  ///   matches void k(int x, int y, int z, ...);
  AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
FunctionProtoType),
  }

Both `functionDecl` and `functionProtoType` match these functions as long as 
the parameter count is matched.

  % echo 'match functionDecl()'|clang-query =(printf 'void f(){}') -- -xc++
  % echo 'match functionProtoType()'|clang-query =(printf 'void f(){}') -- -xc++


Repository:
  rC Clang

https://reviews.llvm.org/D42213



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


[PATCH] D42213: [ASTMatchers] [NFC] Fix code examples

2018-01-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In https://reviews.llvm.org/D42213#982256, @MaskRay wrote:

> I am also not sure about this function:  line 3548
>
>   /// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a
>   /// specific parameter count.
>   ///
>   /// Given
>   /// \code
>   ///   void f(int i) {}
>   ///   void g(int i, int j) {}
>   ///   void h(int i, int j);
>   ///   void j(int i);
>   ///   void k(int x, int y, int z, ...);
>   /// \endcode
>   /// functionDecl(parameterCountIs(2))
>   ///   matches void g(int i, int j) {}
>   /// functionProtoType(parameterCountIs(2))
>   ///   matches void h(int i, int j)
>   /// functionProtoType(parameterCountIs(3))
>   ///   matches void k(int x, int y, int z, ...);
>   AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
> AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
> 
> FunctionProtoType),
>   }
>
>
> Both `functionDecl` and `functionProtoType` match these functions as long as 
> the parameter count is matched.
>
>   % echo 'match functionDecl()'|clang-query =(printf 'void f(){}') -- -xc++
>   % echo 'match functionProtoType()'|clang-query =(printf 'void f(){}') -- 
> -xc++
>


I'm not certain I'm following along. The quoted matcher is for 
`parameterCountIs()`, but the test code you've posted doesn't use that matcher. 
However, the quoted comment seems like it's wrong: 
`functionDecl(parameterCountIs(2))` should match both g() and h(), not just 
g(), I believe.


Repository:
  rC Clang

https://reviews.llvm.org/D42213



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


[PATCH] D41623: [cmake] [libcxxabi] Fix path problems when cross compiling.

2018-01-19 Thread Don Hinton via Phabricator via cfe-commits
hintonda added a comment.

In https://reviews.llvm.org/D41623#982189, @phosek wrote:

> Isn't `NO_DEFAULT_PATH` more appropriate here? That's what libc++ uses as 
> well.


Unfortunately no.

When cross compiling, it's important to look for headers in CMAKE_SYSROOT 
and/or CMAKE_FIND_ROOT_PATH, or you'll end up finding for headers on the host, 
not the target.  To make sure this works as expected, cmake recommends using 
`set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)` -- see 
https://cmake.org/Wiki/CMake_Cross_Compiling for details.

With `CMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY` and `CMAKE_SYSROOT` set, all 
`find_XXX()` commands will add the `CMAKE_SYSROOT` prefix to all the paths used 
in the search.  So, if you are trying to look in a local source directory, 
you'll never find it, because `find_XXX()` will actually use 
`${CMAKE_SYSROOT}/`, which is always the wrong place.

These `find_path()` invocations are looking in specific places which exist on 
the host system, not the target system.


Repository:
  rCXXA libc++abi

https://reviews.llvm.org/D41623



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


[PATCH] D41976: Low-hanging fruit optimization in string::__move_assign().

2018-01-19 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists accepted this revision.
mclow.lists added a comment.
This revision is now accepted and ready to land.

This looks good to me.
Please add a test in test/libcxx/strings/string.modifiers and commit.

Something like this:

  #include 
  #include 
  
  int main () {
  std::string l = "This makes this a long string, I hope; just rambling on 
and on...";
  std::string s = "short";
  assert(l.__invariants());
  assert(s.__invariants());
  
  s.__clear_and_shrink();
  assert(s.__invariants());
  assert(s.size() == 0);
  
  l.__clear_and_shrink();
  assert(l.__invariants());
  assert(l.size() == 0);
  }


https://reviews.llvm.org/D41976



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


[PATCH] D42017: Link sanitized programs on NetBSD with -lkvm

2018-01-19 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka accepted this revision.
vitalybuka added a comment.
This revision is now accepted and ready to land.

LGTM, but please update the summary and git/svn patch description


Repository:
  rL LLVM

https://reviews.llvm.org/D42017



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


[PATCH] D42017: Link sanitized programs on NetBSD with -lkvm

2018-01-19 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka requested changes to this revision.
vitalybuka added a comment.
This revision now requires changes to proceed.

Please update the summary. No need to define kvm. Probably just few example of 
essential functions needed by sanitizers.


Repository:
  rL LLVM

https://reviews.llvm.org/D42017



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


[PATCH] D41623: [cmake] [libcxxabi] Fix path problems when cross compiling.

2018-01-19 Thread Don Hinton via Phabricator via cfe-commits
hintonda added a comment.

In https://reviews.llvm.org/D41623#982262, @hintonda wrote:

> In https://reviews.llvm.org/D41623#982189, @phosek wrote:
>
> > Isn't `NO_DEFAULT_PATH` more appropriate here? That's what libc++ uses as 
> > well.
>
>
> Unfortunately no.
>
> When cross compiling, it's important to look for headers in CMAKE_SYSROOT 
> and/or CMAKE_FIND_ROOT_PATH, or you'll end up finding for headers on the 
> host, not the target.  To make sure this works as expected, cmake recommends 
> using `set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)` -- see 
> https://cmake.org/Wiki/CMake_Cross_Compiling for details.
>
> With `CMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY` and `CMAKE_SYSROOT` set, all 
> `find_XXX()` commands will add the `CMAKE_SYSROOT` prefix to all the paths 
> used in the search.  So, if you are trying to look in a local source 
> directory, you'll never find it, because `find_XXX()` will actually use 
> `${CMAKE_SYSROOT}/`, which is always the wrong place.
>
> These `find_path()` invocations are looking in specific places which exist on 
> the host system, not the target system.


Btw, I'm not saying don't use `NO_DEFAULT_PATH` where appropriate, just that 
`NO_CMAKE_FIND_ROOT_PATH` is also required in this case.


Repository:
  rCXXA libc++abi

https://reviews.llvm.org/D41623



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


[PATCH] D42291: [libcxx] Correctly handle invalid regex character class names

2018-01-19 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists accepted this revision.
mclow.lists added a comment.
This revision is now accepted and ready to land.

This looks fine to me. Thanks!




Comment at: test/std/re/re.regex/re.regex.construct/bad_ctype.pass.cpp:28
+} catch (const std::regex_error &ex) {
+result = (ex.code() == std::regex_constants::error_ctype);
+}

I'm a big fan of the "return NOW" style of programming.
But this matches the other tests, so I'm ok with it.
(If I care enough, I'll change them all later)

try { std::regex re(pat); }
catch catch (const std::regex_error &ex) { return ex.code() == 
std::regex_constants::error_ctype; }
return false;




https://reviews.llvm.org/D42291



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


r322984 - Allow BlockDecl in CXXRecord scope to have no access specifier.

2018-01-19 Thread Richard Trieu via cfe-commits
Author: rtrieu
Date: Fri Jan 19 12:46:19 2018
New Revision: 322984

URL: http://llvm.org/viewvc/llvm-project?rev=322984&view=rev
Log:
Allow BlockDecl in CXXRecord scope to have no access specifier.

Using a BlockDecl in a default member initializer causes it to be attached to
CXXMethodDecl without its access specifier being set.  This prevents a crash
where getAccess is called on this BlockDecl, since that method expects any
Decl in CXXRecord scope to have an access specifier.

Added:
cfe/trunk/test/Modules/odr_hash-blocks.cpp
Modified:
cfe/trunk/lib/AST/DeclBase.cpp

Modified: cfe/trunk/lib/AST/DeclBase.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/DeclBase.cpp?rev=322984&r1=322983&r2=322984&view=diff
==
--- cfe/trunk/lib/AST/DeclBase.cpp (original)
+++ cfe/trunk/lib/AST/DeclBase.cpp Fri Jan 19 12:46:19 2018
@@ -891,12 +891,14 @@ bool Decl::AccessDeclContextSanity() con
   // 4. the context is not a record
   // 5. it's invalid
   // 6. it's a C++0x static_assert.
+  // 7. it's a block literal declaration
   if (isa(this) ||
   isa(this) ||
   isa(this) ||
   !isa(getDeclContext()) ||
   isInvalidDecl() ||
   isa(this) ||
+  isa(this) ||
   // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
   // as DeclContext (?).
   isa(this) ||

Added: cfe/trunk/test/Modules/odr_hash-blocks.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Modules/odr_hash-blocks.cpp?rev=322984&view=auto
==
--- cfe/trunk/test/Modules/odr_hash-blocks.cpp (added)
+++ cfe/trunk/test/Modules/odr_hash-blocks.cpp Fri Jan 19 12:46:19 2018
@@ -0,0 +1,119 @@
+// Clear and create directories
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: mkdir %t/cache
+// RUN: mkdir %t/Inputs
+
+// Build first header file
+// RUN: echo "#define FIRST" >> %t/Inputs/first.h
+// RUN: cat %s   >> %t/Inputs/first.h
+
+// Build second header file
+// RUN: echo "#define SECOND" >> %t/Inputs/second.h
+// RUN: cat %s>> %t/Inputs/second.h
+
+// Test that each header can compile
+// RUN: %clang_cc1 -fsyntax-only -x c++ -std=c++11 -fblocks %t/Inputs/first.h
+// RUN: %clang_cc1 -fsyntax-only -x c++ -std=c++11 -fblocks %t/Inputs/second.h
+
+// Build module map file
+// RUN: echo "module FirstModule {" >> %t/Inputs/module.map
+// RUN: echo "header \"first.h\""   >> %t/Inputs/module.map
+// RUN: echo "}">> %t/Inputs/module.map
+// RUN: echo "module SecondModule {">> %t/Inputs/module.map
+// RUN: echo "header \"second.h\""  >> %t/Inputs/module.map
+// RUN: echo "}">> %t/Inputs/module.map
+
+// Run test
+// RUN: %clang_cc1 -fmodules -fimplicit-module-maps \
+// RUN:-fmodules-cache-path=%t/cache -x c++ -I%t/Inputs \
+// RUN:-verify %s -std=c++11 -fblocks
+
+#if !defined(FIRST) && !defined(SECOND)
+#include "first.h"
+#include "second.h"
+#endif
+
+// Used for testing
+#if defined(FIRST)
+#define ACCESS public:
+#elif defined(SECOND)
+#define ACCESS private:
+#endif
+
+// TODO: S1, S2, and S3 should generate errors.
+namespace Blocks {
+#if defined(FIRST)
+struct S1 {
+  void (^block)(int x) = ^(int x) { };
+};
+#elif defined(SECOND)
+struct S1 {
+  void (^block)(int x) = ^(int y) { };
+};
+#else
+S1 s1;
+#endif
+
+#if defined(FIRST)
+struct S2 {
+  int (^block)(int x) = ^(int x) { return x + 1; };
+};
+#elif defined(SECOND)
+struct S2 {
+  int (^block)(int x) = ^(int x) { return x; };
+};
+#else
+S2 s2;
+#endif
+
+#if defined(FIRST)
+struct S3 {
+  void run(int (^block)(int x));
+};
+#elif defined(SECOND)
+struct S3 {
+  void run(int (^block)(int x, int y));
+};
+#else
+S3 s3;
+#endif
+
+#define DECLS   \
+  int (^block)(int x) = ^(int x) { return x + x; }; \
+  void run(int (^block)(int x, int y));
+
+#if defined(FIRST) || defined(SECOND)
+struct Valid1 {
+  DECLS
+};
+#else
+Valid1 v1;
+#endif
+
+#if defined(FIRST) || defined(SECOND)
+struct Invalid1 {
+  DECLS
+  ACCESS
+};
+#else
+Invalid1 i1;
+// expected-error@second.h:* {{'Blocks::Invalid1' has different definitions in 
different modules; first difference is definition in module 'SecondModule' 
found private access specifier}}
+// expected-note@first.h:* {{but in 'FirstModule' found public access 
specifier}}
+#endif
+
+#undef DECLS
+}
+
+// Keep macros contained to one file.
+#ifdef FIRST
+#undef FIRST
+#endif
+
+#ifdef SECOND
+#undef SECOND
+#endif
+
+#ifdef ACCESS
+#undef ACCESS
+#endif


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


[PATCH] D42307: [OpenCL][6.0.0 Release] Release notes for OpenCL in Clang

2018-01-19 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks!


https://reviews.llvm.org/D42307



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


[PATCH] D42213: [ASTMatchers] [NFC] Fix code examples

2018-01-19 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In https://reviews.llvm.org/D42213#982261, @aaron.ballman wrote:

> In https://reviews.llvm.org/D42213#982256, @MaskRay wrote:
>
> > I am also not sure about this function:  line 3548
> >
> >   /// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a
> >   /// specific parameter count.
> >   ///
> >   /// Given
> >   /// \code
> >   ///   void f(int i) {}
> >   ///   void g(int i, int j) {}
> >   ///   void h(int i, int j);
> >   ///   void j(int i);
> >   ///   void k(int x, int y, int z, ...);
> >   /// \endcode
> >   /// functionDecl(parameterCountIs(2))
> >   ///   matches void g(int i, int j) {}
> >   /// functionProtoType(parameterCountIs(2))
> >   ///   matches void h(int i, int j)
> >   /// functionProtoType(parameterCountIs(3))
> >   ///   matches void k(int x, int y, int z, ...);
> >   AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
> > AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
> > 
> > FunctionProtoType),
> >   }
> >
> >
> > Both `functionDecl` and `functionProtoType` match these functions as long 
> > as the parameter count is matched.
> >
> >   % echo 'match functionDecl()'|clang-query =(printf 'void f(){}') -- -xc++
> >   % echo 'match functionProtoType()'|clang-query =(printf 'void f(){}') -- 
> > -xc++
> >
>
>
> I'm not certain I'm following along. The quoted matcher is for 
> `parameterCountIs()`, but the test code you've posted doesn't use that 
> matcher. However, the quoted comment seems like it's wrong: 
> `functionDecl(parameterCountIs(2))` should match both g() and h(), not just 
> g(), I believe.


Yes, I was asking about this because the results seemed to be wrong. I should 
have used `parameterCountIs()` to reduce the confusion :) I'll leave them 
untouched.


Repository:
  rC Clang

https://reviews.llvm.org/D42213



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


[clang-tools-extra] r322996 - [clangd] Change index scope convention from "outer::inner" to "outer::inner::"

2018-01-19 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Jan 19 13:58:58 2018
New Revision: 322996

URL: http://llvm.org/viewvc/llvm-project?rev=322996&view=rev
Log:
[clangd] Change index scope convention from "outer::inner" to "outer::inner::"

Global scope is "" (was "")
Top-level namespace scope is "ns::" (was "ns")
Nested namespace scope is "ns::ns::" (was "ns::ns")

This composes more naturally:
 - qname = scope + name
 - full scope = resolved scope + unresolved scope (D42073 was the trigger)
It removes a wart from the old way: "foo::" has one more separator than "".

Another alternative that has these properties is "::ns", but that lacks
the property that both the scope and the name are substrings of the
qname as produced by clang.

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/index/Index.h
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=322996&r1=322995&r2=322996&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Fri Jan 19 13:58:58 2018
@@ -313,7 +313,7 @@ llvm::Optional getSymbolID(con
 /// completion (e.g. "ns::ab?").
 struct SpecifiedScope {
   /// The scope specifier as written. For example, for completion "ns::ab?", 
the
-  /// written scope specifier is "ns".
+  /// written scope specifier is "ns::". Doesn't include leading "::".
   std::string Written;
   // If this scope specifier is recognized in Sema (e.g. as a namespace
   // context), this will be set to the fully qualfied name of the corresponding
@@ -321,8 +321,7 @@ struct SpecifiedScope {
   std::string Resolved;
 
   llvm::StringRef forIndex() {
-llvm::StringRef Chosen = Resolved.empty() ? Written : Resolved;
-return Chosen.trim(':');
+return Resolved.empty() ? Written.ltrim('::') : Resolved;
   }
 };
 
@@ -631,15 +630,14 @@ SpecifiedScope getSpecifiedScope(Sema &S
   auto SpecifierRange = SS.getRange();
   Info.Written = Lexer::getSourceText(
   CharSourceRange::getCharRange(SpecifierRange), SM, clang::LangOptions());
+  if (!Info.Written.empty())
+Info.Written += "::"; // Sema excludes the trailing ::.
   if (SS.isValid()) {
 DeclContext *DC = S.computeDeclContext(SS);
 if (auto *NS = llvm::dyn_cast(DC)) {
-  Info.Resolved = NS->getQualifiedNameAsString();
+  Info.Resolved = NS->getQualifiedNameAsString() + "::";
 } else if (llvm::dyn_cast(DC) != nullptr) {
-  Info.Resolved = "::";
-  // Sema does not include the suffix "::" in the range of SS, so we add
-  // it back here.
-  Info.Written = "::";
+  Info.Resolved = "";
 }
   }
   return Info;

Modified: clang-tools-extra/trunk/clangd/index/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.h?rev=322996&r1=322995&r2=322996&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.h (original)
+++ clang-tools-extra/trunk/clangd/index/Index.h Fri Jan 19 13:58:58 2018
@@ -114,10 +114,9 @@ struct Symbol {
   SymbolID ID;
   // The symbol information, like symbol kind.
   index::SymbolInfo SymInfo;
-  // The unqualified name of the symbol, e.g. "bar" (for "n1::n2::bar").
+  // The unqualified name of the symbol, e.g. "bar" (for ns::bar).
   llvm::StringRef Name;
-  // The scope (e.g. namespace) of the symbol, e.g. "n1::n2" (for
-  // "n1::n2::bar").
+  // The containing namespace. e.g. "" (global), "ns::" (top-level namespace).
   llvm::StringRef Scope;
   // The location of the canonical declaration of the symbol.
   //
@@ -221,12 +220,11 @@ struct FuzzyFindRequest {
   /// un-qualified identifiers and should not contain qualifiers like "::".
   std::string Query;
   /// \brief If this is non-empty, symbols must be in at least one of the 
scopes
-  /// (e.g. namespaces) excluding nested scopes. For example, if a scope "xyz"
-  /// is provided, the matched symbols must be defined in scope "xyz" but not
-  /// "xyz::abc".
+  /// (e.g. namespaces) excluding nested scopes. For example, if a scope 
"xyz::"
+  /// is provided, the matched symbols must be defined in namespace xyz but not
+  /// namespace xyz::abc.
   ///
-  /// A scope must be fully qualified without leading or trailing "::" e.g.
-  /// "n1::n2". "" is interpreted as the global namespace, and "::" is invalid.
+  /// The global scope is "", a top level scope is "foo::", etc.
   std::vector Scopes;
   /// \brief The number of top candidates to return. The index may choose to
   /// return more than this, e.g. if i

[PATCH] D42213: [ASTMatchers] [NFC] Fix code examples

2018-01-19 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In https://reviews.llvm.org/D42213#982385, @MaskRay wrote:

> Yes, I was asking about this because the results seemed to be wrong. I should 
> have used `parameterCountIs()` to reduce the confusion :) I'll leave them 
> untouched.


Alternatively, you can try out those declarations and the given matchers in 
clang-query to see if the results match what's listed, and update the comments 
based on what you find. Either way is fine.


Repository:
  rC Clang

https://reviews.llvm.org/D42213



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


[clang-tools-extra] r322998 - Revert "[clangd] Change index scope convention from "outer::inner" to "outer::inner::""

2018-01-19 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Jan 19 14:09:34 2018
New Revision: 322998

URL: http://llvm.org/viewvc/llvm-project?rev=322998&view=rev
Log:
Revert "[clangd] Change index scope convention from "outer::inner" to 
"outer::inner::""

This reverts commit r322996.

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/index/Index.h
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=322998&r1=322997&r2=322998&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Fri Jan 19 14:09:34 2018
@@ -313,7 +313,7 @@ llvm::Optional getSymbolID(con
 /// completion (e.g. "ns::ab?").
 struct SpecifiedScope {
   /// The scope specifier as written. For example, for completion "ns::ab?", 
the
-  /// written scope specifier is "ns::". Doesn't include leading "::".
+  /// written scope specifier is "ns".
   std::string Written;
   // If this scope specifier is recognized in Sema (e.g. as a namespace
   // context), this will be set to the fully qualfied name of the corresponding
@@ -321,7 +321,8 @@ struct SpecifiedScope {
   std::string Resolved;
 
   llvm::StringRef forIndex() {
-return Resolved.empty() ? Written.ltrim('::') : Resolved;
+llvm::StringRef Chosen = Resolved.empty() ? Written : Resolved;
+return Chosen.trim(':');
   }
 };
 
@@ -630,14 +631,15 @@ SpecifiedScope getSpecifiedScope(Sema &S
   auto SpecifierRange = SS.getRange();
   Info.Written = Lexer::getSourceText(
   CharSourceRange::getCharRange(SpecifierRange), SM, clang::LangOptions());
-  if (!Info.Written.empty())
-Info.Written += "::"; // Sema excludes the trailing ::.
   if (SS.isValid()) {
 DeclContext *DC = S.computeDeclContext(SS);
 if (auto *NS = llvm::dyn_cast(DC)) {
-  Info.Resolved = NS->getQualifiedNameAsString() + "::";
+  Info.Resolved = NS->getQualifiedNameAsString();
 } else if (llvm::dyn_cast(DC) != nullptr) {
-  Info.Resolved = "";
+  Info.Resolved = "::";
+  // Sema does not include the suffix "::" in the range of SS, so we add
+  // it back here.
+  Info.Written = "::";
 }
   }
   return Info;

Modified: clang-tools-extra/trunk/clangd/index/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.h?rev=322998&r1=322997&r2=322998&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.h (original)
+++ clang-tools-extra/trunk/clangd/index/Index.h Fri Jan 19 14:09:34 2018
@@ -114,9 +114,10 @@ struct Symbol {
   SymbolID ID;
   // The symbol information, like symbol kind.
   index::SymbolInfo SymInfo;
-  // The unqualified name of the symbol, e.g. "bar" (for ns::bar).
+  // The unqualified name of the symbol, e.g. "bar" (for "n1::n2::bar").
   llvm::StringRef Name;
-  // The containing namespace. e.g. "" (global), "ns::" (top-level namespace).
+  // The scope (e.g. namespace) of the symbol, e.g. "n1::n2" (for
+  // "n1::n2::bar").
   llvm::StringRef Scope;
   // The location of the canonical declaration of the symbol.
   //
@@ -220,11 +221,12 @@ struct FuzzyFindRequest {
   /// un-qualified identifiers and should not contain qualifiers like "::".
   std::string Query;
   /// \brief If this is non-empty, symbols must be in at least one of the 
scopes
-  /// (e.g. namespaces) excluding nested scopes. For example, if a scope 
"xyz::"
-  /// is provided, the matched symbols must be defined in namespace xyz but not
-  /// namespace xyz::abc.
+  /// (e.g. namespaces) excluding nested scopes. For example, if a scope "xyz"
+  /// is provided, the matched symbols must be defined in scope "xyz" but not
+  /// "xyz::abc".
   ///
-  /// The global scope is "", a top level scope is "foo::", etc.
+  /// A scope must be fully qualified without leading or trailing "::" e.g.
+  /// "n1::n2". "" is interpreted as the global namespace, and "::" is invalid.
   std::vector Scopes;
   /// \brief The number of top candidates to return. The index may choose to
   /// return more than this, e.g. if it doesn't know which candidates are best.

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=322998&r1=322997&r2=322998&view=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp F

[clang-tools-extra] r323000 - [clangd] Change index scope convention from "outer::inner" to "outer::inner::"

2018-01-19 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Jan 19 14:18:21 2018
New Revision: 323000

URL: http://llvm.org/viewvc/llvm-project?rev=323000&view=rev
Log:
[clangd] Change index scope convention from "outer::inner" to "outer::inner::"

Global scope is "" (was "")
Top-level namespace scope is "ns::" (was "ns")
Nested namespace scope is "ns::ns::" (was "ns::ns")

This composes more naturally:
- qname = scope + name
- full scope = resolved scope + unresolved scope (D42073 was the trigger)
It removes a wart from the old way: "foo::" has one more separator than "".

Another alternative that has these properties is "::ns", but that lacks
the property that both the scope and the name are substrings of the
qname as produced by clang.

This is re-landing r322996 which didn't build.

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/clangd/index/Index.h
clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
clang-tools-extra/trunk/unittests/clangd/FileIndexTests.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=323000&r1=322999&r2=323000&view=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Fri Jan 19 14:18:21 2018
@@ -313,7 +313,7 @@ llvm::Optional getSymbolID(con
 /// completion (e.g. "ns::ab?").
 struct SpecifiedScope {
   /// The scope specifier as written. For example, for completion "ns::ab?", 
the
-  /// written scope specifier is "ns".
+  /// written scope specifier is "ns::".
   std::string Written;
   // If this scope specifier is recognized in Sema (e.g. as a namespace
   // context), this will be set to the fully qualfied name of the corresponding
@@ -321,8 +321,8 @@ struct SpecifiedScope {
   std::string Resolved;
 
   llvm::StringRef forIndex() {
-llvm::StringRef Chosen = Resolved.empty() ? Written : Resolved;
-return Chosen.trim(':');
+return Resolved.empty() ? StringRef(Written).ltrim("::")
+: StringRef(Resolved);
   }
 };
 
@@ -631,15 +631,14 @@ SpecifiedScope getSpecifiedScope(Sema &S
   auto SpecifierRange = SS.getRange();
   Info.Written = Lexer::getSourceText(
   CharSourceRange::getCharRange(SpecifierRange), SM, clang::LangOptions());
+  if (!Info.Written.empty())
+Info.Written += "::"; // Sema excludes the trailing ::.
   if (SS.isValid()) {
 DeclContext *DC = S.computeDeclContext(SS);
 if (auto *NS = llvm::dyn_cast(DC)) {
-  Info.Resolved = NS->getQualifiedNameAsString();
+  Info.Resolved = NS->getQualifiedNameAsString() + "::";
 } else if (llvm::dyn_cast(DC) != nullptr) {
-  Info.Resolved = "::";
-  // Sema does not include the suffix "::" in the range of SS, so we add
-  // it back here.
-  Info.Written = "::";
+  Info.Resolved = "";
 }
   }
   return Info;

Modified: clang-tools-extra/trunk/clangd/index/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.h?rev=323000&r1=322999&r2=323000&view=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.h (original)
+++ clang-tools-extra/trunk/clangd/index/Index.h Fri Jan 19 14:18:21 2018
@@ -114,10 +114,9 @@ struct Symbol {
   SymbolID ID;
   // The symbol information, like symbol kind.
   index::SymbolInfo SymInfo;
-  // The unqualified name of the symbol, e.g. "bar" (for "n1::n2::bar").
+  // The unqualified name of the symbol, e.g. "bar" (for ns::bar).
   llvm::StringRef Name;
-  // The scope (e.g. namespace) of the symbol, e.g. "n1::n2" (for
-  // "n1::n2::bar").
+  // The containing namespace. e.g. "" (global), "ns::" (top-level namespace).
   llvm::StringRef Scope;
   // The location of the canonical declaration of the symbol.
   //
@@ -221,12 +220,11 @@ struct FuzzyFindRequest {
   /// un-qualified identifiers and should not contain qualifiers like "::".
   std::string Query;
   /// \brief If this is non-empty, symbols must be in at least one of the 
scopes
-  /// (e.g. namespaces) excluding nested scopes. For example, if a scope "xyz"
-  /// is provided, the matched symbols must be defined in scope "xyz" but not
-  /// "xyz::abc".
+  /// (e.g. namespaces) excluding nested scopes. For example, if a scope 
"xyz::"
+  /// is provided, the matched symbols must be defined in namespace xyz but not
+  /// namespace xyz::abc.
   ///
-  /// A scope must be fully qualified without leading or trailing "::" e.g.
-  /// "n1::n2". "" is interpreted as the global namespace, and "::" is invalid.
+  /// The global scope is "", a top level scope is "foo::", etc.
   std::vector Scopes;
   /// \brief The number of top candidates to retu

  1   2   >