r368804 - [NewPM][PassInstrumentation] IR printing support from clang driver

2019-08-14 Thread Taewook Oh via cfe-commits
Author: twoh
Date: Wed Aug 14 00:11:09 2019
New Revision: 368804

URL: http://llvm.org/viewvc/llvm-project?rev=368804&view=rev
Log:
[NewPM][PassInstrumentation] IR printing support from clang driver

Summary: https://reviews.llvm.org/D50923 enabled the IR printing support for 
the new pass manager, but only for the case when `opt` tool is used as a 
driver. This patch is to enable the IR printing when `clang` is used as a 
driver.

Reviewers: fedor.sergeev, philip.pfaffe

Subscribers: cfe-commits, yamauchi, llvm-commits

Tags: #clang

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

Added:
cfe/trunk/test/Misc/printer.c
Modified:
cfe/trunk/lib/CodeGen/BackendUtil.cpp

Modified: cfe/trunk/lib/CodeGen/BackendUtil.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/BackendUtil.cpp?rev=368804&r1=368803&r2=368804&view=diff
==
--- cfe/trunk/lib/CodeGen/BackendUtil.cpp (original)
+++ cfe/trunk/lib/CodeGen/BackendUtil.cpp Wed Aug 14 00:11:09 2019
@@ -37,6 +37,7 @@
 #include "llvm/MC/SubtargetFeature.h"
 #include "llvm/Passes/PassBuilder.h"
 #include "llvm/Passes/PassPlugin.h"
+#include "llvm/Passes/StandardInstrumentations.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -1063,7 +1064,10 @@ void EmitAssemblyHelper::EmitAssemblyWit
   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
 
-  PassBuilder PB(TM.get(), PTO, PGOOpt);
+  PassInstrumentationCallbacks PIC;
+  StandardInstrumentations SI;
+  SI.registerCallbacks(PIC);
+  PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
 
   // Attempt to load pass plugins and register their callbacks with PB.
   for (auto &PluginFN : CodeGenOpts.PassPlugins) {

Added: cfe/trunk/test/Misc/printer.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Misc/printer.c?rev=368804&view=auto
==
--- cfe/trunk/test/Misc/printer.c (added)
+++ cfe/trunk/test/Misc/printer.c Wed Aug 14 00:11:09 2019
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -emit-llvm -fexperimental-new-pass-manager -mllvm 
-print-before-all %s -o %t 2>&1 | FileCheck %s --check-prefix=CHECK-BEFORE
+// RUN: %clang_cc1 -emit-llvm -fexperimental-new-pass-manager -mllvm 
-print-after-all %s -o %t 2>&1 | FileCheck %s --check-prefix=CHECK-AFTER
+// CHECK-BEFORE: *** IR Dump Before AlwaysInlinerPass ***
+// CHECK-AFTER: *** IR Dump After AlwaysInlinerPass ***
+void foo() {}


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


[PATCH] D65975: [NewPM][PassInstrumentation] IR printing support from clang driver

2019-08-14 Thread Taewook Oh via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368804: [NewPM][PassInstrumentation] IR printing support 
from clang driver (authored by twoh, committed by ).
Herald added a project: LLVM.

Changed prior to commit:
  https://reviews.llvm.org/D65975?vs=214855&id=215034#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65975

Files:
  cfe/trunk/lib/CodeGen/BackendUtil.cpp
  cfe/trunk/test/Misc/printer.c


Index: cfe/trunk/test/Misc/printer.c
===
--- cfe/trunk/test/Misc/printer.c
+++ cfe/trunk/test/Misc/printer.c
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -emit-llvm -fexperimental-new-pass-manager -mllvm 
-print-before-all %s -o %t 2>&1 | FileCheck %s --check-prefix=CHECK-BEFORE
+// RUN: %clang_cc1 -emit-llvm -fexperimental-new-pass-manager -mllvm 
-print-after-all %s -o %t 2>&1 | FileCheck %s --check-prefix=CHECK-AFTER
+// CHECK-BEFORE: *** IR Dump Before AlwaysInlinerPass ***
+// CHECK-AFTER: *** IR Dump After AlwaysInlinerPass ***
+void foo() {}
Index: cfe/trunk/lib/CodeGen/BackendUtil.cpp
===
--- cfe/trunk/lib/CodeGen/BackendUtil.cpp
+++ cfe/trunk/lib/CodeGen/BackendUtil.cpp
@@ -37,6 +37,7 @@
 #include "llvm/MC/SubtargetFeature.h"
 #include "llvm/Passes/PassBuilder.h"
 #include "llvm/Passes/PassPlugin.h"
+#include "llvm/Passes/StandardInstrumentations.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -1063,7 +1064,10 @@
   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
 
-  PassBuilder PB(TM.get(), PTO, PGOOpt);
+  PassInstrumentationCallbacks PIC;
+  StandardInstrumentations SI;
+  SI.registerCallbacks(PIC);
+  PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
 
   // Attempt to load pass plugins and register their callbacks with PB.
   for (auto &PluginFN : CodeGenOpts.PassPlugins) {


Index: cfe/trunk/test/Misc/printer.c
===
--- cfe/trunk/test/Misc/printer.c
+++ cfe/trunk/test/Misc/printer.c
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -emit-llvm -fexperimental-new-pass-manager -mllvm -print-before-all %s -o %t 2>&1 | FileCheck %s --check-prefix=CHECK-BEFORE
+// RUN: %clang_cc1 -emit-llvm -fexperimental-new-pass-manager -mllvm -print-after-all %s -o %t 2>&1 | FileCheck %s --check-prefix=CHECK-AFTER
+// CHECK-BEFORE: *** IR Dump Before AlwaysInlinerPass ***
+// CHECK-AFTER: *** IR Dump After AlwaysInlinerPass ***
+void foo() {}
Index: cfe/trunk/lib/CodeGen/BackendUtil.cpp
===
--- cfe/trunk/lib/CodeGen/BackendUtil.cpp
+++ cfe/trunk/lib/CodeGen/BackendUtil.cpp
@@ -37,6 +37,7 @@
 #include "llvm/MC/SubtargetFeature.h"
 #include "llvm/Passes/PassBuilder.h"
 #include "llvm/Passes/PassPlugin.h"
+#include "llvm/Passes/StandardInstrumentations.h"
 #include "llvm/Support/BuryPointer.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -1063,7 +1064,10 @@
   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
 
-  PassBuilder PB(TM.get(), PTO, PGOOpt);
+  PassInstrumentationCallbacks PIC;
+  StandardInstrumentations SI;
+  SI.registerCallbacks(PIC);
+  PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
 
   // Attempt to load pass plugins and register their callbacks with PB.
   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66156: Removed dead code from clang/tools/libclang/CXIndexDataConsumer.{cpp,h}

2019-08-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368805: Removed dead code from 
clang/tools/libclang/CXIndexDataConsumer.{cpp,h} (authored by gribozavr, 
committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66156?vs=214890&id=215035#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66156

Files:
  cfe/trunk/tools/libclang/CXIndexDataConsumer.cpp
  cfe/trunk/tools/libclang/CXIndexDataConsumer.h


Index: cfe/trunk/tools/libclang/CXIndexDataConsumer.h
===
--- cfe/trunk/tools/libclang/CXIndexDataConsumer.h
+++ cfe/trunk/tools/libclang/CXIndexDataConsumer.h
@@ -372,25 +372,6 @@
 
   void startedTranslationUnit();
 
-  void indexDecl(const Decl *D);
-
-  void indexTagDecl(const TagDecl *D);
-
-  void indexTypeSourceInfo(TypeSourceInfo *TInfo, const NamedDecl *Parent,
-   const DeclContext *DC = nullptr);
-
-  void indexTypeLoc(TypeLoc TL, const NamedDecl *Parent,
-const DeclContext *DC = nullptr);
-
-  void indexNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
-   const NamedDecl *Parent,
-   const DeclContext *DC = nullptr);
-
-  void indexDeclContext(const DeclContext *DC);
-  
-  void indexBody(const Stmt *S, const NamedDecl *Parent,
- const DeclContext *DC = nullptr);
-
   void indexDiagnostics();
 
   void handleDiagnosticSet(CXDiagnosticSet CXDiagSet);
@@ -401,8 +382,6 @@
 
   bool handleField(const FieldDecl *D);
 
-  bool handleMSProperty(const MSPropertyDecl *D);
-
   bool handleEnumerator(const EnumConstantDecl *D);
 
   bool handleTagDecl(const TagDecl *D);
@@ -438,18 +417,8 @@
CXIdxEntityRefKind Kind = CXIdxEntityRef_Direct,
CXSymbolRole Role = CXSymbolRole_None);
 
-  bool handleReference(const NamedDecl *D, SourceLocation Loc,
-   const NamedDecl *Parent,
-   const DeclContext *DC,
-   const Expr *E = nullptr,
-   CXIdxEntityRefKind Kind = CXIdxEntityRef_Direct,
-   CXSymbolRole Role = CXSymbolRole_None);
-
   bool isNotFromSourceFile(SourceLocation Loc) const;
 
-  void indexTopLevelDecl(const Decl *D);
-  void indexDeclGroupRef(DeclGroupRef DG);
-
   void translateLoc(SourceLocation Loc, CXIdxClientFile *indexFile, CXFile 
*file,
 unsigned *line, unsigned *column, unsigned *offset);
 
Index: cfe/trunk/tools/libclang/CXIndexDataConsumer.cpp
===
--- cfe/trunk/tools/libclang/CXIndexDataConsumer.cpp
+++ cfe/trunk/tools/libclang/CXIndexDataConsumer.cpp
@@ -633,12 +633,6 @@
   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
 }
 
-bool CXIndexDataConsumer::handleMSProperty(const MSPropertyDecl *D) {
-  DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true,
- /*isContainer=*/false);
-  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
-}
-
 bool CXIndexDataConsumer::handleEnumerator(const EnumConstantDecl *D) {
   DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true,
  /*isContainer=*/false);
@@ -889,20 +883,6 @@
 }
 
 bool CXIndexDataConsumer::handleReference(const NamedDecl *D, SourceLocation 
Loc,
-  const NamedDecl *Parent,
-  const DeclContext *DC,
-  const Expr *E,
-  CXIdxEntityRefKind Kind,
-  CXSymbolRole Role) {
-  if (!D || !DC)
-return false;
-
-  CXCursor Cursor = E ? MakeCXCursor(E, cast(DC), CXTU)
-  : getRefCursor(D, Loc);
-  return handleReference(D, Loc, Cursor, Parent, DC, E, Kind, Role);
-}
-
-bool CXIndexDataConsumer::handleReference(const NamedDecl *D, SourceLocation 
Loc,
   CXCursor Cursor,
   const NamedDecl *Parent,
   const DeclContext *DC,


Index: cfe/trunk/tools/libclang/CXIndexDataConsumer.h
===
--- cfe/trunk/tools/libclang/CXIndexDataConsumer.h
+++ cfe/trunk/tools/libclang/CXIndexDataConsumer.h
@@ -372,25 +372,6 @@
 
   void startedTranslationUnit();
 
-  void indexDecl(const Decl *D);
-
-  void indexTagDecl(const TagDecl *D);
-
-  void indexTypeSourceInfo(TypeSourceInfo *TInfo, const NamedDecl *Parent,
-   const DeclContext *DC = nullptr);
-
-  void indexTypeLoc(TypeLoc TL, const NamedDecl *Parent,
-const DeclContext *DC = nullptr);
-
-  void indexNestedNameSpecifierLoc(N

r368805 - Removed dead code from clang/tools/libclang/CXIndexDataConsumer.{cpp, h}

2019-08-14 Thread Dmitri Gribenko via cfe-commits
Author: gribozavr
Date: Wed Aug 14 00:32:51 2019
New Revision: 368805

URL: http://llvm.org/viewvc/llvm-project?rev=368805&view=rev
Log:
Removed dead code from clang/tools/libclang/CXIndexDataConsumer.{cpp,h}

Reviewers: jkorous

Subscribers: dexonsmith, arphaman, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/tools/libclang/CXIndexDataConsumer.cpp
cfe/trunk/tools/libclang/CXIndexDataConsumer.h

Modified: cfe/trunk/tools/libclang/CXIndexDataConsumer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CXIndexDataConsumer.cpp?rev=368805&r1=368804&r2=368805&view=diff
==
--- cfe/trunk/tools/libclang/CXIndexDataConsumer.cpp (original)
+++ cfe/trunk/tools/libclang/CXIndexDataConsumer.cpp Wed Aug 14 00:32:51 2019
@@ -633,12 +633,6 @@ bool CXIndexDataConsumer::handleField(co
   return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
 }
 
-bool CXIndexDataConsumer::handleMSProperty(const MSPropertyDecl *D) {
-  DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true,
- /*isContainer=*/false);
-  return handleDecl(D, D->getLocation(), getCursor(D), DInfo);
-}
-
 bool CXIndexDataConsumer::handleEnumerator(const EnumConstantDecl *D) {
   DeclInfo DInfo(/*isRedeclaration=*/false, /*isDefinition=*/true,
  /*isContainer=*/false);
@@ -889,20 +883,6 @@ bool CXIndexDataConsumer::handleTypeAlia
 }
 
 bool CXIndexDataConsumer::handleReference(const NamedDecl *D, SourceLocation 
Loc,
-  const NamedDecl *Parent,
-  const DeclContext *DC,
-  const Expr *E,
-  CXIdxEntityRefKind Kind,
-  CXSymbolRole Role) {
-  if (!D || !DC)
-return false;
-
-  CXCursor Cursor = E ? MakeCXCursor(E, cast(DC), CXTU)
-  : getRefCursor(D, Loc);
-  return handleReference(D, Loc, Cursor, Parent, DC, E, Kind, Role);
-}
-
-bool CXIndexDataConsumer::handleReference(const NamedDecl *D, SourceLocation 
Loc,
   CXCursor Cursor,
   const NamedDecl *Parent,
   const DeclContext *DC,

Modified: cfe/trunk/tools/libclang/CXIndexDataConsumer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CXIndexDataConsumer.h?rev=368805&r1=368804&r2=368805&view=diff
==
--- cfe/trunk/tools/libclang/CXIndexDataConsumer.h (original)
+++ cfe/trunk/tools/libclang/CXIndexDataConsumer.h Wed Aug 14 00:32:51 2019
@@ -372,25 +372,6 @@ public:
 
   void startedTranslationUnit();
 
-  void indexDecl(const Decl *D);
-
-  void indexTagDecl(const TagDecl *D);
-
-  void indexTypeSourceInfo(TypeSourceInfo *TInfo, const NamedDecl *Parent,
-   const DeclContext *DC = nullptr);
-
-  void indexTypeLoc(TypeLoc TL, const NamedDecl *Parent,
-const DeclContext *DC = nullptr);
-
-  void indexNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
-   const NamedDecl *Parent,
-   const DeclContext *DC = nullptr);
-
-  void indexDeclContext(const DeclContext *DC);
-  
-  void indexBody(const Stmt *S, const NamedDecl *Parent,
- const DeclContext *DC = nullptr);
-
   void indexDiagnostics();
 
   void handleDiagnosticSet(CXDiagnosticSet CXDiagSet);
@@ -401,8 +382,6 @@ public:
 
   bool handleField(const FieldDecl *D);
 
-  bool handleMSProperty(const MSPropertyDecl *D);
-
   bool handleEnumerator(const EnumConstantDecl *D);
 
   bool handleTagDecl(const TagDecl *D);
@@ -438,18 +417,8 @@ public:
CXIdxEntityRefKind Kind = CXIdxEntityRef_Direct,
CXSymbolRole Role = CXSymbolRole_None);
 
-  bool handleReference(const NamedDecl *D, SourceLocation Loc,
-   const NamedDecl *Parent,
-   const DeclContext *DC,
-   const Expr *E = nullptr,
-   CXIdxEntityRefKind Kind = CXIdxEntityRef_Direct,
-   CXSymbolRole Role = CXSymbolRole_None);
-
   bool isNotFromSourceFile(SourceLocation Loc) const;
 
-  void indexTopLevelDecl(const Decl *D);
-  void indexDeclGroupRef(DeclGroupRef DG);
-
   void translateLoc(SourceLocation Loc, CXIdxClientFile *indexFile, CXFile 
*file,
 unsigned *line, unsigned *column, unsigned *offset);
 


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


[PATCH] D66173: [Codegen] Updated test for D66158

2019-08-14 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 updated this revision to Diff 215039.

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

https://reviews.llvm.org/D66173

Files:
  test/CodeGen/struct-copy.c


Index: test/CodeGen/struct-copy.c
===
--- test/CodeGen/struct-copy.c
+++ test/CodeGen/struct-copy.c
@@ -1,7 +1,39 @@
-// RUN: %clang_cc1 -emit-llvm %s -o - | grep 'call.*llvm.memcpy'
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
 struct x { int a[100]; };
 
-
+// CHECK-LABEL: @foo(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP2:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP1]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP2]], 
i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//
 void foo(struct x *P, struct x *Q) {
   *P = *Q;
 }
+
+// CHECK: declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture 
writeonly, i8* noalias nocapture readonly, i64, i1 immarg)
+
+// CHECK-LABEL: @bar(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP1:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP2:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP2]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP1]], 
i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//
+void bar(struct x *P, struct x *Q) {
+  __builtin_memcpy(P, Q, sizeof(struct x));
+}


Index: test/CodeGen/struct-copy.c
===
--- test/CodeGen/struct-copy.c
+++ test/CodeGen/struct-copy.c
@@ -1,7 +1,39 @@
-// RUN: %clang_cc1 -emit-llvm %s -o - | grep 'call.*llvm.memcpy'
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
 struct x { int a[100]; };
 
-
+// CHECK-LABEL: @foo(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP2:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP1]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP2]], i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//
 void foo(struct x *P, struct x *Q) {
   *P = *Q;
 }
+
+// CHECK: declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture writeonly, i8* noalias nocapture readonly, i64, i1 immarg)
+
+// CHECK-LABEL: @bar(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP2:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP2]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP1]], i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//
+void bar(struct x *P, struct x *Q) {
+  __builtin_memcpy(P, Q, sizeof(struct x));
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r368808 - Fix the -Wunused-variable warning.

2019-08-14 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Aug 14 01:20:42 2019
New Revision: 368808

URL: http://llvm.org/viewvc/llvm-project?rev=368808&view=rev
Log:
Fix the -Wunused-variable warning.

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=368808&r1=368807&r2=368808&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp Wed Aug 14 01:20:42 2019
@@ -2180,7 +2180,7 @@ llvm::iterator_range(getStmt()))
+if (dyn_cast_or_null(getStmt()))
   return llvm::make_range(&ErrorNodeRange, &ErrorNodeRange + 1);
 return llvm::make_range(ranges_iterator(), ranges_iterator());
   }

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=368808&r1=368807&r2=368808&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Wed Aug 14 
01:20:42 2019
@@ -1987,7 +1987,7 @@ bool bugreporter::trackExpressionValue(c
 if (const auto *SR = L->getRegionAs()) {
   if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
 CanDereference = false;
-} else if (const auto *AR = L->getRegionAs())
+} else if (L->getRegionAs())
   CanDereference = false;
 
 // At this point we are dealing with the region's LValue.


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


r368809 - [Codegen] Updated test for D66158

2019-08-14 Thread David Bolvansky via cfe-commits
Author: xbolva00
Date: Wed Aug 14 01:32:31 2019
New Revision: 368809

URL: http://llvm.org/viewvc/llvm-project?rev=368809&view=rev
Log:
[Codegen] Updated test for D66158

Reviewers: jdoerfert

Reviewed By: jdoerfert

Subscribers: cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/test/CodeGen/struct-copy.c

Modified: cfe/trunk/test/CodeGen/struct-copy.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/struct-copy.c?rev=368809&r1=368808&r2=368809&view=diff
==
--- cfe/trunk/test/CodeGen/struct-copy.c (original)
+++ cfe/trunk/test/CodeGen/struct-copy.c Wed Aug 14 01:32:31 2019
@@ -1,7 +1,39 @@
-// RUN: %clang_cc1 -emit-llvm %s -o - | grep 'call.*llvm.memcpy'
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
 struct x { int a[100]; };
 
-
+// CHECK-LABEL: @foo(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP2:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP1]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP2]], 
i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//
 void foo(struct x *P, struct x *Q) {
   *P = *Q;
 }
+
+// CHECK: declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture 
writeonly, i8* noalias nocapture readonly, i64, i1 immarg)
+
+// CHECK-LABEL: @bar(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP1:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP2:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP2]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP1]], 
i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//
+void bar(struct x *P, struct x *Q) {
+  __builtin_memcpy(P, Q, sizeof(struct x));
+}


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


[PATCH] D66173: [Codegen] Updated test for D66158

2019-08-14 Thread Dávid Bolvanský via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368809: [Codegen] Updated test for D66158 (authored by 
xbolva00, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66173?vs=215039&id=215043#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66173

Files:
  cfe/trunk/test/CodeGen/struct-copy.c


Index: cfe/trunk/test/CodeGen/struct-copy.c
===
--- cfe/trunk/test/CodeGen/struct-copy.c
+++ cfe/trunk/test/CodeGen/struct-copy.c
@@ -1,7 +1,39 @@
-// RUN: %clang_cc1 -emit-llvm %s -o - | grep 'call.*llvm.memcpy'
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
 struct x { int a[100]; };
 
-
+// CHECK-LABEL: @foo(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP2:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP1]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP2]], 
i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//
 void foo(struct x *P, struct x *Q) {
   *P = *Q;
 }
+
+// CHECK: declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture 
writeonly, i8* noalias nocapture readonly, i64, i1 immarg)
+
+// CHECK-LABEL: @bar(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP1:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP2:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], 
align 8
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP2]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP1]], 
i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//
+void bar(struct x *P, struct x *Q) {
+  __builtin_memcpy(P, Q, sizeof(struct x));
+}


Index: cfe/trunk/test/CodeGen/struct-copy.c
===
--- cfe/trunk/test/CodeGen/struct-copy.c
+++ cfe/trunk/test/CodeGen/struct-copy.c
@@ -1,7 +1,39 @@
-// RUN: %clang_cc1 -emit-llvm %s -o - | grep 'call.*llvm.memcpy'
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
 struct x { int a[100]; };
 
-
+// CHECK-LABEL: @foo(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP2:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP1]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP2]], i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//
 void foo(struct x *P, struct x *Q) {
   *P = *Q;
 }
+
+// CHECK: declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture writeonly, i8* noalias nocapture readonly, i64, i1 immarg)
+
+// CHECK-LABEL: @bar(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
+// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], align 8
+// CHECK-NEXT:[[TMP1:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
+// CHECK-NEXT:[[TMP2:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], align 8
+// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP2]] to i8*
+// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP1]], i8* align 4 [[TMP3]], i64 400, i1 false)
+// CHECK-NEXT:ret void
+//

[PATCH] D66179: [LifetimeAnalysis] Support more STL idioms (template forward declaration and DependentNameType)

2019-08-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr added inline comments.



Comment at: clang/lib/Sema/SemaAttr.cpp:102
+  dyn_cast_or_null(Record->getDescribedTemplate())) 
{
+if (auto *Def = Record->getDefinition())
+  addGslOwnerPointerAttributeIfNotExisting(Context, Def);

I wonder why this is necessary. Sema should call inference on every 
CXXRecordDecl. Is it because of incorrect short-circuiting in 
`inferGslPointerAttribute` that I'm pointing out below?



Comment at: clang/lib/Sema/SemaAttr.cpp:143
+addGslOwnerPointerAttributeIfNotExisting(
+Context, UnderlyingRecord->getCanonicalDecl());
 }

So... what's the contract for pointer and owner attributes, are they expected 
to be present on every declaration in the redeclaration chain, or is only one 
sufficient?

Seems like here we're adding the attribute only to the canonical decl of the 
iterator, which will lead to the same sort of issue that this patch is trying 
to fix.



Comment at: clang/lib/Sema/SemaAttr.cpp:200
 CXXRecordDecl *Canonical = Record->getCanonicalDecl();
 if (Canonical->hasAttr() || Canonical->hasAttr())
   return;

Should this code not do this short-circuit check? It is prone to going out of 
sync with the code in `addGslOwnerPointerAttributeIfNotExisting`, like it did 
just now.

If you want to check for attribute before doing the string search, you could 
pass the string set into `addGslOwnerPointerAttributeIfNotExisting`, and let 
that decide if it should infer the attribute or not.



Comment at: clang/test/SemaCXX/attr-gsl-owner-pointer-std.cpp:95
 
+// The iterator typedef is a DependentNameType.
+template 

This test file is getting pretty long and subtle, with lots of things are being 
mixed into one file without isolation.

WDYT about refactoring it into a unit test that uses AST matchers to verify 
attribute presence?

See clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp for examples.

Each test case would look approximately like this:

```
EXPECT_TRUE(matches(
  "template class ...",
  classTemplateDecl(hasName("foo"), hasAttr(clang::attr::GslPointer)));
```

Each test case would be isolated from other tests, each test would have a name 
(and optionally a comment) that will make it obvious what exactly is being 
tested.

It would be also possible to verify things like "The iterator typedef is a 
DependentNameType" to ensure that we're testing exactly what we want to test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66179



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


[PATCH] D65935: [ASTImporter] Import ctor initializers after setting flags.

2019-08-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 215056.
balazske added a comment.

- Moved 'ctor initializer' import before import of body.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65935

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/test/Analysis/Inputs/ctu-other.cpp
  clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
  clang/test/Analysis/ctu-main.cpp


Index: clang/test/Analysis/ctu-main.cpp
===
--- clang/test/Analysis/ctu-main.cpp
+++ clang/test/Analysis/ctu-main.cpp
@@ -125,6 +125,8 @@
   static const int Test;
 };
 
+extern int testImportOfDelegateConstructor(int);
+
 int main() {
   clang_analyzer_eval(f(3) == 2); // expected-warning{{TRUE}}
   clang_analyzer_eval(f(4) == 3); // expected-warning{{TRUE}}
@@ -158,4 +160,6 @@
   // clang_analyzer_eval(extSCC.a == 7); // TODO
   clang_analyzer_eval(extU.a == 4); // expected-warning{{TRUE}}
   clang_analyzer_eval(TestAnonUnionUSR::Test == 5); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(testImportOfDelegateConstructor(10) == 10); // 
expected-warning{{TRUE}}
 }
Index: clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
===
--- clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
+++ clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
@@ -26,3 +26,4 @@
 c:@extSCC ctu-other.cpp.ast
 c:@extU ctu-other.cpp.ast
 c:@S@TestAnonUnionUSR@Test ctu-other.cpp.ast
+c:@F@testImportOfDelegateConstructor#I# ctu-other.cpp.ast
Index: clang/test/Analysis/Inputs/ctu-other.cpp
===
--- clang/test/Analysis/Inputs/ctu-other.cpp
+++ clang/test/Analysis/Inputs/ctu-other.cpp
@@ -145,3 +145,14 @@
   static const int Test;
 };
 const int TestAnonUnionUSR::Test = 5;
+
+class TestDelegateConstructor {
+public:
+  TestDelegateConstructor() : TestDelegateConstructor(2) {}
+  TestDelegateConstructor(int) {}
+};
+
+int testImportOfDelegateConstructor(int i) {
+  TestDelegateConstructor TDC;
+  return i;
+}
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -3265,23 +3265,6 @@
 // decl and its redeclarations may be required.
   }
 
-  // Import Ctor initializers.
-  if (auto *FromConstructor = dyn_cast(D)) {
-if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
-  SmallVector CtorInitializers(NumInitializers);
-  // Import first, then allocate memory and copy if there was no error.
-  if (Error Err = ImportContainerChecked(
-  FromConstructor->inits(), CtorInitializers))
-return std::move(Err);
-  auto **Memory =
-  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
-  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
-  auto *ToCtor = cast(ToFunction);
-  ToCtor->setCtorInitializers(Memory);
-  ToCtor->setNumCtorInitializers(NumInitializers);
-}
-  }
-
   ToFunction->setQualifierInfo(ToQualifierLoc);
   ToFunction->setAccess(D->getAccess());
   ToFunction->setLexicalDeclContext(LexicalDC);
@@ -3322,6 +3305,23 @@
   return ToFTOrErr.takeError();
   }
 
+  // Import Ctor initializers.
+  if (auto *FromConstructor = dyn_cast(D)) {
+if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
+  SmallVector CtorInitializers(NumInitializers);
+  // Import first, then allocate memory and copy if there was no error.
+  if (Error Err = ImportContainerChecked(
+  FromConstructor->inits(), CtorInitializers))
+return std::move(Err);
+  auto **Memory =
+  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
+  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
+  auto *ToCtor = cast(ToFunction);
+  ToCtor->setCtorInitializers(Memory);
+  ToCtor->setNumCtorInitializers(NumInitializers);
+}
+  }
+
   if (D->doesThisDeclarationHaveABody()) {
 Error Err = ImportFunctionDeclBody(D, ToFunction);
 


Index: clang/test/Analysis/ctu-main.cpp
===
--- clang/test/Analysis/ctu-main.cpp
+++ clang/test/Analysis/ctu-main.cpp
@@ -125,6 +125,8 @@
   static const int Test;
 };
 
+extern int testImportOfDelegateConstructor(int);
+
 int main() {
   clang_analyzer_eval(f(3) == 2); // expected-warning{{TRUE}}
   clang_analyzer_eval(f(4) == 3); // expected-warning{{TRUE}}
@@ -158,4 +160,6 @@
   // clang_analyzer_eval(extSCC.a == 7); // TODO
   clang_analyzer_eval(extU.a == 4); // expected-warning{{TRUE}}
   clang_analyzer_eval(TestAnonUnionUSR::Test == 5); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(testImportOfDelegateConstructor(10) == 10); // expected-warning{{TRUE}}
 }
I

[PATCH] D65856: [clangd] Added class for mapping TokenColorRules to their associated clangd TextMate scope

2019-08-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:128
+  // Find the rule wich is the longest prefix of scope.
+  if (rule.scope.length <= scope.length &&
+  scope.substr(0, rule.scope.length) === rule.scope &&

jvikstrom wrote:
> hokein wrote:
> > The algorithm doesn't seems correct to me, if scope.length > 
> > rule.scope.length, then we drop it.
> > 
> > I think we should 
> > - calculate the common prefix between two scopes
> > - update the bestRule if the length of common prefix is greater than the 
> > current best length
> If the scope's length is less than the rule's length the rule can not be a 
> prefix.
> (Not sure I fully follow with what you mean in the first sentence though)
> 
> 
> If we check common prefixes we run into this weird case (this is taken from 
> the Light+ theme):
> ```
> variable.css
> variable.scss
> variable.other.less
> variable
> ```
> With that kind of matching we have now this means that `variable.other.less` 
> will match `variable.other` and `variable.other.less` and the variables would 
> be colored as less variables while they should be `variable.other`. Same goes 
> for `variable.other.field`.
> 
> And even if `variable.other.less` did not exist `variable.other` would still 
> match `variable.css` and now be highlighted as css variables.
I thought that we are finding longest common prefix, but actually you are using 
a different one (I checked that "vscode-cpptools" is also using the same 
matching algorithm).

That sounds fair enough, could you add this context to the comment? 





Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:115
+  // The rules for the theme.
+  private rules: TokenColorRule[];
+  // A cache for the getBestThemeRule function.

I'd name it `themeRules`.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts:133
+  scope.substr(0, rule.scope.length) === rule.scope &&
+  rule.scope.length > bestRule.scope.length)
+// This rule matches and is more specific than the old rule.

I think we could simplify the code like 

```
if (scope.startsWith(rule.scope) && rule.scope.length > bestRule.scope.length) {
  ...
}
```



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts:40
+const rules = [
+  {scope : 'c.b', foreground : '1'},
+  {scope : 'a', foreground : '2'},

Even for the test, I'd use the real scopes, e.g. `variable.css`, 
`variable.other.less`.



Comment at: 
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts:47
+const tm = new SM.ThemeRuleMatcher(rules);
+assert.deepEqual(tm.getBestThemeRule('c.b'), rules[0]);
+assert.deepEqual(tm.getBestThemeRule('a.b'), rules[2]);

jvikstrom wrote:
> hokein wrote:
> > I'd use `assert.deepEqual(tm.getBestThemeRule('c.b').scope, 'c.b');` to 
> > make the code more readable.
> > 
> For the `a` case we are interested in the foreground color as well. Should I 
> change the others and keep `assert.deepEqual(tm.getBestThemeRule('a'), 
> rules[1]);` as is or be consistent?
`a` case is interesting here - we have duplicates, but actually we won't have 
duplicates in the theme rules (as we check the scope is being seen when parsing 
theme file).

I think for `a`, just use `assert.deepEqual(tm.getBestThemeRule('a'), 
rules[1]); // we match the first element if there are duplicates`; for others, 
use the scope.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65856



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


[PATCH] D66014: [analyzer] Avoid unnecessary enum range check on LValueToRValue casts

2019-08-14 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 accepted this revision.
gamesh411 added a comment.

@chrish_ericsson_atx Thanks for fixing this! Your help is much appreciated :)


Repository:
  rC Clang

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

https://reviews.llvm.org/D66014



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


[PATCH] D66206: [CodeGen] Don't keep stale pointers to LoopInfos

2019-08-14 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan created this revision.
ebevhan added a reviewer: aaron.ballman.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

CGLoopInfo was keeping pointers to parent loop LoopInfos,
but when the loop info vector grew, it reallocated the
storage and invalidated all of the parent pointers, causing
use-after-free.

Manage the lifetimes of the LoopInfos separately so that
the pointers aren't stale.


Repository:
  rC Clang

https://reviews.llvm.org/D66206

Files:
  lib/CodeGen/CGLoopInfo.cpp
  lib/CodeGen/CGLoopInfo.h
  test/CodeGen/loop-info-asan.c


Index: test/CodeGen/loop-info-asan.c
===
--- /dev/null
+++ test/CodeGen/loop-info-asan.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple x86_64 -emit-llvm %s -o /dev/null
+
+// This test should not exhibit use-after-free in LoopInfo.
+
+int a() {
+  for (;;)
+for (;;)
+  for (;;)
+for (;;)
+  for (;;)
+for (;;)
+  for (;;)
+for (;;)
+  for (;;)
+;
+}
Index: lib/CodeGen/CGLoopInfo.h
===
--- lib/CodeGen/CGLoopInfo.h
+++ lib/CodeGen/CGLoopInfo.h
@@ -275,11 +275,11 @@
   bool hasInfo() const { return !Active.empty(); }
   /// Return the LoopInfo for the current loop. HasInfo should be called
   /// first to ensure LoopInfo is present.
-  const LoopInfo &getInfo() const { return Active.back(); }
+  const LoopInfo &getInfo() const { return *Active.back(); }
   /// The set of attributes that will be applied to the next pushed loop.
   LoopAttributes StagedAttrs;
   /// Stack of active loops.
-  llvm::SmallVector Active;
+  llvm::SmallVector, 4> Active;
 };
 
 } // end namespace CodeGen
Index: lib/CodeGen/CGLoopInfo.cpp
===
--- lib/CodeGen/CGLoopInfo.cpp
+++ lib/CodeGen/CGLoopInfo.cpp
@@ -554,8 +554,9 @@
 
 void LoopInfoStack::push(BasicBlock *Header, const llvm::DebugLoc &StartLoc,
  const llvm::DebugLoc &EndLoc) {
-  Active.push_back(LoopInfo(Header, StagedAttrs, StartLoc, EndLoc,
-Active.empty() ? nullptr : &Active.back()));
+  Active.emplace_back(
+  new LoopInfo(Header, StagedAttrs, StartLoc, EndLoc,
+   Active.empty() ? nullptr : Active.back().get()));
   // Clear the attributes so nested loops do not inherit them.
   StagedAttrs.clear();
 }
@@ -747,16 +748,16 @@
 
 void LoopInfoStack::pop() {
   assert(!Active.empty() && "No active loops to pop");
-  Active.back().finish();
+  Active.back()->finish();
   Active.pop_back();
 }
 
 void LoopInfoStack::InsertHelper(Instruction *I) const {
   if (I->mayReadOrWriteMemory()) {
 SmallVector AccessGroups;
-for (const LoopInfo &AL : Active) {
+for (const auto &AL : Active) {
   // Here we assume that every loop that has an access group is parallel.
-  if (MDNode *Group = AL.getAccessGroup())
+  if (MDNode *Group = AL->getAccessGroup())
 AccessGroups.push_back(Group);
 }
 MDNode *UnionMD = nullptr;


Index: test/CodeGen/loop-info-asan.c
===
--- /dev/null
+++ test/CodeGen/loop-info-asan.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple x86_64 -emit-llvm %s -o /dev/null
+
+// This test should not exhibit use-after-free in LoopInfo.
+
+int a() {
+  for (;;)
+for (;;)
+  for (;;)
+for (;;)
+  for (;;)
+for (;;)
+  for (;;)
+for (;;)
+  for (;;)
+;
+}
Index: lib/CodeGen/CGLoopInfo.h
===
--- lib/CodeGen/CGLoopInfo.h
+++ lib/CodeGen/CGLoopInfo.h
@@ -275,11 +275,11 @@
   bool hasInfo() const { return !Active.empty(); }
   /// Return the LoopInfo for the current loop. HasInfo should be called
   /// first to ensure LoopInfo is present.
-  const LoopInfo &getInfo() const { return Active.back(); }
+  const LoopInfo &getInfo() const { return *Active.back(); }
   /// The set of attributes that will be applied to the next pushed loop.
   LoopAttributes StagedAttrs;
   /// Stack of active loops.
-  llvm::SmallVector Active;
+  llvm::SmallVector, 4> Active;
 };
 
 } // end namespace CodeGen
Index: lib/CodeGen/CGLoopInfo.cpp
===
--- lib/CodeGen/CGLoopInfo.cpp
+++ lib/CodeGen/CGLoopInfo.cpp
@@ -554,8 +554,9 @@
 
 void LoopInfoStack::push(BasicBlock *Header, const llvm::DebugLoc &StartLoc,
  const llvm::DebugLoc &EndLoc) {
-  Active.push_back(LoopInfo(Header, StagedAttrs, StartLoc, EndLoc,
-Active.empty() ? nullptr : &Active.back()));
+  Active.emplace_back(
+  new LoopInfo(Header, StagedAttrs, StartLoc, EndLoc,
+   Active.empty() ? nullptr : Active.back().get()));
   // Clear

r368817 - [analyzer] Note last writes to a condition only in a nested stackframe

2019-08-14 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Wed Aug 14 02:39:38 2019
New Revision: 368817

URL: http://llvm.org/viewvc/llvm-project?rev=368817&view=rev
Log:
[analyzer] Note last writes to a condition only in a nested stackframe

Exactly what it says on the tin! The comments in the code detail this a
little more too.

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

Modified:

cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h?rev=368817&r1=368816&r2=368817&view=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
(original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h 
Wed Aug 14 02:39:38 2019
@@ -132,6 +132,7 @@ class FindLastStoreBRVisitor final : pub
 
   using TrackingKind = bugreporter::TrackingKind;
   TrackingKind TKind;
+  const StackFrameContext *OriginSFC;
 
 public:
   /// Creates a visitor for every VarDecl inside a Stmt and registers it with
@@ -145,11 +146,18 @@ public:
   /// \param EnableNullFPSuppression Whether we should employ false positive
   /// suppression (inlined defensive checks, returned null).
   /// \param TKind May limit the amount of notes added to the bug report.
+  /// \param OriginSFC Only adds notes when the last store happened in a
+  ///different stackframe to this one. Disregarded if the tracking kind
+  ///is thorough.
+  ///This is useful, because for non-tracked regions, notes about
+  ///changes to its value in a nested stackframe could be pruned, and
+  ///this visitor can prevent that without polluting the bugpath too
+  ///much.
   FindLastStoreBRVisitor(KnownSVal V, const MemRegion *R,
- bool InEnableNullFPSuppression,
- TrackingKind TKind)
+ bool InEnableNullFPSuppression, TrackingKind TKind,
+ const StackFrameContext *OriginSFC = nullptr)
   : R(R), V(V), EnableNullFPSuppression(InEnableNullFPSuppression),
-TKind(TKind) {
+TKind(TKind), OriginSFC(OriginSFC) {
 assert(R);
   }
 

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp?rev=368817&r1=368816&r2=368817&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp Wed Aug 14 
02:39:38 2019
@@ -1440,6 +1440,10 @@ FindLastStoreBRVisitor::VisitNode(const
 StoreSite, InitE, BR, TKind, EnableNullFPSuppression);
   }
 
+  if (TKind == TrackingKind::Condition &&
+  !OriginSFC->isParentOf(StoreSite->getStackFrame()))
+return nullptr;
+
   // Okay, we've found the binding. Emit an appropriate message.
   SmallString<256> sbuf;
   llvm::raw_svector_ostream os(sbuf);
@@ -1465,7 +1469,7 @@ FindLastStoreBRVisitor::VisitNode(const
   if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
 if (auto KV = State->getSVal(OriginalR).getAs())
   BR.addVisitor(llvm::make_unique(
-  *KV, OriginalR, EnableNullFPSuppression, TKind));
+  *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC));
   }
 }
   }
@@ -1890,6 +1894,7 @@ bool bugreporter::trackExpressionValue(c
 return false;
 
   ProgramStateRef LVState = LVNode->getState();
+  const StackFrameContext *SFC = LVNode->getStackFrame();
 
   // We only track expressions if we believe that they are important. Chances
   // are good that control dependencies to the tracking point are also 
improtant
@@ -1926,7 +1931,7 @@ bool bugreporter::trackExpressionValue(c
 if (RR && !LVIsNull)
   if (auto KV = LVal.getAs())
 report.addVisitor(llvm::make_unique(
-  *KV, RR, EnableNullFPSuppression, TKind));
+*KV, RR, EnableNullFPSuppression, TKind, SFC));
 
 // In case of C++ references, we want to differentiate between a null
 // reference and reference to null pointer.
@@ -1963,7 +1968,7 @@ bool bugreporter::trackExpressionValue(c
 
   if (auto KV = V.getAs())
 report.addVisitor(llvm::make_unique(
-  *KV, R, EnableNullFPSuppression, TKind));
+*KV, R, EnableNullFPSuppression, TKind, SFC));
   return true;
 }
   }
@@ -2002,7 +2007,7 @@ bool bugreporter::trackExpressionValue(c
 if (CanDereference)
   if (auto KV = RVal.getAs())
 

[PATCH] D64272: [analyzer] Note last writes to a condition only in a nested stackframe

2019-08-14 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368817: [analyzer] Note last writes to a condition only in a 
nested stackframe (authored by Szelethus, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D64272?vs=211758&id=215062#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D64272

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
@@ -132,6 +132,7 @@
 
   using TrackingKind = bugreporter::TrackingKind;
   TrackingKind TKind;
+  const StackFrameContext *OriginSFC;
 
 public:
   /// Creates a visitor for every VarDecl inside a Stmt and registers it with
@@ -145,11 +146,18 @@
   /// \param EnableNullFPSuppression Whether we should employ false positive
   /// suppression (inlined defensive checks, returned null).
   /// \param TKind May limit the amount of notes added to the bug report.
+  /// \param OriginSFC Only adds notes when the last store happened in a
+  ///different stackframe to this one. Disregarded if the tracking kind
+  ///is thorough.
+  ///This is useful, because for non-tracked regions, notes about
+  ///changes to its value in a nested stackframe could be pruned, and
+  ///this visitor can prevent that without polluting the bugpath too
+  ///much.
   FindLastStoreBRVisitor(KnownSVal V, const MemRegion *R,
- bool InEnableNullFPSuppression,
- TrackingKind TKind)
+ bool InEnableNullFPSuppression, TrackingKind TKind,
+ const StackFrameContext *OriginSFC = nullptr)
   : R(R), V(V), EnableNullFPSuppression(InEnableNullFPSuppression),
-TKind(TKind) {
+TKind(TKind), OriginSFC(OriginSFC) {
 assert(R);
   }
 
Index: cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
===
--- cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
+++ cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
@@ -127,10 +127,9 @@
 void test() {
   int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
 
-  if (int flag = foo()) // tracking-note{{'flag' initialized here}}
-// debug-note@-1{{Tracking condition 'flag'}}
-// expected-note@-2{{Assuming 'flag' is not equal to 0}}
-// expected-note@-3{{Taking true branch}}
+  if (int flag = foo()) // debug-note{{Tracking condition 'flag'}}
+// expected-note@-1{{Assuming 'flag' is not equal to 0}}
+// expected-note@-2{{Taking true branch}}
 
 *x = 5; // expected-warning{{Dereference of null pointer}}
 // expected-note@-1{{Dereference of null pointer}}
@@ -157,6 +156,28 @@
 
 } // end of namespace variable_declaration_in_condition
 
+namespace note_from_different_but_not_nested_stackframe {
+
+void nullptrDeref(int *ptr, bool True) {
+  if (True) // expected-note{{'True' is true}}
+// expected-note@-1{{Taking true branch}}
+// debug-note@-2{{Tracking condition 'True}}
+*ptr = 5;
+  // expected-note@-1{{Dereference of null pointer (loaded from variable 'ptr')}}
+  // expected-warning@-2{{Dereference of null pointer (loaded from variable 'ptr')}}
+}
+
+void f() {
+  int *ptr = nullptr;
+  // expected-note@-1{{'ptr' initialized to a null pointer value}}
+  bool True = true;
+  nullptrDeref(ptr, True);
+  // expected-note@-1{{Passing null pointer value via 1st parameter 'ptr'}}
+  // expected-note@-2{{Calling 'nullptrDeref'}}
+}
+
+} // end of namespace note_from_different_but_not_nested_stackframe
+
 namespace important_returning_pointer_loaded_from {
 bool coin();
 
@@ -194,8 +215,8 @@
 int *getIntPtr();
 
 int *conjurePointer() {
-  int *i = getIntPtr(); // tracking-note{{'i' initialized here}}
-  return i; // tracking-note{{Returning pointer (loaded from 'i')}}
+  int *i = getIntPtr();
+  return i;
 }
 
 void f(int *ptr) {
@@ -203,11 +224,9 @@
// expected-note@-1{{Taking false branch}}
 ;
   if (!conjurePointer())
-// tracking-note@-1{{Calling 'conjurePointer'}}
-// tracking-note@-2{{Returning from 'conjurePointer'}}
-// debug-note@-3{{Tracking condition '!conjurePointer()'}}
-// expected-note@-4{{Assuming the condition i

r368818 - [ASTImporter] Import default expression of param before creating the param.

2019-08-14 Thread Balazs Keri via cfe-commits
Author: balazske
Date: Wed Aug 14 02:41:39 2019
New Revision: 368818

URL: http://llvm.org/viewvc/llvm-project?rev=368818&view=rev
Log:
[ASTImporter] Import default expression of param before creating the param.

Summary:
The default expression of a parameter variable should be imported before
the parameter variable object is created. Otherwise the function is created
with an incomplete parameter variable (default argument is nullptr) and in
this intermediary state the expression is imported. This import can have
a reference to the incomplete parameter variable that causes crash.

Reviewers: martong, a.sidorin, shafik

Reviewed By: martong

Subscribers: rnkovacs, dkrupp, Szelethus, gamesh411, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/include/clang/AST/ASTImporter.h
cfe/trunk/lib/AST/ASTImporter.cpp
cfe/trunk/test/Analysis/Inputs/ctu-other.cpp
cfe/trunk/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
cfe/trunk/test/Analysis/ctu-main.cpp

Modified: cfe/trunk/include/clang/AST/ASTImporter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTImporter.h?rev=368818&r1=368817&r2=368818&view=diff
==
--- cfe/trunk/include/clang/AST/ASTImporter.h (original)
+++ cfe/trunk/include/clang/AST/ASTImporter.h Wed Aug 14 02:41:39 2019
@@ -378,6 +378,20 @@ class TypeSourceInfo;
 /// imported. If it does not exist nullptr is returned.
 TranslationUnitDecl *GetFromTU(Decl *ToD);
 
+/// Return the declaration in the "from" context from which the declaration
+/// in the "to" context was imported. If it was not imported or of the 
wrong
+/// type a null value is returned.
+template 
+llvm::Optional getImportedFromDecl(const DeclT *ToD) const {
+  auto FromI = ImportedFromDecls.find(ToD);
+  if (FromI == ImportedFromDecls.end())
+return {};
+  auto *FromD = dyn_cast(FromI->second);
+  if (!FromD)
+return {};
+  return FromD;
+}
+
 /// Import the given declaration context from the "from"
 /// AST context into the "to" AST context.
 ///

Modified: cfe/trunk/lib/AST/ASTImporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTImporter.cpp?rev=368818&r1=368817&r2=368818&view=diff
==
--- cfe/trunk/lib/AST/ASTImporter.cpp (original)
+++ cfe/trunk/lib/AST/ASTImporter.cpp Wed Aug 14 02:41:39 2019
@@ -426,6 +426,9 @@ namespace clang {
 
 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
 
+Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
+ParmVarDecl *ToParam);
+
 template 
 bool hasSameVisibilityContext(T *Found, T *From);
 
@@ -3841,6 +3844,28 @@ ExpectedDecl ASTNodeImporter::VisitImpli
   return ToParm;
 }
 
+Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
+const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
+  ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
+  ToParam->setKNRPromoted(FromParam->isKNRPromoted());
+
+  if (FromParam->hasUninstantiatedDefaultArg()) {
+if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
+  ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
+else
+  return ToDefArgOrErr.takeError();
+  } else if (FromParam->hasUnparsedDefaultArg()) {
+ToParam->setUnparsedDefaultArg();
+  } else if (FromParam->hasDefaultArg()) {
+if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
+  ToParam->setDefaultArg(*ToDefArgOrErr);
+else
+  return ToDefArgOrErr.takeError();
+  }
+
+  return Error::success();
+}
+
 ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
   // Parameters are created in the translation unit's context, then moved
   // into the function declaration's context afterward.
@@ -3867,23 +3892,11 @@ ExpectedDecl ASTNodeImporter::VisitParmV
   /*DefaultArg*/ nullptr))
 return ToParm;
 
-  // Set the default argument.
-  ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
-  ToParm->setKNRPromoted(D->isKNRPromoted());
-
-  if (D->hasUninstantiatedDefaultArg()) {
-if (auto ToDefArgOrErr = import(D->getUninstantiatedDefaultArg()))
-  ToParm->setUninstantiatedDefaultArg(*ToDefArgOrErr);
-else
-  return ToDefArgOrErr.takeError();
-  } else if (D->hasUnparsedDefaultArg()) {
-ToParm->setUnparsedDefaultArg();
-  } else if (D->hasDefaultArg()) {
-if (auto ToDefArgOrErr = import(D->getDefaultArg()))
-  ToParm->setDefaultArg(*ToDefArgOrErr);
-else
-  return ToDefArgOrErr.takeError();
-  }
+  // Set the default argument. It should be no problem if it was already done.
+  // Do not import the default expression before GetImportedOrCreateDecl call
+  // to avoid possible infinite import 

[PATCH] D65577: [ASTImporter] Import default expression of param before creating the param.

2019-08-14 Thread Balázs Kéri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc50959431928: [ASTImporter] Import default expression of 
param before creating the param. (authored by balazske).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65577

Files:
  clang/include/clang/AST/ASTImporter.h
  clang/lib/AST/ASTImporter.cpp
  clang/test/Analysis/Inputs/ctu-other.cpp
  clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
  clang/test/Analysis/ctu-main.cpp

Index: clang/test/Analysis/ctu-main.cpp
===
--- clang/test/Analysis/ctu-main.cpp
+++ clang/test/Analysis/ctu-main.cpp
@@ -125,6 +125,8 @@
   static const int Test;
 };
 
+extern int testImportOfIncompleteDefaultParmDuringImport(int);
+
 int main() {
   clang_analyzer_eval(f(3) == 2); // expected-warning{{TRUE}}
   clang_analyzer_eval(f(4) == 3); // expected-warning{{TRUE}}
@@ -157,5 +159,8 @@
   clang_analyzer_eval(extSubSCN.a == 1); // expected-warning{{TRUE}}
   // clang_analyzer_eval(extSCC.a == 7); // TODO
   clang_analyzer_eval(extU.a == 4); // expected-warning{{TRUE}}
+
   clang_analyzer_eval(TestAnonUnionUSR::Test == 5); // expected-warning{{TRUE}}
+
+  clang_analyzer_eval(testImportOfIncompleteDefaultParmDuringImport(9) == 9); // expected-warning{{TRUE}}
 }
Index: clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
===
--- clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
+++ clang/test/Analysis/Inputs/ctu-other.cpp.externalDefMap.txt
@@ -26,3 +26,4 @@
 c:@extSCC ctu-other.cpp.ast
 c:@extU ctu-other.cpp.ast
 c:@S@TestAnonUnionUSR@Test ctu-other.cpp.ast
+c:@F@testImportOfIncompleteDefaultParmDuringImport#I# ctu-other.cpp.ast
Index: clang/test/Analysis/Inputs/ctu-other.cpp
===
--- clang/test/Analysis/Inputs/ctu-other.cpp
+++ clang/test/Analysis/Inputs/ctu-other.cpp
@@ -145,3 +145,22 @@
   static const int Test;
 };
 const int TestAnonUnionUSR::Test = 5;
+
+struct DefaultParmContext {
+  static const int I;
+  int f();
+};
+
+int fDefaultParm(int I = DefaultParmContext::I) {
+  return I;
+}
+
+int testImportOfIncompleteDefaultParmDuringImport(int I) {
+  return fDefaultParm(I);
+}
+
+const int DefaultParmContext::I = 0;
+
+int DefaultParmContext::f() {
+  return fDefaultParm();
+}
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -426,6 +426,9 @@
 
 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
 
+Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
+ParmVarDecl *ToParam);
+
 template 
 bool hasSameVisibilityContext(T *Found, T *From);
 
@@ -3841,6 +3844,28 @@
   return ToParm;
 }
 
+Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
+const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
+  ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
+  ToParam->setKNRPromoted(FromParam->isKNRPromoted());
+
+  if (FromParam->hasUninstantiatedDefaultArg()) {
+if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
+  ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
+else
+  return ToDefArgOrErr.takeError();
+  } else if (FromParam->hasUnparsedDefaultArg()) {
+ToParam->setUnparsedDefaultArg();
+  } else if (FromParam->hasDefaultArg()) {
+if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
+  ToParam->setDefaultArg(*ToDefArgOrErr);
+else
+  return ToDefArgOrErr.takeError();
+  }
+
+  return Error::success();
+}
+
 ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
   // Parameters are created in the translation unit's context, then moved
   // into the function declaration's context afterward.
@@ -3867,23 +3892,11 @@
   /*DefaultArg*/ nullptr))
 return ToParm;
 
-  // Set the default argument.
-  ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
-  ToParm->setKNRPromoted(D->isKNRPromoted());
-
-  if (D->hasUninstantiatedDefaultArg()) {
-if (auto ToDefArgOrErr = import(D->getUninstantiatedDefaultArg()))
-  ToParm->setUninstantiatedDefaultArg(*ToDefArgOrErr);
-else
-  return ToDefArgOrErr.takeError();
-  } else if (D->hasUnparsedDefaultArg()) {
-ToParm->setUnparsedDefaultArg();
-  } else if (D->hasDefaultArg()) {
-if (auto ToDefArgOrErr = import(D->getDefaultArg()))
-  ToParm->setDefaultArg(*ToDefArgOrErr);
-else
-  return ToDefArgOrErr.takeError();
-  }
+  // Set the default argument. It should be no problem if it was already done.
+  // Do not import the default expression before GetImportedOrCreateDecl call
+  // to avoid possible infinite impo

[PATCH] D66152: Fix false negatives of statement local lifetime analysis for some STL implementation

2019-08-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr accepted this revision.
gribozavr added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Sema/SemaInit.cpp:6579
+  if (Name.size() >= 2 && Name.front() == '_' &&
+  (Name[1] == '_' || llvm::toUpper(Name[1]) == Name[1]))
+return true;

Please use isUppercase from include/clang/Basic/CharInfo.h.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66152



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


[PATCH] D65819: [Driver][Bundler] Improve bundling of object files.

2019-08-14 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

Okay, so I wasn't happy with the current explanations because I don't like 
"fixing" an issue without understanding the problem. Here's a small reproducer:

  $  cat main.cpp 
  #include "test.h"
  
  int main(int argc, char *argv[]) {
m[1] = 2;
return 0;
  }
  $ cat test.h 
  #include 
  #include 
  
  template 
  struct B {
static std::vector v;
  
virtual void f() {
  v.push_back(1);
}
  };
  
  struct C : public B {
C() { }
  };
  
  template 
  std::vector B::v;
  
  extern std::map m;
  $ cat test.cpp 
  #include "test.h"
  
  std::map m;

Compiling with `clang++ -c main.cpp`, `clang++ -c test.cpp`, `clang++ main.o 
test.o -o main` works fine and the resulting executable doesn't crash.
Now if instead partially linking `test.o` like `ld -r test.o -o test.o.ld-r` 
and then linking the executable with `clang++ main.o test.o.ld-r -o main.ld-r` 
outputs a binary that crashes at execution because the constructor of 
`std::map m` is not called.

Digging in the object files reveals the reason:

  $ readelf -S test.o | grep -n1 .init_array
  281-   0008   WAG   0 0 8
  282:  [138] .init_array   INIT_ARRAY     09d0
  283-   0008   WAG   0 0 8
  284:  [139] .rela.init_array  RELA   2460
  285-   0018  0018   G  150   138 8
  286:  [140] .init_array   INIT_ARRAY     09d8
  287-   0008    WA   0 0 8
  288:  [141] .rela.init_array  RELA   2478
  289-   0018  0018  150   140 8
  $ readelf -S test.o.ld-r | grep -n1 .init_array
  279-   0078     A   0 0 4
  280:  [137] .init_array   INIT_ARRAY     1270
  281-   0010  0008 WAG   0 0 8
  282:  [138] .rela.init_array  RELA   3b10
  283-   0030  0018  IG  147   137 8

I haven't further looked into the contents of the sections, but I'd guess that 
the first `.init_array` in `test.o` contains the constructor for `template 
 std::vector B::v`. Because it might need to be merged with 
other TUs (in this case, it's also present in `main.o`) it is marked with a 
group flag (`G`). The second `.init_array` in `test.o` is probably the 
constructor for `std::map m` and not marked with a group, but `ld -r` 
merges these two sections into one `.init_array`, now with a group. So when 
linking with `main.o` which also contains a constructor for `template  std::vector B::v`, the linker drops the call to the constructor of 
`std::map m`:

  $ readelf -S main | grep -n1 .init_array
  43-   0160     A   0 0 4
  44:  [19] .init_array   INIT_ARRAY   6d98  5d98
  45-   0018  0008  WA   0 0 8
  $ readelf -S main.ld-r | grep -n1 .init_array
  43-   0160     A   0 0 4
  44:  [19] .init_array   INIT_ARRAY   6da0  5da0
  45-   0010  0008  WA   0 0 8

(note the difference in size of the two `.init_array` sections!)

Further notes:

- Obviously, linking in a different order like `clang++ test.o.ld-r main.o -o 
main.ld-r2` also results in a working executable, but that's not really a 
solution.
- Calling `ld -Ur` doesn't change anything:

  $ ld -Ur test.o -o test.o.ld-Ur
  $ md5sum test.o.ld-*
  a4d5cead3209ef191d5c05de63e398de  test.o.ld-r
  a4d5cead3209ef191d5c05de63e398de  test.o.ld-Ur

---

Long story short: This very much looks like a bug in `ld` when using partial 
linking. So the best thing that Clang can do to (kind of) workaround this 
problem is ensuring that bundling + unbundling results in the bitwise-same host 
object file. However, I think we should still use partial linking for easy 
access to the host object file, even if we don't extract it from there (other 
tools using it from there have to blame `ld -r`, not `clang-offload-bundler`, 
that the partially linked object file doesn't correctly call global 
initializers).


Repository:
  rC Clang

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

https://reviews.llvm.org/D65819



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


[PATCH] D65856: [clangd] Added class for mapping TokenColorRules to their associated clangd TextMate scope

2019-08-14 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom updated this revision to Diff 215065.
jvikstrom marked 4 inline comments as done.
jvikstrom added a comment.

Simplified matching code. Use real scopes for test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65856

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -1,13 +1,13 @@
 import * as assert from 'assert';
 import * as path from 'path';
 
-import * as TM from '../src/semantic-highlighting';
+import * as SM from '../src/semantic-highlighting';
 
 suite('SemanticHighlighting Tests', () => {
   test('Parses arrays of textmate themes.', async () => {
 const themePath =
 path.join(__dirname, '../../test/assets/includeTheme.jsonc');
-const scopeColorRules = await TM.parseThemeFile(themePath);
+const scopeColorRules = await SM.parseThemeFile(themePath);
 const getScopeRule = (scope: string) =>
 scopeColorRules.find((v) => v.scope === scope);
 assert.equal(scopeColorRules.length, 3);
@@ -33,6 +33,28 @@
   ]
 ];
 testCases.forEach((testCase, i) => assert.deepEqual(
-  TM.decodeTokens(testCase), expected[i]));
+  SM.decodeTokens(testCase), expected[i]));
+  });
+  test('ScopeRules overrides for more specific themes', () => {
+const rules = [
+  {scope : 'variable.other.css', foreground : '1'},
+  {scope : 'variable.other', foreground : '2'},
+  {scope : 'storage', foreground : '3'},
+  {scope : 'storage.static', foreground : '4'},
+  {scope : 'storage', foreground : '5'},
+  {scope : 'variable.other.parameter', foreground : '6'},
+];
+const tm = new SM.ThemeRuleMatcher(rules);
+assert.deepEqual(tm.getBestThemeRule('variable.other.cpp').scope,
+ 'variable.other');
+assert.deepEqual(tm.getBestThemeRule('storage.static').scope,
+ 'storage.static');
+assert.deepEqual(
+tm.getBestThemeRule('storage'),
+rules[2]); // Match the first element if there are duplicates.
+assert.deepEqual(tm.getBestThemeRule('variable.other.parameter').scope,
+ 'variable.other.parameter');
+assert.deepEqual(tm.getBestThemeRule('variable.other.parameter.cpp').scope,
+ 'variable.other.parameter');
   });
 });
Index: clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -47,6 +47,8 @@
   // The TextMate scope lookup table. A token with scope index i has the scopes
   // on index i in the lookup table.
   scopeLookupTable: string[][];
+  // The rules for the current theme.
+  themeRuleMatcher: ThemeRuleMatcher;
   fillClientCapabilities(capabilities: vscodelc.ClientCapabilities) {
 // Extend the ClientCapabilities type and add semantic highlighting
 // capability to the object.
@@ -58,6 +60,12 @@
 };
   }
 
+  async loadCurrentTheme() {
+this.themeRuleMatcher = new ThemeRuleMatcher(
+await loadTheme(vscode.workspace.getConfiguration('workbench')
+.get('colorTheme')));
+  }
+
   initialize(capabilities: vscodelc.ServerCapabilities,
  documentSelector: vscodelc.DocumentSelector|undefined) {
 // The semantic highlighting capability information is in the capabilities
@@ -68,6 +76,7 @@
 if (!serverCapabilities.semanticHighlighting)
   return;
 this.scopeLookupTable = serverCapabilities.semanticHighlighting.scopes;
+this.loadCurrentTheme();
   }
 
   handleNotification(params: SemanticHighlightingParams) {}
@@ -101,6 +110,39 @@
   foreground: string;
 }
 
+export class ThemeRuleMatcher {
+  // The rules for the theme.
+  private themeRules: TokenColorRule[];
+  // A cache for the getBestThemeRule function.
+  private bestRuleCache: Map = new Map();
+  constructor(rules: TokenColorRule[]) { this.themeRules = rules; }
+  // Returns the best rule for a scope.
+  getBestThemeRule(scope: string): TokenColorRule {
+if (this.bestRuleCache.has(scope))
+  return this.bestRuleCache.get(scope);
+let bestRule: TokenColorRule = {scope : '', foreground : ''};
+this.themeRules.forEach((rule) => {
+  // The best rule for a scope is the rule that is the longest prefix of the
+  // scope (unless a perfect match exists in which c

Re: [PATCH] D65819: [Driver][Bundler] Improve bundling of object files.

2019-08-14 Thread Alexey Bataev via cfe-commits
I said this before that most probably this is the bug in partial linking, made 
by ld. But clang-offload-bundler is also nit quite correct here since the 
original host code is actually not unbundled. I'll fix the patch later today to 
keep the partial linking for the host object, but really unbundle it when 
required.

Best regards,
Alexey Bataev

> 14 авг. 2019 г., в 5:48, Jonas Hahnfeld via Phabricator 
>  написал(а):
> 
> Hahnfeld added a comment.
> 
> Okay, so I wasn't happy with the current explanations because I don't like 
> "fixing" an issue without understanding the problem. Here's a small 
> reproducer:
> 
>  $  cat main.cpp 
>  #include "test.h"
> 
>  int main(int argc, char *argv[]) {
>m[1] = 2;
>return 0;
>  }
>  $ cat test.h 
>  #include 
>  #include 
> 
>  template 
>  struct B {
>static std::vector v;
> 
>virtual void f() {
>  v.push_back(1);
>}
>  };
> 
>  struct C : public B {
>C() { }
>  };
> 
>  template 
>  std::vector B::v;
> 
>  extern std::map m;
>  $ cat test.cpp 
>  #include "test.h"
> 
>  std::map m;
> 
> Compiling with `clang++ -c main.cpp`, `clang++ -c test.cpp`, `clang++ main.o 
> test.o -o main` works fine and the resulting executable doesn't crash.
> Now if instead partially linking `test.o` like `ld -r test.o -o test.o.ld-r` 
> and then linking the executable with `clang++ main.o test.o.ld-r -o 
> main.ld-r` outputs a binary that crashes at execution because the constructor 
> of `std::map m` is not called.
> 
> Digging in the object files reveals the reason:
> 
>  $ readelf -S test.o | grep -n1 .init_array
>  281-   0008   WAG   0 0 8
>  282:  [138] .init_array   INIT_ARRAY     09d0
>  283-   0008   WAG   0 0 8
>  284:  [139] .rela.init_array  RELA   2460
>  285-   0018  0018   G  150   138 8
>  286:  [140] .init_array   INIT_ARRAY     09d8
>  287-   0008    WA   0 0 8
>  288:  [141] .rela.init_array  RELA   2478
>  289-   0018  0018  150   140 8
>  $ readelf -S test.o.ld-r | grep -n1 .init_array
>  279-   0078     A   0 0 4
>  280:  [137] .init_array   INIT_ARRAY     1270
>  281-   0010  0008 WAG   0 0 8
>  282:  [138] .rela.init_array  RELA   3b10
>  283-   0030  0018  IG  147   137 8
> 
> I haven't further looked into the contents of the sections, but I'd guess 
> that the first `.init_array` in `test.o` contains the constructor for 
> `template  std::vector B::v`. Because it might need to be 
> merged with other TUs (in this case, it's also present in `main.o`) it is 
> marked with a group flag (`G`). The second `.init_array` in `test.o` is 
> probably the constructor for `std::map m` and not marked with a 
> group, but `ld -r` merges these two sections into one `.init_array`, now with 
> a group. So when linking with `main.o` which also contains a constructor for 
> `template  std::vector B::v`, the linker drops the call 
> to the constructor of `std::map m`:
> 
>  $ readelf -S main | grep -n1 .init_array
>  43-   0160     A   0 0 4
>  44:  [19] .init_array   INIT_ARRAY   6d98  5d98
>  45-   0018  0008  WA   0 0 8
>  $ readelf -S main.ld-r | grep -n1 .init_array
>  43-   0160     A   0 0 4
>  44:  [19] .init_array   INIT_ARRAY   6da0  5da0
>  45-   0010  0008  WA   0 0 8
> 
> (note the difference in size of the two `.init_array` sections!)
> 
> Further notes:
> 
> - Obviously, linking in a different order like `clang++ test.o.ld-r main.o -o 
> main.ld-r2` also results in a working executable, but that's not really a 
> solution.
> - Calling `ld -Ur` doesn't change anything:
> 
>  $ ld -Ur test.o -o test.o.ld-Ur
>  $ md5sum test.o.ld-*
>  a4d5cead3209ef191d5c05de63e398de  test.o.ld-r
>  a4d5cead3209ef191d5c05de63e398de  test.o.ld-Ur
> 
> ---
> 
> Long story short: This very much looks like a bug in `ld` when using partial 
> linking. So the best thing that Clang can do to (kind of) workaround this 
> problem is ensuring that bundling + unbundling results in the bitwise-same 
> host object file. However, I think we should still use partial linking for 
> easy access to the host object file, even if we don't extract it from there 
> (other tools using it from there have to blame `ld -r`, not 
> `clang-offload-bundler`, that the partially linked object file doesn't 
> correctly call global initializers).
> 
> 
> Repository:
>  rC Cla

[PATCH] D66049: [analyzer] PR41729: Fix some false positives and improve strlcat and strlcpy modeling

2019-08-14 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added a comment.

Nice improvements! It was a good catch that a substantial part of the checker 
could be cut out. Accurate modelling of CString and related API-s is really 
important, and this is a good step in that direction.
I would test this on a larger codebase as well before committing, but LGTM 
otherwise.


Repository:
  rC Clang

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

https://reviews.llvm.org/D66049



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


r368822 - Fix _WIN32 / _WIN64 Wundef warnings

2019-08-14 Thread Sven van Haastregt via cfe-commits
Author: svenvh
Date: Wed Aug 14 03:30:18 2019
New Revision: 368822

URL: http://llvm.org/viewvc/llvm-project?rev=368822&view=rev
Log:
Fix _WIN32 / _WIN64 Wundef warnings

For these macros it is the definedness that matters rather than
the value.  Make new uses of these macros consistent with existing
uses.

Modified:
cfe/trunk/lib/Driver/ToolChains/HIP.cpp

Modified: cfe/trunk/lib/Driver/ToolChains/HIP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/HIP.cpp?rev=368822&r1=368821&r2=368822&view=diff
==
--- cfe/trunk/lib/Driver/ToolChains/HIP.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/HIP.cpp Wed Aug 14 03:30:18 2019
@@ -23,7 +23,7 @@ using namespace clang::driver::tools;
 using namespace clang;
 using namespace llvm::opt;
 
-#if _WIN32 || _WIN64
+#if defined(_WIN32) || defined(_WIN64)
 #define NULL_FILE "nul"
 #else
 #define NULL_FILE "/dev/null"


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


[clang-tools-extra] r368824 - [clangd] Fix typos and grammar in a comment. NFC

2019-08-14 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Aug 14 03:49:32 2019
New Revision: 368824

URL: http://llvm.org/viewvc/llvm-project?rev=368824&view=rev
Log:
[clangd] Fix typos and grammar in a comment. NFC

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

Modified: clang-tools-extra/trunk/clangd/FindSymbols.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/FindSymbols.cpp?rev=368824&r1=368823&r2=368824&view=diff
==
--- clang-tools-extra/trunk/clangd/FindSymbols.cpp (original)
+++ clang-tools-extra/trunk/clangd/FindSymbols.cpp Wed Aug 14 03:49:32 2019
@@ -176,14 +176,14 @@ llvm::Optional declToSym
   return SI;
 }
 
-/// A helper class to build an outline for the parse AST. It traverse the AST
+/// A helper class to build an outline for the parse AST. It traverses the AST
 /// directly instead of using RecursiveASTVisitor (RAV) for three main reasons:
-///- there is no way to keep RAV from traversing subtrees we're not
+///- there is no way to keep RAV from traversing subtrees we are not
 ///  interested in. E.g. not traversing function locals or implicit 
template
 ///  instantiations.
-///- it's easier to combine results of recursive passes, e.g.
+///- it's easier to combine results of recursive passes,
 ///- visiting decls is actually simple, so we don't hit the complicated
-///  cases that RAV mostly helps with (types and expressions, etc.)
+///  cases that RAV mostly helps with (types, expressions, etc.)
 class DocumentOutline {
 public:
   DocumentOutline(ParsedAST &AST) : AST(AST) {}


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


[PATCH] D66209: Improved the doc comment for getCommentsInFile

2019-08-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
gribozavr added a reviewer: hokein.
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

thanks!


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66209

Files:
  clang/include/clang/AST/RawCommentList.h


Index: clang/include/clang/AST/RawCommentList.h
===
--- clang/include/clang/AST/RawCommentList.h
+++ clang/include/clang/AST/RawCommentList.h
@@ -199,7 +199,8 @@
   void addComment(const RawComment &RC, const CommentOptions &CommentOpts,
   llvm::BumpPtrAllocator &Allocator);
 
-  /// \returns nullptr in case there are no comments in in \p File.
+  /// \returns A mapping from an offset of the start of the comment to the
+  /// comment itself, or nullptr in case there are no comments in in \p File.
   const std::map *getCommentsInFile(FileID File) const;
 
   bool empty() const;


Index: clang/include/clang/AST/RawCommentList.h
===
--- clang/include/clang/AST/RawCommentList.h
+++ clang/include/clang/AST/RawCommentList.h
@@ -199,7 +199,8 @@
   void addComment(const RawComment &RC, const CommentOptions &CommentOpts,
   llvm::BumpPtrAllocator &Allocator);
 
-  /// \returns nullptr in case there are no comments in in \p File.
+  /// \returns A mapping from an offset of the start of the comment to the
+  /// comment itself, or nullptr in case there are no comments in in \p File.
   const std::map *getCommentsInFile(FileID File) const;
 
   bool empty() const;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66209: Improved the doc comment for getCommentsInFile

2019-08-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66209



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


[PATCH] D66209: Improved the doc comment for getCommentsInFile

2019-08-14 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/include/clang/AST/RawCommentList.h:203
+  /// \returns A mapping from an offset of the start of the comment to the
+  /// comment itself, or nullptr in case there are no comments in in \p File.
   const std::map *getCommentsInFile(FileID File) const;

> in in

Typo?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66209



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


[PATCH] D65526: [Clangd] Initial prototype version of ExtractFunction

2019-08-14 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah updated this revision to Diff 215077.
SureYeaah marked 11 inline comments as done.
SureYeaah added a comment.

Refactored design and added unit tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65526

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
  clang-tools-extra/clangd/unittests/TweakTesting.h
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -133,7 +133,8 @@
   EXPECT_EQ(apply("^if (true) {return 100;} else {continue;}"),
 "if (true) {continue;} else {return 100;}");
   EXPECT_EQ(apply("^if () {return 100;} else {continue;}"),
-"if () {continue;} else {return 100;}") << "broken condition";
+"if () {continue;} else {return 100;}")
+  << "broken condition";
   EXPECT_AVAILABLE("^i^f^^(^t^r^u^e^) { return 100; } ^e^l^s^e^ { continue; }");
   EXPECT_UNAVAILABLE("if (true) {^return ^100;^ } else { ^continue^;^ }");
   // Available in subexpressions of the condition;
@@ -164,7 +165,7 @@
   EXPECT_UNAVAILABLE(R"cpp(R"(multi )" ^"token " u8"str\ning")cpp"); // nonascii
   EXPECT_UNAVAILABLE(R"cpp(^R^"^(^multi )" "token " "str\ning")cpp"); // raw
   EXPECT_UNAVAILABLE(R"cpp(^"token\n" __FILE__)cpp"); // chunk is macro
-  EXPECT_UNAVAILABLE(R"cpp(^"a\r\n";)cpp"); // forbidden escape char
+  EXPECT_UNAVAILABLE(R"cpp(^"a\r\n";)cpp");   // forbidden escape char
 
   const char *Input = R"cpp(R"(multi
 token)" "\nst^ring\n" "literal")cpp";
@@ -345,11 +346,11 @@
  void f(int a) {
int y = PLUS([[1+a]]);
  })cpp",
-  /*FIXME: It should be extracted like this.
-   R"cpp(#define PLUS(x) x++
- void f(int a) {
-   auto dummy = 1+a; int y = PLUS(dummy);
- })cpp"},*/
+   /*FIXME: It should be extracted like this.
+R"cpp(#define PLUS(x) x++
+  void f(int a) {
+auto dummy = 1+a; int y = PLUS(dummy);
+  })cpp"},*/
R"cpp(#define PLUS(x) x++
  void f(int a) {
auto dummy = PLUS(1+a); int y = dummy;
@@ -360,13 +361,13 @@
if(1)
 LOOP(5 + [[3]])
  })cpp",
-  /*FIXME: It should be extracted like this. SelectionTree needs to be
-* fixed for macros.
-   R"cpp(#define LOOP(x) while (1) {a = x;}
-   void f(int a) {
- auto dummy = 3; if(1)
-  LOOP(5 + dummy)
-   })cpp"},*/
+   /*FIXME: It should be extracted like this. SelectionTree needs to be
+ * fixed for macros.
+R"cpp(#define LOOP(x) while (1) {a = x;}
+void f(int a) {
+  auto dummy = 3; if(1)
+   LOOP(5 + dummy)
+})cpp"},*/
R"cpp(#define LOOP(x) while (1) {a = x;}
  void f(int a) {
auto dummy = LOOP(5 + 3); if(1)
@@ -462,8 +463,8 @@
  void f() {
auto dummy = S(2) + S(3) + S(4); S x = S(1) + dummy + S(5);
  })cpp"},
-   // Don't try to analyze across macro boundaries
-   // FIXME: it'd be nice to do this someday (in a safe way)
+  // Don't try to analyze across macro boundaries
+  // FIXME: it'd be nice to do this someday (in a safe way)
   {R"cpp(#define ECHO(X) X
  void f() {
int x = 1 + [[ECHO(2 + 3) + 4]] + 5;
@@ -491,26 +492,27 @@
   checkAvailable(ID, "^vo^id^ ^f(^) {^}^"); // available everywhere.
   checkAvailable(ID, "[[int a; int b;]]");
   const char *Input = "void ^f() {}";
-  const char *Output = "/* storage.type.primitive.cpp */void /* entity.name.function.cpp */f() {}";
+  const char *Output = "/* storage.type.primitive.cpp */void /* "
+   "entity.name.function.cpp */f() {}";
   checkTransform(ID, Input, Output);
 
   checkTransform(ID,
-  R"cpp(
+ R"cpp(
 [[void f1();
 void f2();]]
 )cpp",
-  R"cpp(
+ R"cpp(
 /* storage.type.primitive.cpp */void /* entity.name.function.cpp */f1();
 /* storage.type.primitive.cpp */void /* entity.name.function.cpp */f2();
 )cpp");
 
-   checkTransform(ID,
-  R"cpp(
+  checkTransform(ID,
+ R"cpp(
 void f1();
 void f2() {^};
 )cpp",
 
-  R"cpp(
+ R"cpp(
 void f1();
 /* storage.type.primitive.cpp */void /* entity.name.function.cpp */f2() {};
 )cpp");
@@ -590,7 +592,7 @@
   StartsWith("fail: Could not expand type of lambda expression"));
   // inline 

r368825 - [clang] - An update after LLVM change.

2019-08-14 Thread George Rimar via cfe-commits
Author: grimar
Date: Wed Aug 14 04:10:01 2019
New Revision: 368825

URL: http://llvm.org/viewvc/llvm-project?rev=368825&view=rev
Log:
[clang] - An update after LLVM change.

SectionRef::getName() was changed to return Expected<> (D66089)

Modified:
cfe/trunk/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp

Modified: cfe/trunk/lib/CodeGen/ObjectFilePCHContainerOperations.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/ObjectFilePCHContainerOperations.cpp?rev=368825&r1=368824&r2=368825&view=diff
==
--- cfe/trunk/lib/CodeGen/ObjectFilePCHContainerOperations.cpp (original)
+++ cfe/trunk/lib/CodeGen/ObjectFilePCHContainerOperations.cpp Wed Aug 14 
04:10:01 2019
@@ -335,7 +335,11 @@ ObjectFilePCHContainerReader::ExtractPCH
 // Find the clang AST section in the container.
 for (auto &Section : OF->sections()) {
   StringRef Name;
-  Section.getName(Name);
+  if (Expected NameOrErr = Section.getName())
+Name = *NameOrErr;
+  else
+consumeError(NameOrErr.takeError());
+
   if ((!IsCOFF && Name == "__clangast") || (IsCOFF && Name == "clangast")) 
{
 if (Expected E = Section.getContents())
   return *E;

Modified: cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp?rev=368825&r1=368824&r2=368825&view=diff
==
--- cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp (original)
+++ cfe/trunk/tools/clang-offload-bundler/ClangOffloadBundler.cpp Wed Aug 14 
04:10:01 2019
@@ -390,7 +390,10 @@ class ObjectFileHandler final : public F
   static bool IsOffloadSection(SectionRef CurSection,
StringRef &OffloadTriple) {
 StringRef SectionName;
-CurSection.getName(SectionName);
+if (Expected NameOrErr = CurSection.getName())
+  SectionName = *NameOrErr;
+else
+  consumeError(NameOrErr.takeError());
 
 if (SectionName.empty())
   return false;


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


r368827 - Improved the doc comment for getCommentsInFile

2019-08-14 Thread Dmitri Gribenko via cfe-commits
Author: gribozavr
Date: Wed Aug 14 04:11:52 2019
New Revision: 368827

URL: http://llvm.org/viewvc/llvm-project?rev=368827&view=rev
Log:
Improved the doc comment for getCommentsInFile

Subscribers: cfe-commits

Tags: #clang

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

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

Modified: cfe/trunk/include/clang/AST/RawCommentList.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/RawCommentList.h?rev=368827&r1=368826&r2=368827&view=diff
==
--- cfe/trunk/include/clang/AST/RawCommentList.h (original)
+++ cfe/trunk/include/clang/AST/RawCommentList.h Wed Aug 14 04:11:52 2019
@@ -199,7 +199,8 @@ public:
   void addComment(const RawComment &RC, const CommentOptions &CommentOpts,
   llvm::BumpPtrAllocator &Allocator);
 
-  /// \returns nullptr in case there are no comments in in \p File.
+  /// \returns A mapping from an offset of the start of the comment to the
+  /// comment itself, or nullptr in case there are no comments in \p File.
   const std::map *getCommentsInFile(FileID File) const;
 
   bool empty() const;


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


[PATCH] D66209: Improved the doc comment for getCommentsInFile

2019-08-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368827: Improved the doc comment for getCommentsInFile 
(authored by gribozavr, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66209?vs=215076&id=215078#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66209

Files:
  cfe/trunk/include/clang/AST/RawCommentList.h


Index: cfe/trunk/include/clang/AST/RawCommentList.h
===
--- cfe/trunk/include/clang/AST/RawCommentList.h
+++ cfe/trunk/include/clang/AST/RawCommentList.h
@@ -199,7 +199,8 @@
   void addComment(const RawComment &RC, const CommentOptions &CommentOpts,
   llvm::BumpPtrAllocator &Allocator);
 
-  /// \returns nullptr in case there are no comments in in \p File.
+  /// \returns A mapping from an offset of the start of the comment to the
+  /// comment itself, or nullptr in case there are no comments in \p File.
   const std::map *getCommentsInFile(FileID File) const;
 
   bool empty() const;


Index: cfe/trunk/include/clang/AST/RawCommentList.h
===
--- cfe/trunk/include/clang/AST/RawCommentList.h
+++ cfe/trunk/include/clang/AST/RawCommentList.h
@@ -199,7 +199,8 @@
   void addComment(const RawComment &RC, const CommentOptions &CommentOpts,
   llvm::BumpPtrAllocator &Allocator);
 
-  /// \returns nullptr in case there are no comments in in \p File.
+  /// \returns A mapping from an offset of the start of the comment to the
+  /// comment itself, or nullptr in case there are no comments in \p File.
   const std::map *getCommentsInFile(FileID File) const;
 
   bool empty() const;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66042: [analyzer] Analysis: "Disable" core checkers

2019-08-14 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In D66042#1627760 , @NoQ wrote:

> In D66042#1627193 , @alexfh wrote:
>
> > But without this patch clang seems to have the same two ANALYZE log lines 
> > regardless of whether I enable `core` checkers or not
>
>
> Yup, it seems as if clang-tidy enables `core` as long as at least one Static 
> Analyzer checker is enabled (even if it's path-insensitive).


It would be nice, if Static Analyzer would hide this from the users completely. 
The user would specify the list of checkers they need and CSA would enable 
whatever additional checkers it needs (if any) and then filter out their 
results. Is it feasible?


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

https://reviews.llvm.org/D66042



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


r368828 - [NFC] Make test more robust

2019-08-14 Thread David Bolvansky via cfe-commits
Author: xbolva00
Date: Wed Aug 14 04:13:10 2019
New Revision: 368828

URL: http://llvm.org/viewvc/llvm-project?rev=368828&view=rev
Log:
[NFC] Make test more robust

Currently fails on ARMs

Modified:
cfe/trunk/test/CodeGen/struct-copy.c

Modified: cfe/trunk/test/CodeGen/struct-copy.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/struct-copy.c?rev=368828&r1=368827&r2=368828&view=diff
==
--- cfe/trunk/test/CodeGen/struct-copy.c (original)
+++ cfe/trunk/test/CodeGen/struct-copy.c Wed Aug 14 04:13:10 2019
@@ -1,39 +1,17 @@
-// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // RUN: %clang_cc1 -emit-llvm %s -o - | FileCheck %s
 struct x { int a[100]; };
 
-// CHECK-LABEL: @foo(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
-// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
-// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
-// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
-// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], 
align 8
-// CHECK-NEXT:[[TMP1:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], 
align 8
-// CHECK-NEXT:[[TMP2:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
-// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP1]] to i8*
-// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP2]], 
i8* align 4 [[TMP3]], i64 400, i1 false)
-// CHECK-NEXT:ret void
-//
+
 void foo(struct x *P, struct x *Q) {
+// CHECK-LABEL: @foo(
+// CHECK:call void @llvm.memcpy.p0i8.p0i8.i64
   *P = *Q;
 }
 
 // CHECK: declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture 
writeonly, i8* noalias nocapture readonly, i64, i1 immarg)
 
-// CHECK-LABEL: @bar(
-// CHECK-NEXT:  entry:
-// CHECK-NEXT:[[P_ADDR:%.*]] = alloca %struct.x*, align 8
-// CHECK-NEXT:[[Q_ADDR:%.*]] = alloca %struct.x*, align 8
-// CHECK-NEXT:store %struct.x* [[P:%.*]], %struct.x** [[P_ADDR]], align 8
-// CHECK-NEXT:store %struct.x* [[Q:%.*]], %struct.x** [[Q_ADDR]], align 8
-// CHECK-NEXT:[[TMP0:%.*]] = load %struct.x*, %struct.x** [[P_ADDR]], 
align 8
-// CHECK-NEXT:[[TMP1:%.*]] = bitcast %struct.x* [[TMP0]] to i8*
-// CHECK-NEXT:[[TMP2:%.*]] = load %struct.x*, %struct.x** [[Q_ADDR]], 
align 8
-// CHECK-NEXT:[[TMP3:%.*]] = bitcast %struct.x* [[TMP2]] to i8*
-// CHECK-NEXT:call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 [[TMP1]], 
i8* align 4 [[TMP3]], i64 400, i1 false)
-// CHECK-NEXT:ret void
-//
 void bar(struct x *P, struct x *Q) {
+// CHECK-LABEL: @bar(
+// CHECK:call void @llvm.memcpy.p0i8.p0i8.i64
   __builtin_memcpy(P, Q, sizeof(struct x));
 }


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


[PATCH] D66042: [analyzer] Analysis: "Disable" core checkers

2019-08-14 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

In D66042#1629019 , @alexfh wrote:

> In D66042#1627760 , @NoQ wrote:
>
> > In D66042#1627193 , @alexfh wrote:
> >
> > > But without this patch clang seems to have the same two ANALYZE log lines 
> > > regardless of whether I enable `core` checkers or not
> >
> >
> > Yup, it seems as if clang-tidy enables `core` as long as at least one 
> > Static Analyzer checker is enabled (even if it's path-insensitive).
>
>
> It would be nice, if Static Analyzer would hide this from the users 
> completely. The user would specify the list of checkers they need and CSA 
> would enable whatever additional checkers it needs (if any) and then filter 
> out their results. Is it feasible?


Yes, it is! I've been working on a checker dependency system for a while, and 
just proposed some improvements on it on the mailing list that would achieve 
exactly this :)


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

https://reviews.llvm.org/D66042



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


[PATCH] D66211: [clangd][vscode] Surface the error when applying tweaks fails

2019-08-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: ilya-biryukov.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

The current behavior for a failed request is just to log it in the
output panel. When applyTweak fails for whatever reason, users usually don't get
informed (unless they open the output panel and dig the log).

this patch is to surface these errors by prompting up a message diag.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66211

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts


Index: clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
@@ -91,6 +91,26 @@
 
   const clangdClient = new vscodelc.LanguageClient(
   'Clang Language Server', serverOptions, clientOptions);
+
+  // We override the default implementation for failed requests. The default
+  // behavior is just to log failures in the output panel, however output panel
+  // is designed for extension debugging purpose, normal users will not open 
it,
+  // thus when the failure occurs, normal users doesn't know that.
+  //
+  // For user-interactive operations (e.g. applyFixIt, applyTweaks), we will 
prompt
+  // up the failure to users.
+  clangdClient.logFailedRequest =
+  (rpcReply: vscodelc.RPCMessageType, error: any) => {
+if (error instanceof vscodelc.ResponseError &&
+rpcReply.method === "workspace/executeCommand")
+  vscode.window.showErrorMessage(error.message);
+
+// Keep the default behavior.
+if (error instanceof vscodelc.ResponseError &&
+error.code === vscodelc.ErrorCodes.RequestCancelled)
+  return;
+clangdClient.error(`Request ${rpcReply.method} failed.`, error);
+  };
   console.log('Clang Language Server is now active!');
   context.subscriptions.push(clangdClient.start());
   context.subscriptions.push(vscode.commands.registerCommand(


Index: clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
@@ -91,6 +91,26 @@
 
   const clangdClient = new vscodelc.LanguageClient(
   'Clang Language Server', serverOptions, clientOptions);
+
+  // We override the default implementation for failed requests. The default
+  // behavior is just to log failures in the output panel, however output panel
+  // is designed for extension debugging purpose, normal users will not open it,
+  // thus when the failure occurs, normal users doesn't know that.
+  //
+  // For user-interactive operations (e.g. applyFixIt, applyTweaks), we will prompt
+  // up the failure to users.
+  clangdClient.logFailedRequest =
+  (rpcReply: vscodelc.RPCMessageType, error: any) => {
+if (error instanceof vscodelc.ResponseError &&
+rpcReply.method === "workspace/executeCommand")
+  vscode.window.showErrorMessage(error.message);
+
+// Keep the default behavior.
+if (error instanceof vscodelc.ResponseError &&
+error.code === vscodelc.ErrorCodes.RequestCancelled)
+  return;
+clangdClient.error(`Request ${rpcReply.method} failed.`, error);
+  };
   console.log('Clang Language Server is now active!');
   context.subscriptions.push(clangdClient.start());
   context.subscriptions.push(vscode.commands.registerCommand(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66212: Removed ToolExecutor::isSingleProcess, it is not used by anything

2019-08-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
gribozavr added a reviewer: sammccall.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66212

Files:
  clang/include/clang/Tooling/AllTUsExecution.h
  clang/include/clang/Tooling/Execution.h
  clang/include/clang/Tooling/StandaloneExecution.h
  clang/unittests/Tooling/ExecutionTest.cpp


Index: clang/unittests/Tooling/ExecutionTest.cpp
===
--- clang/unittests/Tooling/ExecutionTest.cpp
+++ clang/unittests/Tooling/ExecutionTest.cpp
@@ -95,8 +95,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   llvm::Error
   execute(llvm::ArrayRef,
ArgumentsAdjuster>>) override {
Index: clang/include/clang/Tooling/StandaloneExecution.h
===
--- clang/include/clang/Tooling/StandaloneExecution.h
+++ clang/include/clang/Tooling/StandaloneExecution.h
@@ -52,8 +52,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   using ToolExecutor::execute;
 
   llvm::Error
Index: clang/include/clang/Tooling/Execution.h
===
--- clang/include/clang/Tooling/Execution.h
+++ clang/include/clang/Tooling/Execution.h
@@ -115,13 +115,6 @@
   /// Returns the name of a specific executor.
   virtual StringRef getExecutorName() const = 0;
 
-  /// Should return true iff executor runs all actions in a single process.
-  /// Clients can use this signal to find out if they can collect results
-  /// in-memory (e.g. to avoid serialization costs of using ToolResults).
-  /// The single-process executors can still run multiple threads, but all
-  /// executions are guaranteed to share the same memory.
-  virtual bool isSingleProcess() const = 0;
-
   /// Executes each action with a corresponding arguments adjuster.
   virtual llvm::Error
   execute(llvm::ArrayRef<
Index: clang/include/clang/Tooling/AllTUsExecution.h
===
--- clang/include/clang/Tooling/AllTUsExecution.h
+++ clang/include/clang/Tooling/AllTUsExecution.h
@@ -44,8 +44,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   using ToolExecutor::execute;
 
   llvm::Error


Index: clang/unittests/Tooling/ExecutionTest.cpp
===
--- clang/unittests/Tooling/ExecutionTest.cpp
+++ clang/unittests/Tooling/ExecutionTest.cpp
@@ -95,8 +95,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   llvm::Error
   execute(llvm::ArrayRef,
ArgumentsAdjuster>>) override {
Index: clang/include/clang/Tooling/StandaloneExecution.h
===
--- clang/include/clang/Tooling/StandaloneExecution.h
+++ clang/include/clang/Tooling/StandaloneExecution.h
@@ -52,8 +52,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   using ToolExecutor::execute;
 
   llvm::Error
Index: clang/include/clang/Tooling/Execution.h
===
--- clang/include/clang/Tooling/Execution.h
+++ clang/include/clang/Tooling/Execution.h
@@ -115,13 +115,6 @@
   /// Returns the name of a specific executor.
   virtual StringRef getExecutorName() const = 0;
 
-  /// Should return true iff executor runs all actions in a single process.
-  /// Clients can use this signal to find out if they can collect results
-  /// in-memory (e.g. to avoid serialization costs of using ToolResults).
-  /// The single-process executors can still run multiple threads, but all
-  /// executions are guaranteed to share the same memory.
-  virtual bool isSingleProcess() const = 0;
-
   /// Executes each action with a corresponding arguments adjuster.
   virtual llvm::Error
   execute(llvm::ArrayRef<
Index: clang/include/clang/Tooling/AllTUsExecution.h
===
--- clang/include/clang/Tooling/AllTUsExecution.h
+++ clang/include/clang/Tooling/AllTUsExecution.h
@@ -44,8 +44,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   using ToolExecutor::execute;
 
   llvm::Error
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r368832 - Removed ToolExecutor::isSingleProcess, it is not used by anything

2019-08-14 Thread Dmitri Gribenko via cfe-commits
Author: gribozavr
Date: Wed Aug 14 04:35:04 2019
New Revision: 368832

URL: http://llvm.org/viewvc/llvm-project?rev=368832&view=rev
Log:
Removed ToolExecutor::isSingleProcess, it is not used by anything

Subscribers: cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/include/clang/Tooling/AllTUsExecution.h
cfe/trunk/include/clang/Tooling/Execution.h
cfe/trunk/include/clang/Tooling/StandaloneExecution.h
cfe/trunk/unittests/Tooling/ExecutionTest.cpp

Modified: cfe/trunk/include/clang/Tooling/AllTUsExecution.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/AllTUsExecution.h?rev=368832&r1=368831&r2=368832&view=diff
==
--- cfe/trunk/include/clang/Tooling/AllTUsExecution.h (original)
+++ cfe/trunk/include/clang/Tooling/AllTUsExecution.h Wed Aug 14 04:35:04 2019
@@ -44,8 +44,6 @@ public:
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   using ToolExecutor::execute;
 
   llvm::Error

Modified: cfe/trunk/include/clang/Tooling/Execution.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Execution.h?rev=368832&r1=368831&r2=368832&view=diff
==
--- cfe/trunk/include/clang/Tooling/Execution.h (original)
+++ cfe/trunk/include/clang/Tooling/Execution.h Wed Aug 14 04:35:04 2019
@@ -115,13 +115,6 @@ public:
   /// Returns the name of a specific executor.
   virtual StringRef getExecutorName() const = 0;
 
-  /// Should return true iff executor runs all actions in a single process.
-  /// Clients can use this signal to find out if they can collect results
-  /// in-memory (e.g. to avoid serialization costs of using ToolResults).
-  /// The single-process executors can still run multiple threads, but all
-  /// executions are guaranteed to share the same memory.
-  virtual bool isSingleProcess() const = 0;
-
   /// Executes each action with a corresponding arguments adjuster.
   virtual llvm::Error
   execute(llvm::ArrayRef<

Modified: cfe/trunk/include/clang/Tooling/StandaloneExecution.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/StandaloneExecution.h?rev=368832&r1=368831&r2=368832&view=diff
==
--- cfe/trunk/include/clang/Tooling/StandaloneExecution.h (original)
+++ cfe/trunk/include/clang/Tooling/StandaloneExecution.h Wed Aug 14 04:35:04 
2019
@@ -52,8 +52,6 @@ public:
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   using ToolExecutor::execute;
 
   llvm::Error

Modified: cfe/trunk/unittests/Tooling/ExecutionTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Tooling/ExecutionTest.cpp?rev=368832&r1=368831&r2=368832&view=diff
==
--- cfe/trunk/unittests/Tooling/ExecutionTest.cpp (original)
+++ cfe/trunk/unittests/Tooling/ExecutionTest.cpp Wed Aug 14 04:35:04 2019
@@ -95,8 +95,6 @@ public:
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   llvm::Error
   execute(llvm::ArrayRef,
ArgumentsAdjuster>>) override {


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


[PATCH] D66212: Removed ToolExecutor::isSingleProcess, it is not used by anything

2019-08-14 Thread Dmitri Gribenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368832: Removed ToolExecutor::isSingleProcess, it is not 
used by anything (authored by gribozavr, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66212?vs=215080&id=215082#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66212

Files:
  cfe/trunk/include/clang/Tooling/AllTUsExecution.h
  cfe/trunk/include/clang/Tooling/Execution.h
  cfe/trunk/include/clang/Tooling/StandaloneExecution.h
  cfe/trunk/unittests/Tooling/ExecutionTest.cpp


Index: cfe/trunk/unittests/Tooling/ExecutionTest.cpp
===
--- cfe/trunk/unittests/Tooling/ExecutionTest.cpp
+++ cfe/trunk/unittests/Tooling/ExecutionTest.cpp
@@ -95,8 +95,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   llvm::Error
   execute(llvm::ArrayRef,
ArgumentsAdjuster>>) override {
Index: cfe/trunk/include/clang/Tooling/StandaloneExecution.h
===
--- cfe/trunk/include/clang/Tooling/StandaloneExecution.h
+++ cfe/trunk/include/clang/Tooling/StandaloneExecution.h
@@ -52,8 +52,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   using ToolExecutor::execute;
 
   llvm::Error
Index: cfe/trunk/include/clang/Tooling/Execution.h
===
--- cfe/trunk/include/clang/Tooling/Execution.h
+++ cfe/trunk/include/clang/Tooling/Execution.h
@@ -115,13 +115,6 @@
   /// Returns the name of a specific executor.
   virtual StringRef getExecutorName() const = 0;
 
-  /// Should return true iff executor runs all actions in a single process.
-  /// Clients can use this signal to find out if they can collect results
-  /// in-memory (e.g. to avoid serialization costs of using ToolResults).
-  /// The single-process executors can still run multiple threads, but all
-  /// executions are guaranteed to share the same memory.
-  virtual bool isSingleProcess() const = 0;
-
   /// Executes each action with a corresponding arguments adjuster.
   virtual llvm::Error
   execute(llvm::ArrayRef<
Index: cfe/trunk/include/clang/Tooling/AllTUsExecution.h
===
--- cfe/trunk/include/clang/Tooling/AllTUsExecution.h
+++ cfe/trunk/include/clang/Tooling/AllTUsExecution.h
@@ -44,8 +44,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   using ToolExecutor::execute;
 
   llvm::Error


Index: cfe/trunk/unittests/Tooling/ExecutionTest.cpp
===
--- cfe/trunk/unittests/Tooling/ExecutionTest.cpp
+++ cfe/trunk/unittests/Tooling/ExecutionTest.cpp
@@ -95,8 +95,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   llvm::Error
   execute(llvm::ArrayRef,
ArgumentsAdjuster>>) override {
Index: cfe/trunk/include/clang/Tooling/StandaloneExecution.h
===
--- cfe/trunk/include/clang/Tooling/StandaloneExecution.h
+++ cfe/trunk/include/clang/Tooling/StandaloneExecution.h
@@ -52,8 +52,6 @@
 
   StringRef getExecutorName() const override { return ExecutorName; }
 
-  bool isSingleProcess() const override { return true; }
-
   using ToolExecutor::execute;
 
   llvm::Error
Index: cfe/trunk/include/clang/Tooling/Execution.h
===
--- cfe/trunk/include/clang/Tooling/Execution.h
+++ cfe/trunk/include/clang/Tooling/Execution.h
@@ -115,13 +115,6 @@
   /// Returns the name of a specific executor.
   virtual StringRef getExecutorName() const = 0;
 
-  /// Should return true iff executor runs all actions in a single process.
-  /// Clients can use this signal to find out if they can collect results
-  /// in-memory (e.g. to avoid serialization costs of using ToolResults).
-  /// The single-process executors can still run multiple threads, but all
-  /// executions are guaranteed to share the same memory.
-  virtual bool isSingleProcess() const = 0;
-
   /// Executes each action with a corresponding arguments adjuster.
   virtual llvm::Error
   execute(llvm::ArrayRef<
Index: cfe/trunk/include/clang/Tooling/AllTUsExecution.h
===
--- cfe/trunk/include/clang/Tooling/AllTUsExecution.h
+++ cfe/trunk/include/clang/Tooling/AllTUsExecution.h
@@ -44,8 +44,6 @@
 
   StringRef getExecut

r368779 - [analyzer] Don't delete TaintConfig copy constructor

2019-08-14 Thread Alex Langford via cfe-commits
Author: xiaobai
Date: Tue Aug 13 18:09:07 2019
New Revision: 368779

URL: http://llvm.org/viewvc/llvm-project?rev=368779&view=rev
Log:
[analyzer] Don't delete TaintConfig copy constructor

Summary:
Explicitly deleting the copy constructor makes compiling the function
`ento::registerGenericTaintChecker` difficult with some compilers. When we
construct an `llvm::Optional`, the optional is constructed with a
const TaintConfig reference which it then uses to invoke the deleted TaintConfig
copy constructor.

I've observered this failing with clang 3.8 on Ubuntu 16.04.

Reviewers: compnerd, Szelethus, boga95, NoQ, alexshap

Subscribers: xazax.hun, baloghadamsoftware, szepet, a.sidorin, mikhail.ramalho, 
donat.nagy, dkrupp, Charusso, llvm-commits, cfe-commits

Tags: #clang

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp?rev=368779&r1=368778&r2=368779&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp Tue Aug 13 
18:09:07 2019
@@ -71,9 +71,9 @@ public:
 std::vector Sinks;
 
 TaintConfiguration() = default;
-TaintConfiguration(const TaintConfiguration &) = delete;
+TaintConfiguration(const TaintConfiguration &) = default;
 TaintConfiguration(TaintConfiguration &&) = default;
-TaintConfiguration &operator=(const TaintConfiguration &) = delete;
+TaintConfiguration &operator=(const TaintConfiguration &) = default;
 TaintConfiguration &operator=(TaintConfiguration &&) = default;
   };
 


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


[PATCH] D65744: [PR42707][OpenCL] Fix addr space deduction for auto

2019-08-14 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D65744#1627589 , @rjmccall wrote:

> I see.  Is the deduction rule recursive or something, where a pointer to 
> pointer is inferred to point to the same address space as the pointee?


It is recursive indeed and we currently deduce all pointees to generic AS.

> I still don't understand why pointers and references are handled differently 
> here, instead of having the rule be "don't infer if the type is opaquely 
> dependent or an `auto` placeholder".

Because we currently only infer pointers and references in TreeTransforms. 
Everything else is inferred earlier. That is mainly because we need some 
context info to infer in most of other cases and therefore it's not easy to do 
in TreeTransforms. There is some more information on this review: 
https://reviews.llvm.org/D64400 where the inference for pointers and references 
was added originally to TreeTransforms.


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

https://reviews.llvm.org/D65744



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


[PATCH] D66215: [clangd] Print qualifiers of out-of-line definitions in document outline

2019-08-14 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added a reviewer: hokein.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

To improve the UX around navigating and searching through the results.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66215

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp

Index: clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
+++ clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
@@ -19,7 +19,6 @@
 namespace {
 
 using ::testing::AllOf;
-using ::testing::AnyOf;
 using ::testing::ElementsAre;
 using ::testing::ElementsAreArray;
 using ::testing::Field;
@@ -414,21 +413,22 @@
AllOf(WithName("KInt"), WithKind(SymbolKind::Variable), Children()),
AllOf(WithName("kStr"), WithKind(SymbolKind::Variable), Children()),
AllOf(WithName("f1"), WithKind(SymbolKind::Function), Children()),
-   AllOf(WithName("foo"), WithKind(SymbolKind::Namespace),
- Children(
- AllOf(WithName("int32"), WithKind(SymbolKind::Class),
-   Children()),
- AllOf(WithName("int32_t"), WithKind(SymbolKind::Class),
-   Children()),
- AllOf(WithName("v1"), WithKind(SymbolKind::Variable),
-   Children()),
- AllOf(WithName("bar"), WithKind(SymbolKind::Namespace),
-   Children(AllOf(WithName("v2"),
-  WithKind(SymbolKind::Variable),
-  Children(,
- AllOf(WithName("baz"), WithKind(SymbolKind::Namespace),
-   Children()),
- AllOf(WithName("v2"), WithKind(SymbolKind::Namespace}));
+   AllOf(
+   WithName("foo"), WithKind(SymbolKind::Namespace),
+   Children(
+   AllOf(WithName("int32"), WithKind(SymbolKind::Class),
+ Children()),
+   AllOf(WithName("int32_t"), WithKind(SymbolKind::Class),
+ Children()),
+   AllOf(WithName("v1"), WithKind(SymbolKind::Variable),
+ Children()),
+   AllOf(WithName("bar"), WithKind(SymbolKind::Namespace),
+ Children(AllOf(WithName("v2"),
+WithKind(SymbolKind::Variable),
+Children(,
+   AllOf(WithName("baz"), WithKind(SymbolKind::Namespace),
+ Children()),
+   AllOf(WithName("v2"), WithKind(SymbolKind::Namespace}));
 }
 
 TEST_F(DocumentSymbolsTest, DeclarationDefinition) {
@@ -442,13 +442,14 @@
 )");
 
   addFile(FilePath, Main.code());
-  EXPECT_THAT(getSymbols(FilePath),
-  ElementsAre(AllOf(WithName("Foo"), WithKind(SymbolKind::Class),
-Children(AllOf(
-WithName("f"), WithKind(SymbolKind::Method),
-SymNameRange(Main.range("decl"),
-  AllOf(WithName("f"), WithKind(SymbolKind::Method),
-SymNameRange(Main.range("def");
+  EXPECT_THAT(
+  getSymbols(FilePath),
+  ElementsAre(
+  AllOf(WithName("Foo"), WithKind(SymbolKind::Class),
+Children(AllOf(WithName("f"), WithKind(SymbolKind::Method),
+   SymNameRange(Main.range("decl"),
+  AllOf(WithName("Foo::f"), WithKind(SymbolKind::Method),
+SymNameRange(Main.range("def");
 }
 
 TEST_F(DocumentSymbolsTest, ExternSymbol) {
@@ -684,5 +685,69 @@
   AllOf(WithName("Foo"), WithKind(SymbolKind::Class;
 }
 
+TEST_F(DocumentSymbolsTest, Qualifiers) {
+  addFile("foo.cpp", R"cpp(
+namespace foo { namespace bar {
+  struct Cls;
+
+  int func1();
+  int func2();
+  int func3();
+  int func4();
+}}
+
+struct foo::bar::Cls { };
+
+int foo::bar::func1() { return 10; }
+int ::foo::bar::func2() { return 20; }
+
+using namespace foo;
+int bar::func3() { return 30; }
+
+namespace alias = foo::bar;
+int ::alias::func4() { return 40; }
+  )cpp");
+
+  // All the qualifiers should be preserved exactly as written.
+  EXPECT_THAT(getSymbols("foo.cpp"),
+  UnorderedElementsAre(
+  WithName("foo"), WithName("foo::bar::Cls"),
+  WithName("foo::bar::func1"), WithName("::foo::bar::func2"),
+  WithName("using namespace foo"), WithName("bar::func3"),
+  WithName("alias"), WithName("::alias::func4")));
+}
+
+TES

[PATCH] D65856: [clangd] Added class for mapping TokenColorRules to their associated clangd TextMate scope

2019-08-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

thanks, looks good.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65856



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


[clang-tools-extra] r368834 - [clangd] Loading TokenColorRules as a class mapping the rules to their associated clangd TextMate scope index.

2019-08-14 Thread Johan Vikstrom via cfe-commits
Author: jvikstrom
Date: Wed Aug 14 05:11:58 2019
New Revision: 368834

URL: http://llvm.org/viewvc/llvm-project?rev=368834&view=rev
Log:
[clangd] Loading TokenColorRules as a class mapping the rules to their 
associated clangd TextMate scope index.

Summary: Loads a mapping of the clangd scope lookup table scopes to the most 
specific rule with the highest "precedence" on initialize. Preprocesses into a 
class so it's simple/fast to access when doing the actual coloring later.

Reviewers: hokein, ilya-biryukov

Subscribers: MaskRay, jkorous, arphaman, kadircet, cfe-commits

Tags: #clang

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

Modified:

clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts

clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Modified: 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts?rev=368834&r1=368833&r2=368834&view=diff
==
--- 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
 (original)
+++ 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
 Wed Aug 14 05:11:58 2019
@@ -47,6 +47,8 @@ export class SemanticHighlightingFeature
   // The TextMate scope lookup table. A token with scope index i has the scopes
   // on index i in the lookup table.
   scopeLookupTable: string[][];
+  // The rules for the current theme.
+  themeRuleMatcher: ThemeRuleMatcher;
   fillClientCapabilities(capabilities: vscodelc.ClientCapabilities) {
 // Extend the ClientCapabilities type and add semantic highlighting
 // capability to the object.
@@ -58,6 +60,12 @@ export class SemanticHighlightingFeature
 };
   }
 
+  async loadCurrentTheme() {
+this.themeRuleMatcher = new ThemeRuleMatcher(
+await loadTheme(vscode.workspace.getConfiguration('workbench')
+.get('colorTheme')));
+  }
+
   initialize(capabilities: vscodelc.ServerCapabilities,
  documentSelector: vscodelc.DocumentSelector|undefined) {
 // The semantic highlighting capability information is in the capabilities
@@ -68,6 +76,7 @@ export class SemanticHighlightingFeature
 if (!serverCapabilities.semanticHighlighting)
   return;
 this.scopeLookupTable = serverCapabilities.semanticHighlighting.scopes;
+this.loadCurrentTheme();
   }
 
   handleNotification(params: SemanticHighlightingParams) {}
@@ -101,6 +110,39 @@ interface TokenColorRule {
   foreground: string;
 }
 
+export class ThemeRuleMatcher {
+  // The rules for the theme.
+  private themeRules: TokenColorRule[];
+  // A cache for the getBestThemeRule function.
+  private bestRuleCache: Map = new Map();
+  constructor(rules: TokenColorRule[]) { this.themeRules = rules; }
+  // Returns the best rule for a scope.
+  getBestThemeRule(scope: string): TokenColorRule {
+if (this.bestRuleCache.has(scope))
+  return this.bestRuleCache.get(scope);
+let bestRule: TokenColorRule = {scope : '', foreground : ''};
+this.themeRules.forEach((rule) => {
+  // The best rule for a scope is the rule that is the longest prefix of 
the
+  // scope (unless a perfect match exists in which case the perfect match 
is
+  // the best). If a rule is not a prefix and we tried to match with 
longest
+  // common prefix instead variables would be highlighted as `less`
+  // variables when using Light+ (as variable.other would be matched 
against
+  // variable.other.less in this case). Doing common prefix matching also
+  // means we could match variable.cpp to variable.css if variable.css
+  // occurs before variable in themeRules.
+  // FIXME: This is not defined in the TextMate standard (it is explicitly
+  // undefined, https://macromates.com/manual/en/scope_selectors). Might
+  // want to rank some other way.
+  if (scope.startsWith(rule.scope) &&
+  rule.scope.length > bestRule.scope.length)
+// This rule matches and is more specific than the old rule.
+bestRule = rule;
+});
+this.bestRuleCache.set(scope, bestRule);
+return bestRule;
+  }
+}
+
 // Get all token color rules provided by the theme.
 function loadTheme(themeName: string): Promise {
   const extension =

Modified: 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts?rev=368834&r1=368833&r2=368834&view=diff
==
--- 
clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
 (original)
+++ 
clang-tools-extra/trunk/clangd/clients/clangd-vsc

[PATCH] D65856: [clangd] Added class for mapping TokenColorRules to their associated clangd TextMate scope

2019-08-14 Thread Johan Vikström via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368834: [clangd] Loading TokenColorRules as a class mapping 
the rules to their… (authored by jvikstrom, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D65856?vs=215065&id=215085#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65856

Files:
  
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Index: clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/trunk/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -1,13 +1,13 @@
 import * as assert from 'assert';
 import * as path from 'path';
 
-import * as TM from '../src/semantic-highlighting';
+import * as SM from '../src/semantic-highlighting';
 
 suite('SemanticHighlighting Tests', () => {
   test('Parses arrays of textmate themes.', async () => {
 const themePath =
 path.join(__dirname, '../../test/assets/includeTheme.jsonc');
-const scopeColorRules = await TM.parseThemeFile(themePath);
+const scopeColorRules = await SM.parseThemeFile(themePath);
 const getScopeRule = (scope: string) =>
 scopeColorRules.find((v) => v.scope === scope);
 assert.equal(scopeColorRules.length, 3);
@@ -33,6 +33,28 @@
   ]
 ];
 testCases.forEach((testCase, i) => assert.deepEqual(
-  TM.decodeTokens(testCase), expected[i]));
+  SM.decodeTokens(testCase), expected[i]));
+  });
+  test('ScopeRules overrides for more specific themes', () => {
+const rules = [
+  {scope : 'variable.other.css', foreground : '1'},
+  {scope : 'variable.other', foreground : '2'},
+  {scope : 'storage', foreground : '3'},
+  {scope : 'storage.static', foreground : '4'},
+  {scope : 'storage', foreground : '5'},
+  {scope : 'variable.other.parameter', foreground : '6'},
+];
+const tm = new SM.ThemeRuleMatcher(rules);
+assert.deepEqual(tm.getBestThemeRule('variable.other.cpp').scope,
+ 'variable.other');
+assert.deepEqual(tm.getBestThemeRule('storage.static').scope,
+ 'storage.static');
+assert.deepEqual(
+tm.getBestThemeRule('storage'),
+rules[2]); // Match the first element if there are duplicates.
+assert.deepEqual(tm.getBestThemeRule('variable.other.parameter').scope,
+ 'variable.other.parameter');
+assert.deepEqual(tm.getBestThemeRule('variable.other.parameter.cpp').scope,
+ 'variable.other.parameter');
   });
 });
Index: clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
===
--- clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -47,6 +47,8 @@
   // The TextMate scope lookup table. A token with scope index i has the scopes
   // on index i in the lookup table.
   scopeLookupTable: string[][];
+  // The rules for the current theme.
+  themeRuleMatcher: ThemeRuleMatcher;
   fillClientCapabilities(capabilities: vscodelc.ClientCapabilities) {
 // Extend the ClientCapabilities type and add semantic highlighting
 // capability to the object.
@@ -58,6 +60,12 @@
 };
   }
 
+  async loadCurrentTheme() {
+this.themeRuleMatcher = new ThemeRuleMatcher(
+await loadTheme(vscode.workspace.getConfiguration('workbench')
+.get('colorTheme')));
+  }
+
   initialize(capabilities: vscodelc.ServerCapabilities,
  documentSelector: vscodelc.DocumentSelector|undefined) {
 // The semantic highlighting capability information is in the capabilities
@@ -68,6 +76,7 @@
 if (!serverCapabilities.semanticHighlighting)
   return;
 this.scopeLookupTable = serverCapabilities.semanticHighlighting.scopes;
+this.loadCurrentTheme();
   }
 
   handleNotification(params: SemanticHighlightingParams) {}
@@ -101,6 +110,39 @@
   foreground: string;
 }
 
+export class ThemeRuleMatcher {
+  // The rules for the theme.
+  private themeRules: TokenColorRule[];
+  // A cache for the getBestThemeRule function.
+  private bestRuleCache: Map = new Map();
+  constructor(rules: TokenColorRule[]) { this.themeRules = rules; }
+  // Returns the best rule for a scope.
+  getBestThemeRule(scope: string): TokenColorRule {
+if (this.bestRuleCache.has(scope))
+  return this.bestRuleCache.get(scope);
+let bestRule:

[PATCH] D65456: [OpenCL] Add generic type handling for builtin functions

2019-08-14 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh added inline comments.



Comment at: clang/lib/Sema/OpenCLBuiltins.td:222
+// GenType definitions.
+def FGenTypeN   : GenericType<"FGenTypeN", TLFloat, VecAndScalar>;
+// Generate basic GenTypes.  Names are like: GenTypeFloatVecAndScalar.

Anastasia wrote:
> svenvh wrote:
> > Anastasia wrote:
> > > Would it make sense to use the same name scheme as below?
> > No, because FGenType is for all floating point types (half / float / 
> > double), as it uses the `TLFloat` type list.  `GenTypeFloatVecAndScalar` is 
> > for the float type (i.e. fp32) only.
> > 
> > I will update the comments of both definitions to clarify the difference.
> Ok, it could though be
> 
> `GenTypeAllFloats`
> 
> `GenTypeF`
> 
> Just that naming scheme feels a bit random right now.
The convention is a bit subtle perhaps, but it is not random.  For manual 
definitions that have multiple base types, the convention is 
typeinfo#GenType#vecinfo.  For generated definitions that have a single base 
type, the convention is GenType#typeinfo#vecinfo.  Having different conventions 
prevents the manual definitions from colliding with the generated ones.



Comment at: clang/lib/Sema/OpenCLBuiltins.td:124
+//
+// Some rules apply for combining GenericTypes in a declaration:
+//   1. The number of vector sizes must be equal or 1 for all gentypes in a

Anastasia wrote:
> What does combining mean?
Clarified.



Comment at: clang/lib/Sema/SemaLookup.cpp:680
+/// \param OpenCLBuiltin (in) The signature currently handled.
+/// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
+///type used as return type or as argument.

Anastasia wrote:
> svenvh wrote:
> > Anastasia wrote:
> > > What if both return and args use GenType, does `GenTypeMaxCnt` return max 
> > > of all? Or do they have to align?
> > They have to be compatible, otherwise we will hit the `llvm_reachable` 
> > below.
> Do we say anywhere they have to be compatible?
Yes, in OpenCLBuiltins.td near the definition of `GenericType`.



Comment at: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp:261
+// a signature to contain different GenTypes if these GenTypes represent
+// the same number of actual types.
+//

Anastasia wrote:
> I feel what you are checking is whether the vector sizes and types match but 
> not just that the number of types match...
"actual types" here means "final" non-generic types, such as half2, int, 
short4, etc.

Rephrased as "actual scalar or vector types", does that help?



Comment at: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp:265
+static void VerifySignature(const std::vector &Signature,
+const Record *B) {
+  unsigned GenTypeVecSizes = 1;

Anastasia wrote:
> Can we rename B to something meaningful or add a comment explaining it?
Renamed to `BuiltinRec`.



Comment at: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp:269
+
+  for (const auto *T : Signature) {
+if (T->isSubClassOf("GenericType")) {

Anastasia wrote:
> I feel there is some black magic here. :)
Added some comments.


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

https://reviews.llvm.org/D65456



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


[PATCH] D65456: [OpenCL] Add generic type handling for builtin functions

2019-08-14 Thread Sven van Haastregt via Phabricator via cfe-commits
svenvh updated this revision to Diff 215086.
svenvh marked 15 inline comments as done.
svenvh added a comment.

- Update comments as per review comments.
- Rename iterator `List` to `VecSizes` in OpenCLBuiltins.td
- Format GenericType definition.


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

https://reviews.llvm.org/D65456

Files:
  clang/lib/Sema/OpenCLBuiltins.td
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaOpenCL/fdeclare-opencl-builtins.cl
  clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp

Index: clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
===
--- clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
+++ clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
@@ -15,12 +15,39 @@
 //
 // For a successful lookup of e.g. the "cos" builtin, isOpenCLBuiltin("cos")
 // returns a pair .
-// OpenCLBuiltins[Index] to OpenCLBuiltins[Index + Len] contains the pairs
+// BuiltinTable[Index] to BuiltinTable[Index + Len] contains the pairs
 //  of the overloads of "cos".
-// OpenCLSignature[SigIndex] to OpenCLSignature[SigIndex + SigLen] contains
-// one of the signatures of "cos". The OpenCLSignature entry can be
-// referenced by other functions, i.e. "sin", since multiple OpenCL builtins
-// share the same signature.
+// SignatureTable[SigIndex] to SignatureTable[SigIndex + SigLen] contains
+// one of the signatures of "cos". The SignatureTable entry can be
+// referenced by other functions, e.g. "sin", to exploit the fact that
+// many OpenCL builtins share the same signature.
+//
+// The file generated by this TableGen emitter contains the following:
+//
+//  * Structs and enums to represent types and function signatures.
+//
+//  * OpenCLTypeStruct TypeTable[]
+//Type information for return types and arguments.
+//
+//  * unsigned SignatureTable[]
+//A list of types representing function signatures.  Each entry is an index
+//into the above TypeTable.  Multiple entries following each other form a
+//signature, where the first entry is the return type and subsequent
+//entries are the argument types.
+//
+//  * OpenCLBuiltinStruct BuiltinTable[]
+//Each entry represents one overload of an OpenCL builtin function and
+//consists of an index into the SignatureTable and the number of arguments.
+//
+//  * std::pair isOpenCLBuiltin(llvm::StringRef Name)
+//Find out whether a string matches an existing OpenCL builtin function
+//name and return an index into BuiltinTable and the number of overloads.
+//
+//  * void OCL2Qual(ASTContext&, OpenCLTypeStruct, std::vector&)
+//Convert an OpenCLTypeStruct type to a list of QualType instances.
+//One OpenCLTypeStruct can represent multiple types, primarily when using
+//GenTypes.
+//
 //===--===//
 
 #include "llvm/ADT/MapVector.h"
@@ -57,34 +84,47 @@
   // The output file.
   raw_ostream &OS;
 
-  // Emit the enums and structs.
+  // Helper function for BuiltinNameEmitter::EmitDeclarations.  Generate enum
+  // definitions in the Output string parameter, and save their Record instances
+  // in the List parameter.
+  // \param Types (in) List containing the Types to extract.
+  // \param TypesSeen (inout) List containing the Types already extracted.
+  // \param Output (out) String containing the enums to emit in the output file.
+  // \param List (out) List containing the extracted Types, except the Types in
+  //TypesSeen.
+  void ExtractEnumTypes(std::vector &Types,
+StringMap &TypesSeen, std::string &Output,
+std::vector &List);
+
+  // Emit the enum or struct used in the generated file.
+  // Populate the TypeList at the same time.
   void EmitDeclarations();
 
-  // Parse the Records generated by TableGen and populate OverloadInfo and
-  // SignatureSet.
+  // Parse the Records generated by TableGen to populate the SignaturesList,
+  // FctOverloadMap and TypeMap.
   void GetOverloads();
 
-  // Emit the OpenCLSignature table. This table contains all possible
-  // signatures, and is a struct OpenCLType. A signature is composed of a
-  // return type (mandatory), followed by zero or more argument types.
+  // Emit the TypeTable containing all types used by OpenCL builtins.
+  void EmitTypeTable();
+
+  // Emit the SignatureTable. This table contains all the possible signatures.
+  // A signature is stored as a list of indexes of the TypeTable.
+  // The first index references the return type (mandatory), and the followings
+  // reference its arguments.
   // E.g.:
-  // // 12
-  // { OCLT_uchar, 4, clang::LangAS::Default, false },
-  // { OCLT_float, 4, clang::LangAS::Default, false },
-  // This means that index 12 represents a signature
-  //   - returning a uchar vector of 4 elements, and
-  //   - taking as first argument a float vector of 4 elements.
+  // 15, 2, 15 can represent a function with the sig

r368836 - [analyzer][CFG] Don't track the condition of asserts

2019-08-14 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Wed Aug 14 05:20:08 2019
New Revision: 368836

URL: http://llvm.org/viewvc/llvm-project?rev=368836&view=rev
Log:
[analyzer][CFG] Don't track the condition of asserts

Well, what is says on the tin I guess!

Some more changes:

* Move isInevitablySinking() from BugReporter.cpp to CFGBlock's interface
* Rename and move findBlockForNode() from BugReporter.cpp to
ExplodedNode::getCFGBlock()

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

Modified:
cfe/trunk/include/clang/Analysis/CFG.h
cfe/trunk/lib/Analysis/CFG.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp

Modified: cfe/trunk/include/clang/Analysis/CFG.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Analysis/CFG.h?rev=368836&r1=368835&r2=368836&view=diff
==
--- cfe/trunk/include/clang/Analysis/CFG.h (original)
+++ cfe/trunk/include/clang/Analysis/CFG.h Wed Aug 14 05:20:08 2019
@@ -855,6 +855,10 @@ public:
   void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
   void setHasNoReturnElement() { HasNoReturnElement = true; }
 
+  /// Returns true if the block would eventually end with a sink (a noreturn
+  /// node).
+  bool isInevitablySinking() const;
+
   CFGTerminator getTerminator() const { return Terminator; }
 
   Stmt *getTerminatorStmt() { return Terminator.getStmt(); }

Modified: cfe/trunk/lib/Analysis/CFG.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Analysis/CFG.cpp?rev=368836&r1=368835&r2=368836&view=diff
==
--- cfe/trunk/lib/Analysis/CFG.cpp (original)
+++ cfe/trunk/lib/Analysis/CFG.cpp Wed Aug 14 05:20:08 2019
@@ -5652,6 +5652,71 @@ void CFGBlock::printTerminatorJson(raw_o
   Out << JsonFormat(TempOut.str(), AddQuotes);
 }
 
+// Returns true if by simply looking at the block, we can be sure that it
+// results in a sink during analysis. This is useful to know when the analysis
+// was interrupted, and we try to figure out if it would sink eventually.
+// There may be many more reasons why a sink would appear during analysis
+// (eg. checkers may generate sinks arbitrarily), but here we only consider
+// sinks that would be obvious by looking at the CFG.
+static bool isImmediateSinkBlock(const CFGBlock *Blk) {
+  if (Blk->hasNoReturnElement())
+return true;
+
+  // FIXME: Throw-expressions are currently generating sinks during analysis:
+  // they're not supported yet, and also often used for actually terminating
+  // the program. So we should treat them as sinks in this analysis as well,
+  // at least for now, but once we have better support for exceptions,
+  // we'd need to carefully handle the case when the throw is being
+  // immediately caught.
+  if (std::any_of(Blk->begin(), Blk->end(), [](const CFGElement &Elm) {
+if (Optional StmtElm = Elm.getAs())
+  if (isa(StmtElm->getStmt()))
+return true;
+return false;
+  }))
+return true;
+
+  return false;
+}
+
+bool CFGBlock::isInevitablySinking() const {
+  const CFG &Cfg = *getParent();
+
+  const CFGBlock *StartBlk = this;
+  if (isImmediateSinkBlock(StartBlk))
+return true;
+
+  llvm::SmallVector DFSWorkList;
+  llvm::SmallPtrSet Visited;
+
+  DFSWorkList.push_back(StartBlk);
+  while (!DFSWorkList.empty()) {
+const CFGBlock *Blk = DFSWorkList.back();
+DFSWorkList.pop_back();
+Visited.insert(Blk);
+
+// If at least one path reaches the CFG exit, it means that control is
+// returned to the caller. For now, say that we are not sure what
+// happens next. If necessary, this can be improved to analyze
+// the parent StackFrameContext's call site in a similar manner.
+if (Blk == &Cfg.getExit())
+  return false;
+
+for (const auto &Succ : Blk->succs()) {
+  if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
+if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
+  // If the block has reachable child blocks that aren't no-return,
+  // add them to the worklist.
+  DFSWorkList.push_back(SuccBlk);
+}
+  }
+}
+  }
+
+  // Nothing reached the exit. It can only mean one thing: there's no return.
+  return true;
+}
+
 const Expr *CFGBlock::getLastCondition() const {
   // If the terminator is a temporary dtor or a virtual base, etc, we can't
   // retrieve a meaningful condition, bail out.

Modified: cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp?rev=368836&r1=368835&r2=368836&view=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/BugReporter

[PATCH] D65287: [analyzer][CFG] Don't track the condition of asserts

2019-08-14 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368836: [analyzer][CFG] Don't track the condition of 
asserts (authored by Szelethus, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D65287?vs=214708&id=215088#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65287

Files:
  cfe/trunk/include/clang/Analysis/CFG.h
  cfe/trunk/lib/Analysis/CFG.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/BugReporter.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/ExplodedGraph.cpp
  cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp

Index: cfe/trunk/include/clang/Analysis/CFG.h
===
--- cfe/trunk/include/clang/Analysis/CFG.h
+++ cfe/trunk/include/clang/Analysis/CFG.h
@@ -855,6 +855,10 @@
   void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
   void setHasNoReturnElement() { HasNoReturnElement = true; }
 
+  /// Returns true if the block would eventually end with a sink (a noreturn
+  /// node).
+  bool isInevitablySinking() const;
+
   CFGTerminator getTerminator() const { return Terminator; }
 
   Stmt *getTerminatorStmt() { return Terminator.getStmt(); }
Index: cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
===
--- cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
+++ cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
@@ -458,3 +458,242 @@
 }
 
 } // end of namespace unimportant_write_before_collapse_point
+
+namespace dont_track_assertlike_conditions {
+
+extern void __assert_fail(__const char *__assertion, __const char *__file,
+  unsigned int __line, __const char *__function)
+__attribute__((__noreturn__));
+#define assert(expr) \
+  ((expr) ? (void)(0) : __assert_fail(#expr, __FILE__, __LINE__, __func__))
+
+int getInt();
+
+int cond1;
+
+void bar() {
+  cond1 = getInt();
+}
+
+void f(int flag) {
+  int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
+
+  flag = getInt();
+
+  bar();
+  assert(cond1); // expected-note{{Assuming 'cond1' is not equal to 0}}
+ // expected-note@-1{{'?' condition is true}}
+
+  if (flag) // expected-note{{'flag' is not equal to 0}}
+// expected-note@-1{{Taking true branch}}
+// debug-note@-2{{Tracking condition 'flag'}}
+*x = 5; // expected-warning{{Dereference of null pointer}}
+// expected-note@-1{{Dereference of null pointer}}
+}
+
+#undef assert
+} // end of namespace dont_track_assertlike_conditions
+
+namespace dont_track_assertlike_and_conditions {
+
+extern void __assert_fail(__const char *__assertion, __const char *__file,
+  unsigned int __line, __const char *__function)
+__attribute__((__noreturn__));
+#define assert(expr) \
+  ((expr) ? (void)(0) : __assert_fail(#expr, __FILE__, __LINE__, __func__))
+
+int getInt();
+
+int cond1;
+int cond2;
+
+void bar() {
+  cond1 = getInt();
+  cond2 = getInt();
+}
+
+void f(int flag) {
+  int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
+
+  flag = getInt();
+
+  bar();
+  assert(cond1 && cond2);
+  // expected-note@-1{{Assuming 'cond1' is not equal to 0}}
+  // expected-note@-2{{Assuming 'cond2' is not equal to 0}}
+  // expected-note@-3{{'?' condition is true}}
+  // expected-note@-4{{Left side of '&&' is true}}
+
+  if (flag) // expected-note{{'flag' is not equal to 0}}
+// expected-note@-1{{Taking true branch}}
+// debug-note@-2{{Tracking condition 'flag'}}
+*x = 5; // expected-warning{{Dereference of null pointer}}
+// expected-note@-1{{Dereference of null pointer}}
+}
+
+#undef assert
+} // end of namespace dont_track_assertlike_and_conditions
+
+namespace dont_track_assertlike_or_conditions {
+
+extern void __assert_fail(__const char *__assertion, __const char *__file,
+  unsigned int __line, __const char *__function)
+__attribute__((__noreturn__));
+#define assert(expr) \
+  ((expr) ? (void)(0) : __assert_fail(#expr, __FILE__, __LINE__, __func__))
+
+int getInt();
+
+int cond1;
+int cond2;
+
+void bar() {
+  cond1 = getInt();
+  cond2 = getInt();
+}
+
+void f(int flag) {
+  int *x = 0; // expected-note{{'x' initialized to a null pointer value}}
+
+  flag = getInt();
+
+  bar();
+  assert(cond1 || cond2);
+  // expected-note@-1{{Assuming 'cond1' is not equal to 0}}
+  // expected-note@-2{{Left side of '||' is true}}
+
+  if (flag) // expected-note{{'flag' is not equal to 0}}
+// expected-note@-1{{Taking true branch}}
+// debug-note@-2{{Tracking condition 'flag'}}
+*x = 5; // expected-warning{{Dereference of null pointer}}
+// 

[PATCH] D66211: [clangd][vscode] Surface the error when applying tweaks fails

2019-08-14 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Surfacing errors to the users in those cases is definitely something we need to 
do, thanks!
How do they look in practice? In particular, should we add more context 
information (either in clangd or in the VSCode extension) to those errors, now 
that we know they are shown to the users?
Something like `Failed to apply a fix: input range is invalid` vs `input range 
is invalid`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66211



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


[PATCH] D66215: [clangd] Print qualifiers of out-of-line definitions in document outline

2019-08-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/AST.cpp:106
+
+/// Returns a nested name specifier if \p ND refers to a an out-of-line
+/// definition.

 `if .. out-of-line definition` seems a bit confusing, I think here we just 
return a nested name specifier if it is written/present in the source code?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66215



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


[PATCH] D65526: [Clangd] Initial prototype version of ExtractFunction

2019-08-14 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah updated this revision to Diff 215089.
SureYeaah added a comment.

Removed unrelated changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65526

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -599,6 +599,93 @@
 R"cpp(const char * x = "test")cpp");
 }
 
+TWEAK_TEST(ExtractFunction);
+TEST_F(ExtractFunctionTest, PrepareFunctionTest) {
+  Header = R"cpp(
+#define F(BODY) void FFF() { BODY }
+  )cpp";
+  Context = Function;
+  EXPECT_AVAILABLE(R"cpp(
+[[int sum = 0;
+for(;;)
+  sum++;]]
+for(int i = 0; i < 5; i++) {
+  sum += i;
+}
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp([[int x;]])cpp");
+  // TODO: Add tests for macros after selectionTree works properly for macros.
+  // EXPECT_AVAILABLE(R"cpp( F (int x = 0; [[x = 1;]])cpp");
+  // FIXME: This should be unavailable since partially selected but
+  // selectionTree doesn't always work correctly for VarDecls.
+  //EXPECT_UNAVAILABLE(R"cpp(int [[x = 0]];)cpp");
+  EXPECT_UNAVAILABLE(R"cpp(
+int sum = 0;
+for(;;)
+  [[sum++;
+sum++;]]
+  )cpp");
+  // Expressions aren't extracted.
+  EXPECT_UNAVAILABLE(R"cpp(int x = 0; [[x++;]])cpp");
+  // FIXME: ExtractFunction should be unavailable inside loop construct
+  // initalizer/condition.
+  // EXPECT_UNAVAILABLE(R"cpp( for([[int i = 0; i < 5;]] i++) )cpp");
+}
+
+TEST_F(ExtractFunctionTest, PrepareMethodTest) {
+  EXPECT_UNAVAILABLE(R"cpp(
+class T {
+  void f() {
+[[int x;]]
+  }
+};
+  )cpp");
+}
+
+TEST_F(ExtractFunctionTest, ApplyTest) {
+  // We can extract from templated functions as long as no reference in the
+  // extraction depends on the template.
+  // Checks const qualifier and extraction parameters.
+  Header = R"cpp(
+  )cpp";
+  EXPECT_EQ(apply(
+R"cpp(
+struct FOO {
+  int x;
+};
+template
+void f(int a) {
+  int b = N; T t; const int c; FOO foo;
+  [[a += foo.x; b = c;]]
+})cpp"),
+R"cpp(
+struct FOO {
+  int x;
+};
+void extracted(int &a, int &b, const int &c, struct FOO &foo) {a += foo.x; b = c;}
+template
+void f(int a) {
+  int b = N; T t; const int c; FOO foo;
+  extracted(a, b, c, foo);
+})cpp");
+  auto ShouldFail = [&](llvm::StringRef Code) {
+EXPECT_THAT(apply(Code), StartsWith("fail:"));
+  };
+  // Don't extract because needs hoisting.
+  ShouldFail(R"cpp( void f() { [[int a = 5;]] a++;})cpp");
+  // Don't extract parameters that depend on template.
+  ShouldFail(R"cpp( template void f() { [[int a = N;]] })cpp");
+  ShouldFail(R"cpp( template void f() { [[T t;]] })cpp");
+  // Don't extract return
+  ShouldFail(R"cpp( int f() { int a = 5; [[return a;]]})cpp");
+  // Don't extract break and continue.
+  // FIXME: We should be able to extract this.
+  ShouldFail(R"cpp( int f() { [[for(;;) break;]]})cpp");
+  ShouldFail(R"cpp( int f() { for(;;) [[continue;]]})cpp");
+  // Don't extract when we need to make a function as a parameter.
+  ShouldFail(R"cpp( void f() { [[int a; f();]] } )cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -0,0 +1,536 @@
+//===--- ExtractFunction.cpp -*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#include "ClangdUnit.h"
+#include "Logger.h"
+#include "Selection.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "clang/Tooling/Refactoring/Extract/SourceExtraction.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/iterator_range.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+using Node = SelectionTree::Node;
+
+// Source is the part of code th

[clang-tools-extra] r368841 - [Clangd] NFC: Fixed comment typo

2019-08-14 Thread Shaurya Gupta via cfe-commits
Author: sureyeaah
Date: Wed Aug 14 05:40:09 2019
New Revision: 368841

URL: http://llvm.org/viewvc/llvm-project?rev=368841&view=rev
Log:
[Clangd] NFC: Fixed comment typo

Modified:
clang-tools-extra/trunk/clangd/unittests/TweakTesting.h

Modified: clang-tools-extra/trunk/clangd/unittests/TweakTesting.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/TweakTesting.h?rev=368841&r1=368840&r2=368841&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/TweakTesting.h (original)
+++ clang-tools-extra/trunk/clangd/unittests/TweakTesting.h Wed Aug 14 05:40:09 
2019
@@ -25,7 +25,7 @@ namespace clangd {
 //   Header = R"cpp(
 // namespace foo { template class X{}; }
 // using namespace foo;
-//   cpp)";
+//   )cpp";
 //   Context = Function;
 //   EXPECT_THAT(apply("[[auto]] X = foo();"),
 //   "foo X = foohttps://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66215: [clangd] Print qualifiers of out-of-line definitions in document outline

2019-08-14 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 215090.
ilya-biryukov marked 2 inline comments as done.
ilya-biryukov added a comment.

- Rename the helper function
- Remove mention of 'out-of-line definition' from a comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66215

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp

Index: clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
+++ clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp
@@ -19,7 +19,6 @@
 namespace {
 
 using ::testing::AllOf;
-using ::testing::AnyOf;
 using ::testing::ElementsAre;
 using ::testing::ElementsAreArray;
 using ::testing::Field;
@@ -414,21 +413,22 @@
AllOf(WithName("KInt"), WithKind(SymbolKind::Variable), Children()),
AllOf(WithName("kStr"), WithKind(SymbolKind::Variable), Children()),
AllOf(WithName("f1"), WithKind(SymbolKind::Function), Children()),
-   AllOf(WithName("foo"), WithKind(SymbolKind::Namespace),
- Children(
- AllOf(WithName("int32"), WithKind(SymbolKind::Class),
-   Children()),
- AllOf(WithName("int32_t"), WithKind(SymbolKind::Class),
-   Children()),
- AllOf(WithName("v1"), WithKind(SymbolKind::Variable),
-   Children()),
- AllOf(WithName("bar"), WithKind(SymbolKind::Namespace),
-   Children(AllOf(WithName("v2"),
-  WithKind(SymbolKind::Variable),
-  Children(,
- AllOf(WithName("baz"), WithKind(SymbolKind::Namespace),
-   Children()),
- AllOf(WithName("v2"), WithKind(SymbolKind::Namespace}));
+   AllOf(
+   WithName("foo"), WithKind(SymbolKind::Namespace),
+   Children(
+   AllOf(WithName("int32"), WithKind(SymbolKind::Class),
+ Children()),
+   AllOf(WithName("int32_t"), WithKind(SymbolKind::Class),
+ Children()),
+   AllOf(WithName("v1"), WithKind(SymbolKind::Variable),
+ Children()),
+   AllOf(WithName("bar"), WithKind(SymbolKind::Namespace),
+ Children(AllOf(WithName("v2"),
+WithKind(SymbolKind::Variable),
+Children(,
+   AllOf(WithName("baz"), WithKind(SymbolKind::Namespace),
+ Children()),
+   AllOf(WithName("v2"), WithKind(SymbolKind::Namespace}));
 }
 
 TEST_F(DocumentSymbolsTest, DeclarationDefinition) {
@@ -442,13 +442,14 @@
 )");
 
   addFile(FilePath, Main.code());
-  EXPECT_THAT(getSymbols(FilePath),
-  ElementsAre(AllOf(WithName("Foo"), WithKind(SymbolKind::Class),
-Children(AllOf(
-WithName("f"), WithKind(SymbolKind::Method),
-SymNameRange(Main.range("decl"),
-  AllOf(WithName("f"), WithKind(SymbolKind::Method),
-SymNameRange(Main.range("def");
+  EXPECT_THAT(
+  getSymbols(FilePath),
+  ElementsAre(
+  AllOf(WithName("Foo"), WithKind(SymbolKind::Class),
+Children(AllOf(WithName("f"), WithKind(SymbolKind::Method),
+   SymNameRange(Main.range("decl"),
+  AllOf(WithName("Foo::f"), WithKind(SymbolKind::Method),
+SymNameRange(Main.range("def");
 }
 
 TEST_F(DocumentSymbolsTest, ExternSymbol) {
@@ -684,5 +685,69 @@
   AllOf(WithName("Foo"), WithKind(SymbolKind::Class;
 }
 
+TEST_F(DocumentSymbolsTest, Qualifiers) {
+  addFile("foo.cpp", R"cpp(
+namespace foo { namespace bar {
+  struct Cls;
+
+  int func1();
+  int func2();
+  int func3();
+  int func4();
+}}
+
+struct foo::bar::Cls { };
+
+int foo::bar::func1() { return 10; }
+int ::foo::bar::func2() { return 20; }
+
+using namespace foo;
+int bar::func3() { return 30; }
+
+namespace alias = foo::bar;
+int ::alias::func4() { return 40; }
+  )cpp");
+
+  // All the qualifiers should be preserved exactly as written.
+  EXPECT_THAT(getSymbols("foo.cpp"),
+  UnorderedElementsAre(
+  WithName("foo"), WithName("foo::bar::Cls"),
+  WithName("foo::bar::func1"), WithName("::foo::bar::func2"),
+  WithName("using namespace foo"), WithName("bar::func3"),
+  WithName("alias

[PATCH] D66211: [clangd][vscode] Surface the error when applying tweaks fails

2019-08-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In D66211#1629112 , @ilya-biryukov 
wrote:

> How do they look in practice? In particular, should we add more context 
> information (either in clangd or in the VSCode extension) to those errors, 
> now that we know they are shown to the users?
>  Something like `Failed to apply a fix: input range is invalid` vs `input 
> range is invalid`.


I don't have a very strong preference on adding more context, the current 
messages seem good enough to me, something like:

- "edits were not applied: "
- "Could not expand type of lambda expression:"
- "Could not obtain range of the 'else' branch. Macros?"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66211



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


[PATCH] D66215: [clangd] Print qualifiers of out-of-line definitions in document outline

2019-08-14 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368842: [clangd] Print qualifiers of out-of-line definitions 
in document outline (authored by ibiryukov, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66215?vs=215090&id=215096#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66215

Files:
  clang-tools-extra/trunk/clangd/AST.cpp
  clang-tools-extra/trunk/clangd/unittests/FindSymbolsTests.cpp

Index: clang-tools-extra/trunk/clangd/AST.cpp
===
--- clang-tools-extra/trunk/clangd/AST.cpp
+++ clang-tools-extra/trunk/clangd/AST.cpp
@@ -12,6 +12,9 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/DeclarationName.h"
+#include "clang/AST/NestedNameSpecifier.h"
+#include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/TemplateBase.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -96,10 +99,27 @@
   return QName;
 }
 
+static bool isAnonymous(const DeclarationName &N) {
+  return N.isIdentifier() && !N.getAsIdentifierInfo();
+}
+
+/// Returns a nested name specifier of \p ND if it was present in the source,
+/// e.g.
+/// void ns::something::foo() -> returns 'ns::something'
+/// void foo() -> returns null
+static NestedNameSpecifier *getQualifier(const NamedDecl &ND) {
+  if (auto *V = llvm::dyn_cast(&ND))
+return V->getQualifier();
+  if (auto *T = llvm::dyn_cast(&ND))
+return T->getQualifier();
+  return nullptr;
+}
+
 std::string printName(const ASTContext &Ctx, const NamedDecl &ND) {
   std::string Name;
   llvm::raw_string_ostream Out(Name);
   PrintingPolicy PP(Ctx.getLangOpts());
+
   // Handle 'using namespace'. They all have the same name - .
   if (auto *UD = llvm::dyn_cast(&ND)) {
 Out << "using namespace ";
@@ -108,19 +128,27 @@
 UD->getNominatedNamespaceAsWritten()->printName(Out);
 return Out.str();
   }
-  ND.getDeclName().print(Out, PP);
-  if (!Out.str().empty()) {
-Out << printTemplateSpecializationArgs(ND);
-return Out.str();
+
+  if (isAnonymous(ND.getDeclName())) {
+// Come up with a presentation for an anonymous entity.
+if (isa(ND))
+  return "(anonymous namespace)";
+if (auto *Cls = llvm::dyn_cast(&ND))
+  return ("(anonymous " + Cls->getKindName() + ")").str();
+if (isa(ND))
+  return "(anonymous enum)";
+return "(anonymous)";
   }
-  // The name was empty, so present an anonymous entity.
-  if (isa(ND))
-return "(anonymous namespace)";
-  if (auto *Cls = llvm::dyn_cast(&ND))
-return ("(anonymous " + Cls->getKindName() + ")").str();
-  if (isa(ND))
-return "(anonymous enum)";
-  return "(anonymous)";
+
+  // Print nested name qualifier if it was written in the source code.
+  if (auto *Qualifier = getQualifier(ND))
+Qualifier->print(Out, PP);
+  // Print the name itself.
+  ND.getDeclName().print(Out, PP);
+  // Print template arguments.
+  Out << printTemplateSpecializationArgs(ND);
+
+  return Out.str();
 }
 
 std::string printTemplateSpecializationArgs(const NamedDecl &ND) {
Index: clang-tools-extra/trunk/clangd/unittests/FindSymbolsTests.cpp
===
--- clang-tools-extra/trunk/clangd/unittests/FindSymbolsTests.cpp
+++ clang-tools-extra/trunk/clangd/unittests/FindSymbolsTests.cpp
@@ -19,7 +19,6 @@
 namespace {
 
 using ::testing::AllOf;
-using ::testing::AnyOf;
 using ::testing::ElementsAre;
 using ::testing::ElementsAreArray;
 using ::testing::Field;
@@ -414,21 +413,22 @@
AllOf(WithName("KInt"), WithKind(SymbolKind::Variable), Children()),
AllOf(WithName("kStr"), WithKind(SymbolKind::Variable), Children()),
AllOf(WithName("f1"), WithKind(SymbolKind::Function), Children()),
-   AllOf(WithName("foo"), WithKind(SymbolKind::Namespace),
- Children(
- AllOf(WithName("int32"), WithKind(SymbolKind::Class),
-   Children()),
- AllOf(WithName("int32_t"), WithKind(SymbolKind::Class),
-   Children()),
- AllOf(WithName("v1"), WithKind(SymbolKind::Variable),
-   Children()),
- AllOf(WithName("bar"), WithKind(SymbolKind::Namespace),
-   Children(AllOf(WithName("v2"),
-  WithKind(SymbolKind::Variable),
-  Children(,
- AllOf(WithName("baz"), WithKind(SymbolKind::Namespace),
-   Children()),
- AllOf(WithName("v2"), WithKind(SymbolKind::Namespace}));
+   AllOf(
+   WithName("foo"), With

[clang-tools-extra] r368842 - [clangd] Print qualifiers of out-of-line definitions in document outline

2019-08-14 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Wed Aug 14 05:51:04 2019
New Revision: 368842

URL: http://llvm.org/viewvc/llvm-project?rev=368842&view=rev
Log:
[clangd] Print qualifiers of out-of-line definitions in document outline

Summary: To improve the UX around navigating and searching through the results.

Reviewers: hokein

Reviewed By: hokein

Subscribers: MaskRay, jkorous, arphaman, kadircet, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/AST.cpp
clang-tools-extra/trunk/clangd/unittests/FindSymbolsTests.cpp

Modified: clang-tools-extra/trunk/clangd/AST.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/AST.cpp?rev=368842&r1=368841&r2=368842&view=diff
==
--- clang-tools-extra/trunk/clangd/AST.cpp (original)
+++ clang-tools-extra/trunk/clangd/AST.cpp Wed Aug 14 05:51:04 2019
@@ -12,6 +12,9 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/DeclarationName.h"
+#include "clang/AST/NestedNameSpecifier.h"
+#include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/TemplateBase.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -96,10 +99,27 @@ std::string printQualifiedName(const Nam
   return QName;
 }
 
+static bool isAnonymous(const DeclarationName &N) {
+  return N.isIdentifier() && !N.getAsIdentifierInfo();
+}
+
+/// Returns a nested name specifier of \p ND if it was present in the source,
+/// e.g.
+/// void ns::something::foo() -> returns 'ns::something'
+/// void foo() -> returns null
+static NestedNameSpecifier *getQualifier(const NamedDecl &ND) {
+  if (auto *V = llvm::dyn_cast(&ND))
+return V->getQualifier();
+  if (auto *T = llvm::dyn_cast(&ND))
+return T->getQualifier();
+  return nullptr;
+}
+
 std::string printName(const ASTContext &Ctx, const NamedDecl &ND) {
   std::string Name;
   llvm::raw_string_ostream Out(Name);
   PrintingPolicy PP(Ctx.getLangOpts());
+
   // Handle 'using namespace'. They all have the same name - .
   if (auto *UD = llvm::dyn_cast(&ND)) {
 Out << "using namespace ";
@@ -108,19 +128,27 @@ std::string printName(const ASTContext &
 UD->getNominatedNamespaceAsWritten()->printName(Out);
 return Out.str();
   }
-  ND.getDeclName().print(Out, PP);
-  if (!Out.str().empty()) {
-Out << printTemplateSpecializationArgs(ND);
-return Out.str();
+
+  if (isAnonymous(ND.getDeclName())) {
+// Come up with a presentation for an anonymous entity.
+if (isa(ND))
+  return "(anonymous namespace)";
+if (auto *Cls = llvm::dyn_cast(&ND))
+  return ("(anonymous " + Cls->getKindName() + ")").str();
+if (isa(ND))
+  return "(anonymous enum)";
+return "(anonymous)";
   }
-  // The name was empty, so present an anonymous entity.
-  if (isa(ND))
-return "(anonymous namespace)";
-  if (auto *Cls = llvm::dyn_cast(&ND))
-return ("(anonymous " + Cls->getKindName() + ")").str();
-  if (isa(ND))
-return "(anonymous enum)";
-  return "(anonymous)";
+
+  // Print nested name qualifier if it was written in the source code.
+  if (auto *Qualifier = getQualifier(ND))
+Qualifier->print(Out, PP);
+  // Print the name itself.
+  ND.getDeclName().print(Out, PP);
+  // Print template arguments.
+  Out << printTemplateSpecializationArgs(ND);
+
+  return Out.str();
 }
 
 std::string printTemplateSpecializationArgs(const NamedDecl &ND) {

Modified: clang-tools-extra/trunk/clangd/unittests/FindSymbolsTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/unittests/FindSymbolsTests.cpp?rev=368842&r1=368841&r2=368842&view=diff
==
--- clang-tools-extra/trunk/clangd/unittests/FindSymbolsTests.cpp (original)
+++ clang-tools-extra/trunk/clangd/unittests/FindSymbolsTests.cpp Wed Aug 14 
05:51:04 2019
@@ -19,7 +19,6 @@ namespace clangd {
 namespace {
 
 using ::testing::AllOf;
-using ::testing::AnyOf;
 using ::testing::ElementsAre;
 using ::testing::ElementsAreArray;
 using ::testing::Field;
@@ -414,21 +413,22 @@ TEST_F(DocumentSymbolsTest, BasicSymbols
AllOf(WithName("KInt"), WithKind(SymbolKind::Variable), Children()),
AllOf(WithName("kStr"), WithKind(SymbolKind::Variable), Children()),
AllOf(WithName("f1"), WithKind(SymbolKind::Function), Children()),
-   AllOf(WithName("foo"), WithKind(SymbolKind::Namespace),
- Children(
- AllOf(WithName("int32"), WithKind(SymbolKind::Class),
-   Children()),
- AllOf(WithName("int32_t"), WithKind(SymbolKind::Class),
-   Children()),
- AllOf(WithName("v1"), WithKind(SymbolKind::Variable),
-   Children()),
- AllOf(WithName(

Re: r368561 - [OpenCL] Ignore parentheses for sampler initialization

2019-08-14 Thread Hans Wennborg via cfe-commits
Yes, merged in r368843.

Thanks,
Hans

On Tue, Aug 13, 2019 at 6:20 PM Anastasia Stulova
 wrote:
>
> Hi Hans,
>
>
> Can this be merged into the release 9.0 branch please?
>
>
> Thank you!
> Anastasia
>
> 
> From: cfe-commits  on behalf of Sven van 
> Haastregt via cfe-commits 
> Sent: 12 August 2019 13:44
> To: cfe-commits@lists.llvm.org 
> Subject: r368561 - [OpenCL] Ignore parentheses for sampler initialization
>
> Author: svenvh
> Date: Mon Aug 12 05:44:26 2019
> New Revision: 368561
>
> URL: http://llvm.org/viewvc/llvm-project?rev=368561&view=rev
> Log:
> [OpenCL] Ignore parentheses for sampler initialization
>
> The sampler handling logic in SemaInit.cpp would inadvertently treat
> parentheses around sampler arguments as an implicit cast, leading to
> an unreachable "can't implicitly cast lvalue to rvalue with
> this cast kind".  Fix by ignoring parentheses once we are in the
> sampler initializer case.
>
> Differential Revision: https://reviews.llvm.org/D66080
>
> Modified:
> cfe/trunk/lib/Sema/SemaInit.cpp
> cfe/trunk/test/SemaOpenCL/sampler_t.cl
>
> Modified: cfe/trunk/lib/Sema/SemaInit.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368561&r1=368560&r2=368561&view=diff
> ==
> --- cfe/trunk/lib/Sema/SemaInit.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaInit.cpp Mon Aug 12 05:44:26 2019
> @@ -8248,7 +8248,7 @@ ExprResult InitializationSequence::Perfo
>// argument passing.
>assert(Step->Type->isSamplerT() &&
>   "Sampler initialization on non-sampler type.");
> -  Expr *Init = CurInit.get();
> +  Expr *Init = CurInit.get()->IgnoreParens();
>QualType SourceType = Init->getType();
>// Case 1
>if (Entity.isParameterKind()) {
>
> Modified: cfe/trunk/test/SemaOpenCL/sampler_t.cl
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaOpenCL/sampler_t.cl?rev=368561&r1=368560&r2=368561&view=diff
> ==
> --- cfe/trunk/test/SemaOpenCL/sampler_t.cl (original)
> +++ cfe/trunk/test/SemaOpenCL/sampler_t.cl Mon Aug 12 05:44:26 2019
> @@ -10,6 +10,9 @@
>  #define CLK_FILTER_NEAREST  0x10
>  #define CLK_FILTER_LINEAR   0x20
>
> +typedef float float4 __attribute__((ext_vector_type(4)));
> +float4 read_imagef(read_only image1d_t, sampler_t, float);
> +
>  constant sampler_t glb_smp = CLK_ADDRESS_CLAMP_TO_EDGE | 
> CLK_NORMALIZED_COORDS_TRUE | CLK_FILTER_LINEAR;
>  constant sampler_t glb_smp2; // expected-error{{variable in constant address 
> space must be initialized}}
>  global sampler_t glb_smp3 = CLK_ADDRESS_CLAMP_TO_EDGE | 
> CLK_NORMALIZED_COORDS_TRUE | CLK_FILTER_NEAREST; // expected-error{{sampler 
> type cannot be used with the __local and __global address space qualifiers}} 
> expected-error {{global sampler requires a const or constant address space 
> qualifier}}
> @@ -74,3 +77,7 @@ void bar() {
>foo(smp1+1); //expected-error{{invalid operands to binary expression 
> ('sampler_t' and 'int')}}
>  }
>
> +void smp_args(read_only image1d_t image) {
> +  // Test that parentheses around sampler arguments are ignored.
> +  float4 res = read_imagef(image, (glb_smp10), 0.0f);
> +}
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
> IMPORTANT NOTICE: The contents of this email and any attachments are 
> confidential and may also be privileged. If you are not the intended 
> recipient, please notify the sender immediately and do not disclose the 
> contents to any other person, use it for any purpose, or store or copy the 
> information in any medium. Thank you.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r368552 - [OpenCL] Fix lang mode predefined macros for C++ mode.

2019-08-14 Thread Hans Wennborg via cfe-commits
Merged in r368844.

Thanks,
Hans

On Tue, Aug 13, 2019 at 6:21 PM Anastasia Stulova
 wrote:
>
> Hi Hans,
>
>
> Can this be merged into the release 9.0 branch please?
>
>
> Thank you!
> Anastasia
>
>
> 
> From: cfe-commits  on behalf of Anastasia 
> Stulova via cfe-commits 
> Sent: 12 August 2019 11:44
> To: cfe-commits@lists.llvm.org 
> Subject: r368552 - [OpenCL] Fix lang mode predefined macros for C++ mode.
>
> Author: stulova
> Date: Mon Aug 12 03:44:07 2019
> New Revision: 368552
>
> URL: http://llvm.org/viewvc/llvm-project?rev=368552&view=rev
> Log:
> [OpenCL] Fix lang mode predefined macros for C++ mode.
>
> In C++ mode we should only avoid adding __OPENCL_C_VERSION__,
> all other predefined macros about the language mode are still
> valid.
>
> This change also fixes the language version check in the
> headers accordingly.
>
> Differential Revision: https://reviews.llvm.org/D65941
>
>
> Modified:
> cfe/trunk/lib/Frontend/InitPreprocessor.cpp
> cfe/trunk/lib/Headers/opencl-c-base.h
> cfe/trunk/lib/Headers/opencl-c.h
>
> Modified: cfe/trunk/lib/Frontend/InitPreprocessor.cpp
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Frontend/InitPreprocessor.cpp?rev=368552&r1=368551&r2=368552&view=diff
> ==
> --- cfe/trunk/lib/Frontend/InitPreprocessor.cpp (original)
> +++ cfe/trunk/lib/Frontend/InitPreprocessor.cpp Mon Aug 12 03:44:07 2019
> @@ -437,17 +437,17 @@ static void InitializeStandardPredefined
>default:
>  llvm_unreachable("Unsupported OpenCL version");
>}
> -  Builder.defineMacro("CL_VERSION_1_0", "100");
> -  Builder.defineMacro("CL_VERSION_1_1", "110");
> -  Builder.defineMacro("CL_VERSION_1_2", "120");
> -  Builder.defineMacro("CL_VERSION_2_0", "200");
> +}
> +Builder.defineMacro("CL_VERSION_1_0", "100");
> +Builder.defineMacro("CL_VERSION_1_1", "110");
> +Builder.defineMacro("CL_VERSION_1_2", "120");
> +Builder.defineMacro("CL_VERSION_2_0", "200");
>
> -  if (TI.isLittleEndian())
> -Builder.defineMacro("__ENDIAN_LITTLE__");
> +if (TI.isLittleEndian())
> +  Builder.defineMacro("__ENDIAN_LITTLE__");
>
> -  if (LangOpts.FastRelaxedMath)
> -Builder.defineMacro("__FAST_RELAXED_MATH__");
> -}
> +if (LangOpts.FastRelaxedMath)
> +  Builder.defineMacro("__FAST_RELAXED_MATH__");
>}
>// Not "standard" per se, but available even with the -undef flag.
>if (LangOpts.AsmPreprocessor)
>
> Modified: cfe/trunk/lib/Headers/opencl-c-base.h
> URL: 
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/opencl-c-base.h?rev=368552&r1=368551&r2=368552&view=diff
> ==
> --- cfe/trunk/lib/Headers/opencl-c-base.h (original)
> +++ cfe/trunk/lib/Headers/opencl-c-base.h Mon Aug 12 03:44:07 2019
> @@ -126,7 +126,7 @@ typedef double double8 __attribute__((ex
>  typedef double double16 __attribute__((ext_vector_type(16)));
>  #endif
>
> -#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
> +#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
> CL_VERSION_2_0)
>  #define NULL ((void*)0)
>  #endif
>
> @@ -276,7 +276,7 @@ typedef uint cl_mem_fence_flags;
>   */
>  #define CLK_GLOBAL_MEM_FENCE   0x02
>
> -#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
> +#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
> CL_VERSION_2_0)
>
>  typedef enum memory_scope {
>memory_scope_work_item = __OPENCL_MEMORY_SCOPE_WORK_ITEM,
> @@ -288,9 +288,6 @@ typedef enum memory_scope {
>  #endif
>  } memory_scope;
>
> -#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0
> -
> -#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
>  /**
>   * Queue a memory fence to ensure correct ordering of memory
>   * operations between work-items of a work-group to
> @@ -313,7 +310,7 @@ typedef enum memory_order
>memory_order_seq_cst = __ATOMIC_SEQ_CST
>  } memory_order;
>
> -#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0
> +#endif // defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
> CL_VERSION_2_0)
>
>  // OpenCL v1.1 s6.11.3, v1.2 s6.12.14, v2.0 s6.13.14 - Image Read and Write 
> Functions
>
> @@ -389,14 +386,10 @@ typedef enum memory_order
>  #endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0
>
>  // OpenCL v2.0 s6.13.16 - Pipe Functions
> -#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
> +#if defined(__OPENCL_CPP_VERSION__) || (__OPENCL_C_VERSION__ >= 
> CL_VERSION_2_0)
>  #define CLK_NULL_RESERVE_ID (__builtin_astype(((void*)(__SIZE_MAX__)), 
> reserve_id_t))
> -#endif //__OPENCL_C_VERSION__ >= CL_VERSION_2_0
> -
>
>  // OpenCL v2.0 s6.13.17 - Enqueue Kernels
> -#if __OPENCL_C_VERSION__ >= CL_VERSION_2_0
> -
>  #define CL_COMPLETE 0x0
>  #define CL_RUNNING  0x1
>  #define CL_SUBMITTED0x2
> @@ -435,7 +428,7 @@ typedef struct {
>size

[PATCH] D66211: [clangd][vscode] Surface the error when applying tweaks fails

2019-08-14 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.
This revision is now accepted and ready to land.

Thanks for providing examples of error messages, also agree they look fine.
If we find bad error messages later, we could revisit the presentation strategy.
LGTM




Comment at: clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts:109
+// Keep the default behavior.
+if (error instanceof vscodelc.ResponseError &&
+error.code === vscodelc.ErrorCodes.RequestCancelled)

Is this how default implementation behaves? Is there a way to call into it 
instead of re-implementing?
If so, it would be nice to do so. If not, I'm also ok if we keep it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66211



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


[PATCH] D65526: [Clangd] Initial prototype version of ExtractFunction

2019-08-14 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah updated this revision to Diff 215098.
SureYeaah added a comment.

Removed debug info


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65526

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -599,6 +599,97 @@
 R"cpp(const char * x = "test")cpp");
 }
 
+TWEAK_TEST(ExtractFunction);
+TEST_F(ExtractFunctionTest, PrepareFunctionTest) {
+  Header = R"cpp(
+#define F(BODY) void FFF() { BODY }
+  )cpp";
+  Context = Function;
+  EXPECT_AVAILABLE(R"cpp(
+[[int sum = 0;
+for(;;)
+  sum++;]]
+for(int i = 0; i < 5; i++) {
+  sum += i;
+}
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp([[int x;]])cpp");
+  // TODO: Add tests for macros after selectionTree works properly for macros.
+  // EXPECT_AVAILABLE(R"cpp( F (int x = 0; [[x = 1;]])cpp");
+  // FIXME: This should be unavailable since partially selected but
+  // selectionTree doesn't always work correctly for VarDecls.
+  //EXPECT_UNAVAILABLE(R"cpp(int [[x = 0]];)cpp");
+  EXPECT_UNAVAILABLE(R"cpp(
+int sum = 0;
+for(;;)
+  [[sum++;
+sum++;]]
+  )cpp");
+  // Expressions aren't extracted.
+  EXPECT_UNAVAILABLE(R"cpp(int x = 0; [[x++;]])cpp");
+  // FIXME: ExtractFunction should be unavailable inside loop construct
+  // initalizer/condition.
+  // EXPECT_UNAVAILABLE(R"cpp( for([[int i = 0; i < 5;]] i++) )cpp");
+}
+
+TEST_F(ExtractFunctionTest, PrepareMethodTest) {
+  EXPECT_UNAVAILABLE(R"cpp(
+class T {
+  void f() {
+[[int x;]]
+  }
+};
+  )cpp");
+}
+
+TEST_F(ExtractFunctionTest, ApplyTest) {
+  // We can extract from templated functions as long as no reference in the
+  // extraction depends on the template.
+  // Checks const qualifier and extraction parameters.
+  Header = R"cpp(
+  )cpp";
+  EXPECT_EQ(apply(
+R"cpp(
+struct FOO {
+  int x;
+};
+template
+void f(int a) {
+  int b = N; T t; const int c; FOO foo;
+  int *ptr = &a;
+  [[a += foo.x; b = c; *ptr++;]]
+})cpp"),
+R"cpp(
+struct FOO {
+  int x;
+};
+void extracted(int &a, int &b, const int &c, struct FOO &foo, int * &ptr) {
+a += foo.x; b = c; *ptr++;
+}
+template
+void f(int a) {
+  int b = N; T t; const int c; FOO foo;
+  int *ptr = &a;
+  extracted(a, b, c, foo, ptr);
+})cpp");
+  auto ShouldFail = [&](llvm::StringRef Code) {
+EXPECT_THAT(apply(Code), StartsWith("fail:"));
+  };
+  // Don't extract because needs hoisting.
+  ShouldFail(R"cpp( void f() { [[int a = 5;]] a++;})cpp");
+  // Don't extract parameters that depend on template.
+  ShouldFail(R"cpp( template void f() { [[int a = N;]] })cpp");
+  ShouldFail(R"cpp( template void f() { [[T t;]] })cpp");
+  // Don't extract return
+  ShouldFail(R"cpp( int f() { int a = 5; [[return a;]]})cpp");
+  // Don't extract break and continue.
+  // FIXME: We should be able to extract this.
+  ShouldFail(R"cpp( int f() { [[for(;;) break;]]})cpp");
+  ShouldFail(R"cpp( int f() { for(;;) [[continue;]]})cpp");
+  // Don't extract when we need to make a function as a parameter.
+  ShouldFail(R"cpp( void f() { [[int a; f();]] } )cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -0,0 +1,534 @@
+//===--- ExtractFunction.cpp -*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#include "ClangdUnit.h"
+#include "Logger.h"
+#include "Selection.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "clang/Tooling/Refactoring/Extract/SourceExtraction.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/iterator_range.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+
+usi

[PATCH] D66058: [NFC][clang] Move much of the argument handling code from Driver::BuildActions to Driver::handleArguments.

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

LGTM!


Repository:
  rC Clang

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

https://reviews.llvm.org/D66058



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


[PATCH] D66018: [ARM] Take into account -mcpu and -mfpu options while handling 'crypto' feature

2019-08-14 Thread Diogo N. Sampaio via Phabricator via cfe-commits
dnsampaio added inline comments.



Comment at: lib/Driver/ToolChains/Arch/ARM.cpp:482-486
+  llvm::ARM::ArchKind ArchKind =
+  !ArchName.empty()
+  ? llvm::ARM::parseArch(arm::getARMArch(ArchName, Triple))
+  : llvm::ARM::parseCPUArch(
+arm::getARMTargetCPU(CPUName, ArchName, Triple));

Could just use `llvm::ARM::ArchKind arm::getLLVMArchKindForARM(StringRef CPU, 
StringRef Arch,  const llvm::Triple &Triple)` ?


Repository:
  rC Clang

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

https://reviews.llvm.org/D66018



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


[PATCH] D65182: [analyzer] Add fix-it hint support.

2019-08-14 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added subscribers: gribozavr, aaron.ballman, alexfh.
Szelethus added a comment.

Hmm, why the need for checker options? Why not have them by default? If fixits 
are an experimental feature, maybe we should have a global `enable-fixits` 
config maybe. But I don't insist :)

Now that we proposed that clang-tidy should also use the BugReporter, maybe we 
should let some clang-tidy folks chip in on this.

In any case, a direction is set and looks great.




Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h:879
 
+  ArrayRef getFixits() const { return Fixits; }
+

Hmm, will this return an immutable container? If not, can we make it so?



Comment at: clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp:743
+assert(!Hint.isNull());
+// FIXME: Add support for InsertFromRange and BeforePreviousInsertion.
+o << "   \n";

Shouldn't we assert this?



Comment at: clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp:84
 namespace {
 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
   DiagnosticsEngine &Diag;

Oh my god. This must be a runner up for "Worst class name in the Clang Static 
Analyzer", and might even all the trophies home. I wanted to make a joke about 
honorable mentions, but nothing compares :^)



Comment at: clang/test/Analysis/objc-arc.m:1
-// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10 
-analyzer-checker=core,osx.cocoa.RetainCount,deadcode -verify -fblocks 
-analyzer-opt-analyze-nested-blocks -fobjc-arc 
-analyzer-output=plist-multi-file -o %t.plist %s
+// RUN: %clang_analyze_cc1 -triple x86_64-apple-darwin10 
-analyzer-checker=core,osx.cocoa.RetainCount,deadcode -verify -fblocks 
-analyzer-opt-analyze-nested-blocks -fobjc-arc 
-analyzer-output=plist-multi-file -analyzer-config 
deadcode.DeadStores:ShowFixIts=true -o %t.plist %s
 // RUN: %normalize_plist <%t.plist | diff -ub 
%S/Inputs/expected-plists/objc-arc.m.plist -

Just thinking aloud, but maybe it'd be time to create a `RUN:` line formatter 
for test files, WDYT?


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

https://reviews.llvm.org/D65182



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


[PATCH] D66211: [clangd][vscode] Surface the error when applying tweaks fails

2019-08-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 215107.
hokein marked an inline comment as done.
hokein added a comment.

avoid re-implementing of the method.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66211

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts


Index: clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
@@ -47,6 +47,20 @@
   dispose() { this.statusBarItem.dispose(); }
 }
 
+class ClangdLanguageClient extends vscodelc.LanguageClient {
+  // Override the default implementation for failed requests. The default
+  // behavior is just to log failures in the output panel, however output panel
+  // is designed for extension debugging purpose, normal users will not open 
it,
+  // thus when the failure occurs, normal users doesn't know that.
+  logFailedRequest(rpcReply: vscodelc.RPCMessageType, error: any) {
+if (error instanceof vscodelc.ResponseError &&
+rpcReply.method === "workspace/executeCommand")
+  vscode.window.showErrorMessage(error.message);
+// Call default implementation.
+super.logFailedRequest(rpcReply, error);
+  }
+}
+
 /**
  *  this method is called when your extension is activate
  *  your extension is activated the very first time the command is executed
@@ -89,8 +103,8 @@
 revealOutputChannelOn: vscodelc.RevealOutputChannelOn.Never
 };
 
-  const clangdClient = new vscodelc.LanguageClient(
-  'Clang Language Server', serverOptions, clientOptions);
+  const clangdClient = new ClangdLanguageClient('Clang Language Server',
+serverOptions, clientOptions);
   console.log('Clang Language Server is now active!');
   context.subscriptions.push(clangdClient.start());
   context.subscriptions.push(vscode.commands.registerCommand(


Index: clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts
@@ -47,6 +47,20 @@
   dispose() { this.statusBarItem.dispose(); }
 }
 
+class ClangdLanguageClient extends vscodelc.LanguageClient {
+  // Override the default implementation for failed requests. The default
+  // behavior is just to log failures in the output panel, however output panel
+  // is designed for extension debugging purpose, normal users will not open it,
+  // thus when the failure occurs, normal users doesn't know that.
+  logFailedRequest(rpcReply: vscodelc.RPCMessageType, error: any) {
+if (error instanceof vscodelc.ResponseError &&
+rpcReply.method === "workspace/executeCommand")
+  vscode.window.showErrorMessage(error.message);
+// Call default implementation.
+super.logFailedRequest(rpcReply, error);
+  }
+}
+
 /**
  *  this method is called when your extension is activate
  *  your extension is activated the very first time the command is executed
@@ -89,8 +103,8 @@
 revealOutputChannelOn: vscodelc.RevealOutputChannelOn.Never
 };
 
-  const clangdClient = new vscodelc.LanguageClient(
-  'Clang Language Server', serverOptions, clientOptions);
+  const clangdClient = new ClangdLanguageClient('Clang Language Server',
+serverOptions, clientOptions);
   console.log('Clang Language Server is now active!');
   context.subscriptions.push(clangdClient.start());
   context.subscriptions.push(vscode.commands.registerCommand(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66211: [clangd][vscode] Surface the error when applying tweaks fails

2019-08-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/clangd/clients/clangd-vscode/src/extension.ts:109
+// Keep the default behavior.
+if (error instanceof vscodelc.ResponseError &&
+error.code === vscodelc.ErrorCodes.RequestCancelled)

ilya-biryukov wrote:
> Is this how default implementation behaves? Is there a way to call into it 
> instead of re-implementing?
> If so, it would be nice to do so. If not, I'm also ok if we keep it.
manage to figure out a way to do it. We have to define a subclass of 
LanguageClient, and override logFailedRequest. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66211



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


[PATCH] D64418: [Docs][OpenCL] Documentation of C++ for OpenCL mode

2019-08-14 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia updated this revision to Diff 215106.
Anastasia marked 26 inline comments as done.
Anastasia added a comment.

Addressed various comments from Kevin.


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

https://reviews.llvm.org/D64418

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

Index: docs/UsersManual.rst
===
--- docs/UsersManual.rst
+++ docs/UsersManual.rst
@@ -2397,7 +2397,8 @@
 This will produce a generic test.bc file that can be used in vendor toolchains
 to perform machine code generation.
 
-Clang currently supports OpenCL C language standards up to v2.0.
+Clang currently supports OpenCL C language standards up to v2.0. Starting from
+Clang 9 a C++ mode is available for OpenCL (see :ref:`C++ for OpenCL `).
 
 OpenCL Specific Options
 ---
@@ -2756,6 +2757,45 @@
   enqueue query functions from `section 6.13.17.5
   `_.
 
+.. _opencl_cpp:
+
+C++ for OpenCL
+--
+
+Starting from Clang9 kernel code can contain C++17 features: classes, templates,
+function overloading, type deduction, etc. Please note that this is not an
+implementation of `OpenCL C++
+`_ and
+there is no plan to support it in clang in any new releases in the near future.
+
+There are only a few restrictions on allowed C++ features. For detailed information
+please refer to documentation on Extensions (:doc:`LanguageExtensions`).
+
+Since C++ features are to be used on top of OpenCL C functionality, all existing
+restrictions from OpenCL C v2.0 will inherently apply. All OpenCL C builtin types
+and function libraries are supported and can be used in the new mode.
+
+To enable the new mode pass the following command line option when compiling ``.cl``
+file ``-cl-std=clc++``, ``-cl-std=CLC++``, ``-std=clc++`` or ``-std=CLC++``.
+
+   .. code-block:: c++
+
+ template T add( T x, T y )
+ {
+   return x + y;
+ }
+
+ __kernel void test( __global float* a, __global float* b)
+ {
+   auto index = get_global_id(0);
+   a[index] = add(b[index], b[index+1]);
+ }
+
+
+   .. code-block:: console
+
+ clang -cl-std=clc++ test.cl
+
 .. _target_features:
 
 Target-Specific Features and Limitations
Index: docs/LanguageExtensions.rst
===
--- docs/LanguageExtensions.rst
+++ docs/LanguageExtensions.rst
@@ -324,6 +324,8 @@
   ...
   #endif
 
+.. _languageextensions-builtin-macros:
+
 Builtin Macros
 ==
 
@@ -1516,6 +1518,284 @@
 Query the presence of this new mangling with
 ``__has_feature(objc_protocol_qualifier_mangling)``.
 
+
+OpenCL Features
+===
+
+C++ for OpenCL
+--
+
+This functionality is built on top of OpenCL C v2.0 and C++17 enabling most of
+regular C++ features in OpenCL kernel code. Most functionality from OpenCL C
+is inherited. This section describes minor differences to OpenCL C and any
+limitations related to C++ support as well as interactions between OpenCL and
+C++ features that are not documented elsewhere.
+
+Restrictions to C++17
+^
+
+The following features are not supported:
+
+- Virtual functions
+- Exceptions
+- ``dynamic_cast`` operator
+- Non-placement ``new``/``delete`` operators
+- Standard C++ libraries. Currently there is no solution for alternative C++
+  libraries provided. Future release will feature library support.
+
+
+Interplay of OpenCL and C++ features
+
+
+Address space behavior
+""
+
+Address spaces are part of the type qualifiers; many rules are just inherited
+from the qualifier behavior documented in OpenCL C v2.0 s6.5 and Embedded C
+extension ISO/IEC JTC1 SC22 WG14 N1021 s3.1. Note that since the address space
+behavior in C++ is not documented formally, Clang extends existing concept
+from C and OpenCL. For example conversion rules are extended from qualification
+conversion but the compatibility is determined using notation of sets and
+overlapping of address spaces from Embedded C (ISO/IEC JTC1 SC22 WG14 N1021
+s3.1.3). For OpenCL it means that implicit conversions are allowed from
+named address space except for ``__constant`` to ``__generic`` address space
+that is a superset of all others except for ``__constant`` (OpenCL C v2.0
+s6.5.5). Reverse conversion is only allowed explicitly.  ``__constant``
+address space does not overlap with any other and therefore no valid conversion
+between ``__constant`` and other address spaces exists. Most of the rules
+follow this logic.
+
+**Casts**
+
+C style cast will follow OpenCL C v2.0 rules (s6.5.5). All cast operators will
+permit conversion to ``__generic`` implicitly. However converting from
+``__generic`` to named address spaces can only be done using ``addrspace_cast``.
+No

r368850 - [Tooling] Added DeclStmtClass to ExtractionSemicolonPolicy

2019-08-14 Thread Shaurya Gupta via cfe-commits
Author: sureyeaah
Date: Wed Aug 14 06:37:39 2019
New Revision: 368850

URL: http://llvm.org/viewvc/llvm-project?rev=368850&view=rev
Log:
[Tooling] Added DeclStmtClass to ExtractionSemicolonPolicy

Since the DeclStmt range includes the semicolon, it doesn't need a
semicolon at the end during extraction

Modified:
cfe/trunk/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp
cfe/trunk/test/Refactor/Extract/ExtractionSemicolonPolicy.cpp

Modified: cfe/trunk/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp?rev=368850&r1=368849&r2=368850&view=diff
==
--- cfe/trunk/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp (original)
+++ cfe/trunk/lib/Tooling/Refactoring/Extract/SourceExtraction.cpp Wed Aug 14 
06:37:39 2019
@@ -45,6 +45,7 @@ bool isSemicolonRequiredAfter(const Stmt
   if(const auto *Case = dyn_cast(S))
 return isSemicolonRequiredAfter(Case->getSubStmt());
   switch (S->getStmtClass()) {
+  case Stmt::DeclStmtClass:
   case Stmt::CXXTryStmtClass:
   case Stmt::ObjCAtSynchronizedStmtClass:
   case Stmt::ObjCAutoreleasePoolStmtClass:

Modified: cfe/trunk/test/Refactor/Extract/ExtractionSemicolonPolicy.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Refactor/Extract/ExtractionSemicolonPolicy.cpp?rev=368850&r1=368849&r2=368850&view=diff
==
--- cfe/trunk/test/Refactor/Extract/ExtractionSemicolonPolicy.cpp (original)
+++ cfe/trunk/test/Refactor/Extract/ExtractionSemicolonPolicy.cpp Wed Aug 14 
06:37:39 2019
@@ -193,7 +193,7 @@ void careForNonCompoundSemicolons2() {
 // CHECK-NEXT: }
 
 void careForSwitchSemicolon() {
-  /*range mextract=->+0:51*/switch(0) default: break;
+  /*range mextract=->+0:53*/switch(0) default: break;
 }
 // CHECK: 1 'mextract' results:
 // CHECK:  static void extracted() {
@@ -203,3 +203,14 @@ void careForSwitchSemicolon() {
 // CHECK-NEXT: extracted();{{$}}
 // CHECK-NEXT: }
 
+void extractStatementNotSemiDecl() {
+  /*range nextract=->+0:38*/int x = 5;
+}
+// CHECK: 1 'nextract' results:
+// CHECK:  static void extracted() {
+// CHECK-NEXT: int x = 5;{{$}}
+// CHECK-NEXT: }{{[[:space:]].*}}
+// CHECK-NEXT: void extractStatementNotSemiDecl() {
+// CHECK-NEXT: extracted();{{$}}
+// CHECK-NEXT: }
+


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


[clang-tools-extra] r368851 - [clangd][vscode] Surface the error when applying tweaks fails

2019-08-14 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Wed Aug 14 06:38:52 2019
New Revision: 368851

URL: http://llvm.org/viewvc/llvm-project?rev=368851&view=rev
Log:
[clangd][vscode] Surface the error when applying tweaks fails

Summary:
The current behavior for a failed request is just to log it in the
output panel. When applyTweak fails for whatever reason, users usually don't get
informed (unless they open the output panel and dig the log).

this patch is to surface these errors by prompting up a message diag.

Reviewers: ilya-biryukov

Subscribers: MaskRay, jkorous, arphaman, kadircet, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts

Modified: clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts?rev=368851&r1=368850&r2=368851&view=diff
==
--- clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts 
(original)
+++ clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts Wed 
Aug 14 06:38:52 2019
@@ -47,6 +47,23 @@ class FileStatus {
   dispose() { this.statusBarItem.dispose(); }
 }
 
+class ClangdLanguageClient extends vscodelc.LanguageClient {
+  // Override the default implementation for failed requests. The default
+  // behavior is just to log failures in the output panel, however output panel
+  // is designed for extension debugging purpose, normal users will not open 
it,
+  // thus when the failure occurs, normal users doesn't know that.
+  //
+  // For user-interactive operations (e.g. applyFixIt, applyTweaks), we will
+  // prompt up the failure to users.
+  logFailedRequest(rpcReply: vscodelc.RPCMessageType, error: any) {
+if (error instanceof vscodelc.ResponseError &&
+rpcReply.method === "workspace/executeCommand")
+  vscode.window.showErrorMessage(error.message);
+// Call default implementation.
+super.logFailedRequest(rpcReply, error);
+  }
+}
+
 /**
  *  this method is called when your extension is activate
  *  your extension is activated the very first time the command is executed
@@ -89,8 +106,8 @@ export function activate(context: vscode
 revealOutputChannelOn: vscodelc.RevealOutputChannelOn.Never
 };
 
-  const clangdClient = new vscodelc.LanguageClient(
-  'Clang Language Server', serverOptions, clientOptions);
+  const clangdClient = new ClangdLanguageClient('Clang Language Server',
+serverOptions, clientOptions);
   console.log('Clang Language Server is now active!');
   context.subscriptions.push(clangdClient.start());
   context.subscriptions.push(vscode.commands.registerCommand(


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


[PATCH] D66211: [clangd][vscode] Surface the error when applying tweaks fails

2019-08-14 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368851: [clangd][vscode] Surface the error when applying 
tweaks fails (authored by hokein, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66211?vs=215107&id=215109#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66211

Files:
  clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts


Index: clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
===
--- clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
+++ clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
@@ -47,6 +47,23 @@
   dispose() { this.statusBarItem.dispose(); }
 }
 
+class ClangdLanguageClient extends vscodelc.LanguageClient {
+  // Override the default implementation for failed requests. The default
+  // behavior is just to log failures in the output panel, however output panel
+  // is designed for extension debugging purpose, normal users will not open 
it,
+  // thus when the failure occurs, normal users doesn't know that.
+  //
+  // For user-interactive operations (e.g. applyFixIt, applyTweaks), we will
+  // prompt up the failure to users.
+  logFailedRequest(rpcReply: vscodelc.RPCMessageType, error: any) {
+if (error instanceof vscodelc.ResponseError &&
+rpcReply.method === "workspace/executeCommand")
+  vscode.window.showErrorMessage(error.message);
+// Call default implementation.
+super.logFailedRequest(rpcReply, error);
+  }
+}
+
 /**
  *  this method is called when your extension is activate
  *  your extension is activated the very first time the command is executed
@@ -89,8 +106,8 @@
 revealOutputChannelOn: vscodelc.RevealOutputChannelOn.Never
 };
 
-  const clangdClient = new vscodelc.LanguageClient(
-  'Clang Language Server', serverOptions, clientOptions);
+  const clangdClient = new ClangdLanguageClient('Clang Language Server',
+serverOptions, clientOptions);
   console.log('Clang Language Server is now active!');
   context.subscriptions.push(clangdClient.start());
   context.subscriptions.push(vscode.commands.registerCommand(


Index: clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
===
--- clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
+++ clang-tools-extra/trunk/clangd/clients/clangd-vscode/src/extension.ts
@@ -47,6 +47,23 @@
   dispose() { this.statusBarItem.dispose(); }
 }
 
+class ClangdLanguageClient extends vscodelc.LanguageClient {
+  // Override the default implementation for failed requests. The default
+  // behavior is just to log failures in the output panel, however output panel
+  // is designed for extension debugging purpose, normal users will not open it,
+  // thus when the failure occurs, normal users doesn't know that.
+  //
+  // For user-interactive operations (e.g. applyFixIt, applyTweaks), we will
+  // prompt up the failure to users.
+  logFailedRequest(rpcReply: vscodelc.RPCMessageType, error: any) {
+if (error instanceof vscodelc.ResponseError &&
+rpcReply.method === "workspace/executeCommand")
+  vscode.window.showErrorMessage(error.message);
+// Call default implementation.
+super.logFailedRequest(rpcReply, error);
+  }
+}
+
 /**
  *  this method is called when your extension is activate
  *  your extension is activated the very first time the command is executed
@@ -89,8 +106,8 @@
 revealOutputChannelOn: vscodelc.RevealOutputChannelOn.Never
 };
 
-  const clangdClient = new vscodelc.LanguageClient(
-  'Clang Language Server', serverOptions, clientOptions);
+  const clangdClient = new ClangdLanguageClient('Clang Language Server',
+serverOptions, clientOptions);
   console.log('Clang Language Server is now active!');
   context.subscriptions.push(clangdClient.start());
   context.subscriptions.push(vscode.commands.registerCommand(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66215: [clangd] Print qualifiers of out-of-line definitions in document outline

2019-08-14 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/AST.cpp:106
+
+/// Returns a nested name specifier if \p ND refers to a an out-of-line
+/// definition.

hokein wrote:
>  `if .. out-of-line definition` seems a bit confusing, I think here we just 
> return a nested name specifier if it is written/present in the source code?
Good point, probably too many related concepts (and even synonyms) mentioned in 
one function.
Renamed to `getQualifier` and not mentioning the out-of-line definition anymore.

With the examples, it should be clear what this function is doing.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D66215



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


[PATCH] D64418: [Docs][OpenCL] Documentation of C++ for OpenCL mode

2019-08-14 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia marked 12 inline comments as done and 2 inline comments as done.
Anastasia added inline comments.



Comment at: docs/LanguageExtensions.rst:327
 
+.. _languageextensions-builtin-macros:
+

FYI, this is not part of my change. It was just hard to produce combined diff.



Comment at: docs/LanguageExtensions.rst:1541
+- Standard C++ libraries. Currently there is no solution for alternative C++
+  libraries provided. Future release will feature library support.
+

kpet wrote:
> I would remove this last sentence. Only a very small portion of the libray 
> can be supported anyway.
I think it's valuable especially for metaprogramming. I was being asked about 
it.



Comment at: docs/LanguageExtensions.rst:1553
+extension ISO/IEC JTC1 SC22 WG14 N1021 s3.1. Note that since the address space
+behavior in C++ is not documented formally yet, Clang extends existing concept
+from C and OpenCL. For example conversion rules are extended from qualification

kpet wrote:
> kpet wrote:
> > I would remove the "yet", unless we can refer to an on-going and visible 
> > effort.
> "Clang extends existing concept" feels like it should be re-worded.
I need to understand what needs re-wording



Comment at: docs/LanguageExtensions.rst:1557
+Embedded C (ISO/IEC JTC1 SC22 WG14 N1021 s3.1.3). For OpenCL it means that
+implicit conversions are allowed from named to ``__generic`` but not vice versa
+(OpenCL C v2.0 s6.5.5) except for ``__constant`` address space. Most of the

kpet wrote:
> Why use `__generic` when `generic` is equally valid and easier on the eyes? 
> The same comment applies to other mentions of address space keywords.
I prefer to use `__` for two reasons (1) it's more official in OpenCL docs and 
tutorials (2) I sometimes omit the noun and just use it as a short term in the 
text.



Comment at: docs/LanguageExtensions.rst:1564
+C style cast will follow OpenCL C v2.0 rules (s6.5.5). All cast operators will
+permit implicit conversion to ``__generic``. However converting from named
+address spaces to ``__generic`` can only be done using ``addrspace_cast``. Note

kpet wrote:
> Isn't a conversion explicit if a cast operator is used?
It's complicated to explain but basically some cast operators perform implicit 
conversions of what they are not expected to do because implicit conversions 
are allowed everywhere even if the operator isn't intended to do the conversion 
explicitly.

Similar example in C++, most of operators accept converting to `const` objects.




Comment at: docs/LanguageExtensions.rst:1565
+permit implicit conversion to ``__generic``. However converting from named
+address spaces to ``__generic`` can only be done using ``addrspace_cast``. Note
+that conversions between ``__constant`` and any other is still disallowed.

kpet wrote:
> kpet wrote:
> > At the time of writing `addrspace_cast` doesn't seem to exist in trunk and 
> > C-style casts seem to work.
> Didn't you mean "from `__generic` to named address spaces"?
> At the time of writing addrspace_cast doesn't seem to exist in trunk and 
> C-style casts seem to work.

I think it's ok to document full extension even if it's WIP.



Comment at: docs/LanguageExtensions.rst:1577
+- non-pointer/non-reference class members except for static data members that 
are
+  deduced to ``__global`` address space.
+- non-pointer/non-reference alias declarations.

kpet wrote:
> Makes me wonder whether const members couldn't be in the `constant` address 
> space.
No `constant` specify memory region but `const` indicates that object is not 
changed during lifetime. You can cast away `const` but you can't convert 
`constant` object to any other address space.



Comment at: docs/LanguageExtensions.rst:1761
+program objects is executed. In OpenCL v2.0 drivers there is no specific
+API for invoking global constructors. However, an easy workaround would be
+to enqueue constructor initialization kernel that has a name

kpet wrote:
> OpenCL doesn't have an API for this per-se, regardless of the version. The 
> only mechanism currently specified is the SPIR-V `Initializer` and 
> `Finalizer` execution modes for entrypoints, either of which currently 
> require an OpenCL 2.2 implementation.
Not sure whether you imply any action here.



Comment at: docs/LanguageExtensions.rst:1779
+
+Global destructors can not be invoked in OpenCL v2.0 drivers. However, all
+memory used for program scope objects is released on ``clReleaseProgram``.

kpet wrote:
> This could be managed by the application with a scheme similar to the one 
> you're proposing for constructor functions.
The Itanium C++ ABIs for destructors are different and we haven't got it 
working yet for OpenCL. I would leave the descriptio

r368853 - [analyzer][NFC] Prove that we only track the evaluated part of the condition

2019-08-14 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Wed Aug 14 06:51:52 2019
New Revision: 368853

URL: http://llvm.org/viewvc/llvm-project?rev=368853&view=rev
Log:
[analyzer][NFC] Prove that we only track the evaluated part of the condition

...because we're working with a BugReporterVisitor, and the non-evaluated part
of the condition isn't in the bugpath.

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

Modified:
cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp

Modified: cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp?rev=368853&r1=368852&r2=368853&view=diff
==
--- cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp (original)
+++ cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp Wed Aug 14 
06:51:52 2019
@@ -532,6 +532,7 @@ void f(int flag) {
 }
 
 #undef assert
+
 } // end of namespace dont_track_assertlike_and_conditions
 
 namespace dont_track_assertlike_or_conditions {
@@ -697,3 +698,37 @@ void f(int flag) {
 
 #undef assert
 } // end of namespace dont_track_assert2like_or_conditions
+
+namespace only_track_the_evaluated_condition {
+
+bool coin();
+
+void bar(int &flag) {
+  flag = coin(); // tracking-note{{Value assigned to 'flag'}}
+}
+
+void bar2(int &flag2) {
+  flag2 = coin();
+}
+
+void f(int *x) {
+  if (x) // expected-note{{Assuming 'x' is null}}
+ // debug-note@-1{{Tracking condition 'x'}}
+ // expected-note@-2{{Taking false branch}}
+return;
+
+  int flag, flag2;
+  bar(flag); // tracking-note{{Calling 'bar'}}
+ // tracking-note@-1{{Returning from 'bar'}}
+  bar2(flag2);
+
+  if (flag && flag2) // expected-note   {{Assuming 'flag' is 0}}
+ // expected-note@-1{{Left side of '&&' is false}}
+ // debug-note@-2{{Tracking condition 'flag'}}
+return;
+
+  *x = 5; // expected-warning{{Dereference of null pointer}}
+  // expected-note@-1{{Dereference of null pointer}}
+}
+
+} // end of namespace only_track_the_evaluated_condition


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


[PATCH] D65290: [analyzer][NFC] Prove that we only track the evaluated part of the condition

2019-08-14 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368853: [analyzer][NFC] Prove that we only track the 
evaluated part of the condition (authored by Szelethus, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D65290?vs=211779&id=215110#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D65290

Files:
  cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp


Index: cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
===
--- cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
+++ cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
@@ -532,6 +532,7 @@
 }
 
 #undef assert
+
 } // end of namespace dont_track_assertlike_and_conditions
 
 namespace dont_track_assertlike_or_conditions {
@@ -697,3 +698,37 @@
 
 #undef assert
 } // end of namespace dont_track_assert2like_or_conditions
+
+namespace only_track_the_evaluated_condition {
+
+bool coin();
+
+void bar(int &flag) {
+  flag = coin(); // tracking-note{{Value assigned to 'flag'}}
+}
+
+void bar2(int &flag2) {
+  flag2 = coin();
+}
+
+void f(int *x) {
+  if (x) // expected-note{{Assuming 'x' is null}}
+ // debug-note@-1{{Tracking condition 'x'}}
+ // expected-note@-2{{Taking false branch}}
+return;
+
+  int flag, flag2;
+  bar(flag); // tracking-note{{Calling 'bar'}}
+ // tracking-note@-1{{Returning from 'bar'}}
+  bar2(flag2);
+
+  if (flag && flag2) // expected-note   {{Assuming 'flag' is 0}}
+ // expected-note@-1{{Left side of '&&' is false}}
+ // debug-note@-2{{Tracking condition 'flag'}}
+return;
+
+  *x = 5; // expected-warning{{Dereference of null pointer}}
+  // expected-note@-1{{Dereference of null pointer}}
+}
+
+} // end of namespace only_track_the_evaluated_condition


Index: cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
===
--- cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
+++ cfe/trunk/test/Analysis/track-control-dependency-conditions.cpp
@@ -532,6 +532,7 @@
 }
 
 #undef assert
+
 } // end of namespace dont_track_assertlike_and_conditions
 
 namespace dont_track_assertlike_or_conditions {
@@ -697,3 +698,37 @@
 
 #undef assert
 } // end of namespace dont_track_assert2like_or_conditions
+
+namespace only_track_the_evaluated_condition {
+
+bool coin();
+
+void bar(int &flag) {
+  flag = coin(); // tracking-note{{Value assigned to 'flag'}}
+}
+
+void bar2(int &flag2) {
+  flag2 = coin();
+}
+
+void f(int *x) {
+  if (x) // expected-note{{Assuming 'x' is null}}
+ // debug-note@-1{{Tracking condition 'x'}}
+ // expected-note@-2{{Taking false branch}}
+return;
+
+  int flag, flag2;
+  bar(flag); // tracking-note{{Calling 'bar'}}
+ // tracking-note@-1{{Returning from 'bar'}}
+  bar2(flag2);
+
+  if (flag && flag2) // expected-note   {{Assuming 'flag' is 0}}
+ // expected-note@-1{{Left side of '&&' is false}}
+ // debug-note@-2{{Tracking condition 'flag'}}
+return;
+
+  *x = 5; // expected-warning{{Dereference of null pointer}}
+  // expected-note@-1{{Dereference of null pointer}}
+}
+
+} // end of namespace only_track_the_evaluated_condition
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D66042: [analyzer] Analysis: Silence checkers

2019-08-14 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 215103.
Charusso marked 4 inline comments as done.
Charusso retitled this revision from "[analyzer] Analysis: "Disable" core 
checkers" to "[analyzer] Analysis: Silence checkers".
Charusso edited the summary of this revision.
Charusso set the repository for this revision to rC Clang.
Charusso added a comment.

- Pink Fluffy Unicorns Dancing On Rainbows 



Repository:
  rC Clang

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

https://reviews.llvm.org/D66042

Files:
  clang-tools-extra/clang-tidy/ClangTidy.cpp
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/StaticAnalyzer/Core/BugReporter.cpp
  clang/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/silence-checker-core-all.cpp
  clang/test/Analysis/silence-checker-core-div-by-zero.cpp
  clang/tools/scan-build/bin/scan-build
  clang/unittests/StaticAnalyzer/RegisterCustomCheckersTest.cpp

Index: clang/unittests/StaticAnalyzer/RegisterCustomCheckersTest.cpp
===
--- clang/unittests/StaticAnalyzer/RegisterCustomCheckersTest.cpp
+++ clang/unittests/StaticAnalyzer/RegisterCustomCheckersTest.cpp
@@ -46,8 +46,7 @@
 std::unique_ptr AnalysisConsumer =
 CreateAnalysisConsumer(Compiler);
 AnalysisConsumer->AddDiagnosticConsumer(new DiagConsumer(DiagsOutput));
-Compiler.getAnalyzerOpts()->CheckersControlList = {
-{"custom.CustomChecker", true}};
+Compiler.getAnalyzerOpts()->Checkers = {{"custom.CustomChecker", true}};
 AnalysisConsumer->AddCheckerRegistrationFn([](CheckerRegistry &Registry) {
   Registry.addChecker("custom.CustomChecker", "Description", "");
 });
Index: clang/tools/scan-build/bin/scan-build
===
--- clang/tools/scan-build/bin/scan-build
+++ clang/tools/scan-build/bin/scan-build
@@ -57,6 +57,7 @@
   KeepEmpty => 0,# Don't remove output directory even with 0 results.
   EnableCheckers => {},
   DisableCheckers => {},
+  SilenceCheckers => {},
   Excludes => [],
   UseCC => undef,# C compiler to use for compilation.
   UseCXX => undef,   # C++ compiler to use for compilation.
@@ -1742,9 +1743,15 @@
 if ($arg eq "-disable-checker") {
   shift @$Args;
   my $Checker = shift @$Args;
-  # Store $NumArgs to preserve the order the checkers were disabled.
-  $Options{DisableCheckers}{$Checker} = $NumArgs;
-  delete $Options{EnableCheckers}{$Checker};
+  # Store $NumArgs to preserve the order the checkers are disabled/silenced.
+  # See whether it is a core checker to disable. That means we do not want
+  # to emit a report from that checker so we have to silence it.
+  if (index($Checker, "core") == 0) {
+$Options{SilenceCheckers}{$Checker} = $NumArgs;
+  } else {
+$Options{DisableCheckers}{$Checker} = $NumArgs;
+delete $Options{EnableCheckers}{$Checker};
+  }
   next;
 }
 
@@ -1882,6 +1889,11 @@
   # Push checkers in order they were disabled.
   push @AnalysesToRun, "-analyzer-disable-checker", $_;
 }
+foreach (sort { $Options{SilenceCheckers}{$a} <=> $Options{SilenceCheckers}{$b} }
+ keys %{$Options{SilenceCheckers}}) {
+  # Push checkers in order they were silenced.
+  push @AnalysesToRun, "-analyzer-config silence-checker", $_;
+}
 if ($Options{AnalyzeHeaders}) { push @AnalysesToRun, "-analyzer-opt-analyze-headers"; }
 if ($Options{AnalyzerStats}) { push @AnalysesToRun, '-analyzer-checker=debug.Stats'; }
 if ($Options{MaxLoop} > 0) { push @AnalysesToRun, "-analyzer-max-loop $Options{MaxLoop}"; }
Index: clang/test/Analysis/silence-checker-core-div-by-zero.cpp
===
--- /dev/null
+++ clang/test/Analysis/silence-checker-core-div-by-zero.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core \
+// RUN:  -analyzer-config silence-checkers=core.DivideZero \
+// RUN:  -verify %s
+
+void test_disable_core_div_by_zero() {
+  (void)(1 / 0);
+  // expected-warning@-1 {{division by zero is undefined}}
+  // no-warning: 'Division by zero'
+}
+
+void test_disable_null_deref(int *p) {
+  if (p)
+return;
+
+  int x = p[0];
+  // expected-warning@-1 {{Array access (from variable 'p') results in a null pointer dereference}}
+}
Index: clang/test/Analysis/silence-checker-core-all.cpp
===
--- /dev/null
+++ clang/test/Analysis/silence-checker-core-all.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core \
+// RUN:  -analyzer-config silence-checkers=core \
+// RUN:  -verify %s
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analy

[PATCH] D66042: [analyzer] Analysis: Silence checkers

2019-08-14 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso added a comment.

I realized that it is meaningless what separator we use to list the checkers, 
so I have picked `;`. The `,` is limited to the `analyzer-config` list.




Comment at: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h:192-197
+  /// Pair of checker name and enable/disable to do analysis.
+  std::vector> CheckerAnalysisVector;
+
+  /// Vector of checker names to do not emit warnings.
+  std::vector CheckerSilenceVector;
 

Szelethus wrote:
> Charusso wrote:
> > NoQ wrote:
> > > `CheckerAnalysisVector` sounds like a vector of checkers that will be 
> > > subject to analysis. But in reality they are the ones that are analyzing 
> > > and nobody is analyzing them.
> > > 
> > > The old name isn't very expressive either, but at least it sounds cool >.<
> > > 
> > > Maybe `EnabledCheckers`, `SilencedCheckers`?
> > The problem with `EnabledCheckers` it is a lie. It would be just `Checkers` 
> > and then whether a given checker is enabled or disabled is determined 
> > later. `CheckerEnableVector` and `CheckerSilenceVector` may would be okay.
> Aye, I've come across this field multiple times and there isn't really a good 
> name for it. However, is this correct? Are these *checkers*, or checkers 
> *and* packages?
`SilencedCheckersAndPackagesAsCommaSeparatedListSplittedToStringRefVector` 
simplified to `SilencedCheckers` and `CheckersControlList` to `Checkers`.


Repository:
  rC Clang

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

https://reviews.llvm.org/D66042



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


[PATCH] D66219: [clangd] Added a colorizer to the vscode extension.

2019-08-14 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom created this revision.
jvikstrom added reviewers: hokein, ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Adds the main colorizer component. It colorizes every time clangd sends a 
publishSemanticHighlighting notification.
Every time it colorizes it does a full recolorization (removes all decorations 
from the editor and applies new ones). The reason for this is that all ranges 
for the same scope share a TextEditorDecorationType. This is due to 
TextEditorDecorationTypes being very expensive to create. The prototype used 
one DecorationType per range but that ran into very big performance problems 
(it took >100 ms to apply 600 lines of highlightings which froze the editor).

This version does not share the problem of being extremly slow, but there is 
probably potential to optimize it even more.

The Colorizer uses a FileColorizer interface to make it possible to mock out 
all the code that applies colorizations to a specific editor so that we can 
test it.

No document/texteditor lifecycle management code in this CL, that will come in 
the next one.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66219

Files:
  clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
  
clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -1,5 +1,6 @@
 import * as assert from 'assert';
 import * as path from 'path';
+import * as vscode from 'vscode';
 
 import * as SM from '../src/semantic-highlighting';
 
@@ -57,4 +58,73 @@
 assert.deepEqual(tm.getBestThemeRule('variable.other.parameter.cpp').scope,
  'variable.other.parameter');
   });
+  test('Colorizer groups decorations correctly', () => {
+const colorizations: {uri: string, decorations: any[]}[] = [];
+// Mock of a colorizer that saves the parameters in the colorizations array.
+class MockFileColorizer {
+  public colorize(uri: string, decorationRangePairs: any[]) {
+colorizations.push({uri : uri, decorations : decorationRangePairs});
+  }
+  public dispose() {}
+}
+// Helper for creating a vscode Range.
+const createRange = (line: number, startCharacter: number,
+ length: number) =>
+new vscode.Range(new vscode.Position(line, startCharacter),
+ new vscode.Position(line, startCharacter + length));
+const scopeTable = [
+  [ 'variable' ], [ 'entity.type.function' ],
+  [ 'entity.type.function.method' ]
+];
+const rules = [
+  {scope : 'variable', foreground : '1'},
+  {scope : 'entity.type', foreground : '2'},
+];
+const tm = new SM.ThemeRuleMatcher(rules);
+const colorizer =
+new SM.Colorizer(MockFileColorizer, scopeTable);
+// No colorization if themeRuleMatcher has not been set.
+colorizer.setFileLines('a', []);
+assert.deepEqual(colorizations, []);
+colorizer.updateThemeRuleMatcher(tm);
+assert.deepEqual(colorizations, [ {decorations : [], uri : 'a'} ]);
+// Groups decorations into the scopes used.
+let line = [
+  {character : 1, length : 2, scopeIndex : 1},
+  {character : 5, length : 2, scopeIndex : 1},
+  {character : 10, length : 2, scopeIndex : 2}
+];
+colorizer.setFileLines(
+'a', [ {line : 1, tokens : line}, {line : 2, tokens : line} ]);
+assert.equal(colorizations[1].uri, 'a');
+assert.equal(colorizations[1].decorations.length, 2);
+// Can't test the actual decorations as vscode does not seem to have an api
+// for getting the actual decoration objects.
+assert.deepEqual(colorizations[1].decorations[0].ranges, [
+  createRange(1, 1, 2), createRange(1, 5, 2), createRange(2, 1, 2),
+  createRange(2, 5, 2)
+]);
+assert.deepEqual(colorizations[1].decorations[1].ranges,
+ [ createRange(1, 10, 2), createRange(2, 10, 2) ]);
+// Keeps state separate between files.
+colorizer.setFileLines('b', [
+  {line : 1, tokens : [ {character : 1, length : 1, scopeIndex : 0} ]}
+]);
+assert.equal(colorizations[2].uri, 'b');
+assert.equal(colorizations[2].decorations.length, 1);
+assert.deepEqual(colorizations[2].decorations[0].ranges,
+ [ createRange(1, 1, 1) ]);
+// Does full colorizations.
+colorizer.setFileLines('a', [
+  {line : 1, tokens : [ {character : 2, length : 1, scopeIndex : 0} ]}
+]);
+assert.equal(colorizations[3].uri, 'a');
+assert.equal(colorizations[3].decorations.length, 3);
+assert.deepEqual(colorizations[3].decorations[0].

[PATCH] D66042: [analyzer] Analysis: Silence checkers

2019-08-14 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

Thanks!!! Please note that BugReporter.cpp (especially the parts you touched) 
just got refactored extensively, so you'll need to rebase on master.




Comment at: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h:192
   /// Pair of checker name and enable/disable.
-  std::vector> CheckersControlList;
+  std::vector> Checkers;
+

Hmm, this doesn't really describe what this field does, does it? This isn't 
even the entire list, only those explicitly specified by `-analyzer-checker` 
and `-analyzer-disable-checker`. Besides, package names are also in this 
container. How about any of these:

* `EnabledCheckersAndPackages`
* `EnabledCheckers`
* `CheckerAndPackageUserInput` (this may just be the name that describes whats 
happening here the best)
* `CheckerUserInput`



Comment at: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.h:195
+  /// Vector of checker names which will not emit warnings.
+  std::vector SilencedCheckers;
 

Same here. I realize the name of the field could get ridiculously long, how 
about we leave this as-is but mention it in the comments that packages are also 
included?



Comment at: clang/lib/StaticAnalyzer/Core/BugReporter.cpp:1924
+
+  // See whether we need to silence the checker.
+  for (const std::string &CheckerName : Opts.SilencedCheckers) {

Could you please add a `FIXME` about that this will not work if the report was 
emitted with the incorrect tag?


Repository:
  rC Clang

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

https://reviews.llvm.org/D66042



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


[PATCH] D61027: Fix crash on switch conditions of non-integer types in templates

2019-08-14 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added a comment.

Thank you for letting me know. I did try reproducing the issue with check-all 
yesterday but was unable to. I do not think I build with 'clang-tools-extra' 
project enabled though.  I'll take another look today.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D61027



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


[PATCH] D66042: [analyzer] Analysis: Silence checkers

2019-08-14 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def:392
+StringRef, RawSilencedCheckers, "silence-checkers",
+"A semicolon separated list of checker and package names to silence.", "")
+

Hmm, maybe we could elaborate on what we mean under silencing.
```
Silenced checkers will remain enabled and work as usual during analysis, but 
bug reports originating from them are suppressed.
```


Repository:
  rC Clang

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

https://reviews.llvm.org/D66042



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


[PATCH] D66042: [analyzer] Analysis: Silence checkers

2019-08-14 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/lib/StaticAnalyzer/Frontend/CheckerRegistry.cpp:468-502
 void CheckerRegistry::validateCheckerOptions() const {
   for (const auto &Config : AnOpts.Config) {
 
 StringRef SuppliedChecker;
 StringRef SuppliedOption;
 std::tie(SuppliedChecker, SuppliedOption) = Config.getKey().split(':');
 

Also, you can validate whether the user-provided checker/package names actually 
exist by modifying this function a bit.

Only if you feel like it, I don't insist :)


Repository:
  rC Clang

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

https://reviews.llvm.org/D66042



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


[PATCH] D65065: [clang-tidy] Possibility of displaying duplicate warnings

2019-08-14 Thread Tibor Brunner via Phabricator via cfe-commits
bruntib updated this revision to Diff 215122.
bruntib added a comment.

Since now the order of diagnostic messages is deterministic, we can count on 
this order in the test file.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D65065

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/test/clang-tidy/duplicate-reports.cpp


Index: clang-tools-extra/test/clang-tidy/duplicate-reports.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/duplicate-reports.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy %s cert-err09-cpp,cert-err61-cpp %t
+
+void alwaysThrows() {
+  int ex = 42;
+  // CHECK-MESSAGES: warning: throw expression should throw anonymous 
temporary values instead [cert-err09-cpp]
+  // CHECK-MESSAGES: warning: throw expression should throw anonymous 
temporary values instead [cert-err61-cpp]
+  throw ex;
+}
+
+void doTheJob() {
+  try {
+alwaysThrows();
+  } catch (int&) {
+  }
+}
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -742,8 +742,9 @@
 const tooling::DiagnosticMessage &M1 = LHS.Message;
 const tooling::DiagnosticMessage &M2 = RHS.Message;
 
-return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
-   std::tie(M2.FilePath, M2.FileOffset, M2.Message);
+return
+  std::tie(M1.FilePath, M1.FileOffset, LHS.DiagnosticName, M1.Message) <
+  std::tie(M2.FilePath, M2.FileOffset, RHS.DiagnosticName, M2.Message);
   }
 };
 struct EqualClangTidyError {


Index: clang-tools-extra/test/clang-tidy/duplicate-reports.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/duplicate-reports.cpp
@@ -0,0 +1,15 @@
+// RUN: %check_clang_tidy %s cert-err09-cpp,cert-err61-cpp %t
+
+void alwaysThrows() {
+  int ex = 42;
+  // CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead [cert-err09-cpp]
+  // CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead [cert-err61-cpp]
+  throw ex;
+}
+
+void doTheJob() {
+  try {
+alwaysThrows();
+  } catch (int&) {
+  }
+}
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -742,8 +742,9 @@
 const tooling::DiagnosticMessage &M1 = LHS.Message;
 const tooling::DiagnosticMessage &M2 = RHS.Message;
 
-return std::tie(M1.FilePath, M1.FileOffset, M1.Message) <
-   std::tie(M2.FilePath, M2.FileOffset, M2.Message);
+return
+  std::tie(M1.FilePath, M1.FileOffset, LHS.DiagnosticName, M1.Message) <
+  std::tie(M2.FilePath, M2.FileOffset, RHS.DiagnosticName, M2.Message);
   }
 };
 struct EqualClangTidyError {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D65453: Improve the accuracy of the Clang call graph analysis

2019-08-14 Thread Joshua Cranmer via Phabricator via cfe-commits
jcranmer-intel added a comment.

The test has been passing for me. What error are you seeing?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65453



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


[PATCH] D66198: AMDGPU: Add builtins for is_local/is_private

2019-08-14 Thread Brian Sumner via Phabricator via cfe-commits
b-sumner added a comment.

Looks fine to me.  Thanks!


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

https://reviews.llvm.org/D66198



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


[PATCH] D65065: [clang-tidy] Possibility of displaying duplicate warnings

2019-08-14 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

LGTM


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D65065



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


r368862 - [libTooling] Fix code to avoid unused-function warning after r368681.

2019-08-14 Thread Yitzhak Mandelbaum via cfe-commits
Author: ymandel
Date: Wed Aug 14 08:20:06 2019
New Revision: 368862

URL: http://llvm.org/viewvc/llvm-project?rev=368862&view=rev
Log:
[libTooling] Fix code to avoid unused-function warning after r368681.

Modified:
cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp

Modified: cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp?rev=368862&r1=368861&r2=368862&view=diff
==
--- cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp (original)
+++ cfe/trunk/lib/Tooling/Refactoring/Transformer.cpp Wed Aug 14 08:20:06 2019
@@ -80,12 +80,14 @@ void tooling::addInclude(RewriteRule &Ru
 Case.AddedIncludes.emplace_back(Header.str(), Format);
 }
 
+#ifndef NDEBUG
 // Filters for supported matcher kinds. FIXME: Explicitly list the allowed 
kinds
 // (all node matcher types except for `QualType` and `Type`), rather than just
 // banning `QualType` and `Type`.
 static bool hasValidKind(const DynTypedMatcher &M) {
   return !M.canConvertTo();
 }
+#endif
 
 // Binds each rule's matcher to a unique (and deterministic) tag based on
 // `TagBase` and the id paired with the case.


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


[PATCH] D66221: [clangd] Added highlighting for non type templates.

2019-08-14 Thread Johan Vikström via Phabricator via cfe-commits
jvikstrom created this revision.
jvikstrom added reviewers: hokein, ilya-biryukov.
Herald added subscribers: cfe-commits, kadircet, arphaman, jkorous, MaskRay.
Herald added a project: clang.

Highlights pointers to variables as variables. Function pointers are 
highlighted as functions. Member function pointers are highlighted as members. 
Values are highlighted as TemplateParameter.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66221

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -323,6 +323,59 @@
   $Primitive[[auto]] $Variable[[Form]] = 10.2 + 2 * 4;
   $Primitive[[decltype]]($Variable[[Form]]) $Variable[[F]] = 10;
   auto $Variable[[Fun]] = []()->$Primitive[[void]]{};
+)cpp",
+R"cpp(
+  class $Class[[G]] {};
+  template<$Class[[G]] *$Variable[[U]]>
+  class $Class[[GP]] {};
+  template<$Class[[G]] &$Variable[[U]]>
+  class $Class[[GR]] {};
+  template<$Primitive[[int]] *$Variable[[U]]>
+  class $Class[[IP]] {
+$Primitive[[void]] $Method[[f]]() {
+  *$Variable[[U]] += 5;
+}
+  };
+  template<$Primitive[[unsigned]] $TemplateParameter[[U]] = 2>
+  class $Class[[Foo]] {
+$Primitive[[void]] $Method[[f]]() {
+  for($Primitive[[int]] $Variable[[I]] = 0;
+$Variable[[I]] < $TemplateParameter[[U]];) {}
+}
+  };
+
+  $Class[[G]] $Variable[[L]];
+  $Primitive[[void]] $Function[[f]]() {
+$Class[[Foo]]<123> $Variable[[F]];
+$Class[[GP]]<&$Variable[[L]]> $Variable[[LL]];
+$Class[[GR]]<$Variable[[L]]> $Variable[[LLL]];
+  }
+)cpp",
+R"cpp(
+  template
+  struct $Class[[G]] {
+$Primitive[[void]] $Method[[foo]](
+$TemplateParameter[[T]] *$Variable[[O]]) {
+  ($Variable[[O]]->*$Method[[method]])(10);
+}
+  };
+  struct $Class[[F]] {
+$Primitive[[void]] $Method[[f]]($Primitive[[int]]);
+  };
+  template<$Primitive[[void]] (*$Function[[Func]])()>
+  struct $Class[[A]] {
+$Primitive[[void]] $Method[[f]]() {
+  (*$Function[[Func]])();
+}
+  };
+
+  $Primitive[[void]] $Function[[foo]]() {
+$Class[[F]] $Variable[[FF]];
+$Class[[G]]<$Class[[F]], &$Class[[F]]::$Method[[f]]> $Variable[[GG]];
+$Variable[[GG]].$Method[[foo]](&$Variable[[FF]]);
+$Class[[A]]<$Function[[foo]]> $Variable[[AA]];
+  }
 )cpp"};
   for (const auto &TestCase : TestCases) {
 checkHighlightings(TestCase);
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -224,6 +224,28 @@
   addToken(Loc, HighlightingKind::TemplateParameter);
   return;
 }
+if (const auto *NTP = dyn_cast(D)) {
+  if (const auto *T = NTP->getTypeSourceInfo())
+if (const auto *TP = T->getTypeLoc().getTypePtr()) {
+  if (TP->isFunctionPointerType()) {
+addToken(Loc, HighlightingKind::Function);
+return;
+  }
+  if (TP->isMemberFunctionPointerType()) {
+addToken(Loc, HighlightingKind::Method);
+return;
+  }
+  if (TP->isPointerType() || TP->isLValueReferenceType()) {
+addToken(Loc, HighlightingKind::Variable);
+return;
+  }
+}
+  // If it's not a function ptr, member ptr, ptr or reference that means it
+  // is probably a builtin value. Those should just be highlighted as 
normal
+  // TemplateParameters.
+  addToken(Loc, HighlightingKind::TemplateParameter);
+  return;
+}
   }
 
   void addToken(SourceLocation Loc, HighlightingKind Kind) {


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -323,6 +323,59 @@
   $Primitive[[auto]] $Variable[[Form]] = 10.2 + 2 * 4;
   $Primitive[[decltype]]($Variable[[Form]]) $Variable[[F]] = 10;
   auto $Variable[[Fun]] = []()->$Primitive[[void]]{};
+)cpp",
+R"cpp(
+  class $Class[[G]] {};
+  template<$Class[[G]] *$Variable[[U]]>
+  class $Class[[GP]] {};
+  template<$Class[[G]] &$Variable[[U]]>
+  class $Class[[GR]] {};
+  template<$Primitive[[int]] *$Variable[[U]]>
+  class $Class[[IP]] {
+$Primitive[[void]] $Method[[f]]() {
+

[PATCH] D65919: [clang-tidy] Add llvm-prefer-register-over-unsigned check and apply it to LLVM

2019-08-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp:26
   void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
+using readability::NamespaceCommentCheck;
+

dsanders wrote:
> aaron.ballman wrote:
> > I would rather use the fully-qualified names below -- the namespaces are 
> > actually of interest when needing to see what checks rely on what other 
> > modules quickly.
> In that case I think I need some more detail on the alphabetical order I need 
> to preserve. Do the namespaces factor into the order? If so, then 
> PreferIsaOrDynCastInConditionalsCheck was in the wrong place prior to this 
> patch and add_new_check.py is behaving correctly. If not, then the existing 
> order was correct but add_new_check.py is inserting new lines incorrectly
We usually alphabetize based on the string literal for the check being 
registered. This usually results in the list also being sorted by the check 
implementation class name, but not always.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65919



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


[PATCH] D65526: [Clangd] Initial prototype version of ExtractFunction

2019-08-14 Thread Shaurya Gupta via Phabricator via cfe-commits
SureYeaah updated this revision to Diff 215131.
SureYeaah added a comment.

Better Naming


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65526

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
  clang-tools-extra/clangd/unittests/TweakTests.cpp

Index: clang-tools-extra/clangd/unittests/TweakTests.cpp
===
--- clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -599,6 +599,103 @@
 R"cpp(const char * x = "test")cpp");
 }
 
+TWEAK_TEST(ExtractFunction);
+TEST_F(ExtractFunctionTest, PrepareFunctionTest) {
+  Header = R"cpp(
+#define F(BODY) void FFF() { BODY }
+  )cpp";
+  Context = Function;
+  EXPECT_AVAILABLE(R"cpp(
+[[int sum = 0;
+for(;;)
+  sum++;]]
+for(int i = 0; i < 5; i++) {
+  sum += i;
+}
+  )cpp");
+  EXPECT_AVAILABLE(R"cpp([[int x;]])cpp");
+  // TODO: Add tests for macros after selectionTree works properly for macros.
+  // EXPECT_AVAILABLE(R"cpp( F (int x = 0; [[x = 1;]])cpp");
+  // FIXME: This should be unavailable since partially selected but
+  // selectionTree doesn't always work correctly for VarDecls.
+  //EXPECT_UNAVAILABLE(R"cpp(int [[x = 0]];)cpp");
+  EXPECT_UNAVAILABLE(R"cpp(
+int sum = 0;
+for(;;)
+  [[sum++;
+sum++;]]
+  )cpp");
+  // Expressions aren't extracted.
+  EXPECT_UNAVAILABLE(R"cpp(int x = 0; [[x++;]])cpp");
+  // FIXME: ExtractFunction should be unavailable inside loop construct
+  // initalizer/condition.
+  // EXPECT_UNAVAILABLE(R"cpp( for([[int i = 0; i < 5;]] i++) )cpp");
+}
+
+TEST_F(ExtractFunctionTest, PrepareMethodTest) {
+  EXPECT_UNAVAILABLE(R"cpp(
+class T {
+  void f() {
+[[int x;]]
+  }
+};
+  )cpp");
+}
+
+TEST_F(ExtractFunctionTest, ApplyTest) {
+  // We can extract from templated functions as long as no reference in the
+  // extraction depends on the template.
+  // Checks const qualifier and extraction parameters.
+  Header = R"cpp(
+  )cpp";
+  EXPECT_EQ(apply(
+R"cpp(
+struct FOO {
+  int x;
+};
+template
+void f(int a) {
+  int b = N; T t; const int c; FOO foo;
+  int *ptr = &a;
+  [[a += foo.x;
+  b = c; 
+  *ptr++;
+  int d = 5 /* check if comment is extracted */ ;]]
+})cpp"),
+R"cpp(
+struct FOO {
+  int x;
+};
+void extracted(int &a, int &b, const int &c, struct FOO &foo, int * &ptr) {
+a += foo.x;
+  b = c; 
+  *ptr++;
+  int d = 5 /* check if comment is extracted */ ;
+}
+template
+void f(int a) {
+  int b = N; T t; const int c; FOO foo;
+  int *ptr = &a;
+  extracted(a, b, c, foo, ptr);
+})cpp");
+  auto ShouldFail = [&](llvm::StringRef Code) {
+EXPECT_THAT(apply(Code), StartsWith("fail:"));
+  };
+  // Don't extract because needs hoisting.
+  ShouldFail(R"cpp( void f() { [[int a = 5;]] a++;})cpp");
+  // Don't extract parameters that depend on template.
+  ShouldFail(R"cpp( template void f() { [[int a = N;]] })cpp");
+  ShouldFail(R"cpp( template void f() { [[T t;]] })cpp");
+  // Don't extract return
+  ShouldFail(R"cpp( int f() { int a = 5; [[return a;]]})cpp");
+  // Don't extract break and continue.
+  // FIXME: We should be able to extract this.
+  ShouldFail(R"cpp( int f() { [[for(;;) break;]]})cpp");
+  ShouldFail(R"cpp( int f() { for(;;) [[continue;]]})cpp");
+  // Don't extract when we need to make a function as a parameter.
+  ShouldFail(R"cpp( void f() { [[int a; f();]] } )cpp");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -0,0 +1,534 @@
+//===--- ExtractFunction.cpp -*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#include "ClangdUnit.h"
+#include "Logger.h"
+#include "Selection.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Stmt.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "clang/Tooling/Refactoring/Extract/SourceExtraction.h"
+#include "llvm/ADT/None.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/iterator_range.h"
+#include "llvm/

r368863 - [NFC] Fix testcase for ARMs

2019-08-14 Thread David Bolvansky via cfe-commits
Author: xbolva00
Date: Wed Aug 14 08:35:40 2019
New Revision: 368863

URL: http://llvm.org/viewvc/llvm-project?rev=368863&view=rev
Log:
[NFC] Fix testcase for ARMs

Modified:
cfe/trunk/test/CodeGen/struct-copy.c

Modified: cfe/trunk/test/CodeGen/struct-copy.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/struct-copy.c?rev=368863&r1=368862&r2=368863&view=diff
==
--- cfe/trunk/test/CodeGen/struct-copy.c (original)
+++ cfe/trunk/test/CodeGen/struct-copy.c Wed Aug 14 08:35:40 2019
@@ -4,14 +4,14 @@ struct x { int a[100]; };
 
 void foo(struct x *P, struct x *Q) {
 // CHECK-LABEL: @foo(
-// CHECK:call void @llvm.memcpy.p0i8.p0i8.i64
+// CHECK:call void @llvm.memcpy.p0i8.p0i8
   *P = *Q;
 }
 
-// CHECK: declare void @llvm.memcpy.p0i8.p0i8.i64(i8* noalias nocapture 
writeonly, i8* noalias nocapture readonly, i64, i1 immarg)
+// CHECK: declare void @llvm.memcpy.p0i8.p0i8{{.*}}(i8* noalias nocapture 
writeonly, i8* noalias nocapture readonly
 
 void bar(struct x *P, struct x *Q) {
 // CHECK-LABEL: @bar(
-// CHECK:call void @llvm.memcpy.p0i8.p0i8.i64
+// CHECK:call void @llvm.memcpy.p0i8.p0i8
   __builtin_memcpy(P, Q, sizeof(struct x));
 }


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


[PATCH] D27165: Add format_dynamic_key_arg attribute to improve "-Wformat" warnings for functions that load the formatting string dynamically based on a key value

2019-08-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

I like this approach much better! LGTM, aside from a minor nit.




Comment at: clang/include/clang/Basic/IdentifierTable.h:754
+  /// If this selector is the specific keyword selector described by Names.
+  bool isKeywordSelector(ArrayRef Names);
+

rjmccall wrote:
> Thanks.  Could you go ahead and add `isUnarySelector(StringRef)` for 
> consistency?
Also, the function should be marked `const`, I would imagine.


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

https://reviews.llvm.org/D27165



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


[PATCH] D65997: Add options rounding and exceptions to pragma fp

2019-08-14 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 215134.
sepavloff added a comment.

Updated patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65997

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParsePragma.cpp
  clang/test/Parser/pragma-fp.cpp

Index: clang/test/Parser/pragma-fp.cpp
===
--- clang/test/Parser/pragma-fp.cpp
+++ clang/test/Parser/pragma-fp.cpp
@@ -1,14 +1,14 @@
 // RUN: %clang_cc1 -std=c++11 -verify %s
 
 void test_0(int *List, int Length) {
-/* expected-error@+1 {{missing option; expected contract}} */
+/* expected-error@+1 {{missing option; expected 'contract', 'rounding' or 'exceptions'}} */
 #pragma clang fp
   for (int i = 0; i < Length; i++) {
 List[i] = i;
   }
 }
 void test_1(int *List, int Length) {
-/* expected-error@+1 {{invalid option 'blah'; expected contract}} */
+/* expected-error@+1 {{invalid option 'blah'; expected 'contract', 'rounding' or 'exceptions'}} */
 #pragma clang fp blah
   for (int i = 0; i < Length; i++) {
 List[i] = i;
@@ -62,3 +62,37 @@
 #pragma clang fp contract(fast)
   }
 }
+
+
+void test_10(float *dest, float a, float b) {
+/* expected-error@+1 {{expected '('}} */
+#pragma clang fp rounding on
+  *dest = a + b;
+}
+
+void test_11(float *dest, float a, float b) {
+/* expected-error@+1 {{unexpected argument 'while' to '#pragma clang fp rounding'; expected 'tonearest', 'downward', 'upward', 'towardzero' or 'dynamic'}} */
+#pragma clang fp rounding(while)
+  *dest = a + b;
+}
+
+void test_12(float *dest, float a, float b) {
+#pragma clang fp rounding(downward)
+  *dest = a + b;
+}
+
+void test_13(float *dest, float a, float b) {
+#pragma clang fp contract(fast) rounding(downward)
+  *dest = a + b;
+}
+
+void test_14(float *dest, float a, float b) {
+/* expected-error@+1 {{unexpected argument 'on' to '#pragma clang fp exceptions'; expected 'ignore', 'maytrap' or 'strict'}} */
+#pragma clang fp exceptions(on)
+  *dest = a + b;
+}
+
+void test_15(float *dest, float a, float b) {
+#pragma clang fp exceptions(maytrap) contract(fast) rounding(downward)
+  *dest = a + b;
+}
Index: clang/lib/Parse/ParsePragma.cpp
===
--- clang/lib/Parse/ParsePragma.cpp
+++ clang/lib/Parse/ParsePragma.cpp
@@ -2654,11 +2654,11 @@
 namespace {
 /// Used as the annotation value for tok::annot_pragma_fp.
 struct TokFPAnnotValue {
-  enum FlagKinds { Contract };
-  enum FlagValues { On, Off, Fast };
+  enum FlagKinds { Contract, RoundingMode, Exceptions };
 
-  FlagKinds FlagKind;
-  FlagValues FlagValue;
+  llvm::Optional ContractValue;
+  llvm::Optional RoundingModeValue;
+  llvm::Optional ExceptionsValue;
 };
 } // end anonymous namespace
 
@@ -2671,10 +2671,11 @@
   PP.Lex(Tok);
   if (Tok.isNot(tok::identifier)) {
 PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
-<< /*MissingOption=*/true << "";
+<< /*MissingOption=*/true;
 return;
   }
 
+  auto *AnnotValue = new (PP.getPreprocessorAllocator()) TokFPAnnotValue;
   while (Tok.is(tok::identifier)) {
 IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
 
@@ -2682,6 +2683,8 @@
 llvm::StringSwitch>(
 OptionInfo->getName())
 .Case("contract", TokFPAnnotValue::Contract)
+.Case("rounding", TokFPAnnotValue::RoundingMode)
+.Case("exceptions", TokFPAnnotValue::Exceptions)
 .Default(None);
 if (!FlagKind) {
   PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
@@ -2699,23 +2702,53 @@
 
 if (Tok.isNot(tok::identifier)) {
   PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
-  << PP.getSpelling(Tok) << OptionInfo->getName();
+  << PP.getSpelling(Tok) << OptionInfo->getName()
+  << *FlagKind;
   return;
 }
 const IdentifierInfo *II = Tok.getIdentifierInfo();
 
-auto FlagValue =
-llvm::StringSwitch>(
-II->getName())
-.Case("on", TokFPAnnotValue::On)
-.Case("off", TokFPAnnotValue::Off)
-.Case("fast", TokFPAnnotValue::Fast)
-.Default(llvm::None);
-
-if (!FlagValue) {
-  PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
-  << PP.getSpelling(Tok) << OptionInfo->getName();
-  return;
+if (FlagKind == TokFPAnnotValue::Contract) {
+  AnnotValue->ContractValue =
+  llvm::StringSwitch>(
+  II->getName())
+  .Case("on", LangOptions::FPContractModeKind::FPC_On)
+  .Case("off", LangOptions::FPContractModeKind::FPC_Off)
+  .Case("fast", LangOptions::FPContractModeKind::FPC_Fast)
+  .Default(llvm::None);
+  if (!AnnotValue->ContractValue) {
+PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
+

[PATCH] D65997: Add options rounding and exceptions to pragma fp

2019-08-14 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff marked 2 inline comments as done.
sepavloff added inline comments.



Comment at: clang/lib/Parse/ParsePragma.cpp:2697
 PP.Lex(Tok);
+StringRef ExpectedArgumentText;
+switch (*FlagKind) {

aaron.ballman wrote:
> sepavloff wrote:
> > aaron.ballman wrote:
> > > Same here.
> > This case is different from the above, the list of expected arguments 
> > depend on the current option.
> The case isn't different in the way that matters -- all of the strings that 
> get passed in to the diagnostic come from string literals. You should be able 
> to put the literals into the %select and map `TokFPAnnotValue::*` to an 
> index, right?
I see, thank you)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65997



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


[PATCH] D66206: [CodeGen] Don't keep stale pointers to LoopInfos

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

LGTM!


Repository:
  rC Clang

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

https://reviews.llvm.org/D66206



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


[PATCH] D62731: [RFC] Add support for options -fp-model= and -fp-speculation= : specify floating point behavior

2019-08-14 Thread Melanie Blower via Phabricator via cfe-commits
mibintc added a comment.

Here's a summary of how the rm and eb options are set

if user requests fp-model=strict, then the ConstrainedIntrinsic will be built 
with ( rmDynamic, ebStrict )

if user requests fp-model=except or fp-model=noexcept then the 
ConstrainedIntrinsic will be built with eb set to Strict or Ignore, 
respectively.  In all cases, if the user options don't otherwise request a 
value for the rounding mode, but the user options has requested a value for 
excepton behavior, then the ConstrainedIntrinsic will use rmToNearest.

The fp-speculation option controls only the eb setting.  There are 3 possible 
values: fast, strict, safe and the ConstrainedIntrinsic will be built with eb 
set to ebIgnore, ebStrict, ebMayTrap respectively.


Repository:
  rL LLVM

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

https://reviews.llvm.org/D62731



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


[PATCH] D66092: [CodeGen] Generate constrained fp intrinsics depending on FPOptions

2019-08-14 Thread Andy Kaylor via Phabricator via cfe-commits
andrew.w.kaylor added a comment.

In D66092#1627339 , @sepavloff wrote:

> In D66092#1625380 , @kpn wrote:
>
> > Also, if any constrained intrinsics are used in a function then the entire 
> > function needs to be constrained. Is this handled anywhere?
>
>
> If we decided to make the entire function constrained, it should be done 
> somewhere in IR transformations, because inlining may mix function bodies 
> with different fp options.


Kevin is right. We have decided that if constrained intrinsics are used 
anywhere in a function they must be used throughout the function. Otherwise, 
there would be nothing to prevent the non-constrained FP operations from 
migrating across constrained operations and the handling could get botched. The 
"relaxed" arguments ("round.tonearest" and "fpexcept.ignore") should be used 
where the default settings would apply. The front end should also be setting 
the "strictfp" attribute on calls within a constrained scope and, I think, 
functions that contain constrained intrinsics.

We will need to teach the inliner to enforce this rule if it isn't already 
doing so, but if things aren't correct coming out of the front end an incorrect 
optimization could already happen before we get to the inliner. We always rely 
on the front end producing IR with fully correct semantics.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66092



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


[PATCH] D65997: Add options rounding and exceptions to pragma fp

2019-08-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

This generally LGTM, but there are open questions on 
https://reviews.llvm.org/D66092#1625380 that I think need to be answered before 
this should be committed.




Comment at: clang/lib/Parse/ParsePragma.cpp:2678
 
+  auto *AnnotValue = new (PP.getPreprocessorAllocator()) TokFPAnnotValue;
   while (Tok.is(tok::identifier)) {

Might as well move this down to around line 2710, closer to where it's used. 
This way we don't allocate something only to ignore it due to errors in fewer 
situations.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D65997



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


[PATCH] D66226: [clangd] Skip function bodies inside processed files while indexing

2019-08-14 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov created this revision.
ilya-biryukov added reviewers: kadircet, sammccall.
Herald added subscribers: arphaman, jkorous, MaskRay.
Herald added a project: clang.

This significantly improves performance of background indexing.

We do not collect references and declarations inside the processed
files, so this does not affect the final indexing results.

The idea is borrowed from libclang, which has a similar optimization in
its indexing functionality.

Measurements show a nice decrease in indexing time, up to ~40% for
building the whole index. These are not proper benchmarks, so one should
not rely on these results too much.

1. Rebuilding the whole index:
  - Before. Total time: 14m58s. ./bin/clangd -pch-storage=memory < 
./clangd.input  23917.67s user 515.86s system 2718% cpu 14:58.68 total
  - After. Total time: 8m40s. ./bin/clangd -pch-storage=memory < ./clangd.input 
 13627.29s user 288.10s system 2672% cpu 8:40.67 total

2. Rebuilding index after removing shards matching '*clangd*' 
(case-insensitively):
  - Before. Total time: 30s. ./bin/clangd -pch-storage=memory < ./clangd.input  
130.94s user 6.82s system 452% cpu 30.423 total
  - After. Total time: 26s. ./bin/clangd -pch-storage=memory < ./clangd.input  
80.51s user 5.40s system 333% cpu 25.777 total


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D66226

Files:
  clang-tools-extra/clangd/index/IndexAction.cpp
  clang-tools-extra/clangd/index/SymbolCollector.cpp
  clang-tools-extra/clangd/index/SymbolCollector.h

Index: clang-tools-extra/clangd/index/SymbolCollector.h
===
--- clang-tools-extra/clangd/index/SymbolCollector.h
+++ clang-tools-extra/clangd/index/SymbolCollector.h
@@ -112,6 +112,11 @@
   RefSlab takeRefs() { return std::move(Refs).build(); }
   RelationSlab takeRelations() { return std::move(Relations).build(); }
 
+  /// Returns true if we are interested in references and declarations from \p
+  /// FID. If this function return false, bodies of functions inside those files
+  /// will be skipped to decrease indexing time.
+  bool shouldProcessFile(FileID FID);
+
   void finish() override;
 
 private:
Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -742,5 +742,12 @@
   return false;
 }
 
+bool SymbolCollector::shouldProcessFile(FileID FID) {
+  assert(ASTCtx);
+  if (!Opts.FileFilter)
+return true;
+  return Opts.FileFilter(ASTCtx->getSourceManager(), FID);
+}
+
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/index/IndexAction.cpp
===
--- clang-tools-extra/clangd/index/IndexAction.cpp
+++ clang-tools-extra/clangd/index/IndexAction.cpp
@@ -11,9 +11,17 @@
 #include "Logger.h"
 #include "index/Relation.h"
 #include "index/SymbolOrigin.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
 #include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/MultiplexConsumer.h"
 #include "clang/Index/IndexingAction.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/STLExtras.h"
+#include 
+#include 
 #include 
 
 namespace clang {
@@ -113,6 +121,40 @@
   IncludeGraph &IG;
 };
 
+/// Returns an ASTConsumer that wraps \p Inner and additionally instructs the
+/// parser to skip bodies of functions in the files that should not be
+/// processed.
+static std::unique_ptr
+skipProcessedFunctions(std::unique_ptr Inner,
+   std::function ShouldProcessFile) {
+  class SkipProcessedFunctions : public ASTConsumer {
+  public:
+SkipProcessedFunctions(std::function FileFilter)
+: ShouldProcessFile(std::move(FileFilter)), Context(nullptr) {
+  assert(this->ShouldProcessFile);
+}
+
+void Initialize(ASTContext &Context) override { this->Context = &Context; }
+bool shouldSkipFunctionBody(Decl *D) override {
+  assert(Context && "Initialize() was never called.");
+  auto &SM = Context->getSourceManager();
+  auto FID = SM.getFileID(SM.getExpansionLoc(D->getLocation()));
+  if (!FID.isValid())
+return false;
+  return !ShouldProcessFile(FID);
+}
+
+  private:
+std::function ShouldProcessFile;
+const ASTContext *Context;
+  };
+  std::vector> Consumers;
+  Consumers.push_back(
+  llvm::make_unique(ShouldProcessFile));
+  Consumers.push_back(std::move(Inner));
+  return llvm::make_unique(std::move(Consumers));
+}
+
 // Wraps the index action and reports index data after each translation unit.
 class IndexAction : public WrapperFrontendAction {
 public:
@@ -137,7 +179,9 @@
 if (IncludeGraphCallback != nullptr)
   CI.getPreprocessor().addPPCallbacks(
   llvm::make_unique(C

[PATCH] D66221: [clangd] Added highlighting for non type templates.

2019-08-14 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:231
+  if (TP->isFunctionPointerType()) {
+addToken(Loc, HighlightingKind::Function);
+return;

Why do we special-case template parameters, but not other kinds of variables?
We definitely need a comment explaining why template parameters are handled in 
a special way, but variables, parameters, fields are not.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D66221



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


r368871 - [LifetimeAnalysis] Fix false negatives of statement local lifetime analysis for some STL implementation

2019-08-14 Thread Gabor Horvath via cfe-commits
Author: xazax
Date: Wed Aug 14 09:34:56 2019
New Revision: 368871

URL: http://llvm.org/viewvc/llvm-project?rev=368871&view=rev
Log:
[LifetimeAnalysis] Fix false negatives of statement local lifetime analysis for 
some STL implementation

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

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=368871&r1=368870&r2=368871&view=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Wed Aug 14 09:34:56 2019
@@ -16,6 +16,7 @@
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
 #include "clang/AST/TypeLoc.h"
+#include "clang/Basic/CharInfo.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/Initialization.h"
@@ -6564,11 +6565,29 @@ template  static bool isReco
   return false;
 }
 
+// Decl::isInStdNamespace will return false for iterators in some STL
+// implementations due to them being defined in a namespace outside of the std
+// namespace.
+static bool isInStlNamespace(const Decl *D) {
+  const DeclContext *DC = D->getDeclContext();
+  if (!DC)
+return false;
+  if (const auto *ND = dyn_cast(DC))
+if (const IdentifierInfo *II = ND->getIdentifier()) {
+  StringRef Name = II->getName();
+  if (Name.size() >= 2 && Name.front() == '_' &&
+  (Name[1] == '_' || isUppercase(Name[1])))
+return true;
+}
+
+  return DC->isStdNamespace();
+}
+
 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
   if (auto *Conv = dyn_cast_or_null(Callee))
 if (isRecordWithAttr(Conv->getConversionType()))
   return true;
-  if (!Callee->getParent()->isInStdNamespace())
+  if (!isInStlNamespace(Callee->getParent()))
 return false;
   if (!isRecordWithAttr(Callee->getThisObjectType()) &&
   !isRecordWithAttr(Callee->getThisObjectType()))
@@ -7107,25 +7126,29 @@ void Sema::checkInitializerLifetime(cons
 SourceLocation DiagLoc = DiagRange.getBegin();
 
 auto *MTE = dyn_cast(L);
-bool IsTempGslOwner = MTE && !MTE->getExtendingDecl() &&
-  isRecordWithAttr(MTE->getType());
-bool IsLocalGslOwner =
-isa(L) && isRecordWithAttr(L->getType());
-
-// Skipping a chain of initializing gsl::Pointer annotated objects.
-// We are looking only for the final source to find out if it was
-// a local or temporary owner or the address of a local variable/param. We
-// do not want to follow the references when returning a pointer 
originating
-// from a local owner to avoid the following false positive:
-//   int &p = *localUniquePtr;
-//   someContainer.add(std::move(localUniquePtr));
-//   return p;
-if (!IsTempGslOwner && pathOnlyInitializesGslPointer(Path) &&
-!(IsLocalGslOwner && !pathContainsInit(Path)))
-  return true;
 
-bool IsGslPtrInitWithGslTempOwner =
-IsTempGslOwner && pathOnlyInitializesGslPointer(Path);
+bool IsGslPtrInitWithGslTempOwner = false;
+bool IsLocalGslOwner = false;
+if (pathOnlyInitializesGslPointer(Path)) {
+  if (isa(L)) {
+// We do not want to follow the references when returning a pointer 
originating
+// from a local owner to avoid the following false positive:
+//   int &p = *localUniquePtr;
+//   someContainer.add(std::move(localUniquePtr));
+//   return p;
+IsLocalGslOwner = isRecordWithAttr(L->getType());
+if (pathContainsInit(Path) || !IsLocalGslOwner)
+  return false;
+  } else {
+IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
+isRecordWithAttr(MTE->getType());
+// Skipping a chain of initializing gsl::Pointer annotated objects.
+// We are looking only for the final source to find out if it was
+// a local or temporary owner or the address of a local variable/param.
+if (!IsGslPtrInitWithGslTempOwner)
+  return true;
+  }
+}
 
 switch (LK) {
 case LK_FullExpression:

Modified: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp?rev=368871&r1=368870&r2=368871&view=diff
==
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp (original)
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp Wed Aug 14 09:34:56 
2019
@@ -119,14 +119,7 @@ void initLocalGslPtrWithTempOwner() {
   global2 = MyLongOwnerWithConversion{}; // TODO ?
 }
 
-namespace std {
-template struct remove_reference   { typedef T type; };
-template struct remove_reference  { typedef T type; };
-template struct remove_re

[PATCH] D66152: Fix false negatives of statement local lifetime analysis for some STL implementation

2019-08-14 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL368871: [LifetimeAnalysis] Fix false negatives of statement 
local lifetime analysis for… (authored by xazax, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D66152?vs=214872&id=215144#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D66152

Files:
  cfe/trunk/lib/Sema/SemaInit.cpp
  cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp

Index: cfe/trunk/lib/Sema/SemaInit.cpp
===
--- cfe/trunk/lib/Sema/SemaInit.cpp
+++ cfe/trunk/lib/Sema/SemaInit.cpp
@@ -16,6 +16,7 @@
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
 #include "clang/AST/TypeLoc.h"
+#include "clang/Basic/CharInfo.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/Initialization.h"
@@ -6564,11 +6565,29 @@
   return false;
 }
 
+// Decl::isInStdNamespace will return false for iterators in some STL
+// implementations due to them being defined in a namespace outside of the std
+// namespace.
+static bool isInStlNamespace(const Decl *D) {
+  const DeclContext *DC = D->getDeclContext();
+  if (!DC)
+return false;
+  if (const auto *ND = dyn_cast(DC))
+if (const IdentifierInfo *II = ND->getIdentifier()) {
+  StringRef Name = II->getName();
+  if (Name.size() >= 2 && Name.front() == '_' &&
+  (Name[1] == '_' || isUppercase(Name[1])))
+return true;
+}
+
+  return DC->isStdNamespace();
+}
+
 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
   if (auto *Conv = dyn_cast_or_null(Callee))
 if (isRecordWithAttr(Conv->getConversionType()))
   return true;
-  if (!Callee->getParent()->isInStdNamespace())
+  if (!isInStlNamespace(Callee->getParent()))
 return false;
   if (!isRecordWithAttr(Callee->getThisObjectType()) &&
   !isRecordWithAttr(Callee->getThisObjectType()))
@@ -7107,25 +7126,29 @@
 SourceLocation DiagLoc = DiagRange.getBegin();
 
 auto *MTE = dyn_cast(L);
-bool IsTempGslOwner = MTE && !MTE->getExtendingDecl() &&
-  isRecordWithAttr(MTE->getType());
-bool IsLocalGslOwner =
-isa(L) && isRecordWithAttr(L->getType());
-
-// Skipping a chain of initializing gsl::Pointer annotated objects.
-// We are looking only for the final source to find out if it was
-// a local or temporary owner or the address of a local variable/param. We
-// do not want to follow the references when returning a pointer originating
-// from a local owner to avoid the following false positive:
-//   int &p = *localUniquePtr;
-//   someContainer.add(std::move(localUniquePtr));
-//   return p;
-if (!IsTempGslOwner && pathOnlyInitializesGslPointer(Path) &&
-!(IsLocalGslOwner && !pathContainsInit(Path)))
-  return true;
 
-bool IsGslPtrInitWithGslTempOwner =
-IsTempGslOwner && pathOnlyInitializesGslPointer(Path);
+bool IsGslPtrInitWithGslTempOwner = false;
+bool IsLocalGslOwner = false;
+if (pathOnlyInitializesGslPointer(Path)) {
+  if (isa(L)) {
+// We do not want to follow the references when returning a pointer originating
+// from a local owner to avoid the following false positive:
+//   int &p = *localUniquePtr;
+//   someContainer.add(std::move(localUniquePtr));
+//   return p;
+IsLocalGslOwner = isRecordWithAttr(L->getType());
+if (pathContainsInit(Path) || !IsLocalGslOwner)
+  return false;
+  } else {
+IsGslPtrInitWithGslTempOwner = MTE && !MTE->getExtendingDecl() &&
+isRecordWithAttr(MTE->getType());
+// Skipping a chain of initializing gsl::Pointer annotated objects.
+// We are looking only for the final source to find out if it was
+// a local or temporary owner or the address of a local variable/param.
+if (!IsGslPtrInitWithGslTempOwner)
+  return true;
+  }
+}
 
 switch (LK) {
 case LK_FullExpression:
Index: cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
===
--- cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ cfe/trunk/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -119,14 +119,7 @@
   global2 = MyLongOwnerWithConversion{}; // TODO ?
 }
 
-namespace std {
-template struct remove_reference   { typedef T type; };
-template struct remove_reference  { typedef T type; };
-template struct remove_reference { typedef T type; };
-
-template
-typename remove_reference::type &&move(T &&t) noexcept;
-
+namespace __gnu_cxx {
 template 
 struct basic_iterator {
   basic_iterator operator++();
@@ -135,10 +128,19 @@
 
 template
 bool operator!=(basic_iterator, basic_iter

  1   2   3   >