[PATCH] D42581: [NVPTX] Emit debug info in DWARF-2 by default for Cuda devices.

2018-01-26 Thread Paul Robinson via Phabricator via cfe-commits
probinson added a comment.

If you want to force DWARF 2, probably clamping the version in LLVM would be 
simpler?  Although most of the debug-info tests are architecture-specific and 
wouldn't run for an NVPTX target anyway.


Repository:
  rC Clang

https://reviews.llvm.org/D42581



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


[PATCH] D42521: [CodeGen] Use the non-virtual alignment when emitting the base class subobject constructor

2018-01-26 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323578: [CodeGen] Use the non-virtual alignment when 
emitting the base (authored by ahatanak, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D42521

Files:
  lib/CodeGen/CGClass.cpp
  test/CodeGenCXX/virtual-bases.cpp


Index: lib/CodeGen/CGClass.cpp
===
--- lib/CodeGen/CGClass.cpp
+++ lib/CodeGen/CGClass.cpp
@@ -615,7 +615,14 @@
 
   llvm::Value *ThisPtr = CGF.LoadCXXThis();
   QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
-  LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
+  LValue LHS;
+
+  // If a base constructor is being emitted, create an LValue that has the
+  // non-virtual alignment.
+  if (CGF.CurGD.getCtorType() == Ctor_Base)
+LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
+  else
+LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
 
   EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
 
Index: test/CodeGenCXX/virtual-bases.cpp
===
--- test/CodeGenCXX/virtual-bases.cpp
+++ test/CodeGenCXX/virtual-bases.cpp
@@ -46,3 +46,37 @@
 D::D() { }
 
 }
+
+namespace virtualBaseAlignment {
+
+// Check that the store to B::x in the base constructor has an 8-byte 
alignment.
+
+// CHECK: define linkonce_odr void 
@_ZN20virtualBaseAlignment1BC1Ev(%[[STRUCT_B:.*]]* %[[THIS:.*]])
+// CHECK: %[[THIS_ADDR:.*]] = alloca %[[STRUCT_B]]*, align 8
+// CHECK: store %[[STRUCT_B]]* %[[THIS]], %[[STRUCT_B]]** %[[THIS_ADDR]], 
align 8
+// CHECK: %[[THIS1:.*]] = load %[[STRUCT_B]]*, %[[STRUCT_B]]** %[[THIS_ADDR]], 
align 8
+// CHECK: %[[X:.*]] = getelementptr inbounds %[[STRUCT_B]], %[[STRUCT_B]]* 
%[[THIS1]], i32 0, i32 2
+// CHECK: store i32 123, i32* %[[X]], align 16
+
+// CHECK: define linkonce_odr void 
@_ZN20virtualBaseAlignment1BC2Ev(%[[STRUCT_B]]* %[[THIS:.*]], i8** %{{.*}})
+// CHECK: %[[THIS_ADDR:.*]] = alloca %[[STRUCT_B]]*, align 8
+// CHECK: store %[[STRUCT_B]]* %[[THIS]], %[[STRUCT_B]]** %[[THIS_ADDR]], 
align 8
+// CHECK: %[[THIS1:.*]] = load %[[STRUCT_B]]*, %[[STRUCT_B]]** %[[THIS_ADDR]], 
align 8
+// CHECK: %[[X:.*]] = getelementptr inbounds %[[STRUCT_B]], %[[STRUCT_B]]* 
%[[THIS1]], i32 0, i32 2
+// CHECK: store i32 123, i32* %[[X]], align 8
+
+struct A {
+  __attribute__((aligned(16))) double data1;
+};
+
+struct B : public virtual A {
+  B() : x(123) {}
+  double a;
+  int x;
+};
+
+struct C : public virtual B {};
+
+void test() { B b; C c; }
+
+}


Index: lib/CodeGen/CGClass.cpp
===
--- lib/CodeGen/CGClass.cpp
+++ lib/CodeGen/CGClass.cpp
@@ -615,7 +615,14 @@
 
   llvm::Value *ThisPtr = CGF.LoadCXXThis();
   QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
-  LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
+  LValue LHS;
+
+  // If a base constructor is being emitted, create an LValue that has the
+  // non-virtual alignment.
+  if (CGF.CurGD.getCtorType() == Ctor_Base)
+LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
+  else
+LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
 
   EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
 
Index: test/CodeGenCXX/virtual-bases.cpp
===
--- test/CodeGenCXX/virtual-bases.cpp
+++ test/CodeGenCXX/virtual-bases.cpp
@@ -46,3 +46,37 @@
 D::D() { }
 
 }
+
+namespace virtualBaseAlignment {
+
+// Check that the store to B::x in the base constructor has an 8-byte alignment.
+
+// CHECK: define linkonce_odr void @_ZN20virtualBaseAlignment1BC1Ev(%[[STRUCT_B:.*]]* %[[THIS:.*]])
+// CHECK: %[[THIS_ADDR:.*]] = alloca %[[STRUCT_B]]*, align 8
+// CHECK: store %[[STRUCT_B]]* %[[THIS]], %[[STRUCT_B]]** %[[THIS_ADDR]], align 8
+// CHECK: %[[THIS1:.*]] = load %[[STRUCT_B]]*, %[[STRUCT_B]]** %[[THIS_ADDR]], align 8
+// CHECK: %[[X:.*]] = getelementptr inbounds %[[STRUCT_B]], %[[STRUCT_B]]* %[[THIS1]], i32 0, i32 2
+// CHECK: store i32 123, i32* %[[X]], align 16
+
+// CHECK: define linkonce_odr void @_ZN20virtualBaseAlignment1BC2Ev(%[[STRUCT_B]]* %[[THIS:.*]], i8** %{{.*}})
+// CHECK: %[[THIS_ADDR:.*]] = alloca %[[STRUCT_B]]*, align 8
+// CHECK: store %[[STRUCT_B]]* %[[THIS]], %[[STRUCT_B]]** %[[THIS_ADDR]], align 8
+// CHECK: %[[THIS1:.*]] = load %[[STRUCT_B]]*, %[[STRUCT_B]]** %[[THIS_ADDR]], align 8
+// CHECK: %[[X:.*]] = getelementptr inbounds %[[STRUCT_B]], %[[STRUCT_B]]* %[[THIS1]], i32 0, i32 2
+// CHECK: store i32 123, i32* %[[X]], align 8
+
+struct A {
+  __attribute__((aligned(16))) double data1;
+};
+
+struct B : public virtual A {
+  B() : x(123) {}
+  double a;
+  int x;
+};
+
+struct C : public virtual B {};
+
+void test() { B b; C c; }
+
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin

r323578 - [CodeGen] Use the non-virtual alignment when emitting the base

2018-01-26 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Fri Jan 26 16:34:09 2018
New Revision: 323578

URL: http://llvm.org/viewvc/llvm-project?rev=323578&view=rev
Log:
[CodeGen] Use the non-virtual alignment when emitting the base
constructor.

Previously, clang would emit an over-aligned (16-byte) store to
initialize B::x in B's base constructor when compiling the following
code:

struct A {
  __attribute__((aligned(16))) double data1;
};

struct B : public virtual A {
  B() : x(123) {}
  double a;
  int x;
};

struct C : public virtual B {};

void test() { B b; C c; }

This was happening because the code in IRGen that does member
initialization was using the alignment of a complete object instead of
the non-virtual alignment.

This commit fixes the bug.

rdar://problem/36382481

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

Modified:
cfe/trunk/lib/CodeGen/CGClass.cpp
cfe/trunk/test/CodeGenCXX/virtual-bases.cpp

Modified: cfe/trunk/lib/CodeGen/CGClass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGClass.cpp?rev=323578&r1=323577&r2=323578&view=diff
==
--- cfe/trunk/lib/CodeGen/CGClass.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGClass.cpp Fri Jan 26 16:34:09 2018
@@ -615,7 +615,14 @@ static void EmitMemberInitializer(CodeGe
 
   llvm::Value *ThisPtr = CGF.LoadCXXThis();
   QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
-  LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
+  LValue LHS;
+
+  // If a base constructor is being emitted, create an LValue that has the
+  // non-virtual alignment.
+  if (CGF.CurGD.getCtorType() == Ctor_Base)
+LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
+  else
+LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
 
   EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
 

Modified: cfe/trunk/test/CodeGenCXX/virtual-bases.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/virtual-bases.cpp?rev=323578&r1=323577&r2=323578&view=diff
==
--- cfe/trunk/test/CodeGenCXX/virtual-bases.cpp (original)
+++ cfe/trunk/test/CodeGenCXX/virtual-bases.cpp Fri Jan 26 16:34:09 2018
@@ -46,3 +46,37 @@ struct D : B, C  {
 D::D() { }
 
 }
+
+namespace virtualBaseAlignment {
+
+// Check that the store to B::x in the base constructor has an 8-byte 
alignment.
+
+// CHECK: define linkonce_odr void 
@_ZN20virtualBaseAlignment1BC1Ev(%[[STRUCT_B:.*]]* %[[THIS:.*]])
+// CHECK: %[[THIS_ADDR:.*]] = alloca %[[STRUCT_B]]*, align 8
+// CHECK: store %[[STRUCT_B]]* %[[THIS]], %[[STRUCT_B]]** %[[THIS_ADDR]], 
align 8
+// CHECK: %[[THIS1:.*]] = load %[[STRUCT_B]]*, %[[STRUCT_B]]** %[[THIS_ADDR]], 
align 8
+// CHECK: %[[X:.*]] = getelementptr inbounds %[[STRUCT_B]], %[[STRUCT_B]]* 
%[[THIS1]], i32 0, i32 2
+// CHECK: store i32 123, i32* %[[X]], align 16
+
+// CHECK: define linkonce_odr void 
@_ZN20virtualBaseAlignment1BC2Ev(%[[STRUCT_B]]* %[[THIS:.*]], i8** %{{.*}})
+// CHECK: %[[THIS_ADDR:.*]] = alloca %[[STRUCT_B]]*, align 8
+// CHECK: store %[[STRUCT_B]]* %[[THIS]], %[[STRUCT_B]]** %[[THIS_ADDR]], 
align 8
+// CHECK: %[[THIS1:.*]] = load %[[STRUCT_B]]*, %[[STRUCT_B]]** %[[THIS_ADDR]], 
align 8
+// CHECK: %[[X:.*]] = getelementptr inbounds %[[STRUCT_B]], %[[STRUCT_B]]* 
%[[THIS1]], i32 0, i32 2
+// CHECK: store i32 123, i32* %[[X]], align 8
+
+struct A {
+  __attribute__((aligned(16))) double data1;
+};
+
+struct B : public virtual A {
+  B() : x(123) {}
+  double a;
+  int x;
+};
+
+struct C : public virtual B {};
+
+void test() { B b; C c; }
+
+}


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


[PATCH] D42248: Always allow "#pragma region".

2018-01-26 Thread Matt Davis via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323577: Always allow "#pragma region". (authored 
by mattd, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D42248

Files:
  lib/Lex/Pragma.cpp
  test/Frontend/region-pragmas.c


Index: test/Frontend/region-pragmas.c
===
--- test/Frontend/region-pragmas.c
+++ test/Frontend/region-pragmas.c
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -Wall -verify %s
+// expected-no-diagnostics
+
+#pragma region foo
+#pragma endregion foo
Index: lib/Lex/Pragma.cpp
===
--- lib/Lex/Pragma.cpp
+++ lib/Lex/Pragma.cpp
@@ -1776,13 +1776,15 @@
   ModuleHandler->AddPragma(new PragmaModuleEndHandler());
   ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
   ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
+
+  // Add region pragmas.
+  AddPragmaHandler(new PragmaRegionHandler("region"));
+  AddPragmaHandler(new PragmaRegionHandler("endregion"));
 
   // MS extensions.
   if (LangOpts.MicrosoftExt) {
 AddPragmaHandler(new PragmaWarningHandler());
 AddPragmaHandler(new PragmaIncludeAliasHandler());
-AddPragmaHandler(new PragmaRegionHandler("region"));
-AddPragmaHandler(new PragmaRegionHandler("endregion"));
   }
 
   // Pragmas added by plugins


Index: test/Frontend/region-pragmas.c
===
--- test/Frontend/region-pragmas.c
+++ test/Frontend/region-pragmas.c
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -Wall -verify %s
+// expected-no-diagnostics
+
+#pragma region foo
+#pragma endregion foo
Index: lib/Lex/Pragma.cpp
===
--- lib/Lex/Pragma.cpp
+++ lib/Lex/Pragma.cpp
@@ -1776,13 +1776,15 @@
   ModuleHandler->AddPragma(new PragmaModuleEndHandler());
   ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
   ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
+
+  // Add region pragmas.
+  AddPragmaHandler(new PragmaRegionHandler("region"));
+  AddPragmaHandler(new PragmaRegionHandler("endregion"));
 
   // MS extensions.
   if (LangOpts.MicrosoftExt) {
 AddPragmaHandler(new PragmaWarningHandler());
 AddPragmaHandler(new PragmaIncludeAliasHandler());
-AddPragmaHandler(new PragmaRegionHandler("region"));
-AddPragmaHandler(new PragmaRegionHandler("endregion"));
   }
 
   // Pragmas added by plugins
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323577 - Always allow "#pragma region".

2018-01-26 Thread Matt Davis via cfe-commits
Author: mattd
Date: Fri Jan 26 16:25:29 2018
New Revision: 323577

URL: http://llvm.org/viewvc/llvm-project?rev=323577&view=rev
Log:
Always allow "#pragma region".

Summary:
Both MS and PS4 targets are capable of recognizing the
existence of:  #pragma region, #pragma endregion.

Since this pragma is only a hint for certain editors, and has no logic,
it seems helpful to permit this pragma in all cases, not just MS compatibility 
mode.



Reviewers: rnk, rsmith, majnemer

Reviewed By: majnemer

Subscribers: Quuxplusone, probinson, majnemer, cfe-commits

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

Added:
cfe/trunk/test/Frontend/region-pragmas.c
Modified:
cfe/trunk/lib/Lex/Pragma.cpp

Modified: cfe/trunk/lib/Lex/Pragma.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/Pragma.cpp?rev=323577&r1=323576&r2=323577&view=diff
==
--- cfe/trunk/lib/Lex/Pragma.cpp (original)
+++ cfe/trunk/lib/Lex/Pragma.cpp Fri Jan 26 16:25:29 2018
@@ -1776,13 +1776,15 @@ void Preprocessor::RegisterBuiltinPragma
   ModuleHandler->AddPragma(new PragmaModuleEndHandler());
   ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
   ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
+
+  // Add region pragmas.
+  AddPragmaHandler(new PragmaRegionHandler("region"));
+  AddPragmaHandler(new PragmaRegionHandler("endregion"));
 
   // MS extensions.
   if (LangOpts.MicrosoftExt) {
 AddPragmaHandler(new PragmaWarningHandler());
 AddPragmaHandler(new PragmaIncludeAliasHandler());
-AddPragmaHandler(new PragmaRegionHandler("region"));
-AddPragmaHandler(new PragmaRegionHandler("endregion"));
   }
 
   // Pragmas added by plugins

Added: cfe/trunk/test/Frontend/region-pragmas.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Frontend/region-pragmas.c?rev=323577&view=auto
==
--- cfe/trunk/test/Frontend/region-pragmas.c (added)
+++ cfe/trunk/test/Frontend/region-pragmas.c Fri Jan 26 16:25:29 2018
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -Wall -verify %s
+// expected-no-diagnostics
+
+#pragma region foo
+#pragma endregion foo


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


[PATCH] D42608: Driver: Prefer vendor supplied gcc toolchain

2018-01-26 Thread Tom Stellard via Phabricator via cfe-commits
tstellar created this revision.
Herald added a subscriber: srhines.

This patch fixes an issue on Fedora where if you had the x86_64 cross
compiler installed on your x86_64 system, then clang would use that compiler
as the default toolchain.  This was happening because the cross compiler
is installed to /usr/lib/gcc/x86_64-linux-gnu/ and this directory comes before
the default compiler directory (/usr/lib/gcc/x86_64-redhat-linux/) in the search
list.

This patch re-orders the search list so that vendor supplied gcc toolchains
are selected before toolchains with a generic target, which should prevent
these kind of issues on other OSes too.


Repository:
  rC Clang

https://reviews.llvm.org/D42608

Files:
  lib/Driver/ToolChains/Gnu.cpp


Index: lib/Driver/ToolChains/Gnu.cpp
===
--- lib/Driver/ToolChains/Gnu.cpp
+++ lib/Driver/ToolChains/Gnu.cpp
@@ -1809,40 +1809,41 @@
   // lifetime or initialization issues.
   static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
   static const char *const AArch64Triples[] = {
-  "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android",
-  "aarch64-redhat-linux", "aarch64-suse-linux"};
+  "aarch64-redhat-linux", "aarch64-suse-linux",
+  "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-linux-android"};
   static const char *const AArch64beLibDirs[] = {"/lib"};
   static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
  "aarch64_be-linux-gnu"};
 
   static const char *const ARMLibDirs[] = {"/lib"};
   static const char *const ARMTriples[] = {"arm-linux-gnueabi",
"arm-linux-androideabi"};
-  static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf",
- "armv7hl-redhat-linux-gnueabi",
+  static const char *const ARMHFTriples[] = {"armv7hl-redhat-linux-gnueabi",
  "armv6hl-suse-linux-gnueabi",
- "armv7hl-suse-linux-gnueabi"};
+ "armv7hl-suse-linux-gnueabi",
+ "arm-linux-gnueabihf",
+  };
   static const char *const ARMebLibDirs[] = {"/lib"};
   static const char *const ARMebTriples[] = {"armeb-linux-gnueabi",
  "armeb-linux-androideabi"};
   static const char *const ARMebHFTriples[] = {
   "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"};
 
   static const char *const X86_64LibDirs[] = {"/lib64", "/lib"};
   static const char *const X86_64Triples[] = {
-  "x86_64-linux-gnu",   "x86_64-unknown-linux-gnu",
-  "x86_64-pc-linux-gnu","x86_64-redhat-linux6E",
-  "x86_64-redhat-linux","x86_64-suse-linux",
-  "x86_64-manbo-linux-gnu", "x86_64-linux-gnu",
-  "x86_64-slackware-linux", "x86_64-linux-android",
+  "x86_64-redhat-linux6E","x86_64-redhat-linux",
+  "x86_64-suse-linux","x86_64-slackware-linux",
+  "x86_64-manbo-linux-gnu",   "x86_64-linux-gnu",
+  "x86_64-unknown-linux-gnu", "x86_64-pc-linux-gnu",
+  "x86_64-linux-gnu", "x86_64-linux-android",
   "x86_64-unknown-linux"};
   static const char *const X32LibDirs[] = {"/libx32"};
   static const char *const X86LibDirs[] = {"/lib32", "/lib"};
   static const char *const X86Triples[] = {
-  "i686-linux-gnu",   "i686-pc-linux-gnu", "i486-linux-gnu",
-  "i386-linux-gnu",   "i386-redhat-linux6E",   "i686-redhat-linux",
-  "i586-redhat-linux","i386-redhat-linux", "i586-suse-linux",
-  "i486-slackware-linux", "i686-montavista-linux", "i686-linux-android",
+  "i386-redhat-linux6E",   "i686-redhat-linux", "i586-redhat-linuxll",
+  "i386-redhat-linux", "i586-suse-linux",   "i486-slackware-linux",
+  "i686-montavista-linux", "i686-linux-gnu","i686-pc-linux-gnu",
+  "i486-linux-gnu","i386-linux-gnu","i686-linux-android",
   "i586-linux-gnu"};
 
   static const char *const MIPSLibDirs[] = {"/lib"};
@@ -1872,16 +1873,16 @@
 
   static const char *const PPCLibDirs[] = {"/lib32", "/lib"};
   static const char *const PPCTriples[] = {
-  "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", "powerpc-linux-gnuspe",
-  "powerpc-suse-linux", "powerpc-montavista-linuxspe"};
+  "powerpc-suse-linux", "powerpc-montavista-linuxspe",
+  "powerpc-linux-gnu", "powerpc-unknown-linux-gnu", 
"powerpc-linux-gnuspe"};
   static const char *const PPC64LibDirs[] = {"/lib64", "/lib"};
   static const char *const PPC64Triples[] = {
-  "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu",
-  "powerpc64-suse-linux", "ppc64-redhat-linux"};
+  "powerpc64-suse-linux", "ppc64-redhat-linux",
+  "powerpc64-linux-gnu", "powerpc64-unknown-linux-gnu"};
   static const char *const PPC64LELibDirs[] = {"/l

[PATCH] D42606: [Coroutines] Use allocator overload when available

2018-01-26 Thread Brian Gesiak via Phabricator via cfe-commits
modocache created this revision.
modocache added reviewers: rsmith, GorNishanov, eric_niebler.
Herald added a subscriber: EricWF.

Depends on https://reviews.llvm.org/D42605.

An implementation of the behavior described in `[dcl.fct.def.coroutine]/7`:
when a promise type overloads `operator new` using a "placement new"
that takes the same argument types as the coroutine function, that
overload is used when allocating the coroutine frame.

Simply passing references to the coroutine function parameters directly
to `operator new` results in invariant violations in LLVM's coroutine
splitting pass, so this implementation modifies Clang codegen to
produce allocator-specific alloc/store/loads for each parameter being
forwarded to the allocator.

Test Plan: `check-clang`


Repository:
  rC Clang

https://reviews.llvm.org/D42606

Files:
  lib/CodeGen/CGCoroutine.cpp
  lib/Sema/SemaCoroutine.cpp
  test/CodeGenCoroutines/coro-alloc.cpp

Index: test/CodeGenCoroutines/coro-alloc.cpp
===
--- test/CodeGenCoroutines/coro-alloc.cpp
+++ test/CodeGenCoroutines/coro-alloc.cpp
@@ -106,6 +106,34 @@
   co_return;
 }
 
+struct promise_matching_placement_new_tag {};
+
+template<>
+struct std::experimental::coroutine_traits {
+  struct promise_type {
+void *operator new(unsigned long, promise_matching_placement_new_tag,
+   int, float, double);
+void get_return_object() {}
+suspend_always initial_suspend() { return {}; }
+suspend_always final_suspend() { return {}; }
+void return_void() {}
+  };
+};
+
+// CHECK-LABEL: f1a(
+extern "C" void f1a(promise_matching_placement_new_tag, int x, float y , double z) {
+  // CHECK: %[[ID:.+]] = call token @llvm.coro.id(i32 16
+  // CHECK: %[[SIZE:.+]] = call i64 @llvm.coro.size.i64()
+  // CHECK: store i32 %x, i32* %coro.allocate.x.addr, align 4
+  // CHECK: %[[INT:.+]] = load i32, i32* %coro.allocate.x.addr, align 4
+  // CHECK: store float %y, float* %coro.allocate.y.addr, align 4
+  // CHECK: %[[FLOAT:.+]] = load float, float* %coro.allocate.y.addr, align 4
+  // CHECK: store double %z, double* %coro.allocate.z.addr, align 8
+  // CHECK: %[[DOUBLE:.+]] = load double, double* %coro.allocate.z.addr, align 8
+  // CHECK: call i8* @_ZNSt12experimental16coroutine_traitsIJv34promise_matching_placement_new_tagifdEE12promise_typenwEmS1_ifd(i64 %[[SIZE]], i32 %[[INT]], float %[[FLOAT]], double %[[DOUBLE]])
+  co_return;
+}
+
 struct promise_delete_tag {};
 
 template<>
Index: lib/Sema/SemaCoroutine.cpp
===
--- lib/Sema/SemaCoroutine.cpp
+++ lib/Sema/SemaCoroutine.cpp
@@ -1050,18 +1050,54 @@
 
   const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
 
-  // FIXME: Add support for stateful allocators.
+  // [dcl.fct.def.coroutine]/7
+  // Lookup allocation functions using a parameter list composed of the
+  // requested size of the coroutine state being allocated, followed by
+  // the coroutine function's arguments. If a matching allocation function
+  // exists, use it. Otherwise, use an allocation function that just takes
+  // the requested size.
 
   FunctionDecl *OperatorNew = nullptr;
   FunctionDecl *OperatorDelete = nullptr;
   FunctionDecl *UnusedResult = nullptr;
   bool PassAlignment = false;
   SmallVector PlacementArgs;
 
+  // [dcl.fct.def.coroutine]/7
+  // "The allocation function’s name is looked up in the scope of P.
+  // [...] If the lookup finds an allocation function in the scope of P,
+  // overload resolution is performed on a function call created by assembling
+  // an argument list."
+  for (auto *PD : FD.parameters()) {
+if (PD->getType()->isDependentType())
+  continue;
+
+// Build a reference to the parameter.
+auto PDLoc = PD->getLocation();
+ExprResult PDRefExpr =
+S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
+   ExprValueKind::VK_LValue, PDLoc);
+if (PDRefExpr.isInvalid())
+  return false;
+
+PlacementArgs.push_back(PDRefExpr.get());
+  }
   S.FindAllocationFunctions(Loc, SourceRange(),
 /*UseGlobal*/ false, PromiseType,
 /*isArray*/ false, PassAlignment, PlacementArgs,
-OperatorNew, UnusedResult);
+OperatorNew, UnusedResult, /*Diagnose*/ false);
+
+  // [dcl.fct.def.coroutine]/7
+  // "If no matching function is found, overload resolution is performed again
+  // on a function call created by passing just the amount of space required as
+  // an argument of type std::size_t."
+  if (!OperatorNew && !PlacementArgs.empty()) {
+PlacementArgs.clear();
+S.FindAllocationFunctions(Loc, SourceRange(),
+  /*UseGlobal*/ false, PromiseType,
+  /*isArray*/ false, PassAlignment,
+  PlacementArgs, OperatorNew, Unu

[PATCH] D42605: [Sema] Toggle diags when finding allocators (NFCI)

2018-01-26 Thread Brian Gesiak via Phabricator via cfe-commits
modocache created this revision.
modocache added reviewers: rsmith, GorNishanov, eric_niebler.

Many methods in Sema take a `bool Diagnose` parameter. Examples of such
methods include `Sema::FindDeallocationFunction` and
`Sema::SpecialMemberIsTrivial`. Calling these methods with
`Diagnose = false` allows callers to, for instance, check for the
existence of a deallocation function, without that check resulting in
error diagnostics being emitted if no matching deallocation function exists.

Add a similar `bool Diagnose` to the `Sema::FindAllocationFunctions`
method, so that checks for the existence of allocation functions can be
made without triggering error diagnostics.

This allows `SemaCoroutine.cpp`, in its implementation of the
Coroutines TS, to check for the existence of a particular `operator new`
overload, but then without error fall back to a default `operator new`
if no matching overload exists.

Test Plan: `check-clang`


Repository:
  rC Clang

https://reviews.llvm.org/D42605

Files:
  include/clang/Sema/Sema.h
  lib/Sema/SemaExprCXX.cpp

Index: lib/Sema/SemaExprCXX.cpp
===
--- lib/Sema/SemaExprCXX.cpp
+++ lib/Sema/SemaExprCXX.cpp
@@ -2137,12 +2137,10 @@
   return false;
 }
 
-static bool
-resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
-  SmallVectorImpl &Args, bool &PassAlignment,
-  FunctionDecl *&Operator,
-  OverloadCandidateSet *AlignedCandidates = nullptr,
-  Expr *AlignArg = nullptr) {
+static bool resolveAllocationOverload(
+Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl &Args,
+bool &PassAlignment, FunctionDecl *&Operator,
+OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
   OverloadCandidateSet Candidates(R.getNameLoc(),
   OverloadCandidateSet::CSK_Normal);
   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
@@ -2188,7 +2186,8 @@
   AlignArg = Args[1];
   Args.erase(Args.begin() + 1);
   return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
-   Operator, &Candidates, AlignArg);
+   Operator, &Candidates, AlignArg,
+   Diagnose);
 }
 
 // MSVC will fall back on trying to find a matching global operator new
@@ -2204,11 +2203,13 @@
   S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
   // FIXME: This will give bad diagnostics pointing at the wrong functions.
   return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
-   Operator, nullptr);
+   Operator, /*Candidates=*/nullptr,
+   /*AlignArg=*/nullptr, Diagnose);
 }
 
-S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
-  << R.getLookupName() << Range;
+if (Diagnose)
+  S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
+  << R.getLookupName() << Range;
 
 // If we have aligned candidates, only note the align_val_t candidates
 // from AlignedCandidates and the non-align_val_t candidates from
@@ -2234,18 +2235,20 @@
 return true;
 
   case OR_Ambiguous:
-S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
-  << R.getLookupName() << Range;
-Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
+if (Diagnose) {
+  S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
+  << R.getLookupName() << Range;
+  Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
+}
 return true;
 
   case OR_Deleted: {
-S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
-  << Best->Function->isDeleted()
-  << R.getLookupName()
-  << S.getDeletedOrUnavailableSuffix(Best->Function)
-  << Range;
-Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
+if (Diagnose) {
+  S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
+  << Best->Function->isDeleted() << R.getLookupName()
+  << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
+  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
+}
 return true;
   }
   }
@@ -2260,7 +2263,8 @@
bool IsArray, bool &PassAlignment,
MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
-   FunctionDecl *&OperatorDelete) {
+   FunctionDecl *&OperatorDelete,
+   bool Diagnose) {
   // --- Choosing an allocation function ---
   // C++ 5.3.4p8 - 14 & 18
   // 1) If UseGlobal is true, only look in the global scope. Else, also look
@@ -2335,7 +2339,8 @@
 R.suppressDiagnostics();
 
 if (resolv

[PATCH] D42508: AST: support protocol conformances on id/class/interfaces in MS ABI

2018-01-26 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd closed this revision.
compnerd added a comment.

SVN r323547


Repository:
  rC Clang

https://reviews.llvm.org/D42508



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


[PATCH] D41720: [clang-tidy] Add a -show-color flag.

2018-01-26 Thread Ian Tessier via Phabricator via cfe-commits
itessier added inline comments.



Comment at: clang-tidy/ClangTidyOptions.h:93
+  /// \brief Show color diagnostics.
+  llvm::Optional ShowColor;
+

alexfh wrote:
> This doesn't belong to ClangTidyOptions. It's specific to the CLI, but CLI is 
> not the only frontend for clang-tidy.
Since we have to propagate the value to the ErrorReporter, how about adding a 
bool param to the ErrorReporter ctor? We could add a setter instead, but that 
would require moving a diag printer call out of the ctor since it uses the 
DiagOpts instance.

The colour logic would then be moved into either clangTidyMain or handleErrors.



Comment at: clang-tidy/tool/ClangTidyMain.cpp:150-152
+Show color diagnostics. If not specified,
+defaults to on when a color-capable terminal
+is detected.)"),

itessier wrote:
> aaron.ballman wrote:
> > I think this raw string can be reflowed a bit?
> > 
> > Instead of "defaults to on", how about "Defaults to true when a 
> > color-capable terminal is detected."?
> I copied that part from the -fcolor-diagnostics flag to be consistent. I 
> don't changing "on" to "true" if you prefer that instead.
That should have read "I don't mind changing..."


https://reviews.llvm.org/D41720



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


Re: [PATCH] D35338: Add the -fdestroy-globals flag

2018-01-26 Thread Vedant Kumar via cfe-commits
Yeah, I think we have internal users who would be happy to use this flag as 
well.

Stepping back a bit. It's been a while since I followed the discussion on 
cfe-dev, but I don't recall there being any objections to the flag name or to 
using it for particular targets.

IIRC the objections are about deviating from the language standard. I'm not 
sure where I stand on the issue. I think if there's evidence -fdestroy-globals 
gives significant space savings, I'm happy to defer to users.

vedant

> On Jan 26, 2018, at 1:10 PM, Nico Weber via cfe-commits 
>  wrote:
> 
> I'd love to use this flag in non-firmware code FWIW.
> 
> On Fri, Jan 26, 2018 at 4:07 PM, Ian Tessier via Phabricator via cfe-commits 
> mailto:cfe-commits@lists.llvm.org>> wrote:
> itessier added a comment.
> 
> > That seems like a nice win and I like the convenience of this approach. 
> > That said I've just remembered that there's a thread on cfe-dev about this:
> > [RFC] Suppress C++ static destructor registration
> > I don't think a consensus was reached. From what I gather, some people 
> > think that the convenience of this flag makes it worth adding to clang, 
> > while others think that adding a non-standard compiler-specific flag is 
> > asking for trouble.
> 
> Given that firmware is a much different (or controlled) environment than a 
> binary running on a full blown OS, would it be acceptable to name the flag 
> -fbaremetal-destroy-globals, and only allow its use if the target triple's OS 
> is set to none (e.g.: arm-**none**-eabi)?
> 
> 
> https://reviews.llvm.org/D35338 
> 
> 
> 
> ___
> 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

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


[PATCH] D42513: [CUDA] Added partial support for CUDA-9.1

2018-01-26 Thread Artem Belevich via Phabricator via cfe-commits
tra updated this revision to Diff 131650.
tra added a comment.

Addressed Justin's comments.


https://reviews.llvm.org/D42513

Files:
  clang/include/clang/Basic/Cuda.h
  clang/lib/Basic/Cuda.cpp
  clang/lib/Basic/Targets/NVPTX.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Headers/__clang_cuda_device_functions.h
  clang/lib/Headers/__clang_cuda_libdevice_declares.h
  clang/lib/Headers/__clang_cuda_runtime_wrapper.h

Index: clang/lib/Headers/__clang_cuda_runtime_wrapper.h
===
--- clang/lib/Headers/__clang_cuda_runtime_wrapper.h
+++ clang/lib/Headers/__clang_cuda_runtime_wrapper.h
@@ -62,7 +62,7 @@
 #include "cuda.h"
 #if !defined(CUDA_VERSION)
 #error "cuda.h did not define CUDA_VERSION"
-#elif CUDA_VERSION < 7000 || CUDA_VERSION > 9000
+#elif CUDA_VERSION < 7000 || CUDA_VERSION > 9010
 #error "Unsupported CUDA version!"
 #endif
 
@@ -84,6 +84,9 @@
 #define __DEVICE_FUNCTIONS_H__
 #define __MATH_FUNCTIONS_H__
 #define __COMMON_FUNCTIONS_H__
+// device_functions_decls is replaced by __clang_cuda_device_functions.h
+// included below.
+#define __DEVICE_FUNCTIONS_DECLS_H__
 
 #undef __CUDACC__
 #if CUDA_VERSION < 9000
@@ -137,20 +140,22 @@
 }
 #endif
 
-// We need decls for functions in CUDA's libdevice with __device__
-// attribute only. Alas they come either as __host__ __device__ or
-// with no attributes at all. To work around that, define __CUDA_RTC__
-// which produces HD variant and undef __host__ which gives us desided
-// decls with __device__ attribute.
-#pragma push_macro("__host__")
-#define __host__
-#define __CUDACC_RTC__
-#include "device_functions_decls.h"
-#undef __CUDACC_RTC__
+// CUDA 9.1 no longer provides declarations for libdevice functions, so we need
+// to provide our own.
+#include <__clang_cuda_libdevice_declares.h>
 
-// Temporarily poison __host__ macro to ensure it's not used by any of
-// the headers we're about to include.
-#define __host__ UNEXPECTED_HOST_ATTRIBUTE
+// Wrappers for many device-side standard library functions became compiler
+// builtins in CUDA-9 and have been removed from the CUDA headers. Clang now
+// provides its own implementation of the wrappers.
+#if CUDA_VERSION >= 9000
+#include <__clang_cuda_device_functions.h>
+#endif
+
+// __THROW is redefined to be empty by device_functions_decls.h in CUDA. Clang's
+// counterpart does not do it, so we need to make it empty here to keep
+// following CUDA includes happy.
+#undef __THROW
+#define __THROW
 
 // CUDA 8.0.41 relies on __USE_FAST_MATH__ and __CUDA_PREC_DIV's values.
 // Previous versions used to check whether they are defined or not.
@@ -167,24 +172,20 @@
 #endif
 #endif
 
+// Temporarily poison __host__ macro to ensure it's not used by any of
+// the headers we're about to include.
+#pragma push_macro("__host__")
+#define __host__ UNEXPECTED_HOST_ATTRIBUTE
+
 // device_functions.hpp and math_functions*.hpp use 'static
 // __forceinline__' (with no __device__) for definitions of device
 // functions. Temporarily redefine __forceinline__ to include
 // __device__.
 #pragma push_macro("__forceinline__")
 #define __forceinline__ __device__ __inline__ __attribute__((always_inline))
-
-#pragma push_macro("__float2half_rn")
-#if CUDA_VERSION >= 9000
-// CUDA-9 has conflicting prototypes for __float2half_rn(float f) in
-// cuda_fp16.h[pp] and device_functions.hpp. We need to get the one in
-// device_functions.hpp out of the way.
-#define __float2half_rn  __float2half_rn_disabled
-#endif
-
+#if CUDA_VERSION < 9000
 #include "device_functions.hpp"
-#pragma pop_macro("__float2half_rn")
-
+#endif
 
 // math_function.hpp uses the __USE_FAST_MATH__ macro to determine whether we
 // get the slow-but-accurate or fast-but-inaccurate versions of functions like
@@ -196,17 +197,27 @@
 #if defined(__CLANG_CUDA_APPROX_TRANSCENDENTALS__)
 #define __USE_FAST_MATH__ 1
 #endif
+
+#if CUDA_VERSION >= 9000
+#include "crt/math_functions.hpp"
+#else
 #include "math_functions.hpp"
+#endif
+
 #pragma pop_macro("__USE_FAST_MATH__")
 
+#if CUDA_VERSION < 9000
 #include "math_functions_dbl_ptx3.hpp"
+#endif
 #pragma pop_macro("__forceinline__")
 
 // Pull in host-only functions that are only available when neither
 // __CUDACC__ nor __CUDABE__ are defined.
 #undef __MATH_FUNCTIONS_HPP__
 #undef __CUDABE__
+#if CUDA_VERSION < 9000
 #include "math_functions.hpp"
+#endif
 // Alas, additional overloads for these functions are hard to get to.
 // Considering that we only need these overloads for a few functions,
 // we can provide them here.
@@ -222,22 +233,36 @@
 static inline float normcdf(float __a) { return normcdff(__a); }
 static inline float erfcx(float __a) { return erfcxf(__a); }
 
+#if CUDA_VERSION < 9000
 // For some reason single-argument variant is not always declared by
 // CUDA headers. Alas, device_functions.hpp included below needs it.
 static inline __device__ void __brkpt(int __c) { __brkpt(); }
+#endif
 
 // Now i

[PATCH] D42493: [clang-format] Fix ObjC message arguments formatting.

2018-01-26 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton accepted this revision.
benhamilton added inline comments.
This revision is now accepted and ready to land.



Comment at: lib/Format/TokenAnnotator.cpp:419
   StartsObjCMethodExpr = true;
+  Left->ParameterCount = 0;
   Contexts.back().ColonIsObjCMethodExpr = true;

What does this line do? Seems like it's initialized to 0 already, right?


Repository:
  rC Clang

https://reviews.llvm.org/D42493



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


[PATCH] D42395: [clang-format] Fix bug where -dump-config failed on ObjC header

2018-01-26 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton requested review of this revision.
benhamilton marked 2 inline comments as done.
benhamilton added inline comments.



Comment at: test/Format/lit.local.cfg:1
+# Suffixes supported by clang-format.
+config.suffixes = ['.c', '.cc', '.cpp', '.h', '.m', '.mm', '.java', '.js',

krasimir wrote:
> Why is this needed?
'.h' is not in the list of file suffixes which lit is configured to look for:

https://github.com/llvm-mirror/clang/blob/master/test/lit.cfg.py#L28

So, we need to provide our own list of file suffixes here.

Other tests do the same:

https://github.com/llvm-mirror/clang/search?utf8=%E2%9C%93&q=%22config.suffixes%22&type=

so I think it's OK to do so here as well.


Repository:
  rC Clang

https://reviews.llvm.org/D42395



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


[libcxx] r323563 - Fix the BinaryPredicate form of std::is_permutation to not rely on operator==

2018-01-26 Thread Peter Collingbourne via cfe-commits
Author: pcc
Date: Fri Jan 26 13:23:27 2018
New Revision: 323563

URL: http://llvm.org/viewvc/llvm-project?rev=323563&view=rev
Log:
Fix the BinaryPredicate form of std::is_permutation to not rely on operator==

According to [1], forms 2 and 4 of std::is_permutation should use the passed in
binary predicate to compare elements. operator== should only be used for forms
1 and 3 which do not take a binary predicate.

This CL fixes forms 2 and 4 which relied on operator== for some comparisons.

[1] http://en.cppreference.com/w/cpp/algorithm/is_permutation

Patch by Thomas Anderson!

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

Modified:
libcxx/trunk/include/algorithm

libcxx/trunk/test/std/algorithms/alg.nonmodifying/alg.is_permutation/is_permutation_pred.pass.cpp

Modified: libcxx/trunk/include/algorithm
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/algorithm?rev=323563&r1=323562&r2=323563&view=diff
==
--- libcxx/trunk/include/algorithm (original)
+++ libcxx/trunk/include/algorithm Fri Jan 26 13:23:27 2018
@@ -1418,7 +1418,11 @@ is_permutation(_ForwardIterator1 __first
 for (_ForwardIterator1 __i = __first1; __i != __last1; ++__i)
 {
 //  Have we already counted the number of *__i in [f1, l1)?
-if (find(__first1, __i, *__i) == __i) {
+_ForwardIterator1 __match = __first1;
+for (; __match != __i; ++__match)
+if (__pred(*__match, *__i))
+break;
+if (__match == __i) {
 // Count number of *__i in [f2, l2)
 _D1 __c2 = 0;
 for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
@@ -1479,7 +1483,11 @@ __is_permutation(_ForwardIterator1 __fir
 for (_ForwardIterator1 __i = __first1; __i != __last1; ++__i)
 {
 //  Have we already counted the number of *__i in [f1, l1)?
-if (find(__first1, __i, *__i) == __i) {
+_ForwardIterator1 __match = __first1;
+for (; __match != __i; ++__match)
+if (__pred(*__match, *__i))
+break;
+if (__match == __i) {
 // Count number of *__i in [f2, l2)
 _D1 __c2 = 0;
 for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)

Modified: 
libcxx/trunk/test/std/algorithms/alg.nonmodifying/alg.is_permutation/is_permutation_pred.pass.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/algorithms/alg.nonmodifying/alg.is_permutation/is_permutation_pred.pass.cpp?rev=323563&r1=323562&r2=323563&view=diff
==
--- 
libcxx/trunk/test/std/algorithms/alg.nonmodifying/alg.is_permutation/is_permutation_pred.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/algorithms/alg.nonmodifying/alg.is_permutation/is_permutation_pred.pass.cpp
 Fri Jan 26 13:23:27 2018
@@ -738,6 +738,30 @@ int main()
std::equal_to()) == false);
 #endif
 }
+{
+  struct S {
+  S(int i) : i_(i) {}
+  bool operator==(const S& other) = delete;
+  int i_;
+  };
+  struct eq {
+  bool operator()(const S& a, const S&b) { return a.i_ == b.i_; }
+  };
+  const S a[] = {S(0), S(1)};
+  const S b[] = {S(1), S(0)};
+  const unsigned sa = sizeof(a)/sizeof(a[0]);
+  assert(std::is_permutation(forward_iterator(a),
+ forward_iterator(a + sa),
+ forward_iterator(b),
+ eq()));
+#if TEST_STD_VER >= 14
+  assert(std::is_permutation(forward_iterator(a),
+ forward_iterator(a + sa),
+ forward_iterator(b),
+ forward_iterator(b + sa),
+ eq()));
+#endif
+}
 
 #if TEST_STD_VER > 17
 static_assert(test_constexpr());


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


Re: [PATCH] D35338: Add the -fdestroy-globals flag

2018-01-26 Thread Nico Weber via cfe-commits
I'd love to use this flag in non-firmware code FWIW.

On Fri, Jan 26, 2018 at 4:07 PM, Ian Tessier via Phabricator via
cfe-commits  wrote:

> itessier added a comment.
>
> > That seems like a nice win and I like the convenience of this approach.
> That said I've just remembered that there's a thread on cfe-dev about this:
> > [RFC] Suppress C++ static destructor registration
> > I don't think a consensus was reached. From what I gather, some people
> think that the convenience of this flag makes it worth adding to clang,
> while others think that adding a non-standard compiler-specific flag is
> asking for trouble.
>
> Given that firmware is a much different (or controlled) environment than a
> binary running on a full blown OS, would it be acceptable to name the flag
> -fbaremetal-destroy-globals, and only allow its use if the target triple's
> OS is set to none (e.g.: arm-**none**-eabi)?
>
>
> https://reviews.llvm.org/D35338
>
>
>
> ___
> 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] D35338: Add the -fdestroy-globals flag

2018-01-26 Thread Ian Tessier via Phabricator via cfe-commits
itessier added a comment.

> That seems like a nice win and I like the convenience of this approach. That 
> said I've just remembered that there's a thread on cfe-dev about this:
> [RFC] Suppress C++ static destructor registration
> I don't think a consensus was reached. From what I gather, some people think 
> that the convenience of this flag makes it worth adding to clang, while 
> others think that adding a non-standard compiler-specific flag is asking for 
> trouble.

Given that firmware is a much different (or controlled) environment than a 
binary running on a full blown OS, would it be acceptable to name the flag 
-fbaremetal-destroy-globals, and only allow its use if the target triple's OS 
is set to none (e.g.: arm-**none**-eabi)?


https://reviews.llvm.org/D35338



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


Re: [libcxx] r323453 - [cmake] [libcxx] Call llvm_setup_rpath() when adding shared libraries.

2018-01-26 Thread Don Hinton via cfe-commits
On Thu, Jan 25, 2018 at 5:20 PM, Duncan P. N. Exon Smith <
dexonsm...@apple.com> wrote:

>
>
> On Jan 25, 2018, at 17:09, Don Hinton  wrote:
>
>
>
> On Thu, Jan 25, 2018 at 4:21 PM, Duncan P. N. Exon Smith <
> dexonsm...@apple.com> wrote:
>
>>
>>
>> On Jan 25, 2018, at 16:18, Duncan P. N. Exon Smith via cfe-commits <
>> cfe-commits@lists.llvm.org> wrote:
>>
>>
>>
>> On Jan 25, 2018, at 13:07, Don Hinton  wrote:
>>
>> On Thu, Jan 25, 2018 at 12:54 PM, Chris Bieneman  wrote:
>>
>>> Historically we have supported building libcxx without llvm-config
>>> available on the system.
>>>
>>> In all likelihood the bots didn't fail because the bots do have
>>> llvm-config because we usually require an llvm build or source checkout in
>>> order to build and run the tests since tests depend on lit and gtest.
>>>
>>
>> Ah, okay, but if the bots don't test/enforce this, does it make sense to
>> continue to support building without llvm-config?
>>
>>
>> I didn't realize we didn't have a bot enforcing this.  I just made one:
>> http://lab.llvm.org:8080/green/view/Libcxx/job/libcxx_master
>> _cmake_standalone
>>
>> I don't want to break upstream users, but the alternative is to duplicate
>> this logic across multiple sub-projects.  (see http://lists.llvm.org/pip
>> ermail/llvm-dev/2018-January/120707.html for a related rpath issue).
>>
>>
>> It's temporary though.  In the brave new world on GitHub with monorepo,
>> the runtime libraries will be able to access a shared set of CMake
>> configuration scripts.
>>
>>
>> Note that there's other stuff duplicated in the runtime libraries, such
>> as preprocessor definitions (LLVM_... => __LIBCXX_...), that we'll never
>> really be able to collapse.
>>
>
> Great, I've changed it to this:
>
> +  if(LLVM_FOUND)
> +llvm_setup_rpath(cxx_shared)
> +  endif()
>
> Which should work for both cases.  Is that okay?
>
>
> SGTM.
>

Turns out LLVM_FOUND doesn't cover all cases, i.e., it's only set by libcxx
and libcxxabi when doing out-of-tree builds.  A better solution is to check
if the command is actually available:

-  if(LLVM_FOUND)
+  if(COMMAND llvm_setup_rpath)
 llvm_setup_rpath(cxx_shared)
   endif()


>
>
>
>>
>>
>>
>>
>>>
>>>
>>> -Chris
>>>
>>>
>>> On Jan 25, 2018, at 12:51 PM, Don Hinton  wrote:
>>>
>>> On Thu, Jan 25, 2018 at 12:29 PM, Duncan P. N. Exon Smith <
>>> dexonsm...@apple.com> wrote:
>>>
 I don't really understand why, but our bots seemed to survive this:
 http://lab.llvm.org:8080/green/view/Libcxx/job/libcxx_master
 _cmake/2137/

 Console output is here:
 http://lab.llvm.org:8080/green/view/Libcxx/job/libcxx_master
 _cmake/2137/consoleFull

 That doesn't necessarily mean it's safe.  Does anyone know why this
 might have "worked"?

>>>
>>> I'm not an expert, but llvm installs all of these cmake modules along
>>> side llvm-config, so if you find llvm-config, you find these modules.
>>>
>>> So, unless I'm missing something, it looks like AddLLVM.cmake is always
>>> available.
>>>
>>>

 On Jan 25, 2018, at 11:02, Shoaib Meenai  wrote:

 This is going to break building libc++ standalone (i.e. without any
 LLVM repository or even its CMake modules), right? Some upstream users care
 a lot about that use case (CC beanz and Duncan).

 *From: *cfe-commits  on behalf of
 Don Hinton via cfe-commits 
 *Reply-To: *Don Hinton 
 *Date: *Thursday, January 25, 2018 at 10:15 AM
 *To: *"cfe-commits@lists.llvm.org" 
 *Subject: *[libcxx] r323453 - [cmake] [libcxx] Call llvm_setup_rpath()
 when adding shared libraries.

 Author: dhinton
 Date: Thu Jan 25 10:13:26 2018
 New Revision: 323453

 URL: https://urldefense.proofpoint.com/v2/url?u=http-3A__llv
 m.org_viewvc_llvm-2Dproject-3Frev-3D323453-26view-3Drev&d=Dw
 IGaQ&c=5VD0RTtNlTh3ycd41b3MUw&r=o3kDXzdBUE3ljQXKeTWOMw&m=zwv
 Smk9ZIfMARYg3JvYvNuA0Iz-PEq3H2i_ICF6vsR8&s=LDCu89byjNdZWoCIY
 HGHaPr3IamIdHLF0JwbnYE92vM&e=
 Log:
 [cmake] [libcxx] Call llvm_setup_rpath() when adding shared libraries.

 Clang and llvm already use llvm_setup_rpath(), so this change will
 help standarize rpath usage across all projects.

 Differential Revision: https://urldefense.p
 roofpoint.com/v2/url?u=https-3A__reviews.llvm.org_D42459&d=D
 wIGaQ&c=5VD0RTtNlTh3ycd41b3MUw&r=o3kDXzdBUE3ljQXKeTWOMw&m=zw
 vSmk9ZIfMARYg3JvYvNuA0Iz-PEq3H2i_ICF6vsR8&s=YCR-YJBua5p-4IK0
 5GjHoZUU7aN8UJAFzL2xaz7byyw&e=

 Modified:
 libcxx/trunk/lib/CMakeLists.txt

 Modified: libcxx/trunk/lib/CMakeLists.txt
 URL: https://urldefense.proofpoint.com/v2/url?u=http-3A__llv
 m.org_viewvc_llvm-2Dproject_libcxx_trunk_lib_CMakeLists.txt-
 3Frev-3D323453-26r1-3D323452-26r2-3D323453-26view-3Ddiff&d=D
 wIGaQ&c=5VD0RTtNlTh3ycd41b3MUw&r=o3kDXzdBUE3ljQXKeTWOMw&m=zw
 vSmk9ZIfMARYg3JvYvNuA0Iz-PEq3H2i_ICF6vsR8&s=Rd7xc2GWS8oyDcm0
 QshNPTqM3BglPY5_aHMIuCRUt1s&e=
 

[PATCH] D16403: Add scope information to CFG

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

> Do we need to have one-to-one mapping between ScopeBegins and corresponding 
> ScopeEnds or is it OK to assume that ScopeEnd can terminate several nested 
> scopes?

It's fine if `ScopeEnds` terminates multiple scopes - as long as it is easy to 
find out what scopes are being terminated by looking at it. Because in the 
analyzer we need to put the scope on the stack when we enter it and pop it from 
the stack when we leave it, and those must match no matter what. So imagine 
that we look at the current `ScopeEnd` and at the stack of scopes we currently 
have. Once we have that, we should be able to figure out what scopes are 
ending, without using `ParentMap` or `CFGStmtMap` or re-visiting a large chunk 
of the AST recursively - ideally by a direct lookup.


Repository:
  rL LLVM

https://reviews.llvm.org/D16403



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


[PATCH] D16403: Add scope information to CFG

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

Hmm. @m.ostapenko @szepet @mgehre - I think it might be a good time to figure 
out if `ScopeBegin`/`ScopeEnd`, `LoopEntrance`/`LoopExit`, `LifetimeEnds`, 
`AutomaticObjectDtor` elements work nicely together. How should they be ordered 
with respect to each other? Is any of these scope representation a superset of 
another scope representation, or maybe fully covered by other two or three 
other scope representations? Would anybody be willing to produce some pictures 
(`-analyzer-checker debug.ViewCFG` and attach here) with current and/or 
intended behavior? Not sure, i guess `LifetimeEnds` is mostly used in 
`clang-tidy` so it does not necessarily need to work together with 
analyzer-specific elements (or maybe it's so great that we should switch to 
using it), but it would still be great if we had a single scope representation 
which would be rich enough to satisfy all needs.


Repository:
  rL LLVM

https://reviews.llvm.org/D16403



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


r323554 - Try to unbreak 32 bit builds after r323528.

2018-01-26 Thread Benjamin Kramer via cfe-commits
Author: d0k
Date: Fri Jan 26 12:01:13 2018
New Revision: 323554

URL: http://llvm.org/viewvc/llvm-project?rev=323554&view=rev
Log:
Try to unbreak 32 bit builds after r323528.

Modified:
cfe/trunk/include/clang/AST/Decl.h

Modified: cfe/trunk/include/clang/AST/Decl.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=323554&r1=323553&r2=323554&view=diff
==
--- cfe/trunk/include/clang/AST/Decl.h (original)
+++ cfe/trunk/include/clang/AST/Decl.h Fri Jan 26 12:01:13 2018
@@ -83,7 +83,7 @@ class VarTemplateDecl;
 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
 /// TL.getStartLoc().print(OS, SrcMgr);
 /// @endcode
-class TypeSourceInfo {
+class LLVM_ALIGNAS(8) TypeSourceInfo {
   // Contains a memory block after the class, used for type source information,
   // allocated by ASTContext.
   friend class ASTContext;
@@ -2813,7 +2813,10 @@ public:
 
 /// Base class for declarations which introduce a typedef-name.
 class TypedefNameDecl : public TypeDecl, public Redeclarable {
-  using ModedTInfo = std::pair;
+  struct LLVM_ALIGNAS(8) ModedTInfo {
+TypeSourceInfo *first;
+QualType second;
+  };
 
   /// If int part is 0, we have not computed IsTransparentTag.
   /// Otherwise, IsTransparentTag is (getInt() >> 1).
@@ -2877,7 +2880,7 @@ public:
 
   void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
-   ModedTInfo(unmodedTSI, modedTy));
+   ModedTInfo({unmodedTSI, modedTy}));
   }
 
   /// Retrieves the canonical declaration of this typedef-name.


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


Re: r323528 - [AST] Use bit packing to reduce sizeof(TypedefNameDecl) from 88 to 80.

2018-01-26 Thread Vlad Tsyrklevich via cfe-commits
This change has broken a number of buildbots, e.g.
http://lab.llvm.org:8011/builders/sanitizer-windows/builds/23163

On Fri, Jan 26, 2018 at 6:15 AM Benjamin Kramer via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: d0k
> Date: Fri Jan 26 06:14:11 2018
> New Revision: 323528
>
> URL: http://llvm.org/viewvc/llvm-project?rev=323528&view=rev
> Log:
> [AST] Use bit packing to reduce sizeof(TypedefNameDecl) from 88 to 80.
>
> We can stash the cached transparent tag bit in existing pointer padding.
> Everything coming out of ASTContext is always aligned to a multiple of
> 8, so we have 8 spare bits.
>
> Modified:
> cfe/trunk/include/clang/AST/Decl.h
> cfe/trunk/lib/AST/Decl.cpp
>
> Modified: cfe/trunk/include/clang/AST/Decl.h
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=323528&r1=323527&r2=323528&view=diff
>
> ==
> --- cfe/trunk/include/clang/AST/Decl.h (original)
> +++ cfe/trunk/include/clang/AST/Decl.h Fri Jan 26 06:14:11 2018
> @@ -2814,12 +2814,12 @@ public:
>  /// Base class for declarations which introduce a typedef-name.
>  class TypedefNameDecl : public TypeDecl, public
> Redeclarable {
>using ModedTInfo = std::pair;
> -  llvm::PointerUnion MaybeModedTInfo;
>
> -  // FIXME: This can be packed into the bitfields in Decl.
> -  /// If 0, we have not computed IsTransparentTag.
> -  /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1).
> -  mutable unsigned CacheIsTransparentTag : 2;
> +  /// If int part is 0, we have not computed IsTransparentTag.
> +  /// Otherwise, IsTransparentTag is (getInt() >> 1).
> +  mutable llvm::PointerIntPair<
> +  llvm::PointerUnion, 2>
> +  MaybeModedTInfo;
>
>void anchor() override;
>
> @@ -2828,7 +2828,7 @@ protected:
>SourceLocation StartLoc, SourceLocation IdLoc,
>IdentifierInfo *Id, TypeSourceInfo *TInfo)
>: TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
> -MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {}
> +MaybeModedTInfo(TInfo, 0) {}
>
>using redeclarable_base = Redeclarable;
>
> @@ -2855,26 +2855,29 @@ public:
>using redeclarable_base::getMostRecentDecl;
>using redeclarable_base::isFirstDecl;
>
> -  bool isModed() const { return MaybeModedTInfo.is(); }
> +  bool isModed() const {
> +return MaybeModedTInfo.getPointer().is();
> +  }
>
>TypeSourceInfo *getTypeSourceInfo() const {
> -return isModed()
> -  ? MaybeModedTInfo.get()->first
> -  : MaybeModedTInfo.get();
> +return isModed() ? MaybeModedTInfo.getPointer().get *>()->first
> + : MaybeModedTInfo.getPointer().get *>();
>}
>
>QualType getUnderlyingType() const {
> -return isModed()
> -  ? MaybeModedTInfo.get()->second
> -  : MaybeModedTInfo.get()->getType();
> +return isModed() ? MaybeModedTInfo.getPointer().get *>()->second
> + : MaybeModedTInfo.getPointer()
> +   .get()
> +   ->getType();
>}
>
>void setTypeSourceInfo(TypeSourceInfo *newType) {
> -MaybeModedTInfo = newType;
> +MaybeModedTInfo.setPointer(newType);
>}
>
>void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType
> modedTy) {
> -MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI,
> modedTy);
> +MaybeModedTInfo.setPointer(new (getASTContext(), 8)
> +   ModedTInfo(unmodedTSI, modedTy));
>}
>
>/// Retrieves the canonical declaration of this typedef-name.
> @@ -2891,8 +2894,8 @@ public:
>/// Determines if this typedef shares a name and spelling location with
> its
>/// underlying tag type, as is the case with the NS_ENUM macro.
>bool isTransparentTag() const {
> -if (CacheIsTransparentTag)
> -  return CacheIsTransparentTag & 0x2;
> +if (MaybeModedTInfo.getInt())
> +  return MaybeModedTInfo.getInt() & 0x2;
>  return isTransparentTagSlow();
>}
>
>
> Modified: cfe/trunk/lib/AST/Decl.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=323528&r1=323527&r2=323528&view=diff
>
> ==
> --- cfe/trunk/lib/AST/Decl.cpp (original)
> +++ cfe/trunk/lib/AST/Decl.cpp Fri Jan 26 06:14:11 2018
> @@ -4372,9 +4372,7 @@ bool TypedefNameDecl::isTransparentTagSl
>};
>
>bool isTransparent = determineIsTransparent();
> -  CacheIsTransparentTag = 1;
> -  if (isTransparent)
> -CacheIsTransparentTag |= 0x2;
> +  MaybeModedTInfo.setInt((isTransparent << 1) | 1);
>return isTransparent;
>  }
>
>
>
> ___
> 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

[PATCH] D42573: [wip] The new threading implementation

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

OK, here's a braindump, probably nothing surprising after our offline 
discussion.

TL;DR: the only design I *know* is extensible in ways we care about is the one 
that basically shards Scheduler into a bunch of per-TU schedulers.
I think that's probably the way to go, but if you can show how to cleanly 
extend one of the other options, we should compare those on the merits.

I think if we do adopt and stick with the sharding design, then a public API 
that reflects it is slightly nicer overall.
But it's not that important to me, tastes may vary, and above all I don't want 
to block the API patch on coming to a decision on the question above.
So I think we should agree on a name and then land the API patch with the 
interface it has now.




Comment at: clangd/ClangdServer.cpp:192
+
 Scheduler::Scheduler(unsigned AsyncThreadsCount, bool StorePreamblesInMemory,
  ASTParsedCallback ASTCallback)

So... scheduler and the queue abstraction.
This works pretty well for the functionality that's in this patch, which is at 
least as good as what's in the live version.
However I think we want to e.g. debounce diagnostic requests, and likely other 
such things, e.g. Indexing is a nice candidate for debouncing *and* preemption.

(Current diagnostics behavior: we compute and send diagnostics for the syntax 
error introduced by the first keystroke. This is wasted load, and increases 
latency for diagnostics on the *last* keystroke, since we have to wait for the 
previous one to finish)

So we should consider some other options...



Comment at: clangd/ClangdServer.cpp:193
 Scheduler::Scheduler(unsigned AsyncThreadsCount, bool StorePreamblesInMemory,
  ASTParsedCallback ASTCallback)
+: Data{StorePreamblesInMemory, std::make_shared(),

Option 1: Put all timing-related logic in scheduler.

I think this probably means Scheduler itself gets a thread whose job it is to 
wake up at certain times and schedule or cancel tasks on the queues.
`update` would set an alarm to add a task on the queue, which would be 
invalidated by any subsequent update. The easiest way to implement this is 
probably to track a version number that increments on update calls and is 
captured by the alarm.

This gets complicated by reads after updates that haven't finished yet - you 
need force the update to  happen now, so you need to schedule the thing and 
prevent the alarm from scheduling it.
It seems like in general trying to do nontrivial things may end up with a bunch 
of interacting actors and shared data structures that are hard to reason about 
and verify.



Comment at: clangd/ClangdServer.cpp:194
  ASTParsedCallback ASTCallback)
-: Units(StorePreamblesInMemory, std::make_shared(),
-std::move(ASTCallback)),
+: Data{StorePreamblesInMemory, std::make_shared(),
+   std::move(ASTCallback)},

Option 2: Share timing-related additions between scheduler and queue, but keep 
the tasks opaque to the queue.
This means extending the queue abstraction e.g. instead of just tasks, 
understand (delay, priority, task) tuples.

This isn't all that different from option 1, but moving some of the pieces out 
of scheduler might reduce the ball of hair to a manageable size, and add some 
conceptual clarity.



Comment at: clangd/ClangdServer.cpp:195
+: Data{StorePreamblesInMemory, std::make_shared(),
+   std::move(ASTCallback)},
   Executor(AsyncThreadsCount) {}

Option 3: extend the responsibilities of Queue so this is naturally its concern.
It needs to understand the timing, dependencies between tasks, and it probably 
makes sense to know when they become redundant etc too.

The easiest way to express this is that Queue owns a thread and implements the 
run-loop for actions on a single TU, and Scheduler's operations basically 
delegate to Queue. 

FWIW, this can be transformed into a version without dedicated threads. First 
we write the thread version in this form:

```
runLoop() {
  while (!shutdown) {
nextThing = decideWhatToDo(); // either action, or a sleep duration
if (nextThing.action)
  nextThing.action();
else
  interrupt.wait(nextThing.sleepDuration); // any update(), withAST etc 
interrupts
  }
}
```

I don't think it'd be hard to write a threadpool-based executor that runs 
"workloads" defined by their decideWhatToDo() function and their interactions 
with the `interrupt` condition variable. (I don't know exactly what a nice API 
would look like, but details...)

That said, I definitely think the thread/runloop based one is an easier place 
to start, and suspect it would be good enough.



Comment at: clangd/ClangdServer.cpp:196
+   std::move(ASTCallback)},
   Executor(AsyncThreadsCount) {}
 

My conclusion (feel free to disagree

[PATCH] D42593: GCC compatibility: Ignore -fstack-clash-protection

2018-01-26 Thread Tom Stellard via Phabricator via cfe-commits
tstellar created this revision.
tstellar added a reviewer: sylvestre.ledru.

Repository:
  rC Clang

https://reviews.llvm.org/D42593

Files:
  include/clang/Driver/Options.td
  test/Driver/clang_f_opts.c


Index: test/Driver/clang_f_opts.c
===
--- test/Driver/clang_f_opts.c
+++ test/Driver/clang_f_opts.c
@@ -284,6 +284,7 @@
 // RUN: -ffriend-injection\
 // RUN: -fno-implement-inlines -fimplement-inlines\
 // RUN: -fstack-check \
+// RUN: -fstack-clash-protection  \
 // RUN: -fforce-addr  \
 // RUN: -malign-functions=100 \
 // RUN: -malign-loops=100 \
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -2705,6 +2705,7 @@
 Group;
 defm spec_constr_count : BooleanFFlag<"spec-constr-count">, 
Group;
 defm stack_check : BooleanFFlag<"stack-check">, Group;
+defm stack_clash_protection : BooleanFFlag<"stack-clash-protection">, 
Group;
 defm strength_reduce :
 BooleanFFlag<"strength-reduce">, 
Group;
 defm tls_model : BooleanFFlag<"tls-model">, Group;


Index: test/Driver/clang_f_opts.c
===
--- test/Driver/clang_f_opts.c
+++ test/Driver/clang_f_opts.c
@@ -284,6 +284,7 @@
 // RUN: -ffriend-injection\
 // RUN: -fno-implement-inlines -fimplement-inlines\
 // RUN: -fstack-check \
+// RUN: -fstack-clash-protection  \
 // RUN: -fforce-addr  \
 // RUN: -malign-functions=100 \
 // RUN: -malign-loops=100 \
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -2705,6 +2705,7 @@
 Group;
 defm spec_constr_count : BooleanFFlag<"spec-constr-count">, Group;
 defm stack_check : BooleanFFlag<"stack-check">, Group;
+defm stack_clash_protection : BooleanFFlag<"stack-clash-protection">, Group;
 defm strength_reduce :
 BooleanFFlag<"strength-reduce">, Group;
 defm tls_model : BooleanFFlag<"tls-model">, Group;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323552 - [X86] Add 'rdrnd' feature to silvermont to match recent gcc bug fix.

2018-01-26 Thread Craig Topper via cfe-commits
Author: ctopper
Date: Fri Jan 26 11:34:45 2018
New Revision: 323552

URL: http://llvm.org/viewvc/llvm-project?rev=323552&view=rev
Log:
[X86] Add 'rdrnd' feature to silvermont to match recent gcc bug fix.

gcc recently fixed this bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83546

Modified:
cfe/trunk/lib/Basic/Targets/X86.cpp
cfe/trunk/test/Preprocessor/predefined-arch-macros.c

Modified: cfe/trunk/lib/Basic/Targets/X86.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/X86.cpp?rev=323552&r1=323551&r2=323552&view=diff
==
--- cfe/trunk/lib/Basic/Targets/X86.cpp (original)
+++ cfe/trunk/lib/Basic/Targets/X86.cpp Fri Jan 26 11:34:45 2018
@@ -239,7 +239,6 @@ bool X86TargetInfo::initFeatureMap(
 
   case CK_Goldmont:
 setFeatureEnabledImpl(Features, "sha", true);
-setFeatureEnabledImpl(Features, "rdrnd", true);
 setFeatureEnabledImpl(Features, "rdseed", true);
 setFeatureEnabledImpl(Features, "xsave", true);
 setFeatureEnabledImpl(Features, "xsaveopt", true);
@@ -250,6 +249,7 @@ bool X86TargetInfo::initFeatureMap(
 setFeatureEnabledImpl(Features, "fsgsbase", true);
 LLVM_FALLTHROUGH;
   case CK_Silvermont:
+setFeatureEnabledImpl(Features, "rdrnd", true);
 setFeatureEnabledImpl(Features, "aes", true);
 setFeatureEnabledImpl(Features, "pclmul", true);
 setFeatureEnabledImpl(Features, "sse4.2", true);

Modified: cfe/trunk/test/Preprocessor/predefined-arch-macros.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Preprocessor/predefined-arch-macros.c?rev=323552&r1=323551&r2=323552&view=diff
==
--- cfe/trunk/test/Preprocessor/predefined-arch-macros.c (original)
+++ cfe/trunk/test/Preprocessor/predefined-arch-macros.c Fri Jan 26 11:34:45 
2018
@@ -1272,6 +1272,7 @@
 // CHECK_SLM_M32: #define __PCLMUL__ 1
 // CHECK_SLM_M32: #define __POPCNT__ 1
 // CHECK_SLM_M32: #define __PRFCHW__ 1
+// CHECK_SLM_M32: #define __RDRND__ 1
 // CHECK_SLM_M32: #define __SSE2__ 1
 // CHECK_SLM_M32: #define __SSE3__ 1
 // CHECK_SLM_M32: #define __SSE4_1__ 1
@@ -1293,6 +1294,7 @@
 // CHECK_SLM_M64: #define __PCLMUL__ 1
 // CHECK_SLM_M64: #define __POPCNT__ 1
 // CHECK_SLM_M64: #define __PRFCHW__ 1
+// CHECK_SLM_M64: #define __RDRND__ 1
 // CHECK_SLM_M64: #define __SSE2_MATH__ 1
 // CHECK_SLM_M64: #define __SSE2__ 1
 // CHECK_SLM_M64: #define __SSE3__ 1


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


[PATCH] D42588: [index] Fix crash when indexing a C++14 PCH/module related to TemplateTemplateParmDecls of alias templates

2018-01-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323549: [index] Fix crash when indexing a C++14 PCH/module 
related to… (authored by akirtzidis, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42588?vs=131620&id=131629#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42588

Files:
  cfe/trunk/lib/Index/IndexDecl.cpp
  cfe/trunk/lib/Serialization/ASTWriter.cpp
  cfe/trunk/test/Index/Core/index-pch.cpp


Index: cfe/trunk/lib/Serialization/ASTWriter.cpp
===
--- cfe/trunk/lib/Serialization/ASTWriter.cpp
+++ cfe/trunk/lib/Serialization/ASTWriter.cpp
@@ -5537,7 +5537,9 @@
 return;
   // FIXME: ParmVarDecls that are part of a function type of a parameter of
   // a function/objc method, should not have TU as lexical context.
-  if (isa(D))
+  // TemplateTemplateParmDecls that are part of an alias template, should not
+  // have TU as lexical context.
+  if (isa(D) || isa(D))
 return;
 
   SourceManager &SM = Context->getSourceManager();
Index: cfe/trunk/lib/Index/IndexDecl.cpp
===
--- cfe/trunk/lib/Index/IndexDecl.cpp
+++ cfe/trunk/lib/Index/IndexDecl.cpp
@@ -664,8 +664,11 @@
 
   bool VisitTemplateDecl(const TemplateDecl *D) {
 
-// Index the default values for the template parameters.
 const NamedDecl *Parent = D->getTemplatedDecl();
+if (!Parent)
+  return true;
+
+// Index the default values for the template parameters.
 if (D->getTemplateParameters() &&
 shouldIndexTemplateParameterDefaultValue(Parent)) {
   const TemplateParameterList *Params = D->getTemplateParameters();
@@ -684,7 +687,7 @@
   }
 }
 
-return Visit(D->getTemplatedDecl());
+return Visit(Parent);
   }
 
   bool VisitFriendDecl(const FriendDecl *D) {
Index: cfe/trunk/test/Index/Core/index-pch.cpp
===
--- cfe/trunk/test/Index/Core/index-pch.cpp
+++ cfe/trunk/test/Index/Core/index-pch.cpp
@@ -0,0 +1,17 @@
+// RUN: c-index-test core -print-source-symbols -- %s -std=c++14 | FileCheck %s
+// RUN: %clang_cc1 -emit-pch %s -std=c++14 -o %t.pch
+// RUN: c-index-test core -print-source-symbols -module-file %t.pch | 
FileCheck %s
+
+// CHECK: [[@LINE+2]]:8 | struct(Gen)/C++ | DETECTOR | [[DETECTOR_USR:.*]] | 
{{.*}} | Def | rel: 0
+template  class _Op, 
class... _Args>
+struct DETECTOR {
+ using value_t = int;
+};
+
+struct nonesuch {};
+
+// CHECK: [[@LINE+4]]:9 | type-alias/C++ | is_detected
+// CHECK: [[@LINE+3]]:32 | struct(Gen)/C++ | DETECTOR | [[DETECTOR_USR]] | 
{{.*}} | Ref,RelCont | rel: 1
+// CHECK-NEXT: RelCont | is_detected
+template  class _Op, class... _Args>
+  using is_detected = typename DETECTOR::value_t;


Index: cfe/trunk/lib/Serialization/ASTWriter.cpp
===
--- cfe/trunk/lib/Serialization/ASTWriter.cpp
+++ cfe/trunk/lib/Serialization/ASTWriter.cpp
@@ -5537,7 +5537,9 @@
 return;
   // FIXME: ParmVarDecls that are part of a function type of a parameter of
   // a function/objc method, should not have TU as lexical context.
-  if (isa(D))
+  // TemplateTemplateParmDecls that are part of an alias template, should not
+  // have TU as lexical context.
+  if (isa(D) || isa(D))
 return;
 
   SourceManager &SM = Context->getSourceManager();
Index: cfe/trunk/lib/Index/IndexDecl.cpp
===
--- cfe/trunk/lib/Index/IndexDecl.cpp
+++ cfe/trunk/lib/Index/IndexDecl.cpp
@@ -664,8 +664,11 @@
 
   bool VisitTemplateDecl(const TemplateDecl *D) {
 
-// Index the default values for the template parameters.
 const NamedDecl *Parent = D->getTemplatedDecl();
+if (!Parent)
+  return true;
+
+// Index the default values for the template parameters.
 if (D->getTemplateParameters() &&
 shouldIndexTemplateParameterDefaultValue(Parent)) {
   const TemplateParameterList *Params = D->getTemplateParameters();
@@ -684,7 +687,7 @@
   }
 }
 
-return Visit(D->getTemplatedDecl());
+return Visit(Parent);
   }
 
   bool VisitFriendDecl(const FriendDecl *D) {
Index: cfe/trunk/test/Index/Core/index-pch.cpp
===
--- cfe/trunk/test/Index/Core/index-pch.cpp
+++ cfe/trunk/test/Index/Core/index-pch.cpp
@@ -0,0 +1,17 @@
+// RUN: c-index-test core -print-source-symbols -- %s -std=c++14 | FileCheck %s
+// RUN: %clang_cc1 -emit-pch %s -std=c++14 -o %t.pch
+// RUN: c-index-test core -print-source-symbols -module-file %t.pch | FileCheck %s
+
+// CHECK: [[@LINE+2]]:8 | struct(Gen)/C++ | DETECTOR | [[DETECTOR_USR:.*]] | {{.*}} | Def | rel: 0
+template  class _Op, class... _Args>
+struct DETECTOR {
+ using value_t = int;
+};
+
+struct nonesuch {};
+
+// CHECK: [[@LINE+4]]:9 | type-alias/C

r323549 - [index] Fix crash when indexing a C++14 PCH/module related to TemplateTemplateParmDecls of alias templates

2018-01-26 Thread Argyrios Kyrtzidis via cfe-commits
Author: akirtzidis
Date: Fri Jan 26 11:26:12 2018
New Revision: 323549

URL: http://llvm.org/viewvc/llvm-project?rev=323549&view=rev
Log:
[index] Fix crash when indexing a C++14 PCH/module related to 
TemplateTemplateParmDecls of alias templates

TemplateTemplateParmDecls of alias templates ended-up serialized as 'file-level 
decls' which was causing a crash while trying to index a PCH/module file that 
contained them.
Commit makes sure TemplateTemplateParmDecls are not recorded as such kind of 
decls.

Fixes crash of rdar://36608297

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

Added:
cfe/trunk/test/Index/Core/index-pch.cpp
Modified:
cfe/trunk/lib/Index/IndexDecl.cpp
cfe/trunk/lib/Serialization/ASTWriter.cpp

Modified: cfe/trunk/lib/Index/IndexDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Index/IndexDecl.cpp?rev=323549&r1=323548&r2=323549&view=diff
==
--- cfe/trunk/lib/Index/IndexDecl.cpp (original)
+++ cfe/trunk/lib/Index/IndexDecl.cpp Fri Jan 26 11:26:12 2018
@@ -664,8 +664,11 @@ public:
 
   bool VisitTemplateDecl(const TemplateDecl *D) {
 
-// Index the default values for the template parameters.
 const NamedDecl *Parent = D->getTemplatedDecl();
+if (!Parent)
+  return true;
+
+// Index the default values for the template parameters.
 if (D->getTemplateParameters() &&
 shouldIndexTemplateParameterDefaultValue(Parent)) {
   const TemplateParameterList *Params = D->getTemplateParameters();
@@ -684,7 +687,7 @@ public:
   }
 }
 
-return Visit(D->getTemplatedDecl());
+return Visit(Parent);
   }
 
   bool VisitFriendDecl(const FriendDecl *D) {

Modified: cfe/trunk/lib/Serialization/ASTWriter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Serialization/ASTWriter.cpp?rev=323549&r1=323548&r2=323549&view=diff
==
--- cfe/trunk/lib/Serialization/ASTWriter.cpp (original)
+++ cfe/trunk/lib/Serialization/ASTWriter.cpp Fri Jan 26 11:26:12 2018
@@ -5537,7 +5537,9 @@ void ASTWriter::associateDeclWithFile(co
 return;
   // FIXME: ParmVarDecls that are part of a function type of a parameter of
   // a function/objc method, should not have TU as lexical context.
-  if (isa(D))
+  // TemplateTemplateParmDecls that are part of an alias template, should not
+  // have TU as lexical context.
+  if (isa(D) || isa(D))
 return;
 
   SourceManager &SM = Context->getSourceManager();

Added: cfe/trunk/test/Index/Core/index-pch.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/Core/index-pch.cpp?rev=323549&view=auto
==
--- cfe/trunk/test/Index/Core/index-pch.cpp (added)
+++ cfe/trunk/test/Index/Core/index-pch.cpp Fri Jan 26 11:26:12 2018
@@ -0,0 +1,17 @@
+// RUN: c-index-test core -print-source-symbols -- %s -std=c++14 | FileCheck %s
+// RUN: %clang_cc1 -emit-pch %s -std=c++14 -o %t.pch
+// RUN: c-index-test core -print-source-symbols -module-file %t.pch | 
FileCheck %s
+
+// CHECK: [[@LINE+2]]:8 | struct(Gen)/C++ | DETECTOR | [[DETECTOR_USR:.*]] | 
{{.*}} | Def | rel: 0
+template  class _Op, 
class... _Args>
+struct DETECTOR {
+ using value_t = int;
+};
+
+struct nonesuch {};
+
+// CHECK: [[@LINE+4]]:9 | type-alias/C++ | is_detected
+// CHECK: [[@LINE+3]]:32 | struct(Gen)/C++ | DETECTOR | [[DETECTOR_USR]] | 
{{.*}} | Ref,RelCont | rel: 1
+// CHECK-NEXT: RelCont | is_detected
+template  class _Op, class... _Args>
+  using is_detected = typename DETECTOR::value_t;


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


[PATCH] D42581: [NVPTX] Emit debug info in DWARF-2 by default for Cuda devices.

2018-01-26 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: lib/Driver/ToolChains/Cuda.cpp:353
   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
+  if (mustEmitDebugInfo(Args) && Args.hasArg(options::OPT_g_Flag))
+CmdArgs.push_back("-g");

ABataev wrote:
> tra wrote:
> > ABataev wrote:
> > > tra wrote:
> > > > There's more than one -g option. Presumably you still want -g here for 
> > > > -g{1,2,3} or -ggdb{1,2,3} or -gdwarf2.
> > > > 
> > > > Speaking of dwarf, what's going to happen if someone passes -gdwarf5?  
> > > > Should we downgrade it to -gdwarf2 on device side and issue a warning?
> > > > 
> > > That's exactly what I want to avoid. I think we can ignore these options 
> > > and handle only `-g` option.
> > > Or I can add a function to ToolChain class to force using the default 
> > > settings for debugger tuning and DWARF version rather than take them from 
> > > the driver options.
> > You should handle at least -gN/-gline-tables-only/-g. Now that we can emit 
> > dwarf debug info, I would want to be able to control it to some degree -- 
> > off/line-info-only/full.
> > 
> > I'm still not sure what's the plan for -gdwarfN unsupported on device side? 
> > - do we ignore it and always emit dwarf2?
> > - do we accept it, emit requested version and let user stare at ptxas (or 
> > cuda-gdb) errors when it fails to deal with it?
> > 
> > 
> > 
> > 
> 1. Ok, will look at this
> 2. -gdwarfN should be ignored, we should always emit DWARF2, otherwise, it 
> will break ptxas.
Works for me. Please add a test to verify that it's always dwarf2 on device 
side.


Repository:
  rC Clang

https://reviews.llvm.org/D42581



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


[PATCH] D42530: Clang permits assignment to vector/extvector elements in a const method

2018-01-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/AST/ExprClassification.cpp:652
+if (Ctx.getCanonicalType(ASE->getBase()->getType()).isConstQualified())
+  return Cl::CM_ConstQualified;
+

avt77 wrote:
> rjmccall wrote:
> > Is there a reason why the places that compute the type of these l-value 
> > expressions don't propagate qualiifers?  This hardly seems restricted to 
> > 'const'.
> Do you mean ExtVectorElementExpr/ArraySubscriptExpr should retrun 
> isConstQualified() == true by themselves (and other qualifiers as well)?
In the sense that Sema should create them with a type that is const-qualified 
when the underlying vector l-value is const-qualified, yes.


https://reviews.llvm.org/D42530



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


[PATCH] D42581: [NVPTX] Emit debug info in DWARF-2 by default for Cuda devices.

2018-01-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/Driver/ToolChains/Cuda.cpp:353
   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
+  if (mustEmitDebugInfo(Args) && Args.hasArg(options::OPT_g_Flag))
+CmdArgs.push_back("-g");

tra wrote:
> ABataev wrote:
> > tra wrote:
> > > There's more than one -g option. Presumably you still want -g here for 
> > > -g{1,2,3} or -ggdb{1,2,3} or -gdwarf2.
> > > 
> > > Speaking of dwarf, what's going to happen if someone passes -gdwarf5?  
> > > Should we downgrade it to -gdwarf2 on device side and issue a warning?
> > > 
> > That's exactly what I want to avoid. I think we can ignore these options 
> > and handle only `-g` option.
> > Or I can add a function to ToolChain class to force using the default 
> > settings for debugger tuning and DWARF version rather than take them from 
> > the driver options.
> You should handle at least -gN/-gline-tables-only/-g. Now that we can emit 
> dwarf debug info, I would want to be able to control it to some degree -- 
> off/line-info-only/full.
> 
> I'm still not sure what's the plan for -gdwarfN unsupported on device side? 
> - do we ignore it and always emit dwarf2?
> - do we accept it, emit requested version and let user stare at ptxas (or 
> cuda-gdb) errors when it fails to deal with it?
> 
> 
> 
> 
1. Ok, will look at this
2. -gdwarfN should be ignored, we should always emit DWARF2, otherwise, it will 
break ptxas.


Repository:
  rC Clang

https://reviews.llvm.org/D42581



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


r323547 - AST: support protocol conformances on id/class/interfaces in MS ABI

2018-01-26 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Fri Jan 26 11:08:26 2018
New Revision: 323547

URL: http://llvm.org/viewvc/llvm-project?rev=323547&view=rev
Log:
AST: support protocol conformances on id/class/interfaces in MS ABI

Add support for mangling ObjC protocol conformances in MS ABI as if they are
COM interfaces. By diverging from the itanium mangling of `objc_protocol`
prefixed names, this approach allows for a semi-reasonable, albeit of
questionable sanity, undecoration via existing tooling. There is also the
possibility of adding an extension and taking part of the namespace to add the
conformance via the `L` and `Z` "modifiers", but the existing tooling would not
be able to properly undecorated the symbol even though incidentally `undname`
currently produces something legible while wine's implementation is not able to
cope with the extension.

This allows for the disambiguation of overloads where the parameter differs
only in the protocol conformance of the ObjC type, e.g.

```
@protocol P;
void f(std::vector);
void f(std::vector>);
```

which clang would previously fail due to the mangling being identical as the
protocol conformance was ignored.

Added:
cfe/trunk/test/CodeGenObjCXX/msabi-protocol-conformance.mm
Modified:
cfe/trunk/lib/AST/MicrosoftMangle.cpp

Modified: cfe/trunk/lib/AST/MicrosoftMangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/MicrosoftMangle.cpp?rev=323547&r1=323546&r2=323547&view=diff
==
--- cfe/trunk/lib/AST/MicrosoftMangle.cpp (original)
+++ cfe/trunk/lib/AST/MicrosoftMangle.cpp Fri Jan 26 11:08:26 2018
@@ -2450,9 +2450,36 @@ void MicrosoftCXXNameMangler::mangleType
 
 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
  SourceRange Range) {
-  // We don't allow overloading by different protocol qualification,
-  // so mangling them isn't necessary.
-  mangleType(T->getBaseType(), Range, QMM_Drop);
+  if (T->qual_empty())
+return mangleType(T->getBaseType(), Range, QMM_Drop);
+
+  ArgBackRefMap OuterArgsContext;
+  BackRefVec OuterTemplateContext;
+
+  TypeBackReferences.swap(OuterArgsContext);
+  NameBackReferences.swap(OuterTemplateContext);
+
+  mangleTagTypeKind(TTK_Struct);
+
+  Out << "?$";
+  if (T->isObjCId())
+mangleSourceName("objc_object");
+  else if (T->isObjCClass())
+mangleSourceName("objc_class");
+  else
+mangleSourceName(T->getInterface()->getName());
+
+  for (const auto &Q : T->quals()) {
+Out << 'Y'; // cointerface
+mangleSourceName(Q->getName());
+Out << '@';
+  }
+  Out << '@';
+
+  Out << '@';
+
+  TypeBackReferences.swap(OuterArgsContext);
+  NameBackReferences.swap(OuterTemplateContext);
 }
 
 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,

Added: cfe/trunk/test/CodeGenObjCXX/msabi-protocol-conformance.mm
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjCXX/msabi-protocol-conformance.mm?rev=323547&view=auto
==
--- cfe/trunk/test/CodeGenObjCXX/msabi-protocol-conformance.mm (added)
+++ cfe/trunk/test/CodeGenObjCXX/msabi-protocol-conformance.mm Fri Jan 26 
11:08:26 2018
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -triple thumbv7-windows-msvc -fobjc-runtime=ios-6.0 -o - 
-emit-llvm %s | FileCheck %s
+
+@protocol P;
+@protocol Q;
+
+@class I;
+
+void f(id, id, id, id) {}
+// CHECK-LABEL: "\01?f@@YAXPAU?$objc_object@YPPAUobjc_object@@01@Z"
+
+void f(id, id, id, id) {}
+// CHECK-LABEL: "\01?f@@YAXPAUobjc_object@@PAU?$objc_object@YP10@Z"
+
+void f(id, id) {}
+// CHECK-LABEL: "\01?f@@YAXPAU?$objc_object@YP0@Z"
+
+void f(id) {}
+// CHECK-LABEL: "\01?f@@YAXPAU?$objc_object@YP@Z"
+
+void f(id) {}
+// CHECK-LABEL: "\01?f@@YAXPAU?$objc_object@YP@@YQ@Z"
+
+void f(Class) {}
+// CHECK-LABEL: "\01?f@@YAXPAU?$objc_class@YP@Z"
+
+void f(Class) {}
+// CHECK-LABEL: "\01?f@@YAXPAU?$objc_class@YP@@YQ@Z"
+
+void f(I *) {}
+// CHECK-LABEL: "\01?f@@YAXPAU?$I@YP@Z"
+
+void f(I *) {}
+// CHECK-LABEL: "\01?f@@YAXPAU?$I@YP@@YQ@Z"
+


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


[PATCH] D42581: [NVPTX] Emit debug info in DWARF-2 by default for Cuda devices.

2018-01-26 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: lib/Driver/ToolChains/Cuda.cpp:353
   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
+  if (mustEmitDebugInfo(Args) && Args.hasArg(options::OPT_g_Flag))
+CmdArgs.push_back("-g");

ABataev wrote:
> tra wrote:
> > There's more than one -g option. Presumably you still want -g here for 
> > -g{1,2,3} or -ggdb{1,2,3} or -gdwarf2.
> > 
> > Speaking of dwarf, what's going to happen if someone passes -gdwarf5?  
> > Should we downgrade it to -gdwarf2 on device side and issue a warning?
> > 
> That's exactly what I want to avoid. I think we can ignore these options and 
> handle only `-g` option.
> Or I can add a function to ToolChain class to force using the default 
> settings for debugger tuning and DWARF version rather than take them from the 
> driver options.
You should handle at least -gN/-gline-tables-only/-g. Now that we can emit 
dwarf debug info, I would want to be able to control it to some degree -- 
off/line-info-only/full.

I'm still not sure what's the plan for -gdwarfN unsupported on device side? 
- do we ignore it and always emit dwarf2?
- do we accept it, emit requested version and let user stare at ptxas (or 
cuda-gdb) errors when it fails to deal with it?






Repository:
  rC Clang

https://reviews.llvm.org/D42581



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


[PATCH] D42588: [index] Fix crash when indexing a C++14 PCH/module related to TemplateTemplateParmDecls of alias templates

2018-01-26 Thread Nathan Hawes via Phabricator via cfe-commits
nathawes accepted this revision.
nathawes added a comment.
This revision is now accepted and ready to land.

Looks good to me!


Repository:
  rC Clang

https://reviews.llvm.org/D42588



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


[PATCH] D42588: [index] Fix crash when indexing a C++14 PCH/module related to TemplateTemplateParmDecls of alias templates

2018-01-26 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi created this revision.
akyrtzi added reviewers: cfe-commits, nathawes.
Herald added subscribers: kristof.beyls, aemerson.

TemplateTemplateParmDecls of alias templates ended-up serialized as 'file-level 
decls' which was causing a crash while trying to index a PCH/module file that 
contained them.
Commit makes sure TemplateTemplateParmDecls are not recorded as such kind of 
decls.

Fixes crash of rdar://36608297


Repository:
  rC Clang

https://reviews.llvm.org/D42588

Files:
  lib/Index/IndexDecl.cpp
  lib/Serialization/ASTWriter.cpp
  test/Index/Core/index-pch.cpp


Index: test/Index/Core/index-pch.cpp
===
--- /dev/null
+++ test/Index/Core/index-pch.cpp
@@ -0,0 +1,17 @@
+// RUN: c-index-test core -print-source-symbols -- %s -std=c++14 | FileCheck %s
+// RUN: %clang_cc1 -emit-pch %s -std=c++14 -o %t.pch
+// RUN: c-index-test core -print-source-symbols -module-file %t.pch | 
FileCheck %s
+
+// CHECK: [[@LINE+2]]:8 | struct(Gen)/C++ | DETECTOR | [[DETECTOR_USR:.*]] | 
{{.*}} | Def | rel: 0
+template  class _Op, 
class... _Args>
+struct DETECTOR {
+ using value_t = int;
+};
+
+struct nonesuch {};
+
+// CHECK: [[@LINE+4]]:9 | type-alias/C++ | is_detected
+// CHECK: [[@LINE+3]]:32 | struct(Gen)/C++ | DETECTOR | [[DETECTOR_USR]] | 
{{.*}} | Ref,RelCont | rel: 1
+// CHECK-NEXT: RelCont | is_detected
+template  class _Op, class... _Args>
+  using is_detected = typename DETECTOR::value_t;
Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -5537,7 +5537,9 @@
 return;
   // FIXME: ParmVarDecls that are part of a function type of a parameter of
   // a function/objc method, should not have TU as lexical context.
-  if (isa(D))
+  // TemplateTemplateParmDecls that are part of an alias template, should not
+  // have TU as lexical context.
+  if (isa(D) || isa(D))
 return;
 
   SourceManager &SM = Context->getSourceManager();
Index: lib/Index/IndexDecl.cpp
===
--- lib/Index/IndexDecl.cpp
+++ lib/Index/IndexDecl.cpp
@@ -664,8 +664,11 @@
 
   bool VisitTemplateDecl(const TemplateDecl *D) {
 
-// Index the default values for the template parameters.
 const NamedDecl *Parent = D->getTemplatedDecl();
+if (!Parent)
+  return true;
+
+// Index the default values for the template parameters.
 if (D->getTemplateParameters() &&
 shouldIndexTemplateParameterDefaultValue(Parent)) {
   const TemplateParameterList *Params = D->getTemplateParameters();
@@ -684,7 +687,7 @@
   }
 }
 
-return Visit(D->getTemplatedDecl());
+return Visit(Parent);
   }
 
   bool VisitFriendDecl(const FriendDecl *D) {


Index: test/Index/Core/index-pch.cpp
===
--- /dev/null
+++ test/Index/Core/index-pch.cpp
@@ -0,0 +1,17 @@
+// RUN: c-index-test core -print-source-symbols -- %s -std=c++14 | FileCheck %s
+// RUN: %clang_cc1 -emit-pch %s -std=c++14 -o %t.pch
+// RUN: c-index-test core -print-source-symbols -module-file %t.pch | FileCheck %s
+
+// CHECK: [[@LINE+2]]:8 | struct(Gen)/C++ | DETECTOR | [[DETECTOR_USR:.*]] | {{.*}} | Def | rel: 0
+template  class _Op, class... _Args>
+struct DETECTOR {
+ using value_t = int;
+};
+
+struct nonesuch {};
+
+// CHECK: [[@LINE+4]]:9 | type-alias/C++ | is_detected
+// CHECK: [[@LINE+3]]:32 | struct(Gen)/C++ | DETECTOR | [[DETECTOR_USR]] | {{.*}} | Ref,RelCont | rel: 1
+// CHECK-NEXT:	RelCont | is_detected
+template  class _Op, class... _Args>
+  using is_detected = typename DETECTOR::value_t;
Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -5537,7 +5537,9 @@
 return;
   // FIXME: ParmVarDecls that are part of a function type of a parameter of
   // a function/objc method, should not have TU as lexical context.
-  if (isa(D))
+  // TemplateTemplateParmDecls that are part of an alias template, should not
+  // have TU as lexical context.
+  if (isa(D) || isa(D))
 return;
 
   SourceManager &SM = Context->getSourceManager();
Index: lib/Index/IndexDecl.cpp
===
--- lib/Index/IndexDecl.cpp
+++ lib/Index/IndexDecl.cpp
@@ -664,8 +664,11 @@
 
   bool VisitTemplateDecl(const TemplateDecl *D) {
 
-// Index the default values for the template parameters.
 const NamedDecl *Parent = D->getTemplatedDecl();
+if (!Parent)
+  return true;
+
+// Index the default values for the template parameters.
 if (D->getTemplateParameters() &&
 shouldIndexTemplateParameterDefaultValue(Parent)) {
   const TemplateParameterList *Params = D->getTemplateParameters();
@@ -684,7 +687,7 @@
   }
 }
 
-return Visit(D->getTemp

r323543 - [X86] Define __IBT__ when -mibt is specified.

2018-01-26 Thread Craig Topper via cfe-commits
Author: ctopper
Date: Fri Jan 26 10:31:14 2018
New Revision: 323543

URL: http://llvm.org/viewvc/llvm-project?rev=323543&view=rev
Log:
[X86] Define __IBT__ when -mibt is specified.

Modified:
cfe/trunk/lib/Basic/Targets/X86.cpp
cfe/trunk/test/Preprocessor/x86_target_features.c

Modified: cfe/trunk/lib/Basic/Targets/X86.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/X86.cpp?rev=323543&r1=323542&r2=323543&view=diff
==
--- cfe/trunk/lib/Basic/Targets/X86.cpp (original)
+++ cfe/trunk/lib/Basic/Targets/X86.cpp Fri Jan 26 10:31:14 2018
@@ -1124,6 +1124,8 @@ void X86TargetInfo::getTargetDefines(con
 Builder.defineMacro("__MPX__");
   if (HasSHSTK)
 Builder.defineMacro("__SHSTK__");
+  if (HasIBT)
+Builder.defineMacro("__IBT__");
   if (HasSGX)
 Builder.defineMacro("__SGX__");
   if (HasPREFETCHWT1)

Modified: cfe/trunk/test/Preprocessor/x86_target_features.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Preprocessor/x86_target_features.c?rev=323543&r1=323542&r2=323543&view=diff
==
--- cfe/trunk/test/Preprocessor/x86_target_features.c (original)
+++ cfe/trunk/test/Preprocessor/x86_target_features.c Fri Jan 26 10:31:14 2018
@@ -376,9 +376,13 @@
 
 // ADX: #define __ADX__ 1
 
-// RUN: %clang -target i386-unknown-unknown -mshstk -x c -E -dM -o - %s | 
FileCheck -match-full-lines --check-prefix=CETSS %s
+// RUN: %clang -target i386-unknown-unknown -mshstk -x c -E -dM -o - %s | 
FileCheck -match-full-lines --check-prefix=SHSTK %s
 
-// CETSS: #define __SHSTK__ 1
+// SHSTK: #define __SHSTK__ 1
+
+// RUN: %clang -target i386-unknown-unknown -mibt -x c -E -dM -o - %s | 
FileCheck -match-full-lines --check-prefix=IBT %s
+
+// IBT: #define __IBT__ 1
 
 // RUN: %clang -target i386-unknown-unknown -march=atom -mrdseed -x c -E -dM 
-o - %s | FileCheck -match-full-lines --check-prefix=RDSEED %s
 


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


[PATCH] D42581: [NVPTX] Emit debug info in DWARF-2 by default for Cuda devices.

2018-01-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/Driver/ToolChains/Cuda.cpp:353
   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
+  if (mustEmitDebugInfo(Args) && Args.hasArg(options::OPT_g_Flag))
+CmdArgs.push_back("-g");

tra wrote:
> There's more than one -g option. Presumably you still want -g here for 
> -g{1,2,3} or -ggdb{1,2,3} or -gdwarf2.
> 
> Speaking of dwarf, what's going to happen if someone passes -gdwarf5?  Should 
> we downgrade it to -gdwarf2 on device side and issue a warning?
> 
That's exactly what I want to avoid. I think we can ignore these options and 
handle only `-g` option.
Or I can add a function to ToolChain class to force using the default settings 
for debugger tuning and DWARF version rather than take them from the driver 
options.



Comment at: test/Driver/cuda-dwarf-2.cu:6-11
+// DEFAULT: "-fcuda-is-device"
+// DEFAULT-SAME: "-dwarf-version=2"
+// DEFAULT: ptxas
+// DEFAULT-NOT: "-g"
+// DEFAULT: fatbinary
+// DEFAULT-NOT: "-g"

tra wrote:
> Nit: you could probably collapse all test cases into two: HAS_DEBUG/NO_DEBUG
Ok, will do


Repository:
  rC Clang

https://reviews.llvm.org/D42581



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


[PATCH] D42581: [NVPTX] Emit debug info in DWARF-2 by default for Cuda devices.

2018-01-26 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: lib/Driver/ToolChains/Cuda.cpp:353
   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
+  if (mustEmitDebugInfo(Args) && Args.hasArg(options::OPT_g_Flag))
+CmdArgs.push_back("-g");

There's more than one -g option. Presumably you still want -g here for 
-g{1,2,3} or -ggdb{1,2,3} or -gdwarf2.

Speaking of dwarf, what's going to happen if someone passes -gdwarf5?  Should 
we downgrade it to -gdwarf2 on device side and issue a warning?




Comment at: test/Driver/cuda-dwarf-2.cu:6-11
+// DEFAULT: "-fcuda-is-device"
+// DEFAULT-SAME: "-dwarf-version=2"
+// DEFAULT: ptxas
+// DEFAULT-NOT: "-g"
+// DEFAULT: fatbinary
+// DEFAULT-NOT: "-g"

Nit: you could probably collapse all test cases into two: HAS_DEBUG/NO_DEBUG


Repository:
  rC Clang

https://reviews.llvm.org/D42581



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


[PATCH] D41698: [DebugInfo] Enable debug information for C99 VLA types

2018-01-26 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added inline comments.



Comment at: lib/CodeGen/CGDebugInfo.h:395
+ CGBuilderTy &Builder,
+ llvm::Metadata **MetadataDecl = nullptr);
 

I think
```
llvm::DILocalVariable* EmitDeclareOfAutoVariable(const VarDecl *Decl, 
llvm::Value *AI,
 CGBuilderTy &Builder);
```
would be more natural.



Comment at: lib/CodeGen/CGDebugInfo.h:474
+   CGBuilderTy &Builder,
+   llvm::Metadata **MetadataDecl = nullptr);
 

same here. Why not just use a return value?



Comment at: lib/CodeGen/CGDecl.cpp:958
 
+/// RegisterVariableArrayDimensions - Emits the alloca and debug information 
for
+/// the size expressions for each dimension of an array. It registers the

LLVM coding style wants this comment to be on the member function declaration 
in the header file and only there. Also we don't repeat the function name in 
the comment any more.



Comment at: lib/CodeGen/CGDecl.cpp:984
+
+  // Now create a 'fake' VarDecl that we'll generate debug info for.
+  IdentifierInfo &NameIdent = getContext().Idents.getOwn(

s/'fake'/artificial/



Comment at: lib/CodeGen/CGDecl.cpp:990
+  D.getLocation(), D.getLocation(), &NameIdent, QT,
+  getContext().CreateTypeSourceInfo(QT), SC_Auto);
+

I think it does, but can you assert me that this generates the same code with 
and without -g ?



Comment at: lib/CodeGen/CodeGenFunction.h:2198
+  /// for the given array type.
+  std::pair
+  getVLAElements1D(const VariableArrayType *vla);

How about defining a struct with named members for improved readability? I 
think you can still use the return {a, b} syntax.


https://reviews.llvm.org/D41698



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


[PATCH] D41698: [DebugInfo] Enable debug information for C99 VLA types

2018-01-26 Thread Sander de Smalen via Phabricator via cfe-commits
sdesmalen added a comment.

Just a gentle reminder that this patch still needs to be accepted (the LLVM 
support for it has been merged).


https://reviews.llvm.org/D41698



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


[PATCH] D42581: [NVPTX] Emit debug info in DWARF-2 by default for Cuda devices.

2018-01-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev created this revision.
ABataev added reviewers: tra, jlebar.
Herald added subscribers: JDevlieghere, aprantl.

NVPTX target supports debug info in DWARF-2 format. Patch adds emission
of debug info in DWARF-2 by default.


Repository:
  rC Clang

https://reviews.llvm.org/D42581

Files:
  lib/Driver/ToolChains/Cuda.cpp
  lib/Driver/ToolChains/Cuda.h
  test/Driver/cuda-dwarf-2.cu
  test/Driver/openmp-offload-gpu.c

Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -142,3 +142,77 @@
 // RUN:   | FileCheck -check-prefix=CHK-NOLIBDEVICE %s
 
 // CHK-NOLIBDEVICE-NOT: error:{{.*}}sm_60
+
+/// ###
+
+/// Check that dbug info is emitted in dwarf-2
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -g 2>&1 \
+// RUN:   | FileCheck -check-prefix=DEFAULT_DEBUG %s
+
+// DEFAULT_DEBUG: "-triple" "nvptx64-nvidia-cuda"
+// DEFAULT_DEBUG-SAME: "-dwarf-version=2"
+// DEFAULT_DEBUG-SAME: "-fopenmp-is-device"
+// DEFAULT_DEBUG: ptxas
+// DEFAULT_DEBUG-NOT: "-g"
+// DEFAULT_DEBUG: nvlink
+// DEFAULT_DEBUG-NOT: "-g"
+
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -g -O0 --no-cuda-noopt-device-debug 2>&1 \
+// RUN:   | FileCheck -check-prefix=O0_NO_DEBUG %s
+
+// O0_NO_DEBUG: "-triple" "nvptx64-nvidia-cuda"
+// O0_NO_DEBUG-SAME: "-dwarf-version=2"
+// O0_NO_DEBUG-SAME: "-fopenmp-is-device"
+// O0_NO_DEBUG: ptxas
+// O0_NO_DEBUG-NOT: "-g"
+// O0_NO_DEBUG: nvlink
+// O0_NO_DEBUG-NOT: "-g"
+
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -g -O0 --cuda-noopt-device-debug 2>&1 \
+// RUN:   | FileCheck -check-prefix=O0_DEBUG %s
+
+// O0_DEBUG: "-triple" "nvptx64-nvidia-cuda"
+// O0_DEBUG-SAME: "-dwarf-version=2"
+// O0_DEBUG-SAME: "-fopenmp-is-device"
+// O0_DEBUG: ptxas
+// O0_DEBUG-SAME: "-g"
+// O0_DEBUG-SAME: "--dont-merge-basicblocks"
+// O0_DEBUG-SAME: "--return-at-end"
+// O0_DEBUG: nvlink
+// O0_DEBUG-SAME: "-g"
+
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -g -O3 2>&1 \
+// RUN:   | FileCheck -check-prefix=DEFAULT_O3_DEBUG %s
+
+// DEFAULT_O3_DEBUG: "-triple" "nvptx64-nvidia-cuda"
+// DEFAULT_O3_DEBUG-SAME: "-dwarf-version=2"
+// DEFAULT_O3_DEBUG-SAME: "-fopenmp-is-device"
+// DEFAULT_O3_DEBUG: ptxas
+// DEFAULT_O3_DEBUG-NOT: "-g"
+// DEFAULT_O3_DEBUG: nvlink
+// DEFAULT_O3_DEBUG-NOT: "-g"
+
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -g -O3 --no-cuda-noopt-device-debug 2>&1 \
+// RUN:   | FileCheck -check-prefix=O3_NO_DEBUG %s
+
+// O3_NO_DEBUG: "-triple" "nvptx64-nvidia-cuda"
+// O3_NO_DEBUG-SAME: "-dwarf-version=2"
+// O3_NO_DEBUG-SAME: "-fopenmp-is-device"
+// O3_NO_DEBUG: ptxas
+// O3_NO_DEBUG-NOT: "-g"
+// O3_NO_DEBUG: nvlink
+// O3_NO_DEBUG-NOT: "-g"
+
+// RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -g -O3 --cuda-noopt-device-debug 2>&1 \
+// RUN:   | FileCheck -check-prefix=O3_DEBUG %s
+
+// O3_DEBUG: "-triple" "nvptx64-nvidia-cuda"
+// O3_DEBUG-SAME: "-dwarf-version=2"
+// O3_DEBUG-SAME: "-fopenmp-is-device"
+// O3_DEBUG: ptxas
+// O3_DEBUG-SAME: "-g"
+// O3_DEBUG-SAME: "--dont-merge-basicblocks"
+// O3_DEBUG-SAME: "--return-at-end"
+// O3_DEBUG: nvlink
+// O3_DEBUG-SAME: "-g"
+
Index: test/Driver/cuda-dwarf-2.cu
===
--- /dev/null
+++ test/Driver/cuda-dwarf-2.cu
@@ -0,0 +1,66 @@
+// REQUIRES: clang-driver
+//
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 %s -g 2>&1 | \
+// RUN:   FileCheck %s -check-prefix DEFAULT
+
+// DEFAULT: "-fcuda-is-device"
+// DEFAULT-SAME: "-dwarf-version=2"
+// DEFAULT: ptxas
+// DEFAULT-NOT: "-g"
+// DEFAULT: fatbinary
+// DEFAULT-NOT: "-g"
+
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 %s -g -O0 --no-cuda-noopt-device-debug 2>&1 | \
+// RUN:   FileCheck %s -check-prefix O0_NO_DEBUG
+
+// O0_NO_DEBUG: "-fcuda-is-device"
+// O0_NO_DEBUG-SAME: "-dwarf-version=2"
+// O0_NO_DEBUG: ptxas
+// O0_NO_DEBUG-NOT: "-g"
+// O0_NO_DEBUG: fatbinary
+// O0_NO_DEBUG-NOT: "-g"
+
+// RUN: %clang -### -target x86_64-linux-gnu -c --cuda-gpu-arch=sm_20 %s -g -O0 --cuda-noopt-device-debug 2>&1 | \
+// RUN:   FileCheck %s -check-prefix O0_DEBUG
+
+// O0_DEBUG: "-fcuda-is-device"
+// O0_DEBUG-SAME: "-dwarf-version=2"
+// O0_DEBUG: ptxas
+// O0_DEBUG-SAME: "-g"
+// O0_DEBUG-SAME: "--dont-merge-basicblocks"
+// O0_DEBUG-SAME: "--return-at-end"
+// O0_DEBUG: fatbinary
+// O0_DEBUG-SAME: "-g"
+
+//

[PATCH] D42578: [AMDGPU] Add ds_fadd, ds_fmin, ds_fmax builtins functions

2018-01-26 Thread Daniil Fukalov via Phabricator via cfe-commits
dfukalov updated this revision to Diff 131593.
dfukalov retitled this revision from "[AMDGPU] Add ds_fadd builtin function" to 
"[AMDGPU] Add ds_fadd, ds_fmin, ds_fmax builtins functions".
dfukalov added a comment.

Sorry, missed them


Repository:
  rC Clang

https://reviews.llvm.org/D42578

Files:
  include/clang/Basic/BuiltinsAMDGPU.def
  test/CodeGenOpenCL/builtins-amdgcn-vi.cl


Index: test/CodeGenOpenCL/builtins-amdgcn-vi.cl
===
--- test/CodeGenOpenCL/builtins-amdgcn-vi.cl
+++ test/CodeGenOpenCL/builtins-amdgcn-vi.cl
@@ -89,3 +89,23 @@
   *out = __builtin_amdgcn_mov_dpp(src, 0, 0, 0, false);
 }
 
+// CHECK-LABEL: @test_ds_fadd
+// CHECK: call float @llvm.amdgcn.ds.fadd(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fadd(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fadd(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmin
+// CHECK: call float @llvm.amdgcn.ds.fmin(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fmin(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmin(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmax
+// CHECK: call float @llvm.amdgcn.ds.fmax(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fmax(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmax(out, src, 0, 0, false);
+}
Index: include/clang/Basic/BuiltinsAMDGPU.def
===
--- include/clang/Basic/BuiltinsAMDGPU.def
+++ include/clang/Basic/BuiltinsAMDGPU.def
@@ -93,6 +93,9 @@
 BUILTIN(__builtin_amdgcn_readfirstlane, "ii", "nc")
 BUILTIN(__builtin_amdgcn_readlane, "iii", "nc")
 BUILTIN(__builtin_amdgcn_fmed3f, "", "nc")
+BUILTIN(__builtin_amdgcn_ds_fadd, "ff*3fiib", "nc")
+BUILTIN(__builtin_amdgcn_ds_fmin, "ff*3fiib", "nc")
+BUILTIN(__builtin_amdgcn_ds_fmax, "ff*3fiib", "nc")
 
 
//===--===//
 // VI+ only builtins.


Index: test/CodeGenOpenCL/builtins-amdgcn-vi.cl
===
--- test/CodeGenOpenCL/builtins-amdgcn-vi.cl
+++ test/CodeGenOpenCL/builtins-amdgcn-vi.cl
@@ -89,3 +89,23 @@
   *out = __builtin_amdgcn_mov_dpp(src, 0, 0, 0, false);
 }
 
+// CHECK-LABEL: @test_ds_fadd
+// CHECK: call float @llvm.amdgcn.ds.fadd(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fadd(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fadd(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmin
+// CHECK: call float @llvm.amdgcn.ds.fmin(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fmin(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmin(out, src, 0, 0, false);
+}
+
+// CHECK-LABEL: @test_ds_fmax
+// CHECK: call float @llvm.amdgcn.ds.fmax(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fmax(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fmax(out, src, 0, 0, false);
+}
Index: include/clang/Basic/BuiltinsAMDGPU.def
===
--- include/clang/Basic/BuiltinsAMDGPU.def
+++ include/clang/Basic/BuiltinsAMDGPU.def
@@ -93,6 +93,9 @@
 BUILTIN(__builtin_amdgcn_readfirstlane, "ii", "nc")
 BUILTIN(__builtin_amdgcn_readlane, "iii", "nc")
 BUILTIN(__builtin_amdgcn_fmed3f, "", "nc")
+BUILTIN(__builtin_amdgcn_ds_fadd, "ff*3fiib", "nc")
+BUILTIN(__builtin_amdgcn_ds_fmin, "ff*3fiib", "nc")
+BUILTIN(__builtin_amdgcn_ds_fmax, "ff*3fiib", "nc")
 
 //===--===//
 // VI+ only builtins.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42561: [PR36008] Avoid -Wsign-compare warning for enum constants in typeof expressions

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



Comment at: lib/Sema/SemaChecking.cpp:8959
+  if (!S.getLangOpts().CPlusPlus) {
+if (const TypeOfExprType *TET = dyn_cast(RHS->getType()))
+  RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();

lebedev.ri wrote:
> Please also add a comment what this is trying to solve.
`const auto *`



Comment at: test/Sema/compare.c:398
+enum PR36008EnumTest {
+kPR36008Value = 0,
+};

Formatting looks off here.


Repository:
  rC Clang

https://reviews.llvm.org/D42561



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


[PATCH] D42578: [AMDGPU] Add ds_fadd builtin function

2018-01-26 Thread Brian Sumner via Phabricator via cfe-commits
b-sumner added a comment.

Were you going to add min and max separately?


Repository:
  rC Clang

https://reviews.llvm.org/D42578



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


r323485 - [Driver] Add an -fexperimental-isel driver option to enable/disable GlobalISel.

2018-01-26 Thread Amara Emerson via cfe-commits
Author: aemerson
Date: Thu Jan 25 16:27:22 2018
New Revision: 323485

URL: http://llvm.org/viewvc/llvm-project?rev=323485&view=rev
Log:
[Driver] Add an -fexperimental-isel driver option to enable/disable GlobalISel.

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

Added:
cfe/trunk/test/Driver/global-isel.c
Modified:
cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Driver/ToolChains/Clang.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td?rev=323485&r1=323484&r2=323485&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticDriverKinds.td Thu Jan 25 16:27:22 
2018
@@ -361,4 +361,12 @@ def warn_drv_fine_grained_bitfield_acces
 def note_drv_verify_prefix_spelling : Note<
   "-verify prefixes must start with a letter and contain only alphanumeric"
   " characters, hyphens, and underscores">;
+
+def warn_drv_experimental_isel_incomplete : Warning<
+  "-fexperimental-isel support for the '%0' architecture is incomplete">,
+  InGroup;
+
+def warn_drv_experimental_isel_incomplete_opt : Warning<
+  "-fexperimental-isel support is incomplete for this architecture at the 
current optimization level">,
+  InGroup;
 }

Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=323485&r1=323484&r2=323485&view=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Thu Jan 25 16:27:22 2018
@@ -985,3 +985,6 @@ def UnknownArgument : DiagGroup<"unknown
 // A warning group for warnings about code that clang accepts when
 // compiling OpenCL C/C++ but which is not compatible with the SPIR spec.
 def SpirCompat : DiagGroup<"spir-compat">;
+
+// Warning for the experimental-isel options.
+def ExperimentalISel : DiagGroup<"experimental-isel">;

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=323485&r1=323484&r2=323485&view=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Thu Jan 25 16:27:22 2018
@@ -1033,6 +1033,8 @@ def finline_functions : Flag<["-"], "fin
 def finline_hint_functions: Flag<["-"], "finline-hint-functions">, 
Group, Flags<[CC1Option]>,
   HelpText<"Inline functions which are (explicitly or implicitly) marked 
inline">;
 def finline : Flag<["-"], "finline">, Group;
+def fexperimental_isel : Flag<["-"], "fexperimental-isel">, 
Group,
+  HelpText<"Enables the experimental global instruction selector">;
 def fexperimental_new_pass_manager : Flag<["-"], 
"fexperimental-new-pass-manager">,
   Group, Flags<[CC1Option]>,
   HelpText<"Enables an experimental new pass manager in LLVM.">;
@@ -1244,6 +1246,8 @@ def fno_exceptions : Flag<["-"], "fno-ex
 def fno_gnu_keywords : Flag<["-"], "fno-gnu-keywords">, Group, 
Flags<[CC1Option]>;
 def fno_inline_functions : Flag<["-"], "fno-inline-functions">, 
Group, Flags<[CC1Option]>;
 def fno_inline : Flag<["-"], "fno-inline">, Group, 
Flags<[CC1Option]>;
+def fno_experimental_isel : Flag<["-"], "fno-experimental-isel">, 
Group,
+  HelpText<"Disables the experimental global instruction selector">;
 def fno_experimental_new_pass_manager : Flag<["-"], 
"fno-experimental-new-pass-manager">,
   Group, Flags<[CC1Option]>,
   HelpText<"Disables an experimental new pass manager in LLVM.">;

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=323485&r1=323484&r2=323485&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Thu Jan 25 16:27:22 2018
@@ -4694,6 +4694,37 @@ void Clang::ConstructJob(Compilation &C,
 CmdArgs.push_back("-fwhole-program-vtables");
   }
 
+  if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
+   options::OPT_fno_experimental_isel)) {
+CmdArgs.push_back("-mllvm");
+if (A->getOption().matches(options::OPT_fexperimental_isel)) {
+  CmdArgs.push_back("-global-isel=1");
+
+  // GISel is on by default on AArch64 -O0, so don't bother adding
+  // the fallback remarks for it. Other combinations will add a warning of
+  // some kind.
+  bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
+  bool IsOptLevelS

[PATCH] D30691: [analyzer] Support for naive cross translational unit analysis

2018-01-26 Thread Nikhil Gupta via Phabricator via cfe-commits
nikhgupt added inline comments.
Herald added a subscriber: hintonda.



Comment at: lib/StaticAnalyzer/Core/PathDiagnostic.cpp:395
+return XFE && !YFE;
+  return XFE->getName() < YFE->getName();
+}

getName could yield incorrect results if two files in the project have the same 
name. This might break the assert for PathDiagnostics 'total ordering' and 
'uniqueness'.
Maybe replacing FileEntry's getName with FullSourceLoc's getFileID could 
resolve this.


https://reviews.llvm.org/D30691



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


[PATCH] D42578: [AMDGPU] Add ds_fadd builtin function

2018-01-26 Thread Daniil Fukalov via Phabricator via cfe-commits
dfukalov created this revision.
dfukalov added reviewers: arsenm, b-sumner.
dfukalov added a project: AMDGPU.
Herald added subscribers: cfe-commits, t-tye, tpr, dstuttard, yaxunl, nhaehnle, 
wdng, kzhuravl.

Repository:
  rC Clang

https://reviews.llvm.org/D42578

Files:
  include/clang/Basic/BuiltinsAMDGPU.def
  test/CodeGenOpenCL/builtins-amdgcn-vi.cl


Index: test/CodeGenOpenCL/builtins-amdgcn-vi.cl
===
--- test/CodeGenOpenCL/builtins-amdgcn-vi.cl
+++ test/CodeGenOpenCL/builtins-amdgcn-vi.cl
@@ -89,3 +89,9 @@
   *out = __builtin_amdgcn_mov_dpp(src, 0, 0, 0, false);
 }
 
+// CHECK-LABEL: @test_ds_fadd
+// CHECK: call float @llvm.amdgcn.ds.fadd(float addrspace(3)* %out, float 
%src, i32 0, i32 0, i1 false)
+void test_ds_fadd(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fadd(out, src, 0, 0, false);
+}
Index: include/clang/Basic/BuiltinsAMDGPU.def
===
--- include/clang/Basic/BuiltinsAMDGPU.def
+++ include/clang/Basic/BuiltinsAMDGPU.def
@@ -93,6 +93,7 @@
 BUILTIN(__builtin_amdgcn_readfirstlane, "ii", "nc")
 BUILTIN(__builtin_amdgcn_readlane, "iii", "nc")
 BUILTIN(__builtin_amdgcn_fmed3f, "", "nc")
+BUILTIN(__builtin_amdgcn_ds_fadd, "ff*3fiib", "nc")
 
 
//===--===//
 // VI+ only builtins.


Index: test/CodeGenOpenCL/builtins-amdgcn-vi.cl
===
--- test/CodeGenOpenCL/builtins-amdgcn-vi.cl
+++ test/CodeGenOpenCL/builtins-amdgcn-vi.cl
@@ -89,3 +89,9 @@
   *out = __builtin_amdgcn_mov_dpp(src, 0, 0, 0, false);
 }
 
+// CHECK-LABEL: @test_ds_fadd
+// CHECK: call float @llvm.amdgcn.ds.fadd(float addrspace(3)* %out, float %src, i32 0, i32 0, i1 false)
+void test_ds_fadd(local float *out, float src)
+{
+  *out = __builtin_amdgcn_ds_fadd(out, src, 0, 0, false);
+}
Index: include/clang/Basic/BuiltinsAMDGPU.def
===
--- include/clang/Basic/BuiltinsAMDGPU.def
+++ include/clang/Basic/BuiltinsAMDGPU.def
@@ -93,6 +93,7 @@
 BUILTIN(__builtin_amdgcn_readfirstlane, "ii", "nc")
 BUILTIN(__builtin_amdgcn_readlane, "iii", "nc")
 BUILTIN(__builtin_amdgcn_fmed3f, "", "nc")
+BUILTIN(__builtin_amdgcn_ds_fadd, "ff*3fiib", "nc")
 
 //===--===//
 // VI+ only builtins.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42570: clang-format: [JS] Prevent ASI before [ and (.

2018-01-26 Thread Martin Probst via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323532: clang-format: [JS] Prevent ASI before [ and (. 
(authored by mprobst, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42570

Files:
  cfe/trunk/lib/Format/TokenAnnotator.cpp
  cfe/trunk/unittests/Format/FormatTestJS.cpp


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -2710,9 +2710,11 @@
 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
   return false; // Otherwise automatic semicolon insertion would trigger.
-if (Left.Tok.getIdentifierInfo() &&
-Right.startsSequence(tok::l_square, tok::r_square))
-  return false;  // breaking in "foo[]" creates illegal TS type syntax.
+if (Right.NestingLevel == 0 &&
+(Left.Tok.getIdentifierInfo() ||
+ Left.isOneOf(tok::r_square, tok::r_paren)) &&
+Right.isOneOf(tok::l_square, tok::l_paren))
+  return false; // Otherwise automatic semicolon insertion would trigger.
 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
   return false;
 if (Left.is(TT_JsTypeColon))
Index: cfe/trunk/unittests/Format/FormatTestJS.cpp
===
--- cfe/trunk/unittests/Format/FormatTestJS.cpp
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp
@@ -1157,6 +1157,9 @@
"foo() {}",
getGoogleJSStyleWithColumns(10));
   verifyFormat("await theReckoning;", getGoogleJSStyleWithColumns(10));
+  verifyFormat("some['a']['b']", getGoogleJSStyleWithColumns(10));
+  verifyFormat("x = (a['a']\n"
+   "  ['b']);", getGoogleJSStyleWithColumns(10));
 }
 
 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {


Index: cfe/trunk/lib/Format/TokenAnnotator.cpp
===
--- cfe/trunk/lib/Format/TokenAnnotator.cpp
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp
@@ -2710,9 +2710,11 @@
 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
   return false; // Otherwise automatic semicolon insertion would trigger.
-if (Left.Tok.getIdentifierInfo() &&
-Right.startsSequence(tok::l_square, tok::r_square))
-  return false;  // breaking in "foo[]" creates illegal TS type syntax.
+if (Right.NestingLevel == 0 &&
+(Left.Tok.getIdentifierInfo() ||
+ Left.isOneOf(tok::r_square, tok::r_paren)) &&
+Right.isOneOf(tok::l_square, tok::l_paren))
+  return false; // Otherwise automatic semicolon insertion would trigger.
 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
   return false;
 if (Left.is(TT_JsTypeColon))
Index: cfe/trunk/unittests/Format/FormatTestJS.cpp
===
--- cfe/trunk/unittests/Format/FormatTestJS.cpp
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp
@@ -1157,6 +1157,9 @@
"foo() {}",
getGoogleJSStyleWithColumns(10));
   verifyFormat("await theReckoning;", getGoogleJSStyleWithColumns(10));
+  verifyFormat("some['a']['b']", getGoogleJSStyleWithColumns(10));
+  verifyFormat("x = (a['a']\n"
+   "  ['b']);", getGoogleJSStyleWithColumns(10));
 }
 
 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323532 - clang-format: [JS] Prevent ASI before [ and (.

2018-01-26 Thread Martin Probst via cfe-commits
Author: mprobst
Date: Fri Jan 26 07:07:49 2018
New Revision: 323532

URL: http://llvm.org/viewvc/llvm-project?rev=323532&view=rev
Log:
clang-format: [JS] Prevent ASI before [ and (.

Summary:
JavaScript automatic semicolon insertion can trigger before [ and (, so
avoid breaking before them if the previous token is likely to terminate
an expression.

Reviewers: djasper

Subscribers: cfe-commits, klimek

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

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestJS.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=323532&r1=323531&r2=323532&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Fri Jan 26 07:07:49 2018
@@ -2710,9 +2710,11 @@ bool TokenAnnotator::canBreakBefore(cons
 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
   return false; // Otherwise automatic semicolon insertion would trigger.
-if (Left.Tok.getIdentifierInfo() &&
-Right.startsSequence(tok::l_square, tok::r_square))
-  return false;  // breaking in "foo[]" creates illegal TS type syntax.
+if (Right.NestingLevel == 0 &&
+(Left.Tok.getIdentifierInfo() ||
+ Left.isOneOf(tok::r_square, tok::r_paren)) &&
+Right.isOneOf(tok::l_square, tok::l_paren))
+  return false; // Otherwise automatic semicolon insertion would trigger.
 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
   return false;
 if (Left.is(TT_JsTypeColon))

Modified: cfe/trunk/unittests/Format/FormatTestJS.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestJS.cpp?rev=323532&r1=323531&r2=323532&view=diff
==
--- cfe/trunk/unittests/Format/FormatTestJS.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp Fri Jan 26 07:07:49 2018
@@ -1157,6 +1157,9 @@ TEST_F(FormatTestJS, WrapRespectsAutomat
"foo() {}",
getGoogleJSStyleWithColumns(10));
   verifyFormat("await theReckoning;", getGoogleJSStyleWithColumns(10));
+  verifyFormat("some['a']['b']", getGoogleJSStyleWithColumns(10));
+  verifyFormat("x = (a['a']\n"
+   "  ['b']);", getGoogleJSStyleWithColumns(10));
 }
 
 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {


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


[PATCH] D42577: [Lexer] Support adding working directory to relative search dir for #include shortening in HeaderSearch.

2018-01-26 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.
ioeric added a reviewer: bkramer.
Herald added subscribers: cfe-commits, hintonda, mgorny.

Repository:
  rC Clang

https://reviews.llvm.org/D42577

Files:
  include/clang/Lex/HeaderSearch.h
  lib/Lex/HeaderSearch.cpp
  unittests/Lex/CMakeLists.txt
  unittests/Lex/HeaderSearchTest.cpp

Index: unittests/Lex/HeaderSearchTest.cpp
===
--- /dev/null
+++ unittests/Lex/HeaderSearchTest.cpp
@@ -0,0 +1,96 @@
+//===- unittests/Lex/HeaderSearchTest.cpp -- HeaderSearch tests ---===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/Lex/HeaderSearch.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/MemoryBufferCache.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TargetInfo.h"
+#include "clang/Basic/TargetOptions.h"
+#include "clang/Lex/HeaderSearch.h"
+#include "clang/Lex/HeaderSearchOptions.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace {
+
+// The test fixture.
+class HeaderSearchTest : public ::testing::Test {
+protected:
+  HeaderSearchTest()
+  : VFS(new vfs::InMemoryFileSystem), FileMgr(FileMgrOpts, VFS),
+DiagID(new DiagnosticIDs()),
+Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()),
+SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions),
+Search(std::make_shared(), SourceMgr, Diags,
+   LangOpts, Target.get()) {
+TargetOpts->Triple = "x86_64-apple-darwin11.1.0";
+Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
+  }
+
+  void addSearchDir(llvm::StringRef Dir) {
+VFS->addFile(Dir, 0, llvm::MemoryBuffer::getMemBuffer(""), /*User=*/None,
+ /*Group=*/None, llvm::sys::fs::file_type::directory_file);
+const DirectoryEntry *DE = FileMgr.getDirectory(Dir);
+assert(DE);
+auto DL = DirectoryLookup(DE, SrcMgr::C_User, /*isFramework=*/false);
+Search.AddSearchPath(DL, /*isAngled=*/false);
+  }
+
+  IntrusiveRefCntPtr VFS;
+  FileSystemOptions FileMgrOpts;
+  FileManager FileMgr;
+  IntrusiveRefCntPtr DiagID;
+  DiagnosticsEngine Diags;
+  SourceManager SourceMgr;
+  LangOptions LangOpts;
+  std::shared_ptr TargetOpts;
+  IntrusiveRefCntPtr Target;
+  HeaderSearch Search;
+};
+
+TEST_F(HeaderSearchTest, NoSearchDir) {
+  EXPECT_EQ(Search.search_dir_size(), 0u);
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/x/y/z", /*WorkingDir=*/""),
+"/x/y/z");
+}
+
+TEST_F(HeaderSearchTest, SimpleShorten) {
+  addSearchDir("/x");
+  addSearchDir("/x/y");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/x/y/z", /*WorkingDir=*/""),
+"z");
+  addSearchDir("/a/b/");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/a/b/c", /*WorkingDir=*/""),
+"c");
+}
+
+TEST_F(HeaderSearchTest, ShortenWithWorkingDir) {
+  addSearchDir("x/y");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/a/b/c/x/y/z",
+   /*WorkingDir=*/"/a/b/c"),
+"z");
+}
+
+TEST_F(HeaderSearchTest, Dots) {
+  addSearchDir("/x/./y/");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/x/y/./z",
+   /*WorkingDir=*/""),
+"z");
+  addSearchDir("a/.././c/");
+  EXPECT_EQ(Search.suggestPathToFileForDiagnostics("/m/n/./c/z",
+   /*WorkingDir=*/"/m/n/"),
+"z");
+}
+
+} // namespace
+} // namespace clang
Index: unittests/Lex/CMakeLists.txt
===
--- unittests/Lex/CMakeLists.txt
+++ unittests/Lex/CMakeLists.txt
@@ -4,6 +4,7 @@
 
 add_clang_unittest(LexTests
   HeaderMapTest.cpp
+  HeaderSearchTest.cpp
   LexerTest.cpp
   PPCallbacksTest.cpp
   PPConditionalDirectiveRecordTest.cpp
Index: lib/Lex/HeaderSearch.cpp
===
--- lib/Lex/HeaderSearch.cpp
+++ lib/Lex/HeaderSearch.cpp
@@ -1580,9 +1580,16 @@
 std::string HeaderSearch::suggestPathToFileForDiagnostics(const FileEntry *File,
   bool *IsSystem) {
   // FIXME: We assume that the path name currently cached in the FileEntry is
-  // the most appropriate one for this analysis (and that it's spelled the same
+  // the most appropriate one for this analysis (and that it's spelled the
+  // same
   // way as the corresponding header search path).
-  StringRef Name = File->getName();
+  return suggestPathToFileForDiagnostics(File->getName(), /*BuildDir=*/"",
+ IsSystem);
+}
+
+std::stri

[PATCH] D42570: clang-format: [JS] Prevent ASI before [ and (.

2018-01-26 Thread Daniel Jasper via Phabricator via cfe-commits
djasper accepted this revision.
djasper added a comment.
This revision is now accepted and ready to land.

Makes sense.


Repository:
  rC Clang

https://reviews.llvm.org/D42570



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


Re: [PATCH] D42395: [clang-format] Fix bug where -dump-config failed on ObjC header

2018-01-26 Thread Ben Hamilton via cfe-commits
It's needed because otherwise lit ignores the .h file, which is the
configuration specified in the lit config in the parent directory.

On Fri, Jan 26, 2018, 01:55 Krasimir Georgiev via Phabricator <
revi...@reviews.llvm.org> wrote:

> krasimir requested changes to this revision.
> krasimir added inline comments.
> This revision now requires changes to proceed.
>
>
> 
> Comment at: test/Format/lit.local.cfg:1
> +# Suffixes supported by clang-format.
> +config.suffixes = ['.c', '.cc', '.cpp', '.h', '.m', '.mm', '.java', '.js',
> 
> Why is this needed?
>
>
> Repository:
>   rC Clang
>
> https://reviews.llvm.org/D42395
>
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42573: [wip] The new threading implementation

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

Thanks, this helps me understand where previous patch is coming from!

I have some comments on the ThreadPool part, which basically amount to trying 
to represent the same abstract structure with fewer pieces.
But I still want to consider whether that's the right structure (specifically: 
whether the Queue abstraction makes it awkward to express task interactions 
like diagnostics debouncing).

So please don't do any work based on these comments yet! More thoughts to 
come...




Comment at: clangd/ClangdServer.h:140
+///  the working threads as soon as an idle thread is available.
+///- scheduleOnQueue will schedule to a specific queue. Requests from the
+///  same queue are not processed concurrently. Requests in each queue are

As discussed offline, Queue's semantics are very similar to a thread, except:
 - cooperatively scheduled: Queues do not yield until idle
 - limited in parallelism by the size of the threadpool

In the interests of keeping things simple and familiar, I think we should start 
out by using `std::thread`.
We can use a semaphore to limit the parallelism (I'm fine with doing this in 
the first iteration, but urge you to consider leaving it out until we see 
actual problems with using the CPU as our limit). This should give both 
properties above (if the Queue only releases the semaphore when idle).
If we still have performance problems we may need to switch to a multiplexing 
version, though I have a hard time imagining it (e.g. even on windows, thread 
spawn should be <1us, and memory usage is trivial compared to anything that 
touches an AST).



Comment at: clangd/ClangdServer.h:141
+///- scheduleOnQueue will schedule to a specific queue. Requests from the
+///  same queue are not processed concurrently. Requests in each queue are
+///  executed in the FIFO order.

Similarly, the free requests look a lot like standalone threads, with a few 
enhancements that are implementable but also possible YAGNI.
 - running code complete first is roughly[1] equivalent to elevating the 
thread's priority (no portability shim in llvm yet, but it's pretty easy). I 
don't think this needs to be in the first patch.
 - limiting parallelism can be done with semaphores. In fact we can easily 
express something like "up to 18 queued tasks, up to 20 free tasks, up to 20 
total", which nice for latency.

[1] I see both advantages and disadvantages, happy to discuss more!



Comment at: clangd/ClangdServer.h:143
+///  executed in the FIFO order.
 class ThreadPool {
 public:

So overall here, I think that we can drop `ThreadPool` without much impact on 
the design.
`Queue` would stay, as a wrapper around `std::thread` that lets you add tasks 
to its runloop. It would be owned by FileData, and shutdown would be triggered 
by its destructor.

The advantage is one less layer here to understand, and an attractive nuisance 
to tweak over time.
The downsides I see:
  - threading is no longer abstracted away, so changes to it are less isolated
I think it's likely that we get away with the model staying simple. If it 
gets complicated, we'll want to add the abstraction back in. But this isn't 
java, we can abstract when we need it :-)
  - RunSynchronously escapes into Scheduler. This is for the worse I think, but 
only slightly.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573



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


r323528 - [AST] Use bit packing to reduce sizeof(TypedefNameDecl) from 88 to 80.

2018-01-26 Thread Benjamin Kramer via cfe-commits
Author: d0k
Date: Fri Jan 26 06:14:11 2018
New Revision: 323528

URL: http://llvm.org/viewvc/llvm-project?rev=323528&view=rev
Log:
[AST] Use bit packing to reduce sizeof(TypedefNameDecl) from 88 to 80.

We can stash the cached transparent tag bit in existing pointer padding.
Everything coming out of ASTContext is always aligned to a multiple of
8, so we have 8 spare bits.

Modified:
cfe/trunk/include/clang/AST/Decl.h
cfe/trunk/lib/AST/Decl.cpp

Modified: cfe/trunk/include/clang/AST/Decl.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=323528&r1=323527&r2=323528&view=diff
==
--- cfe/trunk/include/clang/AST/Decl.h (original)
+++ cfe/trunk/include/clang/AST/Decl.h Fri Jan 26 06:14:11 2018
@@ -2814,12 +2814,12 @@ public:
 /// Base class for declarations which introduce a typedef-name.
 class TypedefNameDecl : public TypeDecl, public Redeclarable {
   using ModedTInfo = std::pair;
-  llvm::PointerUnion MaybeModedTInfo;
 
-  // FIXME: This can be packed into the bitfields in Decl.
-  /// If 0, we have not computed IsTransparentTag.
-  /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1).
-  mutable unsigned CacheIsTransparentTag : 2;
+  /// If int part is 0, we have not computed IsTransparentTag.
+  /// Otherwise, IsTransparentTag is (getInt() >> 1).
+  mutable llvm::PointerIntPair<
+  llvm::PointerUnion, 2>
+  MaybeModedTInfo;
 
   void anchor() override;
 
@@ -2828,7 +2828,7 @@ protected:
   SourceLocation StartLoc, SourceLocation IdLoc,
   IdentifierInfo *Id, TypeSourceInfo *TInfo)
   : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
-MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {}
+MaybeModedTInfo(TInfo, 0) {}
 
   using redeclarable_base = Redeclarable;
 
@@ -2855,26 +2855,29 @@ public:
   using redeclarable_base::getMostRecentDecl;
   using redeclarable_base::isFirstDecl;
 
-  bool isModed() const { return MaybeModedTInfo.is(); }
+  bool isModed() const {
+return MaybeModedTInfo.getPointer().is();
+  }
 
   TypeSourceInfo *getTypeSourceInfo() const {
-return isModed()
-  ? MaybeModedTInfo.get()->first
-  : MaybeModedTInfo.get();
+return isModed() ? MaybeModedTInfo.getPointer().get()->first
+ : MaybeModedTInfo.getPointer().get();
   }
 
   QualType getUnderlyingType() const {
-return isModed()
-  ? MaybeModedTInfo.get()->second
-  : MaybeModedTInfo.get()->getType();
+return isModed() ? MaybeModedTInfo.getPointer().get()->second
+ : MaybeModedTInfo.getPointer()
+   .get()
+   ->getType();
   }
 
   void setTypeSourceInfo(TypeSourceInfo *newType) {
-MaybeModedTInfo = newType;
+MaybeModedTInfo.setPointer(newType);
   }
 
   void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
-MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
+MaybeModedTInfo.setPointer(new (getASTContext(), 8)
+   ModedTInfo(unmodedTSI, modedTy));
   }
 
   /// Retrieves the canonical declaration of this typedef-name.
@@ -2891,8 +2894,8 @@ public:
   /// Determines if this typedef shares a name and spelling location with its
   /// underlying tag type, as is the case with the NS_ENUM macro.
   bool isTransparentTag() const {
-if (CacheIsTransparentTag)
-  return CacheIsTransparentTag & 0x2;
+if (MaybeModedTInfo.getInt())
+  return MaybeModedTInfo.getInt() & 0x2;
 return isTransparentTagSlow();
   }
 

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=323528&r1=323527&r2=323528&view=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Fri Jan 26 06:14:11 2018
@@ -4372,9 +4372,7 @@ bool TypedefNameDecl::isTransparentTagSl
   };
 
   bool isTransparent = determineIsTransparent();
-  CacheIsTransparentTag = 1;
-  if (isTransparent)
-CacheIsTransparentTag |= 0x2;
+  MaybeModedTInfo.setInt((isTransparent << 1) | 1);
   return isTransparent;
 }
 


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


[PATCH] D42575: [clangd] Better handling symbols defined in macros.

2018-01-26 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: ioeric.
Herald added subscribers: jkorous-apple, ilya-biryukov, klimek.

For symbols defined inside macros:

- use expansion location, if the symbol is formed via macro concatenation.
- use spelling location, otherwise.

This will fix some symbols that have ill-format location (especial invalid 
filepath).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42575

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 
+#include "Annotations.h"
 #include "index/SymbolCollector.h"
 #include "index/SymbolYAML.h"
 #include "clang/Basic/FileManager.h"
@@ -44,11 +45,22 @@
   return arg.CompletionSnippetInsertText == S;
 }
 MATCHER_P(QName, Name, "") { return (arg.Scope + arg.Name).str() == Name; }
+MATCHER_P(LocationOffsets, Offsets, "") {
+  // Offset range in SymbolLocation is [start, end] while in Clangd is [start,
+  // end).
+  return arg.CanonicalDeclaration.StartOffset == Offsets.first &&
+  arg.CanonicalDeclaration.EndOffset == Offsets.second - 1;
+}
+MATCHER_P(FilePath, P, "") {
+  return arg.CanonicalDeclaration.FilePath.contains(P);
+}
 
 namespace clang {
 namespace clangd {
 
 namespace {
+const char TestHeaderName[] = "symbols.h";
+const char TestFileName[] = "symbol.cc";
 class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
 public:
   SymbolIndexActionFactory(SymbolCollector::Options COpts)
@@ -77,21 +89,19 @@
 llvm::IntrusiveRefCntPtr Files(
 new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
-const std::string FileName = "symbol.cc";
-const std::string HeaderName = "symbols.h";
 auto Factory = llvm::make_unique(CollectorOpts);
 
 tooling::ToolInvocation Invocation(
-{"symbol_collector", "-fsyntax-only", "-std=c++11", FileName},
+{"symbol_collector", "-fsyntax-only", "-std=c++11", TestFileName},
 Factory->create(), Files.get(),
 std::make_shared());
 
-InMemoryFileSystem->addFile(HeaderName, 0,
+InMemoryFileSystem->addFile(TestHeaderName, 0,
 llvm::MemoryBuffer::getMemBuffer(HeaderCode));
 
-std::string Content = "#include\"" + std::string(HeaderName) + "\"";
+std::string Content = "#include\"" + std::string(TestHeaderName) + "\"";
 Content += "\n" + MainCode.str();
-InMemoryFileSystem->addFile(FileName, 0,
+InMemoryFileSystem->addFile(TestFileName, 0,
 llvm::MemoryBuffer::getMemBuffer(Content));
 Invocation.run();
 Symbols = Factory->Collector->takeSymbols();
@@ -196,6 +206,31 @@
   UnorderedElementsAre(QName("Foo")));
 }
 
+TEST_F(SymbolCollectorTest, SymbolFormedFromMacro) {
+  CollectorOpts.IndexMainFiles = false;
+
+  Annotations Header(R"(
+#define FF(name) \
+  class name##_Test {};
+
+$expansion[[FF(abc)]];
+
+#define FF2() \
+  $spelling[[class Test {}]];
+
+FF2();
+  )");
+  runSymbolCollector(Header.code(), /*Main=*/"");
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("abc_Test"),
+LocationOffsets(Header.offsetRange("expansion")),
+FilePath(TestHeaderName)),
+  AllOf(QName("Test"),
+LocationOffsets(Header.offsetRange("spelling")),
+FilePath(TestHeaderName;
+}
+
 TEST_F(SymbolCollectorTest, IgnoreSymbolsInMainFile) {
   CollectorOpts.IndexMainFiles = false;
   const std::string Header = R"(
Index: unittests/clangd/Annotations.h
===
--- unittests/clangd/Annotations.h
+++ unittests/clangd/Annotations.h
@@ -58,6 +58,10 @@
   // Returns the location of all ranges marked by [[ ]] (or $name[[ ]]).
   std::vector ranges(llvm::StringRef Name = "") const;
 
+  // Returns range in offsets [start, end).
+  std::pair
+  offsetRange(llvm::StringRef Name = "") const;
+
 private:
   std::string Code;
   llvm::StringMap> Points;
Index: unittests/clangd/Annotations.cpp
===
--- unittests/clangd/Annotations.cpp
+++ unittests/clangd/Annotations.cpp
@@ -83,5 +83,11 @@
   return {R.begin(), R.end()};
 }
 
+std::pair
+Annotations::offsetRange(llvm::StringRef Name) const {
+  auto R = range(Name);
+  return {positionToOffset(Code, R.start), positionToOffset(Code, R.end)};
+}
+
 } // namespace clangd
 } // namespace clang
Index: clangd/index/SymbolCollector.cpp
===
-

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

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

ping^2


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] D42419: [clangd] Use new URI with scheme support in place of the existing LSP URI

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

Thanks for the comments!




Comment at: clangd/ClangdLSPServer.cpp:284
+  std::string ResultUri = "";
+  if (Result) {
+auto U = URI::create(*Result);

sammccall wrote:
> But basically I think this shows that the API is awkward. We should have a 
> way to create a file URI from an absolute path that asserts rather than 
> returning expected.
> I'd suggest removing the default "file" scheme from create(), and adding 
> createFile(abspath) that returns URI
That makes a lot of sense. Thanks for the suggestion!



Comment at: clangd/Protocol.h:51
 
-struct URI {
-  std::string uri;
+struct URIWithFile {
+  URI uri;

sammccall wrote:
> sammccall wrote:
> > URIForFile? "withfile" doesn't really capture that they're related
> Hmm actually, what about just `struct URIForFile { std:string AbsPath; }`
> fromJSON and toJSON would do the marshalling to URI, but internally we just 
> want the path, right?
> 
> This also gives us the usual easy null state.
Good idea!



Comment at: clangd/URI.h:32
+  // By default, create a simplest valid file URI.
+  URI() : Scheme("file") {}
+

sammccall wrote:
> ioeric wrote:
> > same here. There are many default constructions of structures that contain 
> > URIs in ClangdLSPServer.cpp...
> Does the struct-with-just-an-abspath idea address this?
Yes!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42419



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


[PATCH] D42419: [clangd] Use new URI with scheme support in place of the existing LSP URI

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

- Address review comments


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42419

Files:
  clangd/ClangdLSPServer.cpp
  clangd/Protocol.cpp
  clangd/Protocol.h
  clangd/URI.cpp
  clangd/URI.h
  clangd/XRefs.cpp
  unittests/clangd/URITests.cpp
  unittests/clangd/XRefsTests.cpp

Index: unittests/clangd/XRefsTests.cpp
===
--- unittests/clangd/XRefsTests.cpp
+++ unittests/clangd/XRefsTests.cpp
@@ -9,6 +9,7 @@
 #include "Annotations.h"
 #include "ClangdUnit.h"
 #include "Matchers.h"
+#include "TestFS.h"
 #include "XRefs.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/PCHContainerOperations.h"
@@ -38,7 +39,9 @@
 
 // FIXME: this is duplicated with FileIndexTests. Share it.
 ParsedAST build(StringRef Code) {
-  auto CI = createInvocationFromCommandLine({"clang", "-xc++", "Foo.cpp"});
+  auto TestFile = getVirtualTestFilePath("Foo.cpp");
+  auto CI =
+  createInvocationFromCommandLine({"clang", "-xc++", TestFile.c_str()});
   auto Buf = MemoryBuffer::getMemBuffer(Code);
   auto AST = ParsedAST::Build(
   Context::empty(), std::move(CI), nullptr, std::move(Buf),
Index: unittests/clangd/URITests.cpp
===
--- unittests/clangd/URITests.cpp
+++ unittests/clangd/URITests.cpp
@@ -40,13 +40,12 @@
 .str();
   }
 
-  llvm::Expected
+  llvm::Expected
   uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
 auto Pos = AbsolutePath.find(TestRoot);
 assert(Pos != llvm::StringRef::npos);
-return FileURI::create(
-Scheme, /*Authority=*/"",
-AbsolutePath.substr(Pos + llvm::StringRef(TestRoot).size()));
+return URI(Scheme, /*Authority=*/"",
+   AbsolutePath.substr(Pos + llvm::StringRef(TestRoot).size()));
   }
 };
 
@@ -57,30 +56,22 @@
 
 std::string createOrDie(llvm::StringRef AbsolutePath,
 llvm::StringRef Scheme = "file") {
-  auto Uri = FileURI::create(AbsolutePath, Scheme);
+  auto Uri = URI::create(AbsolutePath, Scheme);
   if (!Uri)
 llvm_unreachable(llvm::toString(Uri.takeError()).c_str());
   return Uri->toString();
 }
 
-std::string createOrDie(llvm::StringRef Scheme, llvm::StringRef Authority,
-llvm::StringRef Body) {
-  auto Uri = FileURI::create(Scheme, Authority, Body);
-  if (!Uri)
-llvm_unreachable(llvm::toString(Uri.takeError()).c_str());
-  return Uri->toString();
-}
-
-FileURI parseOrDie(llvm::StringRef Uri) {
-  auto U = FileURI::parse(Uri);
+URI parseOrDie(llvm::StringRef Uri) {
+  auto U = URI::parse(Uri);
   if (!U)
 llvm_unreachable(llvm::toString(U.takeError()).c_str());
   return *U;
 }
 
 TEST(PercentEncodingTest, Encode) {
-  EXPECT_EQ(createOrDie("x", /*Authority=*/"", "a/b/c"), "x:a/b/c");
-  EXPECT_EQ(createOrDie("x", /*Authority=*/"", "a!b;c~"), "x:a%21b%3bc~");
+  EXPECT_EQ(URI("x", /*Authority=*/"", "a/b/c").toString(), "x:a/b/c");
+  EXPECT_EQ(URI("x", /*Authority=*/"", "a!b;c~").toString(), "x:a%21b%3bc~");
 }
 
 TEST(PercentEncodingTest, Decode) {
@@ -93,8 +84,8 @@
   EXPECT_EQ(parseOrDie("x:a%21b%3ac~").body(), "a!b:c~");
 }
 
-std::string resolveOrDie(const FileURI &U, llvm::StringRef HintPath = "") {
-  auto Path = FileURI::resolve(U, HintPath);
+std::string resolveOrDie(const URI &U, llvm::StringRef HintPath = "") {
+  auto Path = URI::resolve(U, HintPath);
   if (!Path)
 llvm_unreachable(llvm::toString(Path.takeError()).c_str());
   return *Path;
@@ -110,25 +101,16 @@
 }
 
 TEST(URITest, FailedCreate) {
-  auto Fail = [](llvm::Expected U) {
+  auto Fail = [](llvm::Expected U) {
 if (!U) {
   llvm::consumeError(U.takeError());
   return true;
 }
 return false;
   };
-  // Create from scheme+authority+body:
-  //
-  // Scheme must be provided.
-  EXPECT_TRUE(Fail(FileURI::create("", "auth", "/a")));
-  // Body must start with '/' if authority is present.
-  EXPECT_TRUE(Fail(FileURI::create("scheme", "auth", "x/y/z")));
-
-  // Create from scheme registry:
-  //
-  EXPECT_TRUE(Fail(FileURI::create("/x/y/z", "no")));
+  EXPECT_TRUE(Fail(URI::create("/x/y/z", "no")));
   // Path has to be absolute.
-  EXPECT_TRUE(Fail(FileURI::create("x/y/z")));
+  EXPECT_TRUE(Fail(URI::create("x/y/z", "file")));
 }
 
 TEST(URITest, Parse) {
@@ -163,7 +145,7 @@
 
 TEST(URITest, ParseFailed) {
   auto FailedParse = [](llvm::StringRef U) {
-auto URI = FileURI::parse(U);
+auto URI = URI::parse(U);
 if (!URI) {
   llvm::consumeError(URI.takeError());
   return true;
@@ -194,14 +176,14 @@
 
 TEST(URITest, Platform) {
   auto Path = getVirtualTestFilePath("x");
-  auto U = FileURI::create(Path, "file");
+  auto U = URI::create(Path, "file");
   EXPECT_TRUE(static_cast(U));
   EXPECT_THAT(resolveOrDie(*U), Path.str());
 }
 
 TEST(URITest, ResolveFailed) {
   auto Fa

r323524 - [ASTImporter] avoid warnings: unused var, switch covered

2018-01-26 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Jan 26 04:06:44 2018
New Revision: 323524

URL: http://llvm.org/viewvc/llvm-project?rev=323524&view=rev
Log:
[ASTImporter] avoid warnings: unused var, switch covered

Modified:
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/lib/AST/ExternalASTMerger.cpp

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=323524&r1=323523&r2=323524&view=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Fri Jan 26 04:06:44 2018
@@ -2079,7 +2079,7 @@ bool ASTNodeImporter::ImportTemplateInfo
   switch (FromFD->getTemplatedKind()) {
   case FunctionDecl::TK_NonTemplate:
   case FunctionDecl::TK_FunctionTemplate:
-break;
+return false;
 
   case FunctionDecl::TK_MemberSpecialization: {
 auto *InstFD = cast_or_null(
@@ -2092,7 +2092,7 @@ bool ASTNodeImporter::ImportTemplateInfo
   FromFD->getMemberSpecializationInfo()->getPointOfInstantiation());
 ToFD->setInstantiationOfMemberFunction(InstFD, TSK);
 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
-break;
+return false;
   }
 
   case FunctionDecl::TK_FunctionTemplateSpecialization: {
@@ -2127,7 +2127,7 @@ bool ASTNodeImporter::ImportTemplateInfo
 ToFD->setFunctionTemplateSpecialization(
 Template, ToTAList, /* InsertPos= */ nullptr,
 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, POI);
-break;
+return false;
   }
 
   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
@@ -2153,13 +2153,10 @@ bool ASTNodeImporter::ImportTemplateInfo
 
 ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
  TemplDecls, ToTAInfo);
-break;
+return false;
   }
-  default:
-llvm_unreachable("All cases should be covered!");
   }
-
-  return false;
+  llvm_unreachable("All cases should be covered!");
 }
 
 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {

Modified: cfe/trunk/lib/AST/ExternalASTMerger.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ExternalASTMerger.cpp?rev=323524&r1=323523&r2=323524&view=diff
==
--- cfe/trunk/lib/AST/ExternalASTMerger.cpp (original)
+++ cfe/trunk/lib/AST/ExternalASTMerger.cpp Fri Jan 26 04:06:44 2018
@@ -408,6 +408,7 @@ bool ExternalASTMerger::FindExternalVisi
 bool IsSpecImportFailed =
 importSpecializationsIfNeeded(LookupRes, Importer);
 assert(!IsSpecImportFailed);
+(void)IsSpecImportFailed;
 Decls.push_back(ND);
   }
   SetExternalVisibleDeclsForName(DC, Name, Decls);


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


[PATCH] D42532: [OpenCL] Add "cles_khr_int64" extension.

2018-01-26 Thread Alexey Bader via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323522: [OpenCL] Add "cles_khr_int64" extension. 
(authored by bader, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D42532

Files:
  cfe/trunk/include/clang/Basic/OpenCLExtensions.def
  cfe/trunk/test/SemaOpenCL/extension-version.cl


Index: cfe/trunk/include/clang/Basic/OpenCLExtensions.def
===
--- cfe/trunk/include/clang/Basic/OpenCLExtensions.def
+++ cfe/trunk/include/clang/Basic/OpenCLExtensions.def
@@ -53,6 +53,9 @@
 OPENCLEXT_INTERNAL(cl_khr_gl_event, 110, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_d3d10_sharing, 110, ~0U)
 
+// EMBEDDED_PROFILE
+OPENCLEXT_INTERNAL(cles_khr_int64, 110, ~0U)
+
 // OpenCL 1.2.
 OPENCLEXT_INTERNAL(cl_khr_context_abort, 120, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_d3d11_sharing, 120, ~0U)
Index: cfe/trunk/test/SemaOpenCL/extension-version.cl
===
--- cfe/trunk/test/SemaOpenCL/extension-version.cl
+++ cfe/trunk/test/SemaOpenCL/extension-version.cl
@@ -131,6 +131,15 @@
 #endif
 #pragma OPENCL EXTENSION cl_khr_d3d10_sharing: enable
 
+#if (__OPENCL_C_VERSION__ >= 110)
+#ifndef cles_khr_int64
+#error "Missing cles_khr_int64 define"
+#endif
+#else
+// expected-warning@+2{{unsupported OpenCL extension 'cles_khr_int64' - 
ignoring}}
+#endif
+#pragma OPENCL EXTENSION cles_khr_int64: enable
+
 #if (__OPENCL_C_VERSION__ >= 120)
 #ifndef cl_khr_context_abort
 #error "Missing cl_context_abort define"


Index: cfe/trunk/include/clang/Basic/OpenCLExtensions.def
===
--- cfe/trunk/include/clang/Basic/OpenCLExtensions.def
+++ cfe/trunk/include/clang/Basic/OpenCLExtensions.def
@@ -53,6 +53,9 @@
 OPENCLEXT_INTERNAL(cl_khr_gl_event, 110, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_d3d10_sharing, 110, ~0U)
 
+// EMBEDDED_PROFILE
+OPENCLEXT_INTERNAL(cles_khr_int64, 110, ~0U)
+
 // OpenCL 1.2.
 OPENCLEXT_INTERNAL(cl_khr_context_abort, 120, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_d3d11_sharing, 120, ~0U)
Index: cfe/trunk/test/SemaOpenCL/extension-version.cl
===
--- cfe/trunk/test/SemaOpenCL/extension-version.cl
+++ cfe/trunk/test/SemaOpenCL/extension-version.cl
@@ -131,6 +131,15 @@
 #endif
 #pragma OPENCL EXTENSION cl_khr_d3d10_sharing: enable
 
+#if (__OPENCL_C_VERSION__ >= 110)
+#ifndef cles_khr_int64
+#error "Missing cles_khr_int64 define"
+#endif
+#else
+// expected-warning@+2{{unsupported OpenCL extension 'cles_khr_int64' - ignoring}}
+#endif
+#pragma OPENCL EXTENSION cles_khr_int64: enable
+
 #if (__OPENCL_C_VERSION__ >= 120)
 #ifndef cl_khr_context_abort
 #error "Missing cl_context_abort define"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323522 - [OpenCL] Add "cles_khr_int64" extension.

2018-01-26 Thread Alexey Bader via cfe-commits
Author: bader
Date: Fri Jan 26 03:48:46 2018
New Revision: 323522

URL: http://llvm.org/viewvc/llvm-project?rev=323522&view=rev
Log:
[OpenCL] Add "cles_khr_int64" extension.

Summary:
For OpenCL 1.1 embedded profile 64 bit integers i.e. long,
ulong including the appropriate vector data types and operations
on 64-bit integers are optional. The "cles_khr_int64" extension
string will be reported if the embedded profile implementation
supports 64-bit integers.

Reviewers: Anastasia, bader

Reviewed By: Anastasia, bader

Subscribers: bader, yaxunl, Anastasia, cfe-commits

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

Modified:
cfe/trunk/include/clang/Basic/OpenCLExtensions.def
cfe/trunk/test/SemaOpenCL/extension-version.cl

Modified: cfe/trunk/include/clang/Basic/OpenCLExtensions.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/OpenCLExtensions.def?rev=323522&r1=323521&r2=323522&view=diff
==
--- cfe/trunk/include/clang/Basic/OpenCLExtensions.def (original)
+++ cfe/trunk/include/clang/Basic/OpenCLExtensions.def Fri Jan 26 03:48:46 2018
@@ -53,6 +53,9 @@ OPENCLEXT_INTERNAL(cl_khr_icd, 100, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_gl_event, 110, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_d3d10_sharing, 110, ~0U)
 
+// EMBEDDED_PROFILE
+OPENCLEXT_INTERNAL(cles_khr_int64, 110, ~0U)
+
 // OpenCL 1.2.
 OPENCLEXT_INTERNAL(cl_khr_context_abort, 120, ~0U)
 OPENCLEXT_INTERNAL(cl_khr_d3d11_sharing, 120, ~0U)

Modified: cfe/trunk/test/SemaOpenCL/extension-version.cl
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaOpenCL/extension-version.cl?rev=323522&r1=323521&r2=323522&view=diff
==
--- cfe/trunk/test/SemaOpenCL/extension-version.cl (original)
+++ cfe/trunk/test/SemaOpenCL/extension-version.cl Fri Jan 26 03:48:46 2018
@@ -131,6 +131,15 @@
 #endif
 #pragma OPENCL EXTENSION cl_khr_d3d10_sharing: enable
 
+#if (__OPENCL_C_VERSION__ >= 110)
+#ifndef cles_khr_int64
+#error "Missing cles_khr_int64 define"
+#endif
+#else
+// expected-warning@+2{{unsupported OpenCL extension 'cles_khr_int64' - 
ignoring}}
+#endif
+#pragma OPENCL EXTENSION cles_khr_int64: enable
+
 #if (__OPENCL_C_VERSION__ >= 120)
 #ifndef cl_khr_context_abort
 #error "Missing cl_context_abort define"


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


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

2018-01-26 Thread Aleksei Sidorin via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC323519: [ASTImporter] Support LambdaExprs and improve 
template support (authored by a.sidorin, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D42301?vs=131279&id=131568#toc

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: lib/AST/ExternalASTMerger.cpp
===
--- lib/AST/ExternalASTMerger.cpp
+++ lib/AST/ExternalASTMerger.cpp
@@ -16,6 +16,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ExternalASTMerger.h"
 
 using namespace clang;
@@ -351,6 +352,27 @@
   }
 }
 
+template 
+static bool importSpecializations(DeclTy *D, ASTImporter *Importer) {
+  for (auto *Spec : D->specializations())
+if (!Importer->Import(Spec))
+  return true;
+  return false;
+}
+
+/// Imports specializations from template declarations that can be specialized.
+static bool importSpecializationsIfNeeded(Decl *D, ASTImporter *Importer) {
+  if (!isa(D))
+return false;
+  if (auto *FunctionTD = dyn_cast(D))
+return importSpecializations(FunctionTD, Importer);
+  else if (auto *ClassTD = dyn_cast(D))
+return importSpecializations(ClassTD, Importer);
+  else if (auto *VarTD = dyn_cast(D))
+return importSpecializations(VarTD, Importer);
+  return false;
+}
+
 bool ExternalASTMerger::FindExternalVisibleDeclsByName(const DeclContext *DC,
DeclarationName Name) {
   llvm::SmallVector Decls;
@@ -376,9 +398,17 @@
 
   Decls.reserve(Candidates.size());
   for (const Candidate &C : Candidates) {
-NamedDecl *d = cast(C.second->Import(C.first.get()));
-assert(d);
-Decls.push_back(d);
+Decl *LookupRes = C.first.get();
+ASTImporter *Importer = C.second;
+NamedDecl *ND = cast_or_null(Importer->Import(LookupRes));
+assert(ND);
+// If we don't import specialization, they are not available via lookup
+// because the lookup result is imported TemplateDecl and it does not
+// reference its specializations until they are imported explicitly.
+bool IsSpecImportFailed =
+importSpecializationsIfNeeded(LookupRes, Importer);
+assert(!IsSpecImportFailed);
+Decls.push_back(ND);
   }
   SetExternalVisibleDeclsForName(DC, Name, Decls);
   return true;
Index: lib/AST/ASTStructuralEquivalence.cpp
===
--- lib/AST/ASTStructuralEquivalence.cpp
+++ lib/AST/ASTStructuralEquivalence.cpp
@@ -1153,19 +1153,41 @@
   D2->getTemplateParameters());
 }
 
+static bool IsTemplateDeclCommonStructurallyEquivalent(
+StructuralEquivalenceContext &Ctx, TemplateDecl *D1, TemplateDecl *D2) {
+  if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier()))
+return false;
+  if (!D1->getIdentifier()) // Special name
+if (D1->getNameAsString() != D2->getNameAsString())
+  return false;
+  return IsStructurallyEquivalent(Ctx, D1->getTemplateParameters(),
+  D2->getTemplateParameters());
+}
+
 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
  ClassTemplateDecl *D1,
  ClassTemplateDecl *D2) {
   // Check template parameters.
-  if (!IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
-D2->getTemplateParameters()))
+  if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2))
 return false;
 
   // Check the templated declaration.
   return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
   D2->getTemplatedDecl());
 }
 
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
+ FunctionTemplateDecl *D1,
+ FunctionTemplateDecl *D2) {
+  // Check template parameters.
+  if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2))
+return false;
+
+  // Check the templated declaration.
+  return Context.IsStructurallyEquivalent(D1->getTemplatedDecl()->getType(),
+  D2->getTemplatedDecl()->getType());
+}
+
 /// Determine structur

r323519 - [ASTImporter] Support LambdaExprs and improve template support

2018-01-26 Thread Aleksei Sidorin via cfe-commits
Author: a.sidorin
Date: Fri Jan 26 03:36:54 2018
New Revision: 323519

URL: http://llvm.org/viewvc/llvm-project?rev=323519&view=rev
Log:
[ASTImporter] Support LambdaExprs and improve template support

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

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


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

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=323519&r1=323518&r2=323519&view=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Fri Jan 26 03:36:54 2018
@@ -97,6 +97,8 @@ namespace clang {
 typedef DesignatedInitExpr::Designator Designator;
 Designator ImportDesignator(const Designator &D);
 
+Optional ImportLambdaCapture(const LambdaCapture &From);
+
 
 /// \brief What we should import from the definition.
 enum ImportDefinitionKind { 
@@ -127,16 +129,26 @@ namespace clang {
 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
   ImportDefinitionKind Kind = IDK_Default);
 TemplateParameterList *ImportTemplateParameterList(
- TemplateParameterList 
*Params);
+TemplateParameterList *Params);
 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
 Optional ImportTemplateArgumentLoc(
 const TemplateArgumentLoc &TALoc);
 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
  unsigned NumFromArgs,
-   SmallVectorImpl &ToArgs);
+ SmallVectorImpl &ToArgs);
+
 template 
 bool ImportTemplateArgumentListInfo(const InContainerTy &Container,
 TemplateArgumentListInfo &ToTAInfo);
+
+template
+bool ImportTemplateArgumentListInfo(SourceLocation FromLAngleLoc,
+SourceLocation FromRAngleLoc,
+const InContainerTy &Container,
+TemplateArgumentListInfo &Result);
+
+bool ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
+
 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
bool Complain = true);
 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
@@ -295,6 +307,7 @@ namespace clang {
 Expr *VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
 Expr *VisitMemberExpr(MemberExpr *E);
 Expr *VisitCallExpr(CallExpr *E);
+Expr *VisitLambdaExpr(LambdaExpr *LE);
 Expr *VisitInitListExpr(InitListExpr *E);
 Expr *VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
 Expr *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
@@ -1045,7 +1058,6 @@ bool ASTNodeImporter::ImportDefinition(R
   = FromData.HasDeclaredCopyConstructorWithConstParam;
 ToData.HasDeclaredCopyAssignmentWithConstParam
   = FromData.HasDeclaredCopyAssignmentWithConstParam;
-ToData.IsLambda = FromData.IsLambda;
 
 SmallVector Bases;
 for (const auto &Base1 : FromCXX->bases()) {
@@ -1256,6 +1268,9 @@ bool ASTNodeImporter::ImportTemplateArgu
   return false;
 }
 
+// We cannot use Optional<> pattern here and below because
+// TemplateArgumentListInfo's operator new is declared as deleted so it cannot
+// be stored in Optional.
 template 
 bool ASTNodeImporter::ImportTemplateArgumentListInfo(
 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
@@ -1268,6 +1283,18 @@ bool ASTNodeImporter::ImportTemplateArgu
   return false;
 }
 
+template 
+bool ASTNodeImporter::ImportTemplateArgumentListInfo(
+SourceLocation FromLA

[PATCH] D42573: [wip] The new threading implementation

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



Comment at: clangd/ClangdServer.h:266
+
+ParseInputs Inputs;
+std::shared_ptr Resources;

These fields should probably be grouped into multiple groups:
- `Inputs` - capture the latest input. Can only be used on the main thread.
- `Resource->Preamble` - capture some built preamble (that's always available). 
Can be accessed on both the main thread and any of the worker threads.
- `LastRequestIsUpdate` and `LastUpdateCF` - capture the state of last update 
to allow cancelling it. Can be accessed only on the main thread.
- `Queue` and `Resources->AST` - capture the latest AST, Queue is used to 
schedule requests on the main thread, `Resources->AST` can only be accessed 
from actions on scheduled on the corresponding queue.



Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573



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


[clang-tools-extra] r323518 - [clangd] Fix GCC build break 'declaration changes meaning'

2018-01-26 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Jan 26 03:23:33 2018
New Revision: 323518

URL: http://llvm.org/viewvc/llvm-project?rev=323518&view=rev
Log:
[clangd] Fix GCC build break 'declaration changes meaning'

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

Modified: clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp?rev=323518&r1=323517&r2=323518&view=diff
==
--- clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp (original)
+++ clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp Fri Jan 26 03:23:33 
2018
@@ -29,26 +29,26 @@ class RequestSpan {
   RequestSpan(json::obj *Args) : Args(Args) {}
   std::mutex Mu;
   json::obj *Args;
-  static Key> Key;
+  static Key> RSKey;
 
 public:
   // Return a context that's aware of the enclosing request, identified by 
Span.
   static Context stash(const trace::Span &Span) {
-return Span.Ctx.derive(RequestSpan::Key, std::unique_ptr(
+return Span.Ctx.derive(RSKey, std::unique_ptr(
  new RequestSpan(Span.Args)));
   }
 
   // If there's an enclosing request and the tracer is interested, calls \p F
   // with a json::obj where request info can be added.
   template  static void attach(const Context &Ctx, Func &&F) {
-auto *RequestArgs = Ctx.get(RequestSpan::Key);
+auto *RequestArgs = Ctx.get(RSKey);
 if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args)
   return;
 std::lock_guard Lock((*RequestArgs)->Mu);
 F(*(*RequestArgs)->Args);
   }
 };
-Key> RequestSpan::Key;
+Key> RequestSpan::RSKey;
 } // namespace
 
 void JSONOutput::writeMessage(const json::Expr &Message) {


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


[PATCH] D42573: [wip] The new threading implementation

2018-01-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: sammccall.
Herald added subscribers: cfe-commits, hintonda, ioeric, jkorous-apple, mgorny, 
klimek.

DO NOT SUBMIT (yet). This is a non-final version of the patch.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnitStore.cpp
  clangd/ClangdUnitStore.h
  clangd/threading/Cancellation.cpp
  clangd/threading/Cancellation.h
  clangd/threading/RequestQueue.cpp
  clangd/threading/RequestQueue.h

Index: clangd/threading/RequestQueue.h
===
--- /dev/null
+++ clangd/threading/RequestQueue.h
@@ -0,0 +1,50 @@
+//===--- RequestQueue.h -*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===-===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_THREADING_REQUESTQUEUE_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_THREADING_REQUESTQUEUE_H
+
+#include "Function.h"
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+/// A thread-safe request queue managed by ThreadPool. This is an implementation
+/// detail, see QueueHandle and ThreadPool for user-facing APIs.
+class RequestQueue {
+public:
+  RequestQueue(std::condition_variable &Condition);
+
+  void addToFront(UniqueFunction Req);
+  void addToBack(UniqueFunction Req);
+
+  llvm::Optional> pop();
+
+  bool needsProcessing() const;
+
+  bool isScheduledForRemoval() const;
+  void setScheduledForRemoval();
+
+  void startProcessing();
+  void stopProcessing();
+
+private:
+  std::condition_variable &Condition;
+  mutable std::mutex Mutex;
+  bool IsProcessing;
+  bool IsScheduledForRemoval;
+  std::deque> Requests;
+};
+
+} // namespace clangd
+} // namespace clang
+#endif
Index: clangd/threading/RequestQueue.cpp
===
--- /dev/null
+++ clangd/threading/RequestQueue.cpp
@@ -0,0 +1,78 @@
+//===--- RequestQueue.cpp ---*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===-===//
+#include "RequestQueue.h"
+
+namespace clang {
+namespace clangd {
+
+RequestQueue::RequestQueue(std::condition_variable &Condition)
+: Condition(Condition), IsProcessing(false), IsScheduledForRemoval(false) {}
+
+void RequestQueue::addToFront(UniqueFunction Req) {
+  std::unique_lock Lock(Mutex);
+  Requests.emplace_front(std::move(Req));
+
+  Lock.unlock();
+  Condition.notify_one();
+}
+
+void RequestQueue::addToBack(UniqueFunction Req) {
+  std::unique_lock Lock(Mutex);
+  Requests.emplace_back(std::move(Req));
+
+  Lock.unlock();
+  Condition.notify_one();
+}
+
+llvm::Optional> RequestQueue::pop() {
+  std::unique_lock Lock(Mutex);
+  if (Requests.empty())
+return llvm::None;
+
+  UniqueFunction Result = std::move(Requests.front());
+  Requests.pop_front();
+  return Result;
+}
+
+bool RequestQueue::needsProcessing() const {
+  std::unique_lock Lock(Mutex);
+  if (IsProcessing)
+return false;
+  return !Requests.empty() || IsScheduledForRemoval;
+}
+
+bool RequestQueue::isScheduledForRemoval() const {
+  std::unique_lock Lock(Mutex);
+  return IsScheduledForRemoval;
+}
+
+void RequestQueue::setScheduledForRemoval() {
+  std::unique_lock Lock(Mutex);
+  assert(!IsScheduledForRemoval);
+  IsScheduledForRemoval = true;
+}
+
+void RequestQueue::startProcessing() {
+  std::unique_lock Lock(Mutex);
+  assert(!IsProcessing);
+  assert(!Requests.empty() || IsScheduledForRemoval);
+  IsProcessing = true;
+}
+
+void RequestQueue::stopProcessing() {
+  std::unique_lock Lock(Mutex);
+  assert(IsProcessing);
+  IsProcessing = false;
+
+  Lock.unlock();
+  Condition.notify_one();
+}
+
+} // namespace clangd
+} // namespace clang
Index: clangd/threading/Cancellation.h
===
--- /dev/null
+++ clangd/threading/Cancellation.h
@@ -0,0 +1,44 @@
+//===--- Cancellation.h -*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===-===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_THREADING_CANCELLATION_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_THREADING_CANCELLATION_H
+
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+/// A shared boolean fla

r323517 - [Tooling] Test more APIs of ToolExecutor. NFC.

2018-01-26 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Fri Jan 26 03:10:32 2018
New Revision: 323517

URL: http://llvm.org/viewvc/llvm-project?rev=323517&view=rev
Log:
[Tooling] Test more APIs of ToolExecutor. NFC.

Modified:
cfe/trunk/unittests/Tooling/ExecutionTest.cpp

Modified: cfe/trunk/unittests/Tooling/ExecutionTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/ExecutionTest.cpp?rev=323517&r1=323516&r2=323517&view=diff
==
--- cfe/trunk/unittests/Tooling/ExecutionTest.cpp (original)
+++ cfe/trunk/unittests/Tooling/ExecutionTest.cpp Fri Jan 26 03:10:32 2018
@@ -46,7 +46,10 @@ public:
   }
 
   bool TraverseFunctionDecl(clang::FunctionDecl *Decl) {
-Context->reportResult(Decl->getNameAsString(), "1");
+Context->reportResult(Decl->getNameAsString(),
+  Context->getRevision() + ":" + Context->getCorpus() +
+  ":" + Context->getCurrentCompilationUnit() +
+  "/1");
 return ASTVisitor::TraverseFunctionDecl(Decl);
   }
 
@@ -213,10 +216,12 @@ TEST(StandaloneToolTest, SimpleActionWit
   auto KVs = Executor.getToolResults()->AllKVResults();
   ASSERT_EQ(KVs.size(), 1u);
   EXPECT_EQ("f", KVs[0].first);
-  EXPECT_EQ("1", KVs[0].second);
+  // Currently the standlone executor returns empty corpus, revision, and
+  // compilation unit.
+  EXPECT_EQ("::/1", KVs[0].second);
 
   Executor.getToolResults()->forEachResult(
-  [](StringRef, StringRef Value) { EXPECT_EQ("1", Value); });
+  [](StringRef, StringRef Value) { EXPECT_EQ("::/1", Value); });
 }
 
 class FixedCompilationDatabaseWithFiles : public CompilationDatabase {


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


[PATCH] D42174: [clangd] Refactored threading in ClangdServer

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



Comment at: clangd/ClangdServer.cpp:246
+
+  ParseInputs Inputs = getInputs(File);
+  std::shared_ptr Preamble =

sammccall wrote:
> I think you want to take a reference here, and then capture by value
Makes sense, less copies. Thanks.



Comment at: clangd/ClangdServer.cpp:400
+  CallbackType Callback,
+  llvm::Expected InpPreamble) {
+assert(InpPreamble &&

sammccall wrote:
> nit: "Inp" in InpPreamble is pretty awkward. In this context, Read might 
> work? or IP.
Used IP



Comment at: clangd/ClangdServer.cpp:403
+   "error when trying to read preamble for codeComplete");
+auto Preamble = InpPreamble->Preamble;
+auto &Command = InpPreamble->Inputs.CompileCommand;

sammccall wrote:
> InpPreamble->Preamble->Preamble is pretty hard to understand. Can we find 
> better names for these things? Or at least unpack it on one line?
It's now IP->PreambleData->Preamble. Not great, but should make more sense.



Comment at: clangd/ClangdServer.h:164
 
+/// Handles running tasks for ClangdServer and managing the resources (e.g.,
+/// preambles and ASTs) for opened files.

sammccall wrote:
> ilya-biryukov wrote:
> > sammccall wrote:
> > > This is a nice abstraction, so much better than dealing with Cppfile! A 
> > > couple of observations:
> > > 
> > > 1) all methods refer to a single file, neither the contracts nor the 
> > > implementation have any interactions between files. An API that reflects 
> > > this seems more natural. e.g. it naturally provides operations like "are 
> > > we tracking this file", and makes it natural to be able to e.g. lock at 
> > > the per-file level. e.g.
> > > 
> > >   class WorkingSet {
> > >  shared_ptr get(Path);
> > >  shared_ptr getOrCreate(Path)
> > >}
> > >class TranslationUnit {
> > >  void update(ParseInputs);
> > >  void read(Callback);
> > >}
> > > 
> > > This seems like it would make it easier to explain what the semantics of 
> > > scheduleRemove are, too.
> > > 
> > > 2) The callbacks from individual methods seem more powerful than needed, 
> > > and encourage deeper coupling. Basically, the inputs (changes) and 
> > > outputs (diagnostics, reads) don't seem to want to interact with the same 
> > > code. This suggests decoupling them: the changes are a sequence of input 
> > > events, diagnostics are a sequence of output events, reads look much as 
> > > they do now.
> > > 
> > > One benefit here is that the versioning relationship between inputs and 
> > > outputs no longer show up in the function signatures (by coupling an 
> > > input to a matching output). Expressing them as data makes it easier to 
> > > tweak them.
> > > 
> > > 3) It's not spelled out how this interacts with drafts: whether 
> > > text<->version is maintained here or externally, and what the contracts 
> > > around versions are. There are no options offered, so I would guess that 
> > > scheduleUpdate delivers new-version-or-nothing, and scheduleASTRead 
> > > delivers... current-or-newer? current-or-nothing?
> > > 
> > > I think it would *probably* be clearer to have versions minted by the 
> > > external DraftStore, that way we can decouple "we know about the contents 
> > > of this file" from "we're building this file". e.g. we probably want 
> > > wildly different policies for discarding resources of old versions, when 
> > > "resources" = source code vs "resources" = ASTs and preambles.
> > > 
> > > 4) Scheduler (or anything it decomposes into) is important and isolated 
> > > enough that it deserves its own header.
> > 1. Given the nature of the LSP, the users of the interface will probably 
> > always call only a single function of `TranslationUnit`, so we won't win 
> > much in terms of the code clarity.
> > ```
> > scheduleUpdate(File, Inputs) --> get(File).update(Inputs)
> > ```
> > That adds some complexity to the interface, though. I'd opt for not doing 
> > that in the initial version.
> > 
> > 2. One place where I find these callbacks useful are tests where we could 
> > wait for latest `addDocument` to complete. A more pressing concern is that 
> > the interface of `ClangdServer` does not allow to remove the callbacks 
> > (`addDocument` returns a future) and I would really love to keep the public 
> > interface of `ClangdServer` the same for the first iteration.
> > 
> > 3. I would err on the side of saying that `scheduleASTRead` delivers 
> > current version. This gives correct results for the current callers of the 
> > interface. If we do current-or-newer I'd start with adding the versions to 
> > the interface, so that the callers of the API would have enough context to 
> > know whether the results correspond to the latest version or not. I'd 
> > really love to keep version out of the initial patch, happy to chat about 
> > them for fo

[PATCH] D42174: [clangd] Refactored threading in ClangdServer

2018-01-26 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 131565.
ilya-biryukov marked 14 inline comments as done.
ilya-biryukov added a comment.
Herald added subscribers: hintonda, mgorny.

- Adressed review comments.
- Move threading code to separate files.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42174

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnitStore.h
  clangd/threading/Scheduler.cpp
  clangd/threading/Scheduler.h
  clangd/threading/ThreadPool.cpp
  clangd/threading/ThreadPool.h

Index: clangd/threading/ThreadPool.h
===
--- /dev/null
+++ clangd/threading/ThreadPool.h
@@ -0,0 +1,81 @@
+//===--- ThreadPool.h *- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_THREADING_THREADPOOL_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_THREADING_THREADPOOL_H
+
+#include "Function.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+/// A simple fixed-size thread pool implementation.
+class ThreadPool {
+public:
+  /// If \p AsyncThreadsCount is 0, requests added using addToFront and addToEnd
+  /// will be processed synchronously on the calling thread.
+  // Otherwise, \p AsyncThreadsCount threads will be created to schedule the
+  // requests.
+  ThreadPool(unsigned AsyncThreadsCount);
+  ~ThreadPool();
+
+  /// Add a new request to run function \p F with args \p As to the start of the
+  /// queue. The request will be run on a separate thread.
+  template 
+  void addToFront(Func &&F, Args &&... As) {
+if (RunSynchronously) {
+  std::forward(F)(std::forward(As)...);
+  return;
+}
+
+{
+  std::lock_guard Lock(Mutex);
+  RequestQueue.push_front(
+  BindWithForward(std::forward(F), std::forward(As)...));
+}
+RequestCV.notify_one();
+  }
+
+  /// Add a new request to run function \p F with args \p As to the end of the
+  /// queue. The request will be run on a separate thread.
+  template  void addToEnd(Func &&F, Args &&... As) {
+if (RunSynchronously) {
+  std::forward(F)(std::forward(As)...);
+  return;
+}
+
+{
+  std::lock_guard Lock(Mutex);
+  RequestQueue.push_back(
+  BindWithForward(std::forward(F), std::forward(As)...));
+}
+RequestCV.notify_one();
+  }
+
+private:
+  bool RunSynchronously;
+  mutable std::mutex Mutex;
+  /// We run some tasks on separate threads(parsing, CppFile cleanup).
+  /// These threads looks into RequestQueue to find requests to handle and
+  /// terminate when Done is set to true.
+  std::vector Workers;
+  /// Setting Done to true will make the worker threads terminate.
+  bool Done = false;
+  /// A queue of requests.
+  std::deque> RequestQueue;
+  /// Condition variable to wake up worker threads.
+  std::condition_variable RequestCV;
+};
+} // namespace clangd
+} // namespace clang
+#endif
Index: clangd/threading/ThreadPool.cpp
===
--- /dev/null
+++ clangd/threading/ThreadPool.cpp
@@ -0,0 +1,61 @@
+#include "ThreadPool.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/Threading.h"
+
+namespace clang {
+namespace clangd {
+ThreadPool::ThreadPool(unsigned AsyncThreadsCount)
+: RunSynchronously(AsyncThreadsCount == 0) {
+  if (RunSynchronously) {
+// Don't start the worker thread if we're running synchronously
+return;
+  }
+
+  Workers.reserve(AsyncThreadsCount);
+  for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
+Workers.push_back(std::thread([this, I]() {
+  llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
+  while (true) {
+UniqueFunction Request;
+
+// Pick request from the queue
+{
+  std::unique_lock Lock(Mutex);
+  // Wait for more requests.
+  RequestCV.wait(Lock,
+ [this] { return !RequestQueue.empty() || Done; });
+  if (Done)
+return;
+
+  assert(!RequestQueue.empty() && "RequestQueue was empty");
+
+  // We process requests starting from the front of the queue. Users of
+  // ThreadPool have a way to prioritise their requests by putting
+  // them to the either side of the queue (using either addToEnd or
+  // addToFront).
+  Request = std::move(RequestQueue.front());
+  RequestQueue.pop_front();
+} // unlock Mutex
+
+Request();
+  }
+}));
+  }
+}
+
+ThreadPool::~ThreadPool() {
+  if (RunSynchronously)
+return; // no worker thread is running in that case
+
+  {
+std::lock_guard Lock(Mutex);
+// Wake up the

[PATCH] D42517: [clangd] RFC: Pass Context implicitly using TLS.

2018-01-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 131564.
sammccall added a comment.

Rebase on the Span changes that landed as r323511


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42517

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/ClangdServer.cpp
  clangd/ClangdServer.h
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/Context.cpp
  clangd/Context.h
  clangd/GlobalCompilationDatabase.cpp
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/Logger.cpp
  clangd/Logger.h
  clangd/ProtocolHandlers.cpp
  clangd/ProtocolHandlers.h
  clangd/Trace.cpp
  clangd/Trace.h
  clangd/XRefs.cpp
  clangd/XRefs.h
  clangd/index/FileIndex.cpp
  clangd/index/FileIndex.h
  clangd/index/Index.h
  clangd/index/MemIndex.cpp
  clangd/index/MemIndex.h
  clangd/index/Merge.cpp
  unittests/clangd/FileIndexTests.cpp
  unittests/clangd/IndexTests.cpp
  unittests/clangd/TraceTests.cpp

Index: unittests/clangd/TraceTests.cpp
===
--- unittests/clangd/TraceTests.cpp
+++ unittests/clangd/TraceTests.cpp
@@ -78,8 +78,8 @@
 auto JSONTracer = trace::createJSONTracer(OS);
 trace::Session Session(*JSONTracer);
 {
-  trace::Span Tracer(Context::empty(), "A");
-  trace::log(Tracer.Ctx, "B");
+  trace::Span Tracer("A");
+  trace::log("B");
 }
   }
 
Index: unittests/clangd/IndexTests.cpp
===
--- unittests/clangd/IndexTests.cpp
+++ unittests/clangd/IndexTests.cpp
@@ -92,8 +92,7 @@
 std::vector match(const SymbolIndex &I,
const FuzzyFindRequest &Req) {
   std::vector Matches;
-  auto Ctx = Context::empty();
-  I.fuzzyFind(Ctx, Req, [&](const Symbol &Sym) {
+  I.fuzzyFind(Req, [&](const Symbol &Sym) {
 Matches.push_back(
 (Sym.Scope + (Sym.Scope.empty() ? "" : "::") + Sym.Name).str());
   });
Index: unittests/clangd/FileIndexTests.cpp
===
--- unittests/clangd/FileIndexTests.cpp
+++ unittests/clangd/FileIndexTests.cpp
@@ -76,35 +76,32 @@
 std::vector match(const SymbolIndex &I,
const FuzzyFindRequest &Req) {
   std::vector Matches;
-  auto Ctx = Context::empty();
-  I.fuzzyFind(Ctx, Req, [&](const Symbol &Sym) {
+  I.fuzzyFind(Req, [&](const Symbol &Sym) {
 Matches.push_back((Sym.Scope + Sym.Name).str());
   });
   return Matches;
 }
 
 /// Create an ParsedAST for \p Code. Returns None if \p Code is empty.
 llvm::Optional build(std::string Path, llvm::StringRef Code) {
-  Context Ctx = Context::empty();
   if (Code.empty())
 return llvm::None;
   const char *Args[] = {"clang", "-xc++", Path.c_str()};
 
   auto CI = createInvocationFromCommandLine(Args);
 
   auto Buf = llvm::MemoryBuffer::getMemBuffer(Code);
-  auto AST = ParsedAST::Build(Ctx, std::move(CI), nullptr, std::move(Buf),
+  auto AST = ParsedAST::Build(std::move(CI), nullptr, std::move(Buf),
   std::make_shared(),
   vfs::getRealFileSystem());
   assert(AST.hasValue());
   return std::move(*AST);
 }
 
 TEST(FileIndexTest, IndexAST) {
   FileIndex M;
-  auto Ctx = Context::empty();
   M.update(
-  Ctx, "f1",
+  "f1",
   build("f1", "namespace ns { void f() {} class X {}; }").getPointer());
 
   FuzzyFindRequest Req;
@@ -115,9 +112,8 @@
 
 TEST(FileIndexTest, NoLocal) {
   FileIndex M;
-  auto Ctx = Context::empty();
   M.update(
-  Ctx, "f1",
+  "f1",
   build("f1", "namespace ns { void f() { int local = 0; } class X {}; }")
   .getPointer());
 
@@ -128,12 +124,11 @@
 
 TEST(FileIndexTest, IndexMultiASTAndDeduplicate) {
   FileIndex M;
-  auto Ctx = Context::empty();
   M.update(
-  Ctx, "f1",
+  "f1",
   build("f1", "namespace ns { void f() {} class X {}; }").getPointer());
   M.update(
-  Ctx, "f2",
+  "f2",
   build("f2", "namespace ns { void ff() {} class X {}; }").getPointer());
 
   FuzzyFindRequest Req;
@@ -144,31 +139,28 @@
 
 TEST(FileIndexTest, RemoveAST) {
   FileIndex M;
-  auto Ctx = Context::empty();
   M.update(
-  Ctx, "f1",
+  "f1",
   build("f1", "namespace ns { void f() {} class X {}; }").getPointer());
 
   FuzzyFindRequest Req;
   Req.Query = "";
   Req.Scopes = {"ns::"};
   EXPECT_THAT(match(M, Req), UnorderedElementsAre("ns::f", "ns::X"));
 
-  M.update(Ctx, "f1", nullptr);
+  M.update("f1", nullptr);
   EXPECT_THAT(match(M, Req), UnorderedElementsAre());
 }
 
 TEST(FileIndexTest, RemoveNonExisting) {
   FileIndex M;
-  auto Ctx = Context::empty();
-  M.update(Ctx, "no", nullptr);
+  M.update("no", nullptr);
   EXPECT_THAT(match(M, FuzzyFindRequest()), UnorderedElementsAre());
 }
 
 TEST(FileIndexTest, IgnoreClassMembers) {
   FileIndex M;
-  auto Ctx = Context::empty();
-  M.update(Ctx, "f1",
+  M.update("f1",
build("f1", "c

[PATCH] D42561: [PR36008] Avoid -Wsign-compare warning for enum constants in typeof expressions

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



Comment at: lib/Sema/SemaChecking.cpp:8959
+  if (!S.getLangOpts().CPlusPlus) {
+if (const TypeOfExprType *TET = dyn_cast(RHS->getType()))
+  RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();

Please also add a comment what this is trying to solve.



Comment at: test/Sema/compare.c:404
+  __typeof__(kPR36008Value) y = (kPR36008Value);
+  if (x == y) x = y; // no warning
+}

Can you also add the swapped test:
```
if (y == x) x = y; // no warning
```


Repository:
  rC Clang

https://reviews.llvm.org/D42561



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


[PATCH] D42570: clang-format: [JS] Prevent ASI before [ and (.

2018-01-26 Thread Martin Probst via Phabricator via cfe-commits
mprobst created this revision.
mprobst added a reviewer: djasper.
Herald added a subscriber: klimek.

JavaScript automatic semicolon insertion can trigger before [ and (, so
avoid breaking before them if the previous token is likely to terminate
an expression.


Repository:
  rC Clang

https://reviews.llvm.org/D42570

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTestJS.cpp


Index: unittests/Format/FormatTestJS.cpp
===
--- unittests/Format/FormatTestJS.cpp
+++ unittests/Format/FormatTestJS.cpp
@@ -1157,6 +1157,9 @@
"foo() {}",
getGoogleJSStyleWithColumns(10));
   verifyFormat("await theReckoning;", getGoogleJSStyleWithColumns(10));
+  verifyFormat("some['a']['b']", getGoogleJSStyleWithColumns(10));
+  verifyFormat("x = (a['a']\n"
+   "  ['b']);", getGoogleJSStyleWithColumns(10));
 }
 
 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2710,9 +2710,11 @@
 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
   return false; // Otherwise automatic semicolon insertion would trigger.
-if (Left.Tok.getIdentifierInfo() &&
-Right.startsSequence(tok::l_square, tok::r_square))
-  return false;  // breaking in "foo[]" creates illegal TS type syntax.
+if (Right.NestingLevel == 0 &&
+(Left.Tok.getIdentifierInfo() ||
+ Left.isOneOf(tok::r_square, tok::r_paren)) &&
+Right.isOneOf(tok::l_square, tok::l_paren))
+  return false; // Otherwise automatic semicolon insertion would trigger.
 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
   return false;
 if (Left.is(TT_JsTypeColon))


Index: unittests/Format/FormatTestJS.cpp
===
--- unittests/Format/FormatTestJS.cpp
+++ unittests/Format/FormatTestJS.cpp
@@ -1157,6 +1157,9 @@
"foo() {}",
getGoogleJSStyleWithColumns(10));
   verifyFormat("await theReckoning;", getGoogleJSStyleWithColumns(10));
+  verifyFormat("some['a']['b']", getGoogleJSStyleWithColumns(10));
+  verifyFormat("x = (a['a']\n"
+   "  ['b']);", getGoogleJSStyleWithColumns(10));
 }
 
 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -2710,9 +2710,11 @@
 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
   return false; // Otherwise automatic semicolon insertion would trigger.
-if (Left.Tok.getIdentifierInfo() &&
-Right.startsSequence(tok::l_square, tok::r_square))
-  return false;  // breaking in "foo[]" creates illegal TS type syntax.
+if (Right.NestingLevel == 0 &&
+(Left.Tok.getIdentifierInfo() ||
+ Left.isOneOf(tok::r_square, tok::r_paren)) &&
+Right.isOneOf(tok::l_square, tok::l_paren))
+  return false; // Otherwise automatic semicolon insertion would trigger.
 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
   return false;
 if (Left.is(TT_JsTypeColon))
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42569: [ARM] disable FPU features when using soft floating point.

2018-01-26 Thread Keith Walker via Phabricator via cfe-commits
keith.walker.arm created this revision.
keith.walker.arm added reviewers: efriedma, compnerd.
Herald added subscribers: cfe-commits, kristof.beyls, javed.absar, aemerson.

This change was orignally approved in Differential Revision
https://reviews.llvm.org/D40256 and committed in r319420 and subsequently
reverted in r319425.

The problem was identified due to creating a local string which was placed
in a vector used by the calling function resulting in undefined behaviour;
this revised patch fixes this issue with a call to Args.MakeArgString()
and updates the test results due to the fix (order of expected options
changed requiring more matching patterns) and other changes affecting
the tests since this issue was previously approved (macro hex constants
changing case).  Due to the number of changed lines in the tests I though
I should get this change re-reviewed and approved.

To be compatible with GCC if soft floating point is in effect any FPU
specified is effectively ignored, eg,

  -mfloat-abi=soft -fpu=neon

If any floating point features which require FPU hardware are enabled
they must be disable.

There was some support for doing this for NEON, but it did not handle
VFP, nor did it prevent the backend from emitting the build attribute
Tag_FP_arch describing the generated code as using the floating point
hardware if a FPU was specified (even though soft float does not use
the FPU).

Disabling the hardware floating point features for targets which are
compiling for soft float has meant that some tests which were incorrectly
checking for hardware support also needed to be updated. In such cases,
where appropriate the tests have been updated to check compiling for soft
float and a non-soft float variant (usually softfp). This was usually
because the target specified in the test defaulted to soft float.


Repository:
  rC Clang

https://reviews.llvm.org/D42569

Files:
  lib/Driver/ToolChains/Arch/ARM.cpp
  test/Driver/arm-cortex-cpus.c
  test/Driver/arm-dotprod.c
  test/Driver/arm-mfpu.c
  test/Preprocessor/arm-target-features.c

Index: test/Driver/arm-dotprod.c
===
--- test/Driver/arm-dotprod.c
+++ test/Driver/arm-dotprod.c
@@ -4,8 +4,21 @@
 // RUN: %clang -### -target arm -march=armv8.3a %s 2>&1 | FileCheck %s --check-prefix=CHECK-NONE
 // CHECK-NONE-NOT: "-target-feature" "+dotprod"
 
-// RUN: %clang -### -target arm -march=armv8.2a+dotprod %s 2>&1 | FileCheck %s
-// RUN: %clang -### -target arm -march=armv8.3a+dotprod %s 2>&1 | FileCheck %s
-// RUN: %clang -### -target arm -mcpu=cortex-a75 %s 2>&1 | FileCheck %s
-// RUN: %clang -### -target arm -mcpu=cortex-a55 %s 2>&1 | FileCheck %s
+// RUN: %clang -### -target arm-linux-eabi -march=armv8.2a+dotprod %s 2>&1 | FileCheck %s
+// RUN: %clang -### -target arm-linux-eabi -march=armv8.3a+dotprod %s 2>&1 | FileCheck %s
+// RUN: %clang -### -target arm-linux-eabi -mcpu=cortex-a75 %s 2>&1 | FileCheck %s
+// RUN: %clang -### -target arm-linux-eabi -mcpu=cortex-a55 %s 2>&1 | FileCheck %s
 // CHECK: "+dotprod"
+
+// The following default to -msoft-float
+// RUN: %clang -### -target arm -march=armv8.2a+dotprod %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-NO-DOTPROD
+// RUN: %clang -### -target arm -march=armv8.3a+dotprod %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-NO-DOTPROD
+// RUN: %clang -### -target arm -mcpu=cortex-a75 %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-NO-DOTPROD
+// RUN: %clang -### -target arm -mcpu=cortex-a55 %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=CHECK-NO-DOTPROD
+// We rely on the backend disabling dotprod as it depends on neon, so check that
+// neon is disabled after the dotprod was enabled.
+// CHECK-NO-DOTPROD-NOT: "+dotprod"
Index: test/Driver/arm-cortex-cpus.c
===
--- test/Driver/arm-cortex-cpus.c
+++ test/Driver/arm-cortex-cpus.c
@@ -284,13 +284,13 @@
 // RUN: %clang -target arm -march=armebv8.2-a -mbig-endian -mthumb -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-BE-V82A-THUMB %s
 // CHECK-BE-V82A-THUMB: "-cc1"{{.*}} "-triple" "thumbebv8.2a-{{.*}}" "-target-cpu" "generic"
 
-// RUN: %clang -target armv8a -march=armv8.2-a+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-V82A-FP16 %s
+// RUN: %clang -target armv8a-linux-eabi -march=armv8.2-a+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-V82A-FP16 %s
 // CHECK-V82A-FP16: "-cc1"{{.*}} "-triple" "armv8.2{{.*}}" "-target-cpu" "generic" {{.*}}"-target-feature" "+fullfp16"
 
 // Once we have CPUs with optional v8.2-A FP16, we will need a way to turn it
 // on and off. Cortex-A53 is a placeholder for now.
-// RUN: %clang -target armv8a -mcpu=cortex-a53+fp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-CORTEX-A53-FP16 %s
-// RUN: %clang -target armv8a -mcpu=cortex-a53+nofp16 -### -c %s 2>&1 | FileCheck --check-prefix CHECK-CORTEX-A53-NOFP16 %s
+// RUN: %clang -target armv8a-linux-eabi -mcpu=cortex-a53+fp16 -### 

[PATCH] D42395: [clang-format] Fix bug where -dump-config failed on ObjC header

2018-01-26 Thread Krasimir Georgiev via Phabricator via cfe-commits
krasimir requested changes to this revision.
krasimir added inline comments.
This revision now requires changes to proceed.



Comment at: test/Format/lit.local.cfg:1
+# Suffixes supported by clang-format.
+config.suffixes = ['.c', '.cc', '.cpp', '.h', '.m', '.mm', '.java', '.js',

Why is this needed?


Repository:
  rC Clang

https://reviews.llvm.org/D42395



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


[PATCH] D42530: Clang permits assignment to vector/extvector elements in a const method

2018-01-26 Thread Andrew V. Tischenko via Phabricator via cfe-commits
avt77 added inline comments.



Comment at: lib/AST/ExprClassification.cpp:652
+if (Ctx.getCanonicalType(ASE->getBase()->getType()).isConstQualified())
+  return Cl::CM_ConstQualified;
+

rjmccall wrote:
> Is there a reason why the places that compute the type of these l-value 
> expressions don't propagate qualiifers?  This hardly seems restricted to 
> 'const'.
Do you mean ExtVectorElementExpr/ArraySubscriptExpr should retrun 
isConstQualified() == true by themselves (and other qualifiers as well)?


https://reviews.llvm.org/D42530



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


[PATCH] D42464: add prefix with '_' support for property name. Corresponding apple dev doc: https://developer.apple.com/library/content/qa/qa1908/_index.html

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



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:115
+
+bool prefixedPropertyNameMatches(const llvm::StringRef &PropertyName,
+ const std::vector &Acronyms) {

Wizard wrote:
> hokein wrote:
> > no need to pass const reference of `llvm::StringRef`. `StringRef` is cheap.
> The original property name I directly get from ast is a const. If I remove 
> the const here, I will have to make a copy of the property name before 
> calling this.
> I prefer keep this const to save that copy :-)
Why? `MatchedDecl->getName()` returns `llvm::StringRef`. As the name indicates, 
StringRef is a const reference of String, using StringRef is sufficient.

The same to ArrayRef. So the function is like `bool 
prefixedPropertyNameMatches(llvm::StringRef PropertyName, 
llvm::ArrayRef Acronyms)`.





Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:151
+  hasCategoryPropertyPrefix(MatchedDecl->getName())) {
+const auto *CategoryDecl = (const ObjCCategoryDecl *)(DeclContext);
+if (!prefixedPropertyNameMatches(MatchedDecl->getName(), SpecialAcronyms) 
||

Wizard wrote:
> hokein wrote:
> > Consider using `const auto* CategoryDecl = 
> > dyn_cast(DeclContext)`, we can get rid of this cast, and 
> > `NodeKind` variable.
> Tried that before but I encountered 2 issues:
> 1. 'clang::DeclContext' is not polymorphic
> 2. cannot use dynamic_cast with -fno-rtti
> which are preventing me from using dynamic_cast
Sorry, I mean `llvm::dyn_cast` here, it should work.



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:67
+  if (Style == CategoryProperty) {
+for (size_t i = 0; i < Name.size(); ++i) {
+  if (Name[i] == '_') {

I think we save this code by using `find_first_of` and 
`llvm::StringRef::tolower()` function.



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:95
+// in matchers or not.
+std::string validPropertyNameRegex(const std::vector &Acronyms,
+   bool UsedInMatcher) {

The same, ArrayRef.



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:121
+
+bool hasCategoryPropertyPrefix(const llvm::StringRef &PropertyName) {
+  auto RegexExp = llvm::Regex("^[a-z]+_[a-zA-Z0-9][a-zA-Z0-9_]+$");

The same: `llvm::StringRef`



Comment at: clang-tidy/objc/PropertyDeclarationCheck.cpp:163
+MatchedDecl->getName(),
+llvm::ArrayRef(SpecialAcronyms)) ||
+CategoryDecl->IsClassExtension()) {

Do we need it? I think you can pass `SpecialAcronyms` directly.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42464



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


[PATCH] D42499: [clangd] Modify the Span API so that Spans propagate with contexts.

2018-01-26 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL323511: [clangd] Modify the Span API so that Spans propagate 
with contexts. (authored by sammccall, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42499?vs=131546&id=131547#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42499

Files:
  clang-tools-extra/trunk/clangd/ClangdUnit.cpp
  clang-tools-extra/trunk/clangd/Context.h
  clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp
  clang-tools-extra/trunk/clangd/Trace.cpp
  clang-tools-extra/trunk/clangd/Trace.h
  clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp

Index: clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp
@@ -78,8 +78,8 @@
 auto JSONTracer = trace::createJSONTracer(OS);
 trace::Session Session(*JSONTracer);
 {
-  trace::Span S(Context::empty(), "A");
-  trace::log(Context::empty(), "B");
+  trace::Span Tracer(Context::empty(), "A");
+  trace::log(Tracer.Ctx, "B");
 }
   }
 
Index: clang-tools-extra/trunk/clangd/Trace.h
===
--- clang-tools-extra/trunk/clangd/Trace.h
+++ clang-tools-extra/trunk/clangd/Trace.h
@@ -32,17 +32,15 @@
 /// Implmentations of this interface must be thread-safe.
 class EventTracer {
 public:
-  /// A callback executed when an event with duration ends. Args represent data
-  /// that was attached to the event via SPAN_ATTACH.
-  using EndEventCallback = UniqueFunction;
-
   virtual ~EventTracer() = default;
 
-  /// Called when event that has a duration starts. The returned callback will
-  /// be executed when the event ends. \p Name is a descriptive name
-  /// of the event that was passed to Span constructor.
-  virtual EndEventCallback beginSpan(const Context &Ctx,
- llvm::StringRef Name) = 0;
+  /// Called when event that has a duration starts. \p Name describes the event.
+  /// Returns a derived context that will be destroyed when the event ends.
+  /// Usually implementations will store an object in the returned context
+  /// whose destructor records the end of the event.
+  /// The args are *Args, only complete when the event ends.
+  virtual Context beginSpan(const Context &Ctx, llvm::StringRef Name,
+json::obj *Args) = 0;
 
   /// Called for instant events.
   virtual void instant(const Context &Ctx, llvm::StringRef Name,
@@ -70,30 +68,35 @@
 void log(const Context &Ctx, const llvm::Twine &Name);
 
 /// Records an event whose duration is the lifetime of the Span object.
+/// This lifetime is extended when the span's context is reused.
+///
 /// This is the main public interface for producing tracing events.
 ///
 /// Arbitrary JSON metadata can be attached while this span is active:
 ///   SPAN_ATTACH(MySpan, "Payload", SomeJSONExpr);
+///
 /// SomeJSONExpr is evaluated and copied only if actually needed.
 class Span {
 public:
   Span(const Context &Ctx, llvm::StringRef Name);
-  ~Span();
 
-  /// Returns mutable span metadata if this span is interested.
+  /// Mutable metadata, if this span is interested.
   /// Prefer to use SPAN_ATTACH rather than accessing this directly.
-  json::obj *args() { return Args.get(); }
-
-private:
-  std::unique_ptr Args;
-  EventTracer::EndEventCallback Callback;
+  json::obj *const Args;
+  /// Propagating this context will keep the span alive.
+  const Context Ctx;
 };
 
+/// Returns mutable span metadata if this span is interested.
+/// Prefer to use SPAN_ATTACH rather than accessing this directly.
+json::obj *spanArgs(const Context &Ctx);
+
+/// Attach a key-value pair to a Span event.
+/// This is not threadsafe when used with the same Span.
 #define SPAN_ATTACH(S, Name, Expr) \
   do { \
-if ((S).args() != nullptr) {   \
-  (*((S).args()))[(Name)] = (Expr);\
-}  \
+if (auto *Args = (S).Args) \
+  (*Args)[Name] = Expr;\
   } while (0)
 
 } // namespace trace
Index: clang-tools-extra/trunk/clangd/Context.h
===
--- clang-tools-extra/trunk/clangd/Context.h
+++ clang-tools-extra/trunk/clangd/Context.h
@@ -84,6 +84,9 @@
 ///
 /// Keys are typically used across multiple functions, so most of the time you
 /// would want to make them static class members or global variables.
+///
+/// FIXME: Rather than manual plumbi

[clang-tools-extra] r323511 - [clangd] Modify the Span API so that Spans propagate with contexts.

2018-01-26 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Jan 26 01:00:30 2018
New Revision: 323511

URL: http://llvm.org/viewvc/llvm-project?rev=323511&view=rev
Log:
[clangd] Modify the Span API so that Spans propagate with contexts.

Summary:
This is probably the right behavior for distributed tracers, and makes unpaired
begin-end events impossible without requiring Spans to be bound to a thread.

The API is conceptually clean but syntactically awkward. As discussed offline,
this is basically a naming problem and will go away if (when) we use TLS to
store the current context.

The apparently-unrelated change to onScopeExit are because its move semantics
broken if Func is POD-like since r322838. This is true of function pointers,
and the lambda I use here that captures two pointers only.
I've raised this issue on llvm-dev and will revert this part if we fix it in
some other way.

Reviewers: ilya-biryukov

Subscribers: klimek, jkorous-apple, ioeric, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/ClangdUnit.cpp
clang-tools-extra/trunk/clangd/Context.h
clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp
clang-tools-extra/trunk/clangd/Trace.cpp
clang-tools-extra/trunk/clangd/Trace.h
clang-tools-extra/trunk/unittests/clangd/TraceTests.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdUnit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdUnit.cpp?rev=323511&r1=323510&r2=323511&view=diff
==
--- clang-tools-extra/trunk/clangd/ClangdUnit.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdUnit.cpp Fri Jan 26 01:00:30 2018
@@ -564,15 +564,16 @@ CppFile::deferRebuild(ParseInputs &&Inpu
   CI->getFrontendOpts().SkipFunctionBodies = false;
 
   if (BuiltPreamble) {
-log(Ctx, "Built preamble of size " + Twine(BuiltPreamble->getSize()) +
- " for file " + Twine(That->FileName));
+log(Tracer.Ctx, "Built preamble of size " +
+Twine(BuiltPreamble->getSize()) + " for file " +
+Twine(That->FileName));
 
 return std::make_shared(
 std::move(*BuiltPreamble),
 SerializedDeclsCollector.takeTopLevelDeclIDs(),
 std::move(PreambleDiags));
   } else {
-log(Ctx,
+log(Tracer.Ctx,
 "Could not build a preamble for file " + Twine(That->FileName));
 return nullptr;
   }
@@ -605,8 +606,9 @@ CppFile::deferRebuild(ParseInputs &&Inpu
 {
   trace::Span Tracer(Ctx, "Build");
   SPAN_ATTACH(Tracer, "File", That->FileName);
-  NewAST = ParsedAST::Build(Ctx, std::move(CI), std::move(NewPreamble),
-std::move(ContentsBuffer), PCHs, Inputs.FS);
+  NewAST =
+  ParsedAST::Build(Tracer.Ctx, std::move(CI), std::move(NewPreamble),
+   std::move(ContentsBuffer), PCHs, Inputs.FS);
 }
 
 if (NewAST) {

Modified: clang-tools-extra/trunk/clangd/Context.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Context.h?rev=323511&r1=323510&r2=323511&view=diff
==
--- clang-tools-extra/trunk/clangd/Context.h (original)
+++ clang-tools-extra/trunk/clangd/Context.h Fri Jan 26 01:00:30 2018
@@ -84,6 +84,9 @@ public:
 ///
 /// Keys are typically used across multiple functions, so most of the time you
 /// would want to make them static class members or global variables.
+///
+/// FIXME: Rather than manual plumbing, pass Context using thread-local storage
+/// by default, and make thread boundaries deal with propagation explicitly.
 class Context {
 public:
   /// Returns an empty context that contains no data. Useful for calling
@@ -150,6 +153,18 @@ public:
 std::move(Value))}));
   }
 
+  /// Derives a child context, using an anonymous key.
+  /// Intended for objects stored only for their destructor's side-effect.
+  template  Context derive(Type &&Value) const & {
+static Key::type> Private;
+return derive(Private, std::forward(Value));
+  }
+
+  template  Context derive(Type &&Value) && {
+static Key::type> Private;
+return std::move(this)->derive(Private, std::forward(Value));
+  }
+
   /// Clone this context object.
   Context clone() const;
 

Modified: clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp?rev=323511&r1=323510&r2=323511&view=diff
==
--- clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp (original)
+++ clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp Fri Jan 26 01:00:30 
2018
@@ -20,9 +20,35 @@ using namespace clang;
 using namespace clangd;
 
 namespace {
-static Key> RequestSpan;
 static Key RequestID;
 st

[PATCH] D42499: [clangd] Modify the Span API so that Spans propagate with contexts.

2018-01-26 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 131546.
sammccall marked 2 inline comments as done.
sammccall added a comment.

Address review comments


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42499

Files:
  clangd/ClangdUnit.cpp
  clangd/Context.h
  clangd/Function.h
  clangd/JSONRPCDispatcher.cpp
  clangd/Trace.cpp
  clangd/Trace.h
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/TraceTests.cpp

Index: unittests/clangd/TraceTests.cpp
===
--- unittests/clangd/TraceTests.cpp
+++ unittests/clangd/TraceTests.cpp
@@ -78,8 +78,8 @@
 auto JSONTracer = trace::createJSONTracer(OS);
 trace::Session Session(*JSONTracer);
 {
-  trace::Span S(Context::empty(), "A");
-  trace::log(Context::empty(), "B");
+  trace::Span Tracer(Context::empty(), "A");
+  trace::log(Tracer.Ctx, "B");
 }
   }
 
Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -537,12 +537,13 @@
   /*StorePreamblesInMemory=*/true);
 
   FS.Files[getVirtualTestFilePath("bar.h")] =
-  R"cpp(namespace ns { int preamble; })cpp";
+  R"cpp(namespace ns { struct preamble { int member; }; })cpp";
   auto File = getVirtualTestFilePath("foo.cpp");
   Annotations Test(R"cpp(
   #include "bar.h"
   namespace ns { int local; }
-  void f() { ns::^ }
+  void f() { ns::^; }
+  void f() { ns::preamble().$2^; }
   )cpp");
   Server.addDocument(Context::empty(), File, Test.code()).wait();
   clangd::CodeCompleteOptions Opts = {};
@@ -562,6 +563,11 @@
   .second.Value;
   EXPECT_THAT(WithIndex.items,
   UnorderedElementsAre(Named("local"), Named("index")));
+  auto ClassFromPreamble =
+  Server.codeComplete(Context::empty(), File, Test.point("2"), Opts)
+  .get()
+  .second.Value;
+  EXPECT_THAT(ClassFromPreamble.items, Contains(Named("member")));
 }
 
 TEST(CompletionTest, DynamicIndexMultiFile) {
Index: clangd/Trace.h
===
--- clangd/Trace.h
+++ clangd/Trace.h
@@ -32,17 +32,15 @@
 /// Implmentations of this interface must be thread-safe.
 class EventTracer {
 public:
-  /// A callback executed when an event with duration ends. Args represent data
-  /// that was attached to the event via SPAN_ATTACH.
-  using EndEventCallback = UniqueFunction;
-
   virtual ~EventTracer() = default;
 
-  /// Called when event that has a duration starts. The returned callback will
-  /// be executed when the event ends. \p Name is a descriptive name
-  /// of the event that was passed to Span constructor.
-  virtual EndEventCallback beginSpan(const Context &Ctx,
- llvm::StringRef Name) = 0;
+  /// Called when event that has a duration starts. \p Name describes the event.
+  /// Returns a derived context that will be destroyed when the event ends.
+  /// Usually implementations will store an object in the returned context
+  /// whose destructor records the end of the event.
+  /// The args are *Args, only complete when the event ends.
+  virtual Context beginSpan(const Context &Ctx, llvm::StringRef Name,
+json::obj *Args) = 0;
 
   /// Called for instant events.
   virtual void instant(const Context &Ctx, llvm::StringRef Name,
@@ -70,30 +68,35 @@
 void log(const Context &Ctx, const llvm::Twine &Name);
 
 /// Records an event whose duration is the lifetime of the Span object.
+/// This lifetime is extended when the span's context is reused.
+///
 /// This is the main public interface for producing tracing events.
 ///
 /// Arbitrary JSON metadata can be attached while this span is active:
 ///   SPAN_ATTACH(MySpan, "Payload", SomeJSONExpr);
+///
 /// SomeJSONExpr is evaluated and copied only if actually needed.
 class Span {
-public:
+ public:
   Span(const Context &Ctx, llvm::StringRef Name);
-  ~Span();
 
-  /// Returns mutable span metadata if this span is interested.
+  /// Mutable metadata, if this span is interested.
   /// Prefer to use SPAN_ATTACH rather than accessing this directly.
-  json::obj *args() { return Args.get(); }
-
-private:
-  std::unique_ptr Args;
-  EventTracer::EndEventCallback Callback;
+  json::obj * const Args;
+  /// Propagating this context will keep the span alive.
+  const Context Ctx;
 };
 
+/// Returns mutable span metadata if this span is interested.
+/// Prefer to use SPAN_ATTACH rather than accessing this directly.
+json::obj *spanArgs(const Context &Ctx);
+
+/// Attach a key-value pair to a Span event.
+/// This is not threadsafe when used with the same Span.
 #define SPAN_ATTACH(S, Name, Expr) \
   do { \
-if ((S).args() != nullptr) {  

[PATCH] D42499: [clangd] Modify the Span API so that Spans propagate with contexts.

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



Comment at: clangd/JSONRPCDispatcher.cpp:31
+  RequestArgs(json::obj *Args) : Args(Args) {}
+  std::mutex Mu;
+  json::obj *Args;

ilya-biryukov wrote:
> We could make the fields private and expose only the function to modify args 
> under lock (similar to `FillRequestInfo`, i.e. the last two line of it).
> That would make the class safer to use. But that's work and the class itself 
> is an implementation detail, so we could also leave it as is.
Yeah, good point. Encapsulated the whole mechanism in this class.



Comment at: clangd/Trace.cpp:138
+  Args)
+: Ctx.derive(kSpanArgs, nullptr)) {}
 

ilya-biryukov wrote:
> Would be nice for `Span`s to have zero cost when no tracer is active. We 
> could probably achieve that be not storing the `kSpanArgs` when `T` is null. 
> WDYT?
> That's really not a big deal, so I don't think we should block the patch on 
> this.
Good catch! This was left over from an older revision where SPAN_ATTACH looked 
up the args in the context.
Now this is for ownership only, so I skip derive() if there's no tracer, and 
made the key anonymous.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42499



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


r323509 - [NFC] fix trivial typos in comments and documents

2018-01-26 Thread Hiroshi Inoue via cfe-commits
Author: inouehrs
Date: Fri Jan 26 00:15:52 2018
New Revision: 323509

URL: http://llvm.org/viewvc/llvm-project?rev=323509&view=rev
Log:
[NFC] fix trivial typos in comments and documents

"in in" -> "in", "on on" -> "on" etc.


Modified:
cfe/trunk/docs/InternalsManual.rst
cfe/trunk/docs/doxygen.cfg.in
cfe/trunk/include/clang/AST/OpenMPClause.h
cfe/trunk/include/clang/Frontend/SerializedDiagnosticPrinter.h
cfe/trunk/include/clang/Lex/HeaderSearch.h
cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h
cfe/trunk/lib/CodeGen/CGObjC.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
cfe/trunk/test/Analysis/temporaries.cpp

Modified: cfe/trunk/docs/InternalsManual.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/InternalsManual.rst?rev=323509&r1=323508&r2=323509&view=diff
==
--- cfe/trunk/docs/InternalsManual.rst (original)
+++ cfe/trunk/docs/InternalsManual.rst Fri Jan 26 00:15:52 2018
@@ -1823,7 +1823,7 @@ Note that setting this member to 1 will
 handling, requiring extra implementation efforts to ensure the attribute
 appertains to the appropriate subject, etc.
 
-If the attribute should not be propagated from from a template declaration to 
an
+If the attribute should not be propagated from a template declaration to an
 instantiation of the template, set the ``Clone`` member to 0. By default, all
 attributes will be cloned to template instantiations.
 

Modified: cfe/trunk/docs/doxygen.cfg.in
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/doxygen.cfg.in?rev=323509&r1=323508&r2=323509&view=diff
==
--- cfe/trunk/docs/doxygen.cfg.in (original)
+++ cfe/trunk/docs/doxygen.cfg.in Fri Jan 26 00:15:52 2018
@@ -284,7 +284,7 @@ MARKDOWN_SUPPORT   = YES
 
 # When enabled doxygen tries to link words that correspond to documented
 # classes, or namespaces to their corresponding documentation. Such a link can
-# be prevented in individual cases by by putting a % sign in front of the word
+# be prevented in individual cases by putting a % sign in front of the word
 # or globally by setting AUTOLINK_SUPPORT to NO.
 # The default value is: YES.
 

Modified: cfe/trunk/include/clang/AST/OpenMPClause.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/OpenMPClause.h?rev=323509&r1=323508&r2=323509&view=diff
==
--- cfe/trunk/include/clang/AST/OpenMPClause.h (original)
+++ cfe/trunk/include/clang/AST/OpenMPClause.h Fri Jan 26 00:15:52 2018
@@ -3902,7 +3902,7 @@ public:
   OpenMPMapClauseKind Type, bool TypeIsImplicit,
   SourceLocation TypeLoc);
 
-  /// \brief Creates an empty clause with the place for for \a NumVars original
+  /// \brief Creates an empty clause with the place for \a NumVars original
   /// expressions, \a NumUniqueDeclarations declarations, \NumComponentLists
   /// lists, and \a NumComponents expression components.
   ///

Modified: cfe/trunk/include/clang/Frontend/SerializedDiagnosticPrinter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Frontend/SerializedDiagnosticPrinter.h?rev=323509&r1=323508&r2=323509&view=diff
==
--- cfe/trunk/include/clang/Frontend/SerializedDiagnosticPrinter.h (original)
+++ cfe/trunk/include/clang/Frontend/SerializedDiagnosticPrinter.h Fri Jan 26 
00:15:52 2018
@@ -29,7 +29,7 @@ namespace serialized_diags {
 ///  a bitcode file.
 ///
 /// The created DiagnosticConsumer is designed for quick and lightweight
-/// transfer of of diagnostics to the enclosing build system (e.g., an IDE).
+/// transfer of diagnostics to the enclosing build system (e.g., an IDE).
 /// This allows wrapper tools for Clang to get diagnostics from Clang
 /// (via libclang) without needing to parse Clang's command line output.
 ///

Modified: cfe/trunk/include/clang/Lex/HeaderSearch.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/HeaderSearch.h?rev=323509&r1=323508&r2=323509&view=diff
==
--- cfe/trunk/include/clang/Lex/HeaderSearch.h (original)
+++ cfe/trunk/include/clang/Lex/HeaderSearch.h Fri Jan 26 00:15:52 2018
@@ -416,7 +416,7 @@ public:
 return FrameworkMap[FWName];
   }
 
-  /// \brief Mark the specified file as a target of of a \#include,
+  /// \brief Mark the specified file as a target of a \#include,
   /// \#include_next, or \#import directive.
   ///
   /// \return false if \#including the file will have no effect or true

Modified: cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Lex/MultipleIncludeOpt.h?rev=323509&r1=323508&r2=323509&view=diff
==