[PATCH] D48459: Respect CMAKE_SYSROOT and CMAKE_CROSSCOMPILING when searching for libxml2.

2018-07-06 Thread Stephen Hines via Phabricator via cfe-commits
srhines abandoned this revision.
srhines added a comment.

Removed this in favor of the suggestions here. Setting the 
CMAKE_FIND_ROOT_PATH_MODE* variables does make this properly hermetic.


Repository:
  rC Clang

https://reviews.llvm.org/D48459



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


[PATCH] D49051: [libclang] check that the cursor is declaration before trying to evaluate the cursor like a declaration

2018-07-06 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman created this revision.
arphaman added a reviewer: dexonsmith.

There's a bug in libclang in which it tries to evaluate a statement cursor as a 
declaration cursor, because that statement still has a pointer to the 
declaration parent. This patch fixes it.

rdar://3477


Repository:
  rC Clang

https://reviews.llvm.org/D49051

Files:
  tools/libclang/CIndex.cpp
  unittests/libclang/LibclangTest.cpp


Index: unittests/libclang/LibclangTest.cpp
===
--- unittests/libclang/LibclangTest.cpp
+++ unittests/libclang/LibclangTest.cpp
@@ -461,6 +461,47 @@
   clang_disposeSourceRangeList(Ranges);
 }
 
+TEST_F(LibclangParseTest, EvaluateChildExpression) {
+  std::string Main = "main.m";
+  WriteFile(Main, "#define kFOO @\"foo\"\n"
+  "void foobar(void) {\n"
+  " {kFOO;}\n"
+  "}\n");
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0, 
nullptr,
+   0, TUFlags);
+
+  CXCursor C = clang_getTranslationUnitCursor(ClangTU);
+  clang_visitChildren(
+  C,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+if (clang_getCursorKind(cursor) == CXCursor_FunctionDecl) {
+  int numberedStmt = 0;
+  clang_visitChildren(
+  cursor,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+int  = *((int *)client_data);
+if (clang_getCursorKind(cursor) == CXCursor_CompoundStmt) {
+  if (numberedStmt) {
+CXEvalResult RE = clang_Cursor_Evaluate(cursor);
+EXPECT_NE(RE, nullptr);
+EXPECT_EQ(clang_EvalResult_getKind(RE),
+  CXEval_ObjCStrLiteral);
+return CXChildVisit_Break;
+  }
+  numberedStmt++;
+}
+return CXChildVisit_Recurse;
+  },
+  );
+  EXPECT_EQ(numberedStmt, 1);
+}
+return CXChildVisit_Continue;
+  },
+  nullptr);
+}
+
 class LibclangReparseTest : public LibclangParseTest {
 public:
   void DisplayDiagnostics() {
Index: tools/libclang/CIndex.cpp
===
--- tools/libclang/CIndex.cpp
+++ tools/libclang/CIndex.cpp
@@ -3890,18 +3890,20 @@
 }
 
 CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
-  const Decl *D = getCursorDecl(C);
-  if (D) {
-const Expr *expr = nullptr;
-if (auto *Var = dyn_cast(D)) {
-  expr = Var->getInit();
-} else if (auto *Field = dyn_cast(D)) {
-  expr = Field->getInClassInitializer();
+  if (clang_isDeclaration(C.kind)) {
+const Decl *D = getCursorDecl(C);
+if (D) {
+  const Expr *expr = nullptr;
+  if (auto *Var = dyn_cast(D)) {
+expr = Var->getInit();
+  } else if (auto *Field = dyn_cast(D)) {
+expr = Field->getInClassInitializer();
+  }
+  if (expr)
+return const_cast(reinterpret_cast(
+evaluateExpr(const_cast(expr), C)));
+  return nullptr;
 }
-if (expr)
-  return const_cast(reinterpret_cast(
-  evaluateExpr(const_cast(expr), C)));
-return nullptr;
   }
 
   const CompoundStmt *compoundStmt = 
dyn_cast_or_null(getCursorStmt(C));


Index: unittests/libclang/LibclangTest.cpp
===
--- unittests/libclang/LibclangTest.cpp
+++ unittests/libclang/LibclangTest.cpp
@@ -461,6 +461,47 @@
   clang_disposeSourceRangeList(Ranges);
 }
 
+TEST_F(LibclangParseTest, EvaluateChildExpression) {
+  std::string Main = "main.m";
+  WriteFile(Main, "#define kFOO @\"foo\"\n"
+  "void foobar(void) {\n"
+  " {kFOO;}\n"
+  "}\n");
+  ClangTU = clang_parseTranslationUnit(Index, Main.c_str(), nullptr, 0, nullptr,
+   0, TUFlags);
+
+  CXCursor C = clang_getTranslationUnitCursor(ClangTU);
+  clang_visitChildren(
+  C,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+if (clang_getCursorKind(cursor) == CXCursor_FunctionDecl) {
+  int numberedStmt = 0;
+  clang_visitChildren(
+  cursor,
+  [](CXCursor cursor, CXCursor parent,
+ CXClientData client_data) -> CXChildVisitResult {
+int  = *((int *)client_data);
+if (clang_getCursorKind(cursor) == CXCursor_CompoundStmt) {
+  if (numberedStmt) {
+CXEvalResult RE = clang_Cursor_Evaluate(cursor);
+EXPECT_NE(RE, nullptr);
+EXPECT_EQ(clang_EvalResult_getKind(RE),
+  CXEval_ObjCStrLiteral);
+return 

r336478 - [Sema] Emit -Wincomplete-implementation for partial methods.

2018-07-06 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Fri Jul  6 18:50:20 2018
New Revision: 336478

URL: http://llvm.org/viewvc/llvm-project?rev=336478=rev
Log:
[Sema] Emit -Wincomplete-implementation for partial methods.

Fixes rdar://40634455

Modified:
cfe/trunk/lib/Sema/SemaDeclObjC.cpp
cfe/trunk/test/SemaObjC/incomplete-implementation.m

Modified: cfe/trunk/lib/Sema/SemaDeclObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclObjC.cpp?rev=336478=336477=336478=diff
==
--- cfe/trunk/lib/Sema/SemaDeclObjC.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclObjC.cpp Fri Jul  6 18:50:20 2018
@@ -2188,17 +2188,9 @@ static void WarnUndefinedMethod(Sema ,
 unsigned DiagID,
 NamedDecl *NeededFor = nullptr) {
   // No point warning no definition of method which is 'unavailable'.
-  switch (method->getAvailability()) {
-  case AR_Available:
-  case AR_Deprecated:
-break;
-
-  // Don't warn about unavailable or not-yet-introduced methods.
-  case AR_NotYetIntroduced:
-  case AR_Unavailable:
+  if (method->getAvailability() == AR_Unavailable)
 return;
-  }
-  
+
   // FIXME: For now ignore 'IncompleteImpl'.
   // Previously we grouped all unimplemented methods under a single
   // warning, but some users strongly voiced that they would prefer

Modified: cfe/trunk/test/SemaObjC/incomplete-implementation.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaObjC/incomplete-implementation.m?rev=336478=336477=336478=diff
==
--- cfe/trunk/test/SemaObjC/incomplete-implementation.m (original)
+++ cfe/trunk/test/SemaObjC/incomplete-implementation.m Fri Jul  6 18:50:20 2018
@@ -13,6 +13,13 @@
 - Meth {return 0;} // expected-warning {{category is implementing a method 
which will also be implemented by its primary class}}
 @end
 
+// rdar://40634455
+@interface MyClass
+-(void)mymeth __attribute__((availability(macos, introduced=100))); // 
expected-note{{here}}
+@end
+@implementation MyClass // expected-warning{{'mymeth' not found}}
+@end
+
 #pragma GCC diagnostic ignored "-Wincomplete-implementation"
 @interface I2
 - Meth; // expected-note{{method 'Meth' declared here}}


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


[PATCH] D47814: Teach libc++ to use native NetBSD's max_align_t

2018-07-06 Thread Chandler Carruth via Phabricator via cfe-commits
chandlerc resigned from this revision.
chandlerc added a comment.

I don't have any problem with this patch's code in theory but:

1. The question of whether this macro approach is better or worse than 
FreeBSD's or MUSL's seems a question for libc++ maintainers, not me.
2. The question of whether this is correct for NetBSD seems for the NetBSD 
maintainer.

Since the above folks are already on the list of reviewers, I'll bow out of 
this review.




Comment at: include/stddef.h:55
 
 // Re-use the compiler's  max_align_t where possible.
 #if !defined(__CLANG_MAX_ALIGN_T_DEFINED) && !defined(_GCC_MAX_ALIGN_T) && \

Unrelated to your patch, but this comment is now amazingly out of place.


Repository:
  rL LLVM

https://reviews.llvm.org/D47814



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


r336475 - Check returned type is valid before using it.

2018-07-06 Thread Richard Trieu via cfe-commits
Author: rtrieu
Date: Fri Jul  6 17:17:25 2018
New Revision: 336475

URL: http://llvm.org/viewvc/llvm-project?rev=336475=rev
Log:
Check returned type is valid before using it.

Add a .isNull() check to returned QualType.  Fixes PR38077

Modified:
cfe/trunk/lib/Sema/SemaCXXScopeSpec.cpp
cfe/trunk/test/SemaCXX/overloaded-name.cpp

Modified: cfe/trunk/lib/Sema/SemaCXXScopeSpec.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCXXScopeSpec.cpp?rev=336475=336474=336475=diff
==
--- cfe/trunk/lib/Sema/SemaCXXScopeSpec.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCXXScopeSpec.cpp Fri Jul  6 17:17:25 2018
@@ -846,6 +846,9 @@ bool Sema::ActOnCXXNestedNameSpecifierDe
   assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
 
   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
+  if (T.isNull())
+return true;
+
   if (!T->isDependentType() && !T->getAs()) {
 Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace) 
   << T << getLangOpts().CPlusPlus;

Modified: cfe/trunk/test/SemaCXX/overloaded-name.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/overloaded-name.cpp?rev=336475=336474=336475=diff
==
--- cfe/trunk/test/SemaCXX/overloaded-name.cpp (original)
+++ cfe/trunk/test/SemaCXX/overloaded-name.cpp Fri Jul  6 17:17:25 2018
@@ -28,3 +28,11 @@ namespace rdar9623945 {
 }
   };
 }
+
+namespace PR38077 {
+  template  void bar() {} // expected-note {{possible target for 
call}}
+
+  int run() {
+decltype(bar)::does_not_exist; // expected-error {{reference to overloaded 
function could not be resolved; did you mean to call it?}}
+  }
+}


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


[PATCH] D48412: [RISCV] Add support for interrupt attribute

2018-07-06 Thread Ana Pazos via Phabricator via cfe-commits
apazos added a comment.

Hi Aaron, I have commit rights and will commit if after Alex and other RISC-V 
colleagues get a chance to review too.


https://reviews.llvm.org/D48412



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


[PATCH] D45712: Diagnose invalid cv-qualifiers for friend decls.

2018-07-06 Thread Eli Friedman via Phabricator via cfe-commits
efriedma updated this revision to Diff 154471.
efriedma retitled this revision from "[WIP] Diagnose invalid cv-qualifiers for 
friend decls." to "Diagnose invalid cv-qualifiers for friend decls.".
efriedma edited the summary of this revision.
efriedma added a comment.

Updated to handle the template case.


Repository:
  rC Clang

https://reviews.llvm.org/D45712

Files:
  lib/Parse/ParseDeclCXX.cpp
  lib/Sema/SemaDeclCXX.cpp
  test/CXX/class.access/class.friend/p3-cxx0x.cpp
  test/Modules/odr_hash.cpp

Index: test/Modules/odr_hash.cpp
===
--- test/Modules/odr_hash.cpp
+++ test/Modules/odr_hash.cpp
@@ -2048,22 +2048,6 @@
 #endif
 
 #if defined(FIRST)
-struct T3 {};
-struct S3 {
-  friend const T3;
-};
-#elif defined(SECOND)
-struct T3 {};
-struct S3 {
-  friend T3;
-};
-#else
-S3 s3;
-// expected-error@second.h:* {{'Friend::S3' has different definitions in different modules; first difference is definition in module 'SecondModule' found friend 'Friend::T3'}}
-// expected-note@first.h:* {{but in 'FirstModule' found friend 'const Friend::T3'}}
-#endif
-
-#if defined(FIRST)
 struct T4 {};
 struct S4 {
   friend T4;
@@ -2096,14 +2080,12 @@
   friend class FriendA;  \
   friend struct FriendB; \
   friend FriendC;\
-  friend const FriendD;  \
   friend void Function();
 
 #if defined(FIRST) || defined(SECOND)
 class FriendA {};
 class FriendB {};
 class FriendC {};
-class FriendD {};
 #endif
 
 #if defined(FIRST) || defined(SECOND)
Index: test/CXX/class.access/class.friend/p3-cxx0x.cpp
===
--- test/CXX/class.access/class.friend/p3-cxx0x.cpp
+++ test/CXX/class.access/class.friend/p3-cxx0x.cpp
@@ -52,14 +52,25 @@
   // Ill-formed
   int friend; // expected-error {{'friend' must appear first in a non-function declaration}}
   unsigned friend int; // expected-error {{'friend' must appear first in a non-function declaration}}
-  const volatile friend int; // expected-error {{'friend' must appear first in a non-function declaration}}
+  const volatile friend int; // expected-error {{'friend' must appear first in a non-function declaration}} \
+ // expected-error {{'const' is invalid in friend declarations}} \
+ // expected-error {{'volatile' is invalid in friend declarations}}
   int
   friend; // expected-error {{'friend' must appear first in a non-function declaration}}
+  friend const int; // expected-error {{'const' is invalid in friend declarations}}
+  friend volatile int; // expected-error {{'volatile' is invalid in friend declarations}}
+  template  friend const class X; // expected-error {{'const' is invalid in friend declarations}}
+  // C++ doesn't have restrict and _Atomic, but they're both the same sort
+  // of qualifier.
+  typedef int *PtrToInt;
+  friend __restrict PtrToInt; // expected-error {{'restrict' is invalid in friend declarations}} \
+  // expected-error {{restrict requires a pointer or reference}}
+  friend _Atomic int; // expected-error {{'_Atomic' is invalid in friend declarations}}
 
   // OK
   int friend foo(void);
+  const int friend foo2(void);
   friend int;
-  friend const volatile int;
   friend
 
   float;
Index: lib/Sema/SemaDeclCXX.cpp
===
--- lib/Sema/SemaDeclCXX.cpp
+++ lib/Sema/SemaDeclCXX.cpp
@@ -14067,6 +14067,29 @@
 return nullptr;
   }
 
+  // C++ [class.friend]p3:
+  // A friend declaration that does not declare a function shall have one of
+  // the following forms:
+  // friend elaborated-type-specifier ;
+  // friend simple-type-specifier ;
+  // friend typename-specifier ;
+  //
+  // Any declaration with a type qualifier does not have that form. (It's
+  // legal to specify a qualified type as a friend, you just can't write the
+  // keywords.)
+  if (DS.getTypeQualifiers()) {
+if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
+  Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
+if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
+  Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
+if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
+  Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
+if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
+  Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
+if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
+  Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
+  }
+
   // C++98 [class.friend]p1: A friend of a class is a function
   //   or class that is not a member of the class . . .
   // This is fixed in DR77, which just barely didn't make the C++03
Index: lib/Parse/ParseDeclCXX.cpp
===
--- 

[PATCH] D48395: Added PublicOnly flag

2018-07-06 Thread Annie Cherkaev via Phabricator via cfe-commits
anniecherk updated this revision to Diff 154470.
anniecherk added a comment.

Updated according to Julie's suggestions, mostly adjusted formatting.


https://reviews.llvm.org/D48395

Files:
  clang-tools-extra/clang-doc/ClangDoc.cpp
  clang-tools-extra/clang-doc/ClangDoc.h
  clang-tools-extra/clang-doc/Mapper.cpp
  clang-tools-extra/clang-doc/Mapper.h
  clang-tools-extra/clang-doc/Representation.cpp
  clang-tools-extra/clang-doc/Representation.h
  clang-tools-extra/clang-doc/Serialize.cpp
  clang-tools-extra/clang-doc/Serialize.h
  clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
  clang-tools-extra/test/clang-doc/yaml-module.cpp
  clang-tools-extra/test/clang-doc/yaml-public-module.cpp
  clang-tools-extra/test/clang-doc/yaml-public-records.cpp

Index: clang-tools-extra/test/clang-doc/yaml-public-records.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-doc/yaml-public-records.cpp
@@ -0,0 +1,339 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo "" > %t/compile_flags.txt
+// RUN: cp "%s" "%t/test.cpp"
+// RUN: clang-doc --public --doxygen -p %t %t/test.cpp -output=%t/docs
+// RUN: clang-doc --doxygen -p %t %t/test.cpp -output=%t/docs-without-flag
+// RUN: cat %t/docs/function.yaml | FileCheck %s --check-prefix=CHECK-A
+// RUN: cat %t/docs/inlinedFunction.yaml | FileCheck %s --check-prefix=CHECK-B
+// RUN: cat %t/docs/functionWithInnerClass.yaml | FileCheck %s --check-prefix=CHECK-C
+// RUN: cat %t/docs/inlinedFunctionWithInnerClass.yaml | FileCheck %s --check-prefix=CHECK-D
+// RUN: cat %t/docs/Class/publicMethod.yaml| FileCheck %s --check-prefix=CHECK-E
+// RUN: cat %t/docs/Class.yaml| FileCheck %s --check-prefix=CHECK-F
+// RUN: cat %t/docs/Class/protectedMethod.yaml| FileCheck %s --check-prefix=CHECK-G
+// RUN: cat %t/docs/named.yaml| FileCheck %s --check-prefix=CHECK-H
+// RUN: cat %t/docs/named/NamedClass.yaml| FileCheck %s --check-prefix=CHECK-I
+// RUN: cat %t/docs/named/namedFunction.yaml| FileCheck %s --check-prefix=CHECK-J
+// RUN: cat %t/docs/named/namedInlineFunction.yaml| FileCheck %s --check-prefix=CHECK-K
+// RUN: cat %t/docs/named/NamedClass/namedPublicMethod.yaml| FileCheck %s --check-prefix=CHECK-L
+// RUN: cat %t/docs/named/NamedClass/namedProtectedMethod.yaml| FileCheck %s --check-prefix=CHECK-M
+// RUN: (diff -qry %t/docs-without-flag %t/docs | sed 's:.*/::' > %t/public.diff) || true
+// RUN: cat %t/public.diff | FileCheck %s --check-prefix=CHECK-N
+
+void function(int x);
+
+// CHECK-A: ---
+// CHECK-A-NEXT: USR: '{{[0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z]}}'
+// CHECK-A-NEXT: Name:'function'
+// CHECK-A-NEXT: Location:
+// CHECK-A-NEXT:   - LineNumber:  23
+// CHECK-A-NEXT: Filename:{{.*}}
+// CHECK-A-NEXT: Params:
+// CHECK-A-NEXT:   - Type:
+// CHECK-A-NEXT:   Name:'int'
+// CHECK-A-NEXT: Name:'x'
+// CHECK-A-NEXT: ReturnType:
+// CHECK-A-NEXT:   Type:
+// CHECK-A-NEXT: Name:'void'
+// CHECK-A-NEXT: ...
+
+inline int inlinedFunction(int x);
+
+// CHECK-B: ---
+// CHECK-B-NEXT: USR: '{{[0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z]}}'
+// CHECK-B-NEXT: Name:'inlinedFunction'
+// CHECK-B-NEXT: Location:
+// CHECK-B-NEXT:   - LineNumber:  40
+// CHECK-B-NEXT: Filename:{{.*}}
+// CHECK-B-NEXT: Params:
+// CHECK-B-NEXT:   - Type:
+// CHECK-B-NEXT:   Name:'int'
+// CHECK-B-NEXT: Name:'x'
+// CHECK-B-NEXT: ReturnType:
+// CHECK-B-NEXT:   Type:
+// CHECK-B-NEXT: Name:'int'
+// CHECK-B-NEXT: ...
+
+int functionWithInnerClass(int x){
+class InnerClass { //NoLinkage
+  public:
+int innerPublicMethod() { return 2; };
+}; //end class
+InnerClass temp;
+return temp.innerPublicMethod();
+};
+
+// CHECK-C: ---
+// CHECK-C-NEXT: USR: '{{[0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z][0-9A-Z]}}'
+// CHECK-C-NEXT: Name:'functionWithInnerClass'
+// CHECK-C-NEXT: DefLocation:
+// CHECK-C-NEXT:   LineNumber:  57
+// CHECK-C-NEXT:   Filename:{{.*}}
+// CHECK-C-NEXT: Params:
+// CHECK-C-NEXT:   

r336472 - [X86] When creating a select for scalar masked sqrt and div builtins make sure we optimize the all ones mask case.

2018-07-06 Thread Craig Topper via cfe-commits
Author: ctopper
Date: Fri Jul  6 15:46:52 2018
New Revision: 336472

URL: http://llvm.org/viewvc/llvm-project?rev=336472=rev
Log:
[X86] When creating a select for scalar masked sqrt and div builtins make sure 
we optimize the all ones mask case.

This case occurs in the intrinsic headers so we should avoid emitting the mask 
in those cases.

Factor the code into a helper function to make this easy.

Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/test/CodeGen/avx512f-builtins.c

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=336472=336471=336472=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Fri Jul  6 15:46:52 2018
@@ -8517,6 +8517,21 @@ static Value *EmitX86Select(CodeGenFunct
   return CGF.Builder.CreateSelect(Mask, Op0, Op1);
 }
 
+static Value *EmitX86ScalarSelect(CodeGenFunction ,
+  Value *Mask, Value *Op0, Value *Op1) {
+  // If the mask is all ones just return first argument.
+  if (const auto *C = dyn_cast(Mask))
+if (C->isAllOnesValue())
+  return Op0;
+
+  llvm::VectorType *MaskTy =
+llvm::VectorType::get(CGF.Builder.getInt1Ty(),
+  Mask->getType()->getIntegerBitWidth());
+  Mask = CGF.Builder.CreateBitCast(Mask, MaskTy);
+  Mask = CGF.Builder.CreateExtractElement(Mask, (uint64_t)0);
+  return CGF.Builder.CreateSelect(Mask, Op0, Op1);
+}
+
 static Value *EmitX86MaskedCompareResult(CodeGenFunction , Value *Cmp,
  unsigned NumElts, Value *MaskIn) {
   if (MaskIn) {
@@ -9884,12 +9899,9 @@ Value *CodeGenFunction::EmitX86BuiltinEx
 }
 Value *A = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
 Function *F = CGM.getIntrinsic(Intrinsic::sqrt, A->getType());
+A = Builder.CreateCall(F, A);
 Value *Src = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
-int MaskSize = Ops[3]->getType()->getScalarSizeInBits();
-llvm::Type *MaskTy = llvm::VectorType::get(Builder.getInt1Ty(), MaskSize);
-Value *Mask = Builder.CreateBitCast(Ops[3], MaskTy);
-Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
-A = Builder.CreateSelect(Mask, Builder.CreateCall(F, {A}), Src);
+A = EmitX86ScalarSelect(*this, Ops[3], A, Src);
 return Builder.CreateInsertElement(Ops[0], A, (uint64_t)0);
   }
   case X86::BI__builtin_ia32_sqrtpd256:
@@ -10024,14 +10036,9 @@ Value *CodeGenFunction::EmitX86BuiltinEx
 Value *A = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
 Value *B = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
 Value *C = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
-Value *Mask = Ops[3];
 Value *Div = Builder.CreateFDiv(A, B);
-llvm::VectorType *MaskTy = llvm::VectorType::get(Builder.getInt1Ty(),
- 
cast(Mask->getType())->getBitWidth());
-Mask = Builder.CreateBitCast(Mask, MaskTy);
-Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
-Value *Select = Builder.CreateSelect(Mask, Div, C);
-return Builder.CreateInsertElement(Ops[0], Select, (uint64_t)0);
+Div = EmitX86ScalarSelect(*this, Ops[3], Div, C);
+return Builder.CreateInsertElement(Ops[0], Div, (uint64_t)0);
   }
 
   // 3DNow!

Modified: cfe/trunk/test/CodeGen/avx512f-builtins.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/avx512f-builtins.c?rev=336472=336471=336472=diff
==
--- cfe/trunk/test/CodeGen/avx512f-builtins.c (original)
+++ cfe/trunk/test/CodeGen/avx512f-builtins.c Fri Jul  6 15:46:52 2018
@@ -3581,27 +3581,26 @@ __m128 test_mm_maskz_div_round_ss(__mmas
 }
 __m128 test_mm_mask_div_ss(__m128 __W, __mmask8 __U, __m128 __A, __m128 __B) {
   // CHECK-LABEL: @test_mm_mask_div_ss
-  // CHECK-NOT: @llvm.x86.avx512.mask.div.ss.round
   // CHECK: extractelement <4 x float> %{{.*}}, i64 0
-  // CHECK: extractelement <4 x float> %{{.*}}, i64 0
-  // CHECK: extractelement <4 x float> %{{.*}}, i64 0
-  // CHECK: fdiv float %{{.*}}, %{{.*}}
-  // CHECK: bitcast i8 %{{.*}} to <8 x i1>
-  // CHECK: extractelement <8 x i1> %{{.*}}, i64 0
-  // CHECK: select i1 %{{.*}}, float %{{.*}}, float %{{.*}}
-  // CHECK: insertelement <4 x float> %{{.*}}, float %{{.*}}, i64 0
+  // CHECK-NEXT: extractelement <4 x float> %{{.*}}, i64 0
+  // CHECK-NEXT: extractelement <4 x float> %{{.*}}, i64 0
+  // CHECK-NEXT: fdiv float %{{.*}}, %{{.*}}
+  // CHECK-NEXT: bitcast i8 %{{.*}} to <8 x i1>
+  // CHECK-NEXT: extractelement <8 x i1> %{{.*}}, i64 0
+  // CHECK-NEXT: select i1 %{{.*}}, float %{{.*}}, float %{{.*}}
+  // CHECK-NEXT: insertelement <4 x float> %{{.*}}, float %{{.*}}, i64 0
   return _mm_mask_div_ss(__W,__U,__A,__B); 
 }
 __m128 test_mm_maskz_div_ss(__mmask8 __U, __m128 __A, __m128 __B) {
   // CHECK-LABEL: 

[PATCH] D48661: [Fixed Point Arithmetic] Fixed Point Constant

2018-07-06 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan added inline comments.



Comment at: lib/Basic/FixedPoint.cpp:40
+  if (DstWidth > Val.getBitWidth())
+Val = Val.extend(DstWidth);
+  if (Upscaling)

ebevhan wrote:
> leonardchan wrote:
> > ebevhan wrote:
> > > It should be possible to replace this with `extOrTrunc` and move it below 
> > > the saturation.
> > I don't think we can move the extension below saturation since saturation 
> > requires checking the bits above the dst width which may require extending 
> > and shifting beforehand.
> > 
> > Still leaving it above saturation may require checking for the width over 
> > using `extOrTrunc` to prevent truncating early before right shifting.
> I think the cases where saturation takes effect are limited to simply 
> truncation, since when we upscale we automatically extend first to avoid 
> shifting out bits. This means that the only situation where we need to check 
> for saturation is right before we truncate, and we don't have to worry about 
> anything happening when we upscale.
> 
> Do you have an example of when the extension is needed? (In case it wasn't 
> clear, I mean the `NewVal = NewVal.extend(DstWidth);` extension, not the 
> extension that is part of the upscale)
Ooh I see. Sorry this confused me for a bit. Thanks.



Comment at: unittests/Basic/FixedPointTest.cpp:380
+}
+
+// Check the value in a given fixed point sema overflows to the saturated max

ebevhan wrote:
> Technically, neither CheckSaturatedConversion function checks whether or not 
> the result was correct, only that it saturated.
Could you elaborate on this? It should be correct that the value saturates to 
the respective min/max for the destination type right?



Comment at: unittests/Basic/FixedPointTest.cpp:506
+TEST(FixedPoint, AccConversionOverflow) {
+  // To SAcc max limit (65536)
+  CheckSaturatedConversionMax(getLAccSema(), Saturated(getAccSema()),

ebevhan wrote:
> Acc?
Short for Accum. Changed to `Accum` since it wasn't clear at first.


Repository:
  rC Clang

https://reviews.llvm.org/D48661



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


[PATCH] D48661: [Fixed Point Arithmetic] Fixed Point Constant

2018-07-06 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan updated this revision to Diff 154465.
leonardchan marked 4 inline comments as done.

Repository:
  rC Clang

https://reviews.llvm.org/D48661

Files:
  include/clang/AST/ASTContext.h
  include/clang/Basic/FixedPoint.h
  include/clang/Basic/TargetInfo.h
  lib/AST/ASTContext.cpp
  lib/Basic/CMakeLists.txt
  lib/Basic/FixedPoint.cpp
  lib/Sema/SemaExpr.cpp
  test/Frontend/fixed_point_declarations.c
  unittests/Basic/CMakeLists.txt
  unittests/Basic/FixedPointTest.cpp

Index: unittests/Basic/FixedPointTest.cpp
===
--- /dev/null
+++ unittests/Basic/FixedPointTest.cpp
@@ -0,0 +1,683 @@
+//===- unittests/Basic/FixedPointTest.cpp -- fixed point number tests -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/Basic/FixedPoint.h"
+#include "llvm/ADT/APSInt.h"
+#include "gtest/gtest.h"
+
+using clang::APFixedPoint;
+using clang::FixedPointSemantics;
+using llvm::APInt;
+using llvm::APSInt;
+
+namespace {
+
+FixedPointSemantics Saturated(FixedPointSemantics Sema) {
+  Sema.setSaturated(true);
+  return Sema;
+}
+
+FixedPointSemantics getSAccumSema() {
+  return FixedPointSemantics(/*width=*/16, /*scale=*/7, /*isSigned=*/true,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getAccumSema() {
+  return FixedPointSemantics(/*width=*/32, /*scale=*/15, /*isSigned=*/true,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getLAccumSema() {
+  return FixedPointSemantics(/*width=*/64, /*scale=*/31, /*isSigned=*/true,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getSFractSema() {
+  return FixedPointSemantics(/*width=*/8, /*scale=*/7, /*isSigned=*/true,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getFractSema() {
+  return FixedPointSemantics(/*width=*/16, /*scale=*/15, /*isSigned=*/true,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getLFractSema() {
+  return FixedPointSemantics(/*width=*/32, /*scale=*/31, /*isSigned=*/true,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getUSAccumSema() {
+  return FixedPointSemantics(/*width=*/16, /*scale=*/8, /*isSigned=*/false,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getUAccumSema() {
+  return FixedPointSemantics(/*width=*/32, /*scale=*/16, /*isSigned=*/false,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getULAccumSema() {
+  return FixedPointSemantics(/*width=*/64, /*scale=*/32, /*isSigned=*/false,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getUSFractSema() {
+  return FixedPointSemantics(/*width=*/8, /*scale=*/8, /*isSigned=*/false,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getUFractSema() {
+  return FixedPointSemantics(/*width=*/16, /*scale=*/16, /*isSigned=*/false,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getULFractSema() {
+  return FixedPointSemantics(/*width=*/32, /*scale=*/32, /*isSigned=*/false,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/false);
+}
+
+FixedPointSemantics getPadUSAccumSema() {
+  return FixedPointSemantics(/*width=*/16, /*scale=*/7, /*isSigned=*/false,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/true);
+}
+
+FixedPointSemantics getPadUAccumSema() {
+  return FixedPointSemantics(/*width=*/32, /*scale=*/15, /*isSigned=*/false,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/true);
+}
+
+FixedPointSemantics getPadULAccumSema() {
+  return FixedPointSemantics(/*width=*/64, /*scale=*/31, /*isSigned=*/false,
+ /*isSaturated=*/false,
+ /*hasUnsignedPadding=*/true);
+}
+
+FixedPointSemantics getPadUSFractSema() {
+  return FixedPointSemantics(/*width=*/8, /*scale=*/7, /*isSigned=*/false,
+ 

r336471 - [MachineOutliner] Properly pass -moutline along to the toolchain

2018-07-06 Thread Jessica Paquette via cfe-commits
Author: paquette
Date: Fri Jul  6 15:24:56 2018
New Revision: 336471

URL: http://llvm.org/viewvc/llvm-project?rev=336471=rev
Log:
[MachineOutliner] Properly pass -moutline along to the toolchain

This moves the LTO-specific code for outlining from ToolChains/Clang.cpp to
ToolChains/Darwin.cpp. Passing -mllvm flags isn't sufficient for making sure
that the specified pass will actually run in LTO. This makes sure that when
-moutline is passed, the MachineOutliner will actually be added to the LTO
pass pipeline as expected.

Modified:
cfe/trunk/lib/Driver/ToolChains/Clang.cpp
cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
cfe/trunk/test/Driver/aarch64-outliner.c
cfe/trunk/test/Driver/darwin-ld.c

Modified: cfe/trunk/lib/Driver/ToolChains/Clang.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Clang.cpp?rev=336471=336470=336471=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Clang.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Clang.cpp Fri Jul  6 15:24:56 2018
@@ -4757,16 +4757,8 @@ void Clang::ConstructJob(Compilation ,
   if (Triple.getArch() != llvm::Triple::aarch64) {
 D.Diag(diag::warn_drv_moutline_unsupported_opt) << 
Triple.getArchName();
   } else {
-CmdArgs.push_back("-mllvm");
-CmdArgs.push_back("-enable-machine-outliner");
-
-// The outliner shouldn't compete with linkers that dedupe linkonceodr
-// functions in LTO. Enable that behaviour by default when compiling 
with
-// LTO.
-if (getToolChain().getDriver().isUsingLTO()) {
   CmdArgs.push_back("-mllvm");
-  CmdArgs.push_back("-enable-linkonceodr-outlining");
-}
+  CmdArgs.push_back("-enable-machine-outliner");
   }
 } else {
   // Disable all outlining behaviour.

Modified: cfe/trunk/lib/Driver/ToolChains/Darwin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Darwin.cpp?rev=336471=336470=336471=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Darwin.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Darwin.cpp Fri Jul  6 15:24:56 2018
@@ -479,6 +479,18 @@ void darwin::Linker::ConstructJob(Compil
 }
   }
 
+  // Propagate the -moutline flag to the linker in LTO.
+  if (Args.hasFlag(options::OPT_moutline, options::OPT_mno_outline, false)) {
+if (getMachOToolChain().getMachOArchName(Args) == "arm64") {
+  CmdArgs.push_back("-mllvm");
+  CmdArgs.push_back("-enable-machine-outliner");
+
+  // Outline from linkonceodr functions by default in LTO.
+  CmdArgs.push_back("-mllvm");
+  CmdArgs.push_back("-enable-linkonceodr-outlining");
+}
+  }
+
   // It seems that the 'e' option is completely ignored for dynamic executables
   // (the default), and with static executables, the last one wins, as 
expected.
   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, 
options::OPT_t,

Modified: cfe/trunk/test/Driver/aarch64-outliner.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/aarch64-outliner.c?rev=336471=336470=336471=diff
==
--- cfe/trunk/test/Driver/aarch64-outliner.c (original)
+++ cfe/trunk/test/Driver/aarch64-outliner.c Fri Jul  6 15:24:56 2018
@@ -3,10 +3,6 @@
 // ON: "-mllvm" "-enable-machine-outliner"
 // RUN: %clang -target aarch64 -moutline -mno-outline -S %s -### 2>&1 | 
FileCheck %s -check-prefix=OFF
 // OFF: "-mllvm" "-enable-machine-outliner=never"
-// RUN: %clang -target aarch64 -moutline -flto=thin -S %s -### 2>&1 | 
FileCheck %s -check-prefix=FLTO
-// FLTO: "-mllvm" "-enable-linkonceodr-outlining"
-// RUN: %clang -target aarch64 -moutline -flto=full -S %s -### 2>&1 | 
FileCheck %s -check-prefix=TLTO
-// TLTO: "-mllvm" "-enable-linkonceodr-outlining"
 // RUN: %clang -target x86_64 -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=WARN
 // WARN: warning: The 'x86_64' architecture does not support -moutline; flag 
ignored [-Woption-ignored]
 // WARN-NOT: "-mllvm" "-enable-machine-outliner"

Modified: cfe/trunk/test/Driver/darwin-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/darwin-ld.c?rev=336471=336470=336471=diff
==
--- cfe/trunk/test/Driver/darwin-ld.c (original)
+++ cfe/trunk/test/Driver/darwin-ld.c Fri Jul  6 15:24:56 2018
@@ -371,3 +371,9 @@
 // RUN: %clang -target x86_64-apple-darwin12 -fprofile-instr-generate -### 
%t.o 2> %t.log
 // RUN: FileCheck -check-prefix=NO_PROFILE_EXPORT %s < %t.log
 // NO_PROFILE_EXPORT-NOT: "-exported_symbol"
+//
+// Check that we can pass the outliner down to the linker.
+// RUN: env IPHONEOS_DEPLOYMENT_TARGET=7.0 \
+// RUN:   %clang -target arm64-apple-darwin -moutline -### %t.o 2> %t.log
+// MOUTLINE: ld
+// MOUTLINE-SAME: "-mllvm" 

[PATCH] D48753: [libcxx] Use custom allocator's `construct` in C++03 when available.

2018-07-06 Thread Arthur O'Dwyer via Phabricator via cfe-commits
Quuxplusone added inline comments.



Comment at: libcxx/include/memory:1470
+decltype(_VSTD::declval<_Alloc>().construct(_VSTD::declval<_Pointer>(),
+_VSTD::declval<_Args>())),
+void

vsapsai wrote:
> Quuxplusone wrote:
> > I think you should replace this `)))` with `)), void())` for absolute 
> > correctness (e.g. `construct` might plausibly return a pointer to the 
> > constructed object, and I think C++03 is okay with that).
> > Otherwise, awesome, this looks like what I'd expect. :)
> The standard says the result of `construct` is not used but I haven't found 
> any mention it **must** be `void`.
> 
> That being said, the proposed change fails for the C++03 macro-based decltype 
> shim:
> 
> error: too many arguments provided to function-like macro invocation
> _VSTD::declval<_Args>()), void()),
>   ^
> 
> One option to fix that is to use
> 
> is_same
> <
> decltype(_as_before_),
> decltype(_the_same_copy_pasted_argument_)
> >
> 
> But I don't think this use case is worth such hacks.
I think the workaround is easier. Try

```
template 
struct __has_construct<_Alloc, _Pointer, _A0, typename enable_if<
  is_same<
decltype((_VSTD::declval<_Alloc>().construct(
  _VSTD::declval<_Pointer>(),
  _VSTD::declval<_A0>()
), void() )),
void
  >::value
>::type> : std::true_type {};
```

i.e. with an extra set of parens to group the argument to the `decltype` macro: 
`decltype(())` instead of `decltype()`. I also drive-by edited `Args` to `A0`, 
matching how it's done elsewhere in pseudo-variadic-templates in this file.


https://reviews.llvm.org/D48753



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


[PATCH] D47474: Implement cpu_dispatch/cpu_specific Multiversioning

2018-07-06 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Some drive-by nits.
General observation: this is kinda large.
I would //personally// split split off the codegen part into a second patch.




Comment at: include/clang/AST/Decl.h:2212-2213
 
+  bool isCPUDispatchMultiVersion() const;
+  bool isCPUSpecificMultiVersion() const;
+

Everything else has comments, and i'm not sure it is obvious what those mean 
without knowing the context.



Comment at: include/clang/Basic/AttrDocs.td:223
+A dispatching (or resolving) function can be declared anywhere in your
+compilation with ``cpu_dispatch``. This attribute takes one or more CPU names
+as a parameter (like ``cpu_specific``). Functions marked with ``cpu_dispatch``

s/compilation/source code/?



Comment at: include/clang/Basic/X86Target.def:288
+
+// FIXME: When commented out features are supported in LLVM, enable them here.
+CPU_SPECIFIC("generic", 'A', "")

This is going to go stale.
It already does not have znver1, btver2.
Surely this info already exists elsewhere in llvm?
Can it be deduplicated somehow?



Comment at: lib/CodeGen/CodeGenFunction.cpp:2421
+  // Main function's basic block.
+  llvm::BasicBlock *CurBlock = createBasicBlock("entry", Resolver);
+  Builder.SetInsertPoint(CurBlock);

Those are arbitrary names, right?
Maybe somehow convey that this is CPUDispatchMultiVersionResolver logic in the 
names?



Comment at: lib/CodeGen/CodeGenModule.cpp:868
+  const auto  = CGM.getTarget();
+  return std::string(".") + Target.CPUSpecificManglingCharacter(Name);
+}

I think
```
return Twine(".", Target.CPUSpecificManglingCharacter(Name)).str();
```


https://reviews.llvm.org/D47474



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


r336470 - [X86] Add missing scalar fma intrinsics with rounding, but no mask.

2018-07-06 Thread Craig Topper via cfe-commits
Author: ctopper
Date: Fri Jul  6 15:08:43 2018
New Revision: 336470

URL: http://llvm.org/viewvc/llvm-project?rev=336470=rev
Log:
[X86] Add missing scalar fma intrinsics with rounding, but no mask.

We had the mask versions of the rounding intrinsics, but not one without 
masking.

Also change the rounding tests to not use the CUR_DIRECTION rounding mode.

Modified:
cfe/trunk/lib/Headers/avx512fintrin.h
cfe/trunk/test/CodeGen/avx512f-builtins.c

Modified: cfe/trunk/lib/Headers/avx512fintrin.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/avx512fintrin.h?rev=336470=336469=336470=diff
==
--- cfe/trunk/lib/Headers/avx512fintrin.h (original)
+++ cfe/trunk/lib/Headers/avx512fintrin.h Fri Jul  6 15:08:43 2018
@@ -7824,6 +7824,12 @@ _mm_mask_fmadd_ss (__m128 __W, __mmask8
  return __W;
 }
 
+#define _mm_fmadd_round_ss(A, B, C, R) \
+  (__m128d)__builtin_ia32_vfmaddss3_mask((__v2df)(__m128d)(A), \
+ (__v2df)(__m128d)(B), \
+ (__v2df)(__m128d)(C), (__mmask8)-1, \
+ (int)(R))
+
 #define _mm_mask_fmadd_round_ss(W, U, A, B, R) \
   (__m128d)__builtin_ia32_vfmaddss3_mask((__v2df)(__m128d)(W), \
  (__v2df)(__m128d)(A), \
@@ -7872,6 +7878,12 @@ _mm_mask_fmsub_ss (__m128 __W, __mmask8
  return __W;
 }
 
+#define _mm_fmsub_round_ss(A, B, C, R) \
+  (__m128)__builtin_ia32_vfmaddss3_mask((__v4sf)(__m128)(A), \
+(__v4sf)(__m128)(B), \
+-(__v4sf)(__m128)(C), (__mmask8)-1, \
+(int)(R))
+
 #define _mm_mask_fmsub_round_ss(W, U, A, B, R) \
   (__m128)__builtin_ia32_vfmaddss3_mask((__v4sf)(__m128)(W), \
 (__v4sf)(__m128)(A), \
@@ -7920,6 +7932,12 @@ _mm_mask_fnmadd_ss (__m128 __W, __mmask8
  return __W;
 }
 
+#define _mm_fnmadd_round_ss(A, B, C, R) \
+  (__m128)__builtin_ia32_vfmaddss3_mask((__v4sf)(__m128)(A), \
+-(__v4sf)(__m128)(B), \
+(__v4sf)(__m128)(C), (__mmask8)-1, \
+(int)(R))
+
 #define _mm_mask_fnmadd_round_ss(W, U, A, B, R) \
   (__m128)__builtin_ia32_vfmaddss3_mask((__v4sf)(__m128)(W), \
 -(__v4sf)(__m128)(A), \
@@ -7968,6 +7986,12 @@ _mm_mask_fnmsub_ss (__m128 __W, __mmask8
  return __W;
 }
 
+#define _mm_fnmsub_round_ss(A, B, C, R) \
+  (__m128)__builtin_ia32_vfmaddss3_mask((__v4sf)(__m128)(A), \
+-(__v4sf)(__m128)(B), \
+-(__v4sf)(__m128)(C), (__mmask8)-1, \
+(int)(R))
+
 #define _mm_mask_fnmsub_round_ss(W, U, A, B, R) \
   (__m128)__builtin_ia32_vfmaddss3_mask((__v4sf)(__m128)(W), \
 -(__v4sf)(__m128)(A), \
@@ -8016,6 +8040,12 @@ _mm_mask_fmadd_sd (__m128d __W, __mmask8
  return __W;
 }
 
+#define _mm_fmadd_round_sd(A, B, C, R) \
+  (__m128d)__builtin_ia32_vfmaddsd3_mask((__v2df)(__m128d)(A), \
+ (__v2df)(__m128d)(B), \
+ (__v2df)(__m128d)(C), (__mmask8)-1, \
+ (int)(R))
+
 #define _mm_mask_fmadd_round_sd(W, U, A, B, R) \
   (__m128d)__builtin_ia32_vfmaddsd3_mask((__v2df)(__m128d)(W), \
  (__v2df)(__m128d)(A), \
@@ -8064,6 +8094,12 @@ _mm_mask_fmsub_sd (__m128d __W, __mmask8
  return __W;
 }
 
+#define _mm_fmsub_round_sd(A, B, C, R) \
+  (__m128d)__builtin_ia32_vfmaddsd3_mask((__v2df)(__m128d)(A), \
+ (__v2df)(__m128d)(B), \
+ -(__v2df)(__m128d)(C), (__mmask8)-1, \
+ (int)(R))
+
 #define _mm_mask_fmsub_round_sd(W, U, A, B, R) \
   (__m128d)__builtin_ia32_vfmaddsd3_mask((__v2df)(__m128d)(W), \
  (__v2df)(__m128d)(A), \
@@ -8112,6 +8148,12 @@ _mm_mask_fnmadd_sd (__m128d __W, __mmask
  return __W;
 }
 
+#define _mm_fnmadd_round_sd(A, B, C, R) \
+  (__m128d)__builtin_ia32_vfmaddsd3_mask((__v2df)(__m128d)(A), \
+ -(__v2df)(__m128d)(B), \
+ (__v2df)(__m128d)(C), (__mmask8)-1, \
+ (int)(R))
+
 #define _mm_mask_fnmadd_round_sd(W, U, A, B, R) \
   (__m128d)__builtin_ia32_vfmaddsd3_mask((__v2df)(__m128d)(W), \
  -(__v2df)(__m128d)(A), \
@@ -8160,6 +8202,12 @@ _mm_mask_fnmsub_sd (__m128d __W, __mmask
  return __W;
 }
 
+#define _mm_fnmsub_round_sd(A, B, C, R) \
+  (__m128d)__builtin_ia32_vfmaddsd3_mask((__v2df)(__m128d)(A), \

[PATCH] D48903: [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name

2018-07-06 Thread Simon Marchi via Phabricator via cfe-commits
simark added a comment.

I found something fishy.  There is this code in FileManager.cpp:

  if (UFE.File)
if (auto RealPathName = UFE.File->getName())
  UFE.RealPathName = *RealPathName;

The real path is obtained from `UFE.File->getName()`.  In the `RealFile` 
implementation, it returns the `RealName` field, which is fine.  For other 
implementations, it uses `File::getName`, which is:

  /// Get the name of the file
  virtual llvm::ErrorOr getName() {
if (auto Status = status())
  return Status->getName().str();
else
  return Status.getError();
  }

With the `InMemoryFileSystem`, this now returns a non-real path.  The result is 
that we fill `RealPathName` with that non-real path.  I see two options here:

1. Either the FileManager is wrong to assume that `File::getName` returns a 
real path, and should call `FS->getRealPath` to do the job.
2. If the contract is that the ` File::getName` interface should return a real 
path, then we should fix the `File::getName` implementation to do that somehow.

I would opt for 1.  This way, we could compute the `RealPathName` field even if 
we don't open the file (unlike currently).


Repository:
  rC Clang

https://reviews.llvm.org/D48903



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


[PATCH] D49045: PR15730/PR16986 Allow dependently typed vector_size types.

2018-07-06 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.
erichkeane added reviewers: rsmith, aaron.ballman, mibintc, mikerice, Manna.

As listed in the above PRs, vector_size doesn't allow 
dependent types/values.  This patch introduces a new 
DependentVectorType to handle a VectorType that has a dependent
size or type.

In the future, ALL the vector-types should be able to create one
of these to handle dependent types/sizes as well. For example,
DependentSizedExtVectorType could likely be switched to just use 
this instead, though that is left as an exercise for the future.


https://reviews.llvm.org/D49045

Files:
  include/clang/AST/ASTContext.h
  include/clang/AST/RecursiveASTVisitor.h
  include/clang/AST/Type.h
  include/clang/AST/TypeLoc.h
  include/clang/AST/TypeNodes.def
  include/clang/Sema/Sema.h
  include/clang/Serialization/ASTBitCodes.h
  lib/AST/ASTContext.cpp
  lib/AST/ASTStructuralEquivalence.cpp
  lib/AST/ItaniumMangle.cpp
  lib/AST/MicrosoftMangle.cpp
  lib/AST/Type.cpp
  lib/AST/TypePrinter.cpp
  lib/Sema/SemaTemplate.cpp
  lib/Sema/SemaTemplateDeduction.cpp
  lib/Sema/SemaType.cpp
  lib/Sema/TreeTransform.h
  lib/Serialization/ASTReader.cpp
  lib/Serialization/ASTWriter.cpp
  test/SemaCXX/vector.cpp
  tools/libclang/CIndex.cpp

Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -454,6 +454,15 @@
   Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR;
 }
 
+void ASTTypeWriter::VisitDependentVectorType(
+const DependentVectorType *T) {
+  Record.AddTypeRef(T->getElementType());
+  Record.AddStmt(T->getSizeExpr());
+  Record.AddSourceLocation(T->getAttributeLoc());
+  Record.push_back(T->getVectorKind());
+  Code = TYPE_DEPENDENT_SIZED_VECTOR;
+}
+
 void
 ASTTypeWriter::VisitDependentAddressSpaceType(
 const DependentAddressSpaceType *T) {
@@ -675,6 +684,11 @@
   Record.AddSourceLocation(TL.getNameLoc());
 }
 
+void TypeLocWriter::VisitDependentVectorTypeLoc(
+DependentVectorTypeLoc TL) {
+  Record.AddSourceLocation(TL.getNameLoc());
+}
+
 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
   Record.AddSourceLocation(TL.getNameLoc());
 }
Index: lib/Serialization/ASTReader.cpp
===
--- lib/Serialization/ASTReader.cpp
+++ lib/Serialization/ASTReader.cpp
@@ -6369,6 +6369,17 @@
 return Context.getPipeType(ElementType, ReadOnly);
   }
 
+  case TYPE_DEPENDENT_SIZED_VECTOR: {
+unsigned Idx = 0;
+QualType ElementType = readType(*Loc.F, Record, Idx);
+Expr *SizeExpr = ReadExpr(*Loc.F);
+SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
+unsigned VecKind = Record[Idx];
+
+return Context.getDependentVectorType(ElementType, SizeExpr, AttrLoc,
+   (VectorType::VectorKind)VecKind);
+  }
+
   case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
 unsigned Idx = 0;
 
@@ -6549,6 +6560,11 @@
   TL.setNameLoc(ReadSourceLocation());
 }
 
+void TypeLocReader::VisitDependentVectorTypeLoc(
+DependentVectorTypeLoc TL) {
+  TL.setNameLoc(ReadSourceLocation());
+}
+
 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
   TL.setNameLoc(ReadSourceLocation());
 }
Index: lib/AST/ASTStructuralEquivalence.cpp
===
--- lib/AST/ASTStructuralEquivalence.cpp
+++ lib/AST/ASTStructuralEquivalence.cpp
@@ -405,6 +405,20 @@
 break;
   }
 
+  case Type::DependentVector: {
+const auto *Vec1 = cast(T1);
+const auto *Vec2 = cast(T2);
+if (Vec1->getVectorKind() != Vec2->getVectorKind())
+  return false;
+if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(),
+  Vec2->getSizeExpr()))
+  return false;
+if (!IsStructurallyEquivalent(Context, Vec1->getElementType(),
+  Vec2->getElementType()))
+  return false;
+break;
+  }
+
   case Type::Vector:
   case Type::ExtVector: {
 const auto *Vec1 = cast(T1);
Index: lib/AST/ItaniumMangle.cpp
===
--- lib/AST/ItaniumMangle.cpp
+++ lib/AST/ItaniumMangle.cpp
@@ -539,7 +539,9 @@
   void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
   const FunctionDecl *FD = nullptr);
   void mangleNeonVectorType(const VectorType *T);
+  void mangleNeonVectorType(const DependentVectorType *T);
   void mangleAArch64NeonVectorType(const VectorType *T);
+  void mangleAArch64NeonVectorType(const DependentVectorType *T);
 
   void mangleIntegerLiteral(QualType T, const llvm::APSInt );
   void mangleMemberExprBase(const Expr *base, bool isArrow);
@@ -1930,6 +1932,7 @@
   case Type::VariableArray:
   case Type::DependentSizedArray:
   case Type::DependentAddressSpace:
+  case Type::DependentVector:
   case Type::DependentSizedExtVector:
   case 

[PATCH] D47474: Implement cpu_dispatch/cpu_specific Multiversioning

2018-07-06 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

Bump!


https://reviews.llvm.org/D47474



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


[PATCH] D48753: [libcxx] Use custom allocator's `construct` in C++03 when available.

2018-07-06 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added inline comments.



Comment at: libcxx/include/memory:1470
+decltype(_VSTD::declval<_Alloc>().construct(_VSTD::declval<_Pointer>(),
+_VSTD::declval<_Args>())),
+void

Quuxplusone wrote:
> I think you should replace this `)))` with `)), void())` for absolute 
> correctness (e.g. `construct` might plausibly return a pointer to the 
> constructed object, and I think C++03 is okay with that).
> Otherwise, awesome, this looks like what I'd expect. :)
The standard says the result of `construct` is not used but I haven't found any 
mention it **must** be `void`.

That being said, the proposed change fails for the C++03 macro-based decltype 
shim:

error: too many arguments provided to function-like macro invocation
_VSTD::declval<_Args>()), void()),
  ^

One option to fix that is to use

is_same
<
decltype(_as_before_),
decltype(_the_same_copy_pasted_argument_)
>

But I don't think this use case is worth such hacks.


https://reviews.llvm.org/D48753



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


[PATCH] D48910: [ASTMatchers] A matcher for Objective-C @autoreleasepool

2018-07-06 Thread George Karpenkov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC336468: [ASTMatchers] A matcher for Objective-C 
@autoreleasepool (authored by george.karpenkov, committed by ).
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D48910?vs=154311=154460#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48910

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

Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -662,6 +662,18 @@
 
 
 
+Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Stmt.html;>StmtautoreleasePoolStmtMatcherhttp://clang.llvm.org/doxygen/classclang_1_1ObjCAutoreleasePoolStmt.html;>ObjCAutoreleasePoolStmt...
+Matches an Objective-C autorelease pool statement.
+
+Given
+  @autoreleasepool {
+int x = 0;
+  }
+autoreleasePoolStmt(stmt()) matches the declaration of "x"
+inside the autorelease pool.
+
+
+
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Stmt.html;>StmtbinaryConditionalOperatorMatcherhttp://clang.llvm.org/doxygen/classclang_1_1BinaryConditionalOperator.html;>BinaryConditionalOperator...
 Matches binary conditional operator expressions (GNU extension).
 
@@ -5222,8 +5234,8 @@
 
 
 
-Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Expr.html;>ExprhasTypeMatcherhttp://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl InnerMatcher
-Overloaded to match the declaration of the expression's or value
+Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Expr.html;>ExprhasTypeMatcherhttp://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl InnerMatcher
+Overloaded to match the declaration of the expression's or value
 declaration's type.
 
 In case of a value declaration (for example a variable declaration),
@@ -5234,8 +5246,10 @@
 
 Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
 and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
+and friend class X (matcher = friendDecl(hasType("X"))
  class X {};
  void y(X x) { x; X z; }
+ class Y { friend class X; };
 
 Usable as: Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Expr.html;>Expr, Matcherhttp://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html;>ValueDecl
 
@@ -5248,9 +5262,11 @@
 Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
 and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
 and U (matcher = typedefDecl(hasType(asString("int")))
+and friend class X (matcher = friendDecl(hasType("X"))
  class X {};
  void y(X x) { x; X z; }
  typedef int U;
+ class Y { friend class X; };
 
 
 
@@ -5396,6 +5412,42 @@
 
 
 
+Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FriendDecl.html;>FriendDeclhasTypeMatcherhttp://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl InnerMatcher
+Overloaded to match the declaration of the expression's or value
+declaration's type.
+
+In case of a value declaration (for example a variable declaration),
+this resolves one layer of indirection. For example, in the value
+declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
+X, while varDecl(hasType(cxxRecordDecl(hasName("X" matches the
+declaration of x.
+
+Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
+and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
+and friend class X (matcher = friendDecl(hasType("X"))
+ class X {};
+ void y(X x) { x; X z; }
+ class Y { friend class X; };
+
+Usable as: Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Expr.html;>Expr, Matcherhttp://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html;>ValueDecl
+
+
+
+Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FriendDecl.html;>FriendDeclhasTypeMatcherhttp://clang.llvm.org/doxygen/classclang_1_1QualType.html;>QualType InnerMatcher
+Matches if the expression's or declaration's type matches a type
+matcher.
+
+Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
+and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
+and U (matcher = typedefDecl(hasType(asString("int")))
+and friend class X (matcher = friendDecl(hasType("X"))
+ class X {};
+ void y(X x) { x; X z; }
+ typedef int U;
+ class Y { friend class X; };
+
+
+
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html;>FunctionDeclhasAnyParameterMatcherhttp://clang.llvm.org/doxygen/classclang_1_1ParmVarDecl.html;>ParmVarDecl InnerMatcher
 Matches any parameter of a function or an ObjC method declaration or a
 block.
@@ -6432,16 +6484,18 @@
 
 
 

r336468 - [ASTMatchers] A matcher for Objective-C @autoreleasepool

2018-07-06 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Fri Jul  6 14:36:04 2018
New Revision: 336468

URL: http://llvm.org/viewvc/llvm-project?rev=336468=rev
Log:
[ASTMatchers] A matcher for Objective-C @autoreleasepool

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

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
cfe/trunk/lib/ASTMatchers/ASTMatchersInternal.cpp
cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp
cfe/trunk/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=336468=336467=336468=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Fri Jul  6 14:36:04 2018
@@ -662,6 +662,18 @@ Example matches __atomic_load_n(ptr, 1)
 
 
 
+Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Stmt.html;>StmtautoreleasePoolStmtMatcherhttp://clang.llvm.org/doxygen/classclang_1_1ObjCAutoreleasePoolStmt.html;>ObjCAutoreleasePoolStmt...
+Matches an 
Objective-C autorelease pool statement.
+
+Given
+  @autoreleasepool {
+int x = 0;
+  }
+autoreleasePoolStmt(stmt()) matches the declaration of "x"
+inside the autorelease pool.
+
+
+
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Stmt.html;>StmtbinaryConditionalOperatorMatcherhttp://clang.llvm.org/doxygen/classclang_1_1BinaryConditionalOperator.html;>BinaryConditionalOperator...
 Matches 
binary conditional operator expressions (GNU extension).
 
@@ -5222,8 +5234,8 @@ actual casts "explicit" casts.)
 
 
 
-Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Expr.html;>ExprhasTypeMatcherhttp://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl 
InnerMatcher
-Overloaded to match the 
declaration of the expression's or value
+Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Expr.html;>ExprhasTypeMatcherhttp://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl 
InnerMatcher
+Overloaded to match the 
declaration of the expression's or value
 declaration's type.
 
 In case of a value declaration (for example a variable declaration),
@@ -5234,8 +5246,10 @@ declaration of x.
 
 Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
 and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
+and friend class X (matcher = friendDecl(hasType("X"))
  class X {};
  void y(X x) { x; X z; }
+ class Y { friend class X; };
 
 Usable as: Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Expr.html;>Expr, 
Matcherhttp://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html;>ValueDecl
 
@@ -5248,9 +5262,11 @@ matcher.
 Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
 and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
 and U (matcher = typedefDecl(hasType(asString("int")))
+and friend class X (matcher = friendDecl(hasType("X"))
  class X {};
  void y(X x) { x; X z; }
  typedef int U;
+ class Y { friend class X; };
 
 
 
@@ -5396,6 +5412,42 @@ matches 'int x = 0' in
 
 
 
+Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FriendDecl.html;>FriendDeclhasTypeMatcherhttp://clang.llvm.org/doxygen/classclang_1_1Decl.html;>Decl 
InnerMatcher
+Overloaded to match the 
declaration of the expression's or value
+declaration's type.
+
+In case of a value declaration (for example a variable declaration),
+this resolves one layer of indirection. For example, in the value
+declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
+X, while varDecl(hasType(cxxRecordDecl(hasName("X" matches the
+declaration of x.
+
+Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
+and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
+and friend class X (matcher = friendDecl(hasType("X"))
+ class X {};
+ void y(X x) { x; X z; }
+ class Y { friend class X; };
+
+Usable as: Matcherhttp://clang.llvm.org/doxygen/classclang_1_1Expr.html;>Expr, 
Matcherhttp://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html;>ValueDecl
+
+
+
+Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FriendDecl.html;>FriendDeclhasTypeMatcherhttp://clang.llvm.org/doxygen/classclang_1_1QualType.html;>QualType
 InnerMatcher
+Matches if the expression's 
or declaration's type matches a type
+matcher.
+
+Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")
+and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")
+and U (matcher = typedefDecl(hasType(asString("int")))
+and friend class X (matcher = friendDecl(hasType("X"))
+ class X {};
+ void y(X x) { x; X z; }
+ typedef int U;
+ class Y { friend class X; };
+
+
+
 

r336467 - [OPENMP] Fix PR38026: Link -latomic when -fopenmp is used.

2018-07-06 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Fri Jul  6 14:13:41 2018
New Revision: 336467

URL: http://llvm.org/viewvc/llvm-project?rev=336467=rev
Log:
[OPENMP] Fix PR38026: Link -latomic when -fopenmp is used.

On Linux atomic constructs in OpenMP require libatomic library. Patch
links libatomic when -fopenmp is used.

Modified:
cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
cfe/trunk/test/OpenMP/linking.c

Modified: cfe/trunk/lib/Driver/ToolChains/Gnu.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Gnu.cpp?rev=336467=336466=336467=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Gnu.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Gnu.cpp Fri Jul  6 14:13:41 2018
@@ -479,6 +479,7 @@ void tools::gnutools::Linker::ConstructJ
 
   bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  Args.hasArg(options::OPT_pthreads);
+  bool WantAtomic = false;
 
   // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that
   // require librt. Most modern Linux platforms do, but some may not.
@@ -487,13 +488,16 @@ void tools::gnutools::Linker::ConstructJ
/* GompNeedsRT= */ true))
 // OpenMP runtimes implies pthreads when using the GNU toolchain.
 // FIXME: Does this really make sense for all GNU toolchains?
-WantPthread = true;
+WantAtomic = WantPthread = true;
 
   AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
 
   if (WantPthread && !isAndroid)
 CmdArgs.push_back("-lpthread");
 
+  if (WantAtomic)
+CmdArgs.push_back("-latomic");
+
   if (Args.hasArg(options::OPT_fsplit_stack))
 CmdArgs.push_back("--wrap=pthread_create");
 

Modified: cfe/trunk/test/OpenMP/linking.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/linking.c?rev=336467=336466=336467=diff
==
--- cfe/trunk/test/OpenMP/linking.c (original)
+++ cfe/trunk/test/OpenMP/linking.c Fri Jul  6 14:13:41 2018
@@ -8,14 +8,14 @@
 // RUN:   | FileCheck --check-prefix=CHECK-LD-32 %s
 // CHECK-LD-32: "{{.*}}ld{{(.exe)?}}"
 // CHECK-LD-32: "-l[[DEFAULT_OPENMP_LIB:[^"]*]]"
-// CHECK-LD-32: "-lpthread" "-lc"
+// CHECK-LD-32: "-lpthread" "-latomic" "-lc"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -fopenmp -target x86_64-unknown-linux -rtlib=platform \
 // RUN:   | FileCheck --check-prefix=CHECK-LD-64 %s
 // CHECK-LD-64: "{{.*}}ld{{(.exe)?}}"
 // CHECK-LD-64: "-l[[DEFAULT_OPENMP_LIB:[^"]*]]"
-// CHECK-LD-64: "-lpthread" "-lc"
+// CHECK-LD-64: "-lpthread" "-latomic" "-lc"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -fopenmp=libgomp -target i386-unknown-linux -rtlib=platform \
@@ -27,7 +27,7 @@
 // SIMD-ONLY2-NOT: liomp
 // CHECK-GOMP-LD-32: "{{.*}}ld{{(.exe)?}}"
 // CHECK-GOMP-LD-32: "-lgomp" "-lrt"
-// CHECK-GOMP-LD-32: "-lpthread" "-lc"
+// CHECK-GOMP-LD-32: "-lpthread" "-latomic" "-lc"
 
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 -fopenmp-simd 
-target i386-unknown-linux -rtlib=platform | FileCheck --check-prefix 
SIMD-ONLY2 %s
 // SIMD-ONLY2-NOT: lgomp
@@ -39,21 +39,21 @@
 // RUN:   | FileCheck --check-prefix=CHECK-GOMP-LD-64 %s
 // CHECK-GOMP-LD-64: "{{.*}}ld{{(.exe)?}}"
 // CHECK-GOMP-LD-64: "-lgomp" "-lrt"
-// CHECK-GOMP-LD-64: "-lpthread" "-lc"
+// CHECK-GOMP-LD-64: "-lpthread" "-latomic" "-lc"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -fopenmp -target i386-unknown-linux -rtlib=platform \
 // RUN:   | FileCheck --check-prefix=CHECK-IOMP5-LD-32 %s
 // CHECK-IOMP5-LD-32: "{{.*}}ld{{(.exe)?}}"
 // CHECK-IOMP5-LD-32: "-l[[DEFAULT_OPENMP_LIB:[^"]*]]"
-// CHECK-IOMP5-LD-32: "-lpthread" "-lc"
+// CHECK-IOMP5-LD-32: "-lpthread" "-latomic" "-lc"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -fopenmp -target x86_64-unknown-linux -rtlib=platform \
 // RUN:   | FileCheck --check-prefix=CHECK-IOMP5-LD-64 %s
 // CHECK-IOMP5-LD-64: "{{.*}}ld{{(.exe)?}}"
 // CHECK-IOMP5-LD-64: "-l[[DEFAULT_OPENMP_LIB:[^"]*]]"
-// CHECK-IOMP5-LD-64: "-lpthread" "-lc"
+// CHECK-IOMP5-LD-64: "-lpthread" "-latomic" "-lc"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -fopenmp=lib -target i386-unknown-linux \
@@ -71,7 +71,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-LD-OVERRIDE-32 %s
 // CHECK-LD-OVERRIDE-32: "{{.*}}ld{{(.exe)?}}"
 // CHECK-LD-OVERRIDE-32: "-lgomp" "-lrt"
-// CHECK-LD-OVERRIDE-32: "-lpthread" "-lc"
+// CHECK-LD-OVERRIDE-32: "-lpthread" "-latomic" "-lc"
 //
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -fopenmp -fopenmp=libgomp -target x86_64-unknown-linux \
@@ -79,7 +79,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-LD-OVERRIDE-64 %s
 // CHECK-LD-OVERRIDE-64: "{{.*}}ld{{(.exe)?}}"
 // CHECK-LD-OVERRIDE-64: "-lgomp" "-lrt"
-// CHECK-LD-OVERRIDE-64: 

[PATCH] D48412: [RISCV] Add support for interrupt attribute

2018-07-06 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! Do you need me to commit on your behalf, or do you have commit privileges?


https://reviews.llvm.org/D48412



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


[PATCH] D48412: [RISCV] Add support for interrupt attribute

2018-07-06 Thread Ana Pazos via Phabricator via cfe-commits
apazos updated this revision to Diff 154447.
apazos added a comment.

Thanks Aaron, I appreciate you taking the time to review. 
I have updated the test and removed the warning as discussed.


https://reviews.llvm.org/D48412

Files:
  include/clang/Basic/Attr.td
  include/clang/Basic/AttrDocs.td
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/CodeGen/TargetInfo.cpp
  lib/Sema/SemaDeclAttr.cpp
  test/Sema/riscv-interrupt-attr.c
  test/Sema/riscv-interrupt-attr.cpp

Index: test/Sema/riscv-interrupt-attr.cpp
===
--- /dev/null
+++ test/Sema/riscv-interrupt-attr.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 %s -triple riscv32-unknown-elf -verify -fsyntax-only
+// RUN: %clang_cc1 %s -triple riscv64-unknown-elf -verify -fsyntax-only
+
+[[gnu::interrupt]] [[gnu::interrupt]] void foo1() {} // expected-warning {{repeated RISC-V 'interrupt' attribute}} \
+ // expected-note {{repeated RISC-V 'interrupt' attribute is here}}
+[[gnu::interrupt]] void foo2() {}
+
Index: test/Sema/riscv-interrupt-attr.c
===
--- /dev/null
+++ test/Sema/riscv-interrupt-attr.c
@@ -0,0 +1,36 @@
+// RUN: %clang_cc1 %s -triple riscv32-unknown-elf -verify -fsyntax-only
+// RUN: %clang_cc1 %s -triple riscv64-unknown-elf -verify -fsyntax-only
+
+struct a { int b; };
+
+struct a test __attribute__((interrupt)); // expected-warning {{'interrupt' attribute only applies to functions}}
+
+__attribute__((interrupt("USER"))) void foo1(void) {} // expected-warning {{'interrupt' attribute argument not supported: USER}}
+
+__attribute__((interrupt("user", 1))) void foo2(void) {} // expected-error {{'interrupt' attribute takes no more than 1 argument}}
+
+__attribute__((interrupt)) int foo3(void) {return 0;} // expected-warning {{RISC-V 'interrupt' attribute only applies to functions that have a 'void' return type}}
+
+__attribute__((interrupt())) void foo4();
+__attribute__((interrupt())) void foo4() {};
+
+__attribute__((interrupt())) void foo5(int a) {} // expected-warning {{RISC-V 'interrupt' attribute only applies to functions that have no parameters}}
+
+__attribute__((interrupt("user"), interrupt("supervisor"))) void foo6(void) {} // expected-warning {{repeated RISC-V 'interrupt' attribute}} \
+  // expected-note {{repeated RISC-V 'interrupt' attribute is here}}
+
+__attribute__((interrupt, interrupt)) void foo7(void) {} // expected-warning {{repeated RISC-V 'interrupt' attribute}} \
+ // expected-note {{repeated RISC-V 'interrupt' attribute is here}}
+
+__attribute__((interrupt(""))) void foo8(void) {} // expected-warning {{'interrupt' attribute argument not supported}}
+
+__attribute__((interrupt("user"))) void foo9(void);
+__attribute__((interrupt("supervisor"))) void foo9(void);
+__attribute__((interrupt("machine"))) void foo9(void);
+
+__attribute__((interrupt("user"))) void foo10(void) {}
+__attribute__((interrupt("supervisor"))) void foo11(void) {}
+__attribute__((interrupt("machine"))) void foo12(void) {}
+__attribute__((interrupt())) void foo13(void) {}
+__attribute__((interrupt)) void foo14(void) {}
+
Index: lib/Sema/SemaDeclAttr.cpp
===
--- lib/Sema/SemaDeclAttr.cpp
+++ lib/Sema/SemaDeclAttr.cpp
@@ -5266,6 +5266,63 @@
   handleSimpleAttribute(S, D, AL);
 }
 
+static void handleRISCVInterruptAttr(Sema , Decl *D,
+ const AttributeList ) {
+  // Warn about repeated attributes.
+  if (const auto *A = D->getAttr()) {
+S.Diag(AL.getRange().getBegin(),
+  diag::warn_riscv_repeated_interrupt_attribute);
+S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
+return;
+  }
+
+  // Check the attribute argument. Argument is optional.
+  if (!checkAttributeAtMostNumArgs(S, AL, 1))
+return;
+
+  StringRef Str;
+  SourceLocation ArgLoc;
+
+  // 'machine'is the default interrupt mode.
+  if (AL.getNumArgs() == 0)
+Str = "machine";
+  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, ))
+return;
+
+  // Semantic checks for a function with the 'interrupt' attribute:
+  // - Must be a function.
+  // - Must have no parameters.
+  // - Must have the 'void' return type.
+  // - The attribute itself must either have no argument or one of the
+  //   valid interrupt types, see [RISCVInterruptDocs].
+
+  if (D->getFunctionType() == nullptr) {
+S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
+  << "'interrupt'" << ExpectedFunction;
+return;
+  }
+
+  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
+S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 0;
+return;
+  }
+
+  if (!getFunctionOrMethodResultType(D)->isVoidType()) {
+S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 1;
+return;
+  }
+
+  

[PATCH] D47687: [Sema] Missing -Wlogical-op-parentheses warnings in macros (PR18971)

2018-07-06 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

In https://reviews.llvm.org/D47687#1136351, @Higuoxing wrote:

> Sorry, It seems a little bit difficult for me to add a proper fix-it hint for 
> expressions in macros, because I cannot find the exact position of the last 
> char of the token on right hand side of operator. Any suggestion?


Can you please clarify what exactly isn't working? `SuggestParentheses` is 
doing most of what you need but in this case it doesn't work because of macro 
locations:

  static void SuggestParentheses(Sema , SourceLocation Loc,
 const PartialDiagnostic ,
 SourceRange ParenRange) {
SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
EndLoc.isValid()) {
  Self.Diag(Loc, Note)
<< FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
<< FixItHint::CreateInsertion(EndLoc, ")");
} else {
  // We can't display the parentheses, so just show the bare note.
  Self.Diag(Loc, Note) << ParenRange;
}
  }

Hope this gives you an idea how you can try to make fix-its work.


https://reviews.llvm.org/D47687



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


r336460 - [OPENMP] Make clauses closing loc point to right bracket.

2018-07-06 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Fri Jul  6 12:35:42 2018
New Revision: 336460

URL: http://llvm.org/viewvc/llvm-project?rev=336460=rev
Log:
[OPENMP] Make clauses closing loc point to right bracket.

For some of the clauses the closing location erroneously points to the
beginning of the next clause rather than on the location of the closing
bracket of the clause.

Modified:
cfe/trunk/include/clang/Parse/Parser.h
cfe/trunk/lib/Parse/ParseOpenMP.cpp
cfe/trunk/test/OpenMP/dump.cpp

Modified: cfe/trunk/include/clang/Parse/Parser.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Parse/Parser.h?rev=336460=336459=336460=diff
==
--- cfe/trunk/include/clang/Parse/Parser.h (original)
+++ cfe/trunk/include/clang/Parse/Parser.h Fri Jul  6 12:35:42 2018
@@ -2822,6 +2822,7 @@ public:
   struct OpenMPVarListDataTy {
 Expr *TailExpr = nullptr;
 SourceLocation ColonLoc;
+SourceLocation RLoc;
 CXXScopeSpec ReductionIdScopeSpec;
 DeclarationNameInfo ReductionId;
 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;

Modified: cfe/trunk/lib/Parse/ParseOpenMP.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseOpenMP.cpp?rev=336460=336459=336460=diff
==
--- cfe/trunk/lib/Parse/ParseOpenMP.cpp (original)
+++ cfe/trunk/lib/Parse/ParseOpenMP.cpp Fri Jul  6 12:35:42 2018
@@ -424,13 +424,15 @@ void Parser::ParseOpenMPReductionInitial
   SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
 } else {
   // Match the ')'.
-  T.consumeClose();
+  SourceLocation RLoc = Tok.getLocation();
+  if (!T.consumeClose())
+RLoc = T.getCloseLocation();
 
   assert(!Exprs.empty() && Exprs.size() - 1 == CommaLocs.size() &&
  "Unexpected number of commas!");
 
-  ExprResult Initializer = Actions.ActOnParenListExpr(
-  T.getOpenLocation(), T.getCloseLocation(), Exprs);
+  ExprResult Initializer =
+  Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs);
   Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(),
/*DirectInit=*/true);
 }
@@ -1378,9 +1380,10 @@ ExprResult Parser::ParseOpenMPParensExpr
   Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc);
 
   // Parse ')'.
-  T.consumeClose();
+  RLoc = Tok.getLocation();
+  if (!T.consumeClose())
+RLoc = T.getCloseLocation();
 
-  RLoc = T.getCloseLocation();
   return Val;
 }
 
@@ -1457,12 +1460,13 @@ OMPClause *Parser::ParseOpenMPSimpleClau
 ConsumeAnyToken();
 
   // Parse ')'.
-  T.consumeClose();
+  SourceLocation RLoc = Tok.getLocation();
+  if (!T.consumeClose())
+RLoc = T.getCloseLocation();
 
   if (ParseOnly)
 return nullptr;
-  return Actions.ActOnOpenMPSimpleClause(Kind, Type, TypeLoc, LOpen, Loc,
- Tok.getLocation());
+  return Actions.ActOnOpenMPSimpleClause(Kind, Type, TypeLoc, LOpen, Loc, 
RLoc);
 }
 
 /// Parsing of OpenMP clauses like 'ordered'.
@@ -1633,7 +1637,9 @@ OMPClause *Parser::ParseOpenMPSingleExpr
   }
 
   // Parse ')'.
-  T.consumeClose();
+  SourceLocation RLoc = Tok.getLocation();
+  if (!T.consumeClose())
+RLoc = T.getCloseLocation();
 
   if (NeedAnExpression && Val.isInvalid())
 return nullptr;
@@ -1641,8 +1647,7 @@ OMPClause *Parser::ParseOpenMPSingleExpr
   if (ParseOnly)
 return nullptr;
   return Actions.ActOnOpenMPSingleExprWithArgClause(
-  Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc,
-  T.getCloseLocation());
+  Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc);
 }
 
 static bool ParseReductionId(Parser , CXXScopeSpec ,
@@ -1914,7 +1919,9 @@ bool Parser::ParseOpenMPVarList(OpenMPDi
   }
 
   // Parse ')'.
-  T.consumeClose();
+  Data.RLoc = Tok.getLocation();
+  if (!T.consumeClose())
+Data.RLoc = T.getCloseLocation();
   return (Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown &&
   Vars.empty()) ||
  (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
@@ -1979,7 +1986,7 @@ OMPClause *Parser::ParseOpenMPVarListCla
   if (ParseOnly)
 return nullptr;
   return Actions.ActOnOpenMPVarListClause(
-  Kind, Vars, Data.TailExpr, Loc, LOpen, Data.ColonLoc, Tok.getLocation(),
+  Kind, Vars, Data.TailExpr, Loc, LOpen, Data.ColonLoc, Data.RLoc,
   Data.ReductionIdScopeSpec, Data.ReductionId, Data.DepKind, Data.LinKind,
   Data.MapTypeModifier, Data.MapType, Data.IsMapTypeImplicit,
   Data.DepLinMapLoc);

Modified: cfe/trunk/test/OpenMP/dump.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/OpenMP/dump.cpp?rev=336460=336459=336460=diff
==
--- cfe/trunk/test/OpenMP/dump.cpp (original)
+++ cfe/trunk/test/OpenMP/dump.cpp Fri Jul  6 12:35:42 2018
@@ -44,10 

[PATCH] D48685: [PCH+Modules] Load -fmodule-map-file content before including PCHs

2018-07-06 Thread Bruno Cardoso Lopes via Phabricator via cfe-commits
bruno added a comment.
Herald added a subscriber: dexonsmith.

Ping!


https://reviews.llvm.org/D48685



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


[PATCH] D44539: [Sema][Objective-C] Add check to warn when property of objc type has assign attribute

2018-07-06 Thread Alfred Zien via Phabricator via cfe-commits
QF5690 added inline comments.



Comment at: lib/Sema/SemaObjCProperty.cpp:2554
+  PropertyTy->isObjCRetainableType() &&
+  !PropertyTy->isObjCClassType()) {
+Diag(Loc, diag::warn_objc_property_assign_on_object);

rjmccall wrote:
> Please use `isObjCARCImplicitlyUnretainedType` here.
Thanks, didn't notice it.



Comment at: test/SemaObjC/property-in-class-extension-1.m:18
 
-@property (assign, readonly) NSString* changeMemoryModel; // expected-note 
{{property declared here}}
+@property (unsafe_unretained, readonly) NSString* changeMemoryModel; // 
expected-note {{property declared here}}
 

rjmccall wrote:
> Whoa, why is this test case using `-Weverything`?  That seems unnecessarily 
> fragile.
Do you think it should be relaxed only to warnings that are appearing here?


Repository:
  rC Clang

https://reviews.llvm.org/D44539



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


[PATCH] D48903: [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name

2018-07-06 Thread Simon Marchi via Phabricator via cfe-commits
simark updated this revision to Diff 154422.
simark marked an inline comment as done.
simark added a comment.

- Use StringRef in InMemoryNode::getStatus
- Remove unused variable in TEST_F(InMemoryFileSystemTest, StatusName)


Repository:
  rC Clang

https://reviews.llvm.org/D48903

Files:
  lib/Basic/VirtualFileSystem.cpp
  unittests/Basic/VirtualFileSystemTest.cpp
  unittests/Driver/ToolChainTest.cpp

Index: unittests/Driver/ToolChainTest.cpp
===
--- unittests/Driver/ToolChainTest.cpp
+++ unittests/Driver/ToolChainTest.cpp
@@ -113,7 +113,7 @@
   std::replace(S.begin(), S.end(), '\\', '/');
 #endif
   EXPECT_EQ("Found candidate GCC installation: "
-"/home/test/lib/gcc/arm-linux-gnueabi/4.6.1\n"
+"/home/test/bin/../lib/gcc/arm-linux-gnueabi/4.6.1\n"
 "Selected GCC installation: "
 "/home/test/bin/../lib/gcc/arm-linux-gnueabi/4.6.1\n"
 "Candidate multilib: .;@m32\n"
Index: unittests/Basic/VirtualFileSystemTest.cpp
===
--- unittests/Basic/VirtualFileSystemTest.cpp
+++ unittests/Basic/VirtualFileSystemTest.cpp
@@ -794,7 +794,7 @@
 
   auto Stat = FS.status("/b/c");
   ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n" << FS.toString();
-  ASSERT_EQ("c", Stat->getName());
+  ASSERT_EQ("/b/c", Stat->getName());
   ASSERT_EQ("/b", *FS.getCurrentWorkingDirectory());
 
   Stat = FS.status("c");
@@ -919,6 +919,37 @@
   ASSERT_TRUE(Stat->isRegularFile());
 }
 
+// Test that the name returned by status() is in the same form as the path that
+// was requested (to match the behavior of RealFileSystem).
+TEST_F(InMemoryFileSystemTest, StatusName) {
+  NormalizedFS.addFile("/a/b/c", 0, MemoryBuffer::getMemBuffer("abc"),
+   /*User=*/None,
+   /*Group=*/None, sys::fs::file_type::regular_file);
+  NormalizedFS.setCurrentWorkingDirectory("/a/b");
+
+  // Access using InMemoryFileSystem::status.
+  auto Stat = NormalizedFS.status("../b/c");
+  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n"
+<< NormalizedFS.toString();
+  ASSERT_TRUE(Stat->isRegularFile());
+  ASSERT_EQ("../b/c", Stat->getName());
+
+  // Access using InMemoryFileAdaptor::status.
+  auto File = NormalizedFS.openFileForRead("../b/c");
+  ASSERT_FALSE(File.getError()) << File.getError() << "\n"
+<< NormalizedFS.toString();
+  Stat = (*File)->status();
+  ASSERT_FALSE(Stat.getError()) << Stat.getError() << "\n"
+<< NormalizedFS.toString();
+  ASSERT_TRUE(Stat->isRegularFile());
+  ASSERT_EQ("../b/c", Stat->getName());
+
+  // Access using a directory iterator.
+  std::error_code EC;
+  clang::vfs::directory_iterator It = NormalizedFS.dir_begin("../b", EC);
+  ASSERT_EQ("../b/c", It->getName());
+}
+
 // NOTE: in the tests below, we use '//root/' as our root directory, since it is
 // a legal *absolute* path on Windows as well as *nix.
 class VFSFromYAMLTest : public ::testing::Test {
Index: lib/Basic/VirtualFileSystem.cpp
===
--- lib/Basic/VirtualFileSystem.cpp
+++ lib/Basic/VirtualFileSystem.cpp
@@ -479,7 +479,13 @@
   : Stat(std::move(Stat)), Kind(Kind) {}
   virtual ~InMemoryNode() = default;
 
-  const Status () const { return Stat; }
+  /// Return the \p Status for this node. \p RequestedName should be the name
+  /// through which the caller referred to this node. It will override
+  /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
+  Status getStatus(StringRef RequestedName) const {
+return Status::copyWithNewName(Stat, RequestedName);
+  }
+  StringRef getName() const { return Stat.getName(); }
   InMemoryNodeKind getKind() const { return Kind; }
   virtual std::string toString(unsigned Indent) const = 0;
 };
@@ -496,22 +502,30 @@
   llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
 
   std::string toString(unsigned Indent) const override {
-return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
+return (std::string(Indent, ' ') + getName() + "\n").str();
   }
 
   static bool classof(const InMemoryNode *N) {
 return N->getKind() == IME_File;
   }
 };
 
-/// Adapt a InMemoryFile for VFS' File interface.
+/// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
+/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
+/// \p RealFile.
 class InMemoryFileAdaptor : public File {
   InMemoryFile 
 
+  /// The name to use when returning a Status for this file.
+  std::string RequestedName;
+
 public:
-  explicit InMemoryFileAdaptor(InMemoryFile ) : Node(Node) {}
+  explicit InMemoryFileAdaptor(InMemoryFile , std::string RequestedName)
+  : Node(Node), RequestedName(std::move(RequestedName)) {}
 
-  llvm::ErrorOr status() override { return Node.getStatus(); }

[PATCH] D47632: [ASTImporter] Refactor Decl creation

2018-07-06 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 154421.
martong added a comment.

Fix indentation


Repository:
  rC Clang

https://reviews.llvm.org/D47632

Files:
  include/clang/AST/ASTImporter.h
  include/clang/AST/ASTStructuralEquivalence.h
  include/clang/AST/DeclBase.h
  lib/AST/ASTImporter.cpp
  lib/AST/ASTStructuralEquivalence.cpp
  lib/AST/ExternalASTMerger.cpp
  lib/Sema/SemaType.cpp
  unittests/AST/ASTImporterTest.cpp
  unittests/AST/StructuralEquivalenceTest.cpp

Index: unittests/AST/StructuralEquivalenceTest.cpp
===
--- unittests/AST/StructuralEquivalenceTest.cpp
+++ unittests/AST/StructuralEquivalenceTest.cpp
@@ -60,8 +60,9 @@
 
   bool testStructuralMatch(NamedDecl *D0, NamedDecl *D1) {
 llvm::DenseSet> NonEquivalentDecls;
-StructuralEquivalenceContext Ctx(D0->getASTContext(), D1->getASTContext(),
- NonEquivalentDecls, false, false);
+StructuralEquivalenceContext Ctx(
+D0->getASTContext(), D1->getASTContext(), NonEquivalentDecls,
+StructuralEquivalenceKind::Default, false, false);
 return Ctx.IsStructurallyEquivalent(D0, D1);
   }
 
Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -284,19 +284,32 @@
   // Buffer for the To context, must live in the test scope.
   std::string ToCode;
 
+  // Represents a "From" translation unit and holds an importer object which we
+  // use to import from this translation unit.
   struct TU {
 // Buffer for the context, must live in the test scope.
 std::string Code;
 std::string FileName;
 std::unique_ptr Unit;
 TranslationUnitDecl *TUDecl = nullptr;
+std::unique_ptr Importer;
 TU(StringRef Code, StringRef FileName, ArgVector Args)
 : Code(Code), FileName(FileName),
   Unit(tooling::buildASTFromCodeWithArgs(this->Code, Args,
  this->FileName)),
   TUDecl(Unit->getASTContext().getTranslationUnitDecl()) {
   Unit->enableSourceFileDiagnostics();
 }
+
+Decl *import(ASTUnit *ToAST, Decl *FromDecl) {
+  assert(ToAST);
+  if (!Importer) {
+Importer.reset(new ASTImporter(
+ToAST->getASTContext(), ToAST->getFileManager(),
+Unit->getASTContext(), Unit->getFileManager(), false));
+  }
+  return Importer->Import(FromDecl);
+}
   };
 
   // We may have several From contexts and related translation units. In each
@@ -329,14 +342,10 @@
 ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, OutputFileName);
 ToAST->enableSourceFileDiagnostics();
 
-ASTContext  = FromTU.Unit->getASTContext(),
-= ToAST->getASTContext();
+ASTContext  = FromTU.Unit->getASTContext();
 
 createVirtualFileIfNeeded(ToAST.get(), InputFileName, FromTU.Code);
 
-ASTImporter Importer(ToCtx, ToAST->getFileManager(), FromCtx,
- FromTU.Unit->getFileManager(), false);
-
 IdentifierInfo *ImportedII = (Identifier);
 assert(ImportedII && "Declaration with the given identifier "
  "should be specified in test!");
@@ -347,7 +356,8 @@
 
 assert(FoundDecls.size() == 1);
 
-Decl *Imported = Importer.Import(FoundDecls.front());
+Decl *Imported = FromTU.import(ToAST.get(), FoundDecls.front());
+
 assert(Imported);
 return std::make_tuple(*FoundDecls.begin(), Imported);
   }
@@ -401,11 +411,7 @@
 assert(It != FromTUs.end());
 createVirtualFileIfNeeded(ToAST.get(), It->FileName, It->Code);
 
-ASTContext  = From->getASTContext(),
-= ToAST->getASTContext();
-ASTImporter Importer(ToCtx, ToAST->getFileManager(), FromCtx,
- FromCtx.getSourceManager().getFileManager(), false);
-return Importer.Import(From);
+return It->import(ToAST.get(), From);
   }
 
   ~ASTImporterTestBase() {
@@ -1089,8 +1095,7 @@
   EXPECT_EQ(ToTemplated1, ToTemplated);
 }
 
-TEST_P(ASTImporterTestBase,
-   DISABLED_ImportOfTemplatedDeclOfFunctionTemplateDecl) {
+TEST_P(ASTImporterTestBase, ImportOfTemplatedDeclOfFunctionTemplateDecl) {
   Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX);
   auto From = FirstDeclMatcher().match(
   FromTU, functionTemplateDecl());
@@ -1166,7 +1171,7 @@
   ASSERT_EQ(ToTemplated1, ToTemplated);
 }
 
-TEST_P(ASTImporterTestBase, DISABLED_ImportFunctionWithBackReferringParameter) {
+TEST_P(ASTImporterTestBase, ImportFunctionWithBackReferringParameter) {
   Decl *From, *To;
   std::tie(From, To) = getImportedDecl(
   R"(
@@ -1711,6 +1716,49 @@
   EXPECT_NE(To0->getCanonicalDecl(), To1->getCanonicalDecl());
 }
 
+TEST_P(ASTImporterTestBase, ImportDoesUpdateUsedFlag) {
+  auto Pattern = varDecl(hasName("x"));
+  VarDecl *Imported1;
+  {
+Decl *FromTU = getTuDecl("extern int x;", Lang_CXX, "input0.cc");

[PATCH] D48291: [analyzer][UninitializedObjectChecker] Fixed captured lambda variable name

2018-07-06 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus marked 3 inline comments as done.
Szelethus added inline comments.



Comment at: lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp:691
 
+StringRef getVariableName(const FieldDecl *Field) {
+  // If \p Field is a captured lambda variable, Field->getName() will return

george.karpenkov wrote:
> Is this a member method? Then it should be prefixed with a class name.
> Currently it looks like you have a member method without an implementation 
> and a separate C-style function?
It is a statically defined method, and you can see its forward declaration in 
the same diff.

Back when I started writing this checker, the amount of function laying in the 
anonymous namespace was very few, but this has changed. I'll fix it sometime 
because it's getting somewhat annoying (and is against the [[ 
https://llvm.org/docs/CodingStandards.html | coding standards ]]).


https://reviews.llvm.org/D48291



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


[PATCH] D48291: [analyzer][UninitializedObjectChecker] Fixed captured lambda variable name

2018-07-06 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 154420.
Szelethus added a comment.

Finding the correct captured variable now works with 
`FieldDecl::getFieldIndex()`.


https://reviews.llvm.org/D48291

Files:
  lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
  test/Analysis/cxx-uninitialized-object.cpp

Index: test/Analysis/cxx-uninitialized-object.cpp
===
--- test/Analysis/cxx-uninitialized-object.cpp
+++ test/Analysis/cxx-uninitialized-object.cpp
@@ -737,6 +737,22 @@
 //===--===//
 
 template 
+struct LambdaThisTest {
+  Callable functor;
+
+  LambdaThisTest(const Callable , int) : functor(functor) {
+// All good!
+  }
+};
+
+struct HasCapturableThis {
+  void fLambdaThisTest() {
+auto isEven = [this](int a) { return a % 2 == 0; }; // no-crash
+LambdaThisTest(isEven, int());
+  }
+};
+
+template 
 struct LambdaTest1 {
   Callable functor;
 
@@ -760,7 +776,7 @@
 
 void fLambdaTest2() {
   int b;
-  auto equals = [](int a) { return a == b; }; // expected-note{{uninitialized field 'this->functor.'}}
+  auto equals = [](int a) { return a == b; }; // expected-note{{uninitialized field 'this->functor.b'}}
   LambdaTest2(equals, int());
 }
 #else
@@ -782,8 +798,8 @@
 namespace LT3Detail {
 
 struct RecordType {
-  int x; // expected-note{{uninitialized field 'this->functor..x'}}
-  int y; // expected-note{{uninitialized field 'this->functor..y'}}
+  int x; // expected-note{{uninitialized field 'this->functor.rec1.x'}}
+  int y; // expected-note{{uninitialized field 'this->functor.rec1.y'}}
 };
 
 } // namespace LT3Detail
@@ -826,6 +842,35 @@
 }
 #endif //PEDANTIC
 
+template 
+struct MultipleLambdaCapturesTest1 {
+  Callable functor;
+  int dontGetFilteredByNonPedanticMode = 0;
+
+  MultipleLambdaCapturesTest1(const Callable , int) : functor(functor) {} // expected-warning{{2 uninitialized field}}
+};
+
+void fMultipleLambdaCapturesTest1() {
+  int b1, b2 = 3, b3;
+  auto equals = [, , ](int a) { return a == b1 == b2 == b3; }; // expected-note{{uninitialized field 'this->functor.b1'}}
+  // expected-note@-1{{uninitialized field 'this->functor.b3'}}
+  MultipleLambdaCapturesTest1(equals, int());
+}
+
+template 
+struct MultipleLambdaCapturesTest2 {
+  Callable functor;
+  int dontGetFilteredByNonPedanticMode = 0;
+
+  MultipleLambdaCapturesTest2(const Callable , int) : functor(functor) {} // expected-warning{{1 uninitialized field}}
+};
+
+void fMultipleLambdaCapturesTest2() {
+  int b1, b2 = 3, b3;
+  auto equals = [b1, , ](int a) { return a == b1 == b2 == b3; }; // expected-note{{uninitialized field 'this->functor.b3'}}
+  MultipleLambdaCapturesTest2(equals, int());
+}
+
 //===--===//
 // System header tests.
 //===--===//
Index: lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
+++ lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
@@ -230,6 +230,10 @@
 /// Constructs a note message for a given FieldChainInfo object.
 void printNoteMessage(llvm::raw_ostream , const FieldChainInfo );
 
+/// Returns with Field's name. This is a helper function to get the correct name
+/// even if Field is a captured lambda variable.
+StringRef getVariableName(const FieldDecl *Field);
+
 } // end of anonymous namespace
 
 //===--===//
@@ -596,30 +600,14 @@
 // "uninitialized field 'this->x'", but we can't refer to 'x' directly,
 // we need an explicit namespace resolution whether the uninit field was
 // 'D1::x' or 'D2::x'.
-//
-// TODO: If a field in the fieldchain is a captured lambda parameter, this
-// function constructs an empty string for it:
-//
-//   template  struct A {
-// Callable c;
-// A(const Callable , int) : c(c) {}
-//   };
-//
-//   int b; // say that this isn't zero initialized
-//   auto alwaysTrue = [](int a) { return true; };
-//
-// A call with these parameters: A::A(alwaysTrue, int())
-// will emit a note with the message "uninitialized field: 'this->c.'". If
-// possible, the lambda parameter name should be retrieved or be replaced with a
-// "" or something similar.
 void FieldChainInfo::print(llvm::raw_ostream ) const {
   if (Chain.isEmpty())
 return;
 
   const llvm::ImmutableListImpl *L =
   Chain.getInternalPointer();
   printTail(Out, L->getTail());
-  Out << L->getHead()->getDecl()->getNameAsString();
+  Out << getVariableName(L->getHead()->getDecl());
 }
 
 void FieldChainInfo::printTail(
@@ -630,7 +618,7 @@
 
   printTail(Out, L->getTail());
   const FieldDecl *Field = L->getHead()->getDecl();
-  Out << Field->getNameAsString();
+  Out << getVariableName(Field);
   Out << 

[PATCH] D47632: [ASTImporter] Refactor Decl creation

2018-07-06 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 154418.
martong added a comment.

- Rebase from master
- Enable some disabled tests
- Update the isUsed flag
- Add a new config `Minimal` to the structural eq check, so lldb tests can pass 
now
- Return with a bool value and use LLVM_NODISCARD in CreateDecl
- Rename CreateDecl


Repository:
  rC Clang

https://reviews.llvm.org/D47632

Files:
  include/clang/AST/ASTImporter.h
  include/clang/AST/ASTStructuralEquivalence.h
  include/clang/AST/DeclBase.h
  lib/AST/ASTImporter.cpp
  lib/AST/ASTStructuralEquivalence.cpp
  lib/AST/ExternalASTMerger.cpp
  lib/Sema/SemaType.cpp
  unittests/AST/ASTImporterTest.cpp
  unittests/AST/StructuralEquivalenceTest.cpp

Index: unittests/AST/StructuralEquivalenceTest.cpp
===
--- unittests/AST/StructuralEquivalenceTest.cpp
+++ unittests/AST/StructuralEquivalenceTest.cpp
@@ -60,8 +60,9 @@
 
   bool testStructuralMatch(NamedDecl *D0, NamedDecl *D1) {
 llvm::DenseSet> NonEquivalentDecls;
-StructuralEquivalenceContext Ctx(D0->getASTContext(), D1->getASTContext(),
- NonEquivalentDecls, false, false);
+StructuralEquivalenceContext Ctx(
+D0->getASTContext(), D1->getASTContext(), NonEquivalentDecls,
+StructuralEquivalenceKind::Default, false, false);
 return Ctx.IsStructurallyEquivalent(D0, D1);
   }
 
Index: unittests/AST/ASTImporterTest.cpp
===
--- unittests/AST/ASTImporterTest.cpp
+++ unittests/AST/ASTImporterTest.cpp
@@ -284,19 +284,32 @@
   // Buffer for the To context, must live in the test scope.
   std::string ToCode;
 
+  // Represents a "From" translation unit and holds an importer object which we
+  // use to import from this translation unit.
   struct TU {
 // Buffer for the context, must live in the test scope.
 std::string Code;
 std::string FileName;
 std::unique_ptr Unit;
 TranslationUnitDecl *TUDecl = nullptr;
+std::unique_ptr Importer;
 TU(StringRef Code, StringRef FileName, ArgVector Args)
 : Code(Code), FileName(FileName),
   Unit(tooling::buildASTFromCodeWithArgs(this->Code, Args,
  this->FileName)),
   TUDecl(Unit->getASTContext().getTranslationUnitDecl()) {
   Unit->enableSourceFileDiagnostics();
 }
+
+Decl *import(ASTUnit *ToAST, Decl *FromDecl) {
+  assert(ToAST);
+  if (!Importer) {
+Importer.reset(new ASTImporter(
+ToAST->getASTContext(), ToAST->getFileManager(),
+Unit->getASTContext(), Unit->getFileManager(), false));
+  }
+  return Importer->Import(FromDecl);
+}
   };
 
   // We may have several From contexts and related translation units. In each
@@ -329,14 +342,10 @@
 ToAST = tooling::buildASTFromCodeWithArgs(ToCode, ToArgs, OutputFileName);
 ToAST->enableSourceFileDiagnostics();
 
-ASTContext  = FromTU.Unit->getASTContext(),
-= ToAST->getASTContext();
+ASTContext  = FromTU.Unit->getASTContext();
 
 createVirtualFileIfNeeded(ToAST.get(), InputFileName, FromTU.Code);
 
-ASTImporter Importer(ToCtx, ToAST->getFileManager(), FromCtx,
- FromTU.Unit->getFileManager(), false);
-
 IdentifierInfo *ImportedII = (Identifier);
 assert(ImportedII && "Declaration with the given identifier "
  "should be specified in test!");
@@ -347,7 +356,8 @@
 
 assert(FoundDecls.size() == 1);
 
-Decl *Imported = Importer.Import(FoundDecls.front());
+Decl *Imported = FromTU.import(ToAST.get(), FoundDecls.front());
+
 assert(Imported);
 return std::make_tuple(*FoundDecls.begin(), Imported);
   }
@@ -401,11 +411,7 @@
 assert(It != FromTUs.end());
 createVirtualFileIfNeeded(ToAST.get(), It->FileName, It->Code);
 
-ASTContext  = From->getASTContext(),
-= ToAST->getASTContext();
-ASTImporter Importer(ToCtx, ToAST->getFileManager(), FromCtx,
- FromCtx.getSourceManager().getFileManager(), false);
-return Importer.Import(From);
+return It->import(ToAST.get(), From);
   }
 
   ~ASTImporterTestBase() {
@@ -1089,8 +1095,7 @@
   EXPECT_EQ(ToTemplated1, ToTemplated);
 }
 
-TEST_P(ASTImporterTestBase,
-   DISABLED_ImportOfTemplatedDeclOfFunctionTemplateDecl) {
+TEST_P(ASTImporterTestBase, ImportOfTemplatedDeclOfFunctionTemplateDecl) {
   Decl *FromTU = getTuDecl("template void f(){}", Lang_CXX);
   auto From = FirstDeclMatcher().match(
   FromTU, functionTemplateDecl());
@@ -1166,7 +1171,7 @@
   ASSERT_EQ(ToTemplated1, ToTemplated);
 }
 
-TEST_P(ASTImporterTestBase, DISABLED_ImportFunctionWithBackReferringParameter) {
+TEST_P(ASTImporterTestBase, ImportFunctionWithBackReferringParameter) {
   Decl *From, *To;
   std::tie(From, To) = getImportedDecl(
   R"(
@@ -1711,6 +1716,49 @@
   EXPECT_NE(To0->getCanonicalDecl(), 

[PATCH] D48892: [libc++] Replace uses of _LIBCPP_ALWAYS_INLINE by _LIBCPP_INLINE_VISIBILITY

2018-07-06 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added inline comments.



Comment at: libcxx/include/streambuf:261
 
-_LIBCPP_ALWAYS_INLINE
+_LIBCPP_INLINE_VISIBILITY
 void __pbump(streamsize __n) { __nout_ += __n; }

This one was marked as `_LIBCPP_EXTERN_TEMPLATE_INLINE_VISIBILITY` instead of 
`_LIBCPP_INLINE_VISIBILITY` in the previous revision. This is what caused the 
`check-cxx-abilist` test to fail.


Repository:
  rL LLVM

https://reviews.llvm.org/D48892



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


[PATCH] D48892: [libc++] Replace uses of _LIBCPP_ALWAYS_INLINE by _LIBCPP_INLINE_VISIBILITY

2018-07-06 Thread Louis Dionne via Phabricator via cfe-commits
ldionne updated this revision to Diff 154415.
ldionne added a comment.

This revision to the patch fixes a problem where __pbump had been applied
_LIBCPP_EXTERN_TEMPLATE_INLINE_VISIBILITY instead of _LIBCPP_INLINE_VISIBILITY,
which caused the symbols exported in the ABI to change and broke the CI.

Independently, LLDB tests that were failing because they relied on
_LIBCPP_INLINE_VISIBILITY were fixed so that this change should not
break them again.

I still haven't been able to run the ABI tests locally (they fail on my
machine), and I'd like to do that before I submit this patch.


Repository:
  rL LLVM

https://reviews.llvm.org/D48892

Files:
  libcxx/docs/DesignDocs/VisibilityMacros.rst
  libcxx/include/__bsd_locale_fallbacks.h
  libcxx/include/__config
  libcxx/include/__locale
  libcxx/include/__nullptr
  libcxx/include/any
  libcxx/include/cmath
  libcxx/include/codecvt
  libcxx/include/exception
  libcxx/include/experimental/dynarray
  libcxx/include/experimental/filesystem
  libcxx/include/functional
  libcxx/include/future
  libcxx/include/initializer_list
  libcxx/include/ios
  libcxx/include/locale
  libcxx/include/math.h
  libcxx/include/memory
  libcxx/include/new
  libcxx/include/ostream
  libcxx/include/regex
  libcxx/include/stdexcept
  libcxx/include/streambuf
  libcxx/include/support/android/locale_bionic.h
  libcxx/include/support/xlocale/__posix_l_fallback.h
  libcxx/include/support/xlocale/__strtonum_fallback.h
  libcxx/include/system_error
  libcxx/include/typeinfo
  libcxx/include/vector
  libcxx/src/support/win32/thread_win32.cpp

Index: libcxx/src/support/win32/thread_win32.cpp
===
--- libcxx/src/support/win32/thread_win32.cpp
+++ libcxx/src/support/win32/thread_win32.cpp
@@ -138,7 +138,7 @@
 }
 
 // Execute Once
-static inline _LIBCPP_ALWAYS_INLINE BOOL CALLBACK
+static inline _LIBCPP_INLINE_VISIBILITY BOOL CALLBACK
 __libcpp_init_once_execute_once_thunk(PINIT_ONCE __init_once, PVOID __parameter,
   PVOID *__context)
 {
@@ -178,7 +178,7 @@
   void *__arg;
 };
 
-static inline _LIBCPP_ALWAYS_INLINE unsigned WINAPI
+static inline _LIBCPP_INLINE_VISIBILITY unsigned WINAPI
 __libcpp_beginthreadex_thunk(void *__raw_data)
 {
   auto *__data =
Index: libcxx/include/vector
===
--- libcxx/include/vector
+++ libcxx/include/vector
@@ -295,7 +295,7 @@
 class __vector_base_common
 {
 protected:
-_LIBCPP_ALWAYS_INLINE __vector_base_common() {}
+_LIBCPP_INLINE_VISIBILITY __vector_base_common() {}
 _LIBCPP_NORETURN void __throw_length_error() const;
 _LIBCPP_NORETURN void __throw_out_of_range() const;
 };
Index: libcxx/include/typeinfo
===
--- libcxx/include/typeinfo
+++ libcxx/include/typeinfo
@@ -226,7 +226,7 @@
 #endif // defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_NO_VCRUNTIME)
 
 _LIBCPP_BEGIN_NAMESPACE_STD
-_LIBCPP_NORETURN inline _LIBCPP_ALWAYS_INLINE
+_LIBCPP_NORETURN inline _LIBCPP_INLINE_VISIBILITY
 void __throw_bad_cast()
 {
 #ifndef _LIBCPP_NO_EXCEPTIONS
Index: libcxx/include/system_error
===
--- libcxx/include/system_error
+++ libcxx/include/system_error
@@ -203,7 +203,7 @@
 defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
 error_category() _NOEXCEPT;
 #else
-_LIBCPP_ALWAYS_INLINE
+_LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR_AFTER_CXX11 error_category() _NOEXCEPT _LIBCPP_DEFAULT
 #endif
 private:
@@ -217,13 +217,13 @@
 virtual bool equivalent(const error_code& __code, int __condition) const _NOEXCEPT;
 virtual string message(int __ev) const = 0;
 
-_LIBCPP_ALWAYS_INLINE
+_LIBCPP_INLINE_VISIBILITY
 bool operator==(const error_category& __rhs) const _NOEXCEPT {return this == &__rhs;}
 
-_LIBCPP_ALWAYS_INLINE
+_LIBCPP_INLINE_VISIBILITY
 bool operator!=(const error_category& __rhs) const _NOEXCEPT {return !(*this == __rhs);}
 
-_LIBCPP_ALWAYS_INLINE
+_LIBCPP_INLINE_VISIBILITY
 bool operator< (const error_category& __rhs) const _NOEXCEPT {return this < &__rhs;}
 
 friend class _LIBCPP_HIDDEN __do_message;
@@ -244,52 +244,52 @@
 int __val_;
 const error_category* __cat_;
 public:
-_LIBCPP_ALWAYS_INLINE
+_LIBCPP_INLINE_VISIBILITY
 error_condition() _NOEXCEPT : __val_(0), __cat_(_category()) {}
 
-_LIBCPP_ALWAYS_INLINE
+_LIBCPP_INLINE_VISIBILITY
 error_condition(int __val, const error_category& __cat) _NOEXCEPT
 : __val_(__val), __cat_(&__cat) {}
 
 template 
-_LIBCPP_ALWAYS_INLINE
+_LIBCPP_INLINE_VISIBILITY
 error_condition(_Ep __e,
   typename enable_if::value>::type* = 0
  ) _NOEXCEPT
 {*this = make_error_condition(__e);}
 

[PATCH] D49028: [clangd] Support indexing MACROs.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 154414.
ioeric added a comment.

- Another minor cleanup.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49028

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -992,6 +992,32 @@
Field(::Origin, SymbolOrigin::Static)));
 }
 
+TEST_F(SymbolCollectorTest, CollectMacros) {
+  CollectorOpts.CollectIncludePath = true;
+  Annotations Header(R"(
+#define X 1
+#define $mac[[MAC]](x) int x
+#define $used[[USED]](y) float y;
+
+MAC(p);
+  )");
+  const std::string Main = R"(
+#define MAIN 1  // not indexed
+USED(t);
+  )";
+  CollectorOpts.CountReferences = true;
+  CollectorOpts.CollectMacro = true;
+  runSymbolCollector(Header.code(), Main);
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  QName("p"),
+  AllOf(QName("X"), DeclURI(TestHeaderURI),
+IncludeHeader(TestHeaderURI)),
+  AllOf(Labeled("MAC(x)"), Refs(0), DeclRange(Header.range("mac"))),
+  AllOf(Labeled("USED(y)"), Refs(1), DeclRange(Header.range("used");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -54,6 +54,11 @@
 bool CountReferences = false;
 // Every symbol collected will be stamped with this origin.
 SymbolOrigin Origin = SymbolOrigin::Unknown;
+/// Collect macros.
+/// Note that SymbolCollector must be run with preprocessor in order to
+/// collect macros. For example, `indexTopLevelDecls` will not index any
+/// macro even if this is true.
+bool CollectMacro = false;
   };
 
   SymbolCollector(Options Opts);
@@ -75,6 +80,10 @@
   SourceLocation Loc,
   index::IndexDataConsumer::ASTNodeInfo ASTNode) override;
 
+  bool handleMacroOccurence(const IdentifierInfo , const MacroInfo ,
+index::SymbolRoleSet Roles,
+SourceLocation Loc) override;
+
   SymbolSlab takeSymbols() { return std::move(Symbols).build(); }
 
   void finish() override;
@@ -90,8 +99,8 @@
   std::shared_ptr CompletionAllocator;
   std::unique_ptr CompletionTUInfo;
   Options Opts;
-  // Decls referenced from the current TU, flushed on finish().
-  llvm::DenseSet ReferencedDecls;
+  // Macros referenced from the current TU, flushed on finish().
+  llvm::DenseSet ReferencedSymbols;
   // Maps canonical declaration provided by clang to canonical declaration for
   // an index symbol, if clangd prefers a different declaration than that
   // provided by clang. For example, friend declaration might be considered
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -183,22 +183,19 @@
   return toURI(SM, Header, Opts);
 }
 
-// Return the symbol location of the given declaration `D`.
-//
-// For symbols defined inside macros:
-//   * use expansion location, if the symbol is formed via macro concatenation.
-//   * use spelling location, otherwise.
-llvm::Optional getSymbolLocation(
-const NamedDecl , SourceManager , const SymbolCollector::Options ,
-const clang::LangOptions , std::string ) {
-  SourceLocation NameLoc = findNameLoc();
-  auto U = toURI(SM, SM.getFilename(NameLoc), Opts);
+// Return the symbol location of the token at \p Loc.
+llvm::Optional
+getTokenLocation(SourceLocation TokLoc, const SourceManager ,
+ const SymbolCollector::Options ,
+ const clang::LangOptions ,
+ std::string ) {
+  auto U = toURI(SM, SM.getFilename(TokLoc), Opts);
   if (!U)
 return llvm::None;
   FileURIStorage = std::move(*U);
   SymbolLocation Result;
   Result.FileURI = FileURIStorage;
-  auto TokenLength = clang::Lexer::MeasureTokenLength(NameLoc, SM, LangOpts);
+  auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
 
   auto CreatePosition = [](SourceLocation Loc) {
 auto LSPLoc = sourceLocToPosition(SM, Loc);
@@ -208,8 +205,8 @@
 return Pos;
   };
 
-  Result.Start = CreatePosition(NameLoc);
-  auto EndLoc = NameLoc.getLocWithOffset(TokenLength);
+  Result.Start = CreatePosition(TokLoc);
+  auto EndLoc = TokLoc.getLocWithOffset(TokenLength);
   Result.End = CreatePosition(EndLoc);
 
   return std::move(Result);
@@ -309,26 +306,26 @@
   if (!ND)
 return true;
 
+  llvm::SmallString<128> USR;
+  if (index::generateUSRForDecl(ND, USR))
+return true;
+  SymbolID ID(USR);
+
   // Mark D as referenced if 

[PATCH] D49028: [clangd] Support indexing MACROs.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 154413.
ioeric added a comment.

- Some cleanup.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49028

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -992,6 +992,32 @@
Field(::Origin, SymbolOrigin::Static)));
 }
 
+TEST_F(SymbolCollectorTest, CollectMacros) {
+  CollectorOpts.CollectIncludePath = true;
+  Annotations Header(R"(
+#define X 1
+#define $mac[[MAC]](x) int x
+#define $used[[USED]](y) float y;
+
+MAC(p);
+  )");
+  const std::string Main = R"(
+#define MAIN 1  // not indexed
+USED(t);
+  )";
+  CollectorOpts.CountReferences = true;
+  CollectorOpts.CollectMacro = true;
+  runSymbolCollector(Header.code(), Main);
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  QName("p"),
+  AllOf(QName("X"), DeclURI(TestHeaderURI),
+IncludeHeader(TestHeaderURI)),
+  AllOf(Labeled("MAC(x)"), Refs(0), DeclRange(Header.range("mac"))),
+  AllOf(Labeled("USED(y)"), Refs(1), DeclRange(Header.range("used");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -50,10 +50,12 @@
 /// If set, this is used to map symbol #include path to a potentially
 /// different #include path.
 const CanonicalIncludes *Includes = nullptr;
-// Populate the Symbol.References field.
+/// Populate the Symbol.References field.
 bool CountReferences = false;
 // Every symbol collected will be stamped with this origin.
 SymbolOrigin Origin = SymbolOrigin::Unknown;
+/// Collect macros.
+bool CollectMacro = false;
   };
 
   SymbolCollector(Options Opts);
@@ -75,6 +77,10 @@
   SourceLocation Loc,
   index::IndexDataConsumer::ASTNodeInfo ASTNode) override;
 
+  bool handleMacroOccurence(const IdentifierInfo , const MacroInfo ,
+index::SymbolRoleSet Roles,
+SourceLocation Loc) override;
+
   SymbolSlab takeSymbols() { return std::move(Symbols).build(); }
 
   void finish() override;
@@ -90,8 +96,8 @@
   std::shared_ptr CompletionAllocator;
   std::unique_ptr CompletionTUInfo;
   Options Opts;
-  // Decls referenced from the current TU, flushed on finish().
-  llvm::DenseSet ReferencedDecls;
+  // Macros referenced from the current TU, flushed on finish().
+  llvm::DenseSet ReferencedSymbols;
   // Maps canonical declaration provided by clang to canonical declaration for
   // an index symbol, if clangd prefers a different declaration than that
   // provided by clang. For example, friend declaration might be considered
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -183,22 +183,19 @@
   return toURI(SM, Header, Opts);
 }
 
-// Return the symbol location of the given declaration `D`.
-//
-// For symbols defined inside macros:
-//   * use expansion location, if the symbol is formed via macro concatenation.
-//   * use spelling location, otherwise.
-llvm::Optional getSymbolLocation(
-const NamedDecl , SourceManager , const SymbolCollector::Options ,
-const clang::LangOptions , std::string ) {
-  SourceLocation NameLoc = findNameLoc();
-  auto U = toURI(SM, SM.getFilename(NameLoc), Opts);
+// Return the symbol location of the token at \p Loc.
+llvm::Optional
+getTokenLocation(SourceLocation TokLoc, const SourceManager ,
+ const SymbolCollector::Options ,
+ const clang::LangOptions ,
+ std::string ) {
+  auto U = toURI(SM, SM.getFilename(TokLoc), Opts);
   if (!U)
 return llvm::None;
   FileURIStorage = std::move(*U);
   SymbolLocation Result;
   Result.FileURI = FileURIStorage;
-  auto TokenLength = clang::Lexer::MeasureTokenLength(NameLoc, SM, LangOpts);
+  auto TokenLength = clang::Lexer::MeasureTokenLength(TokLoc, SM, LangOpts);
 
   auto CreatePosition = [](SourceLocation Loc) {
 auto LSPLoc = sourceLocToPosition(SM, Loc);
@@ -208,8 +205,8 @@
 return Pos;
   };
 
-  Result.Start = CreatePosition(NameLoc);
-  auto EndLoc = NameLoc.getLocWithOffset(TokenLength);
+  Result.Start = CreatePosition(TokLoc);
+  auto EndLoc = TokLoc.getLocWithOffset(TokenLength);
   Result.End = CreatePosition(EndLoc);
 
   return std::move(Result);
@@ -309,26 +306,26 @@
   if (!ND)
 return true;
 
+  llvm::SmallString<128> USR;
+  if (index::generateUSRForDecl(ND, USR))
+return true;
+  

[PATCH] D49028: [clangd] Support indexing MACROs.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.
ioeric added a reviewer: sammccall.
Herald added subscribers: cfe-commits, jkorous, MaskRay, ilya-biryukov.

This is not enabled in the global-symbol-builder or dynamic index yet.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49028

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

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -992,6 +992,32 @@
Field(::Origin, SymbolOrigin::Static)));
 }
 
+TEST_F(SymbolCollectorTest, CollectMacros) {
+  CollectorOpts.CollectIncludePath = true;
+  Annotations Header(R"(
+#define X 1
+#define $mac[[MAC]](x) int x
+#define $used[[USED]](y) float y;
+
+MAC(p);
+  )");
+  const std::string Main = R"(
+#define MAIN 1  // not indexed
+USED(t);
+  )";
+  CollectorOpts.CountReferences = true;
+  CollectorOpts.CollectMacro = true;
+  runSymbolCollector(Header.code(), Main);
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  QName("p"),
+  AllOf(QName("X"), DeclURI(TestHeaderURI),
+IncludeHeader(TestHeaderURI)),
+  AllOf(Labeled("MAC(x)"), Refs(0), DeclRange(Header.range("mac"))),
+  AllOf(Labeled("USED(y)"), Refs(1), DeclRange(Header.range("used");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -50,10 +50,12 @@
 /// If set, this is used to map symbol #include path to a potentially
 /// different #include path.
 const CanonicalIncludes *Includes = nullptr;
-// Populate the Symbol.References field.
+/// Populate the Symbol.References field.
 bool CountReferences = false;
 // Every symbol collected will be stamped with this origin.
 SymbolOrigin Origin = SymbolOrigin::Unknown;
+/// Collect macros.
+bool CollectMacro = false;
   };
 
   SymbolCollector(Options Opts);
@@ -75,6 +77,10 @@
   SourceLocation Loc,
   index::IndexDataConsumer::ASTNodeInfo ASTNode) override;
 
+  bool handleMacroOccurence(const IdentifierInfo , const MacroInfo ,
+index::SymbolRoleSet Roles,
+SourceLocation Loc) override;
+
   SymbolSlab takeSymbols() { return std::move(Symbols).build(); }
 
   void finish() override;
@@ -92,6 +98,8 @@
   Options Opts;
   // Decls referenced from the current TU, flushed on finish().
   llvm::DenseSet ReferencedDecls;
+  // Macros referenced from the current TU, flushed on finish().
+  llvm::DenseSet ReferencedMacros;
   // Maps canonical declaration provided by clang to canonical declaration for
   // an index symbol, if clangd prefers a different declaration than that
   // provided by clang. For example, friend declaration might be considered
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -183,15 +183,13 @@
   return toURI(SM, Header, Opts);
 }
 
-// Return the symbol location of the given declaration `D`.
-//
-// For symbols defined inside macros:
-//   * use expansion location, if the symbol is formed via macro concatenation.
-//   * use spelling location, otherwise.
-llvm::Optional getSymbolLocation(
-const NamedDecl , SourceManager , const SymbolCollector::Options ,
-const clang::LangOptions , std::string ) {
-  SourceLocation NameLoc = findNameLoc();
+// Return the symbol location of the declaration at \p Loc. The range covers the
+// token.
+llvm::Optional
+getSymbolLocation(SourceLocation NameLoc, const SourceManager ,
+  const SymbolCollector::Options ,
+  const clang::LangOptions ,
+  std::string ) {
   auto U = toURI(SM, SM.getFilename(NameLoc), Opts);
   if (!U)
 return llvm::None;
@@ -346,17 +344,94 @@
 }
 
 void SymbolCollector::finish() {
-  // At the end of the TU, add 1 to the refcount of the ReferencedDecls.
+  // At the end of the TU, add 1 to the refcount of all referenced symbols.
+  auto IncRef = [this](const SymbolID ) {
+if (const auto *S = Symbols.find(ID)) {
+  Symbol Inc = *S;
+  ++Inc.References;
+  Symbols.insert(Inc);
+}
+  };
   for (const auto *ND : ReferencedDecls) {
 llvm::SmallString<128> USR;
 if (!index::generateUSRForDecl(ND, USR))
-  if (const auto *S = Symbols.find(SymbolID(USR))) {
-Symbol Inc = *S;
-++Inc.References;
-Symbols.insert(Inc);
-  }
+  IncRef(SymbolID(USR));
   }
+  for (const auto  : ReferencedMacros)
+IncRef(ID);
   

[PATCH] D49008: [clangd] Upgrade logging facilities with levels and formatv.

2018-07-06 Thread Simon Marchi via Phabricator via cfe-commits
simark added a comment.

In https://reviews.llvm.org/D49008#1154196, @sammccall wrote:

> @simark - is it OK if I pick this up?


Yes, totally fine.  I didn't have time to follow up on my patch, and I think 
you did a great job here.  I tested it, and I see that my main pain point was 
addressed.  With the patch, clangd is more quiet by default, only outputting 
errors, so I'm happy :).


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49008



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


[PATCH] D49008: [clangd] Upgrade logging facilities with levels and formatv.

2018-07-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 154402.
sammccall added a comment.

rebase


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49008

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdServer.cpp
  clangd/ClangdUnit.cpp
  clangd/CodeComplete.cpp
  clangd/Compiler.cpp
  clangd/Diagnostics.cpp
  clangd/FileDistance.cpp
  clangd/FindSymbols.cpp
  clangd/GlobalCompilationDatabase.cpp
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/Logger.cpp
  clangd/Logger.h
  clangd/Protocol.cpp
  clangd/ProtocolHandlers.cpp
  clangd/SourceCode.cpp
  clangd/TUScheduler.cpp
  clangd/XRefs.cpp
  clangd/index/SymbolCollector.cpp
  clangd/tool/ClangdMain.cpp

Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -98,6 +98,14 @@
 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
 llvm::cl::init(false));
 
+static llvm::cl::opt LogLevel(
+"log", llvm::cl::desc("Verbosity of log messages written to stderr"),
+llvm::cl::values(clEnumValN(Logger::Error, "error", "Error messages only"),
+ clEnumValN(Logger::Info, "info",
+"High level execution tracing"),
+ clEnumValN(Logger::Debug, "verbose", "Low level details")),
+llvm::cl::init(Logger::Info));
+
 static llvm::cl::opt Test(
 "lit-test",
 llvm::cl::desc(
@@ -223,7 +231,7 @@
   if (Tracer)
 TracingSession.emplace(*Tracer);
 
-  JSONOutput Out(llvm::outs(), llvm::errs(),
+  JSONOutput Out(llvm::outs(), llvm::errs(), LogLevel,
  InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
  PrettyPrint);
 
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -52,7 +52,7 @@
   if (std::error_code EC =
   SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
   AbsolutePath))
-log("Warning: could not make absolute file: " + EC.message());
+log("Warning: could not make absolute file: {0}", EC.message());
   if (llvm::sys::path::is_absolute(AbsolutePath)) {
 // Handle the symbolic link path case where the current working directory
 // (getCurrentWorkingDirectory) is a symlink./ We always want to the real
@@ -86,8 +86,7 @@
   return U->toString();
 ErrMsg += llvm::toString(U.takeError()) + "\n";
   }
-  log(llvm::Twine("Failed to create an URI for file ") + AbsolutePath + ": " +
-  ErrMsg);
+  log("Failed to create an URI for file {0}: {1}", AbsolutePath, ErrMsg);
   return llvm::None;
 }
 
Index: clangd/XRefs.cpp
===
--- clangd/XRefs.cpp
+++ clangd/XRefs.cpp
@@ -46,12 +46,12 @@
 return llvm::None;
   auto Uri = URI::parse(Loc.FileURI);
   if (!Uri) {
-log("Could not parse URI: " + Loc.FileURI);
+log("Could not parse URI: {0}", Loc.FileURI);
 return llvm::None;
   }
   auto Path = URI::resolve(*Uri, HintPath);
   if (!Path) {
-log("Could not resolve URI: " + Loc.FileURI);
+log("Could not resolve URI: {0}", Loc.FileURI);
 return llvm::None;
   }
   Location LSPLoc;
Index: clangd/TUScheduler.cpp
===
--- clangd/TUScheduler.cpp
+++ clangd/TUScheduler.cpp
@@ -321,14 +321,14 @@
 // Remove the old AST if it's still in cache.
 IdleASTs.take(this);
 
-log("Updating file " + FileName + " with command [" +
-Inputs.CompileCommand.Directory + "] " +
+log("Updating file {0} with command [{1}] {2}", FileName,
+Inputs.CompileCommand.Directory,
 llvm::join(Inputs.CompileCommand.CommandLine, " "));
 // Rebuild the preamble and the AST.
 std::unique_ptr Invocation =
 buildCompilerInvocation(Inputs);
 if (!Invocation) {
-  log("Could not build CompilerInvocation for file " + FileName);
+  elog("Could not build CompilerInvocation for file {0}", FileName);
   return;
 }
 
@@ -611,8 +611,8 @@
 void TUScheduler::remove(PathRef File) {
   bool Removed = Files.erase(File);
   if (!Removed)
-log("Trying to remove file from TUScheduler that is not tracked. File:" +
-File);
+elog("Trying to remove file from TUScheduler that is not tracked: {0}",
+ File);
 }
 
 void TUScheduler::runWithAST(
Index: clangd/SourceCode.cpp
===
--- clangd/SourceCode.cpp
+++ clangd/SourceCode.cpp
@@ -192,7 +192,7 @@
 FilePath = F->getName();
   if (!llvm::sys::path::is_absolute(FilePath)) {
 if (!SourceMgr.getFileManager().makeAbsolutePath(FilePath)) {
-  log("Could not turn relative path to absolute: " + FilePath);
+  log("Could not turn relative path to absolute: {0}", FilePath);
   return llvm::None;
 }
   

[PATCH] D48325: [analyzer][UninitializedObjectChecker] Support for MemberPointerTypes

2018-07-06 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus updated this revision to Diff 154398.
Szelethus added a comment.

MemberPointerTypes are regarded as primitive types from now. I agree with @NoQ, 
it makes so much more sense this way :)


https://reviews.llvm.org/D48325

Files:
  lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
  test/Analysis/cxx-uninitialized-object-ptr-ref.cpp

Index: test/Analysis/cxx-uninitialized-object-ptr-ref.cpp
===
--- test/Analysis/cxx-uninitialized-object-ptr-ref.cpp
+++ test/Analysis/cxx-uninitialized-object-ptr-ref.cpp
@@ -416,14 +416,12 @@
 
 #ifdef PEDANTIC
 struct PointerToMemberFunctionTest1 {
-  // TODO: we'd expect the note {{uninitialized field 'this->f'}}
-  void (UsefulFunctions::*f)(void); // no-note
+  void (UsefulFunctions::*f)(void); // expected-note{{uninitialized field 'this->f'}}
   PointerToMemberFunctionTest1() {}
 };
 
 void fPointerToMemberFunctionTest1() {
-  // TODO: we'd expect the warning {{1 uninitialized field}}
-  PointerToMemberFunctionTest1(); // no-warning
+  PointerToMemberFunctionTest1(); // expected-warning{{1 uninitialized field}}
 }
 
 struct PointerToMemberFunctionTest2 {
@@ -460,14 +458,12 @@
 }
 
 struct PointerToMemberDataTest1 {
-  // TODO: we'd expect the note {{uninitialized field 'this->f'}}
-  int UsefulFunctions::*d; // no-note
+  int UsefulFunctions::*d; // expected-note{{uninitialized field 'this->d'}}
   PointerToMemberDataTest1() {}
 };
 
 void fPointerToMemberDataTest1() {
-  // TODO: we'd expect the warning {{1 uninitialized field}}
-  PointerToMemberDataTest1(); // no-warning
+  PointerToMemberDataTest1(); // expected-warning{{1 uninitialized field}}
 }
 
 struct PointerToMemberDataTest2 {
Index: lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
+++ lib/StaticAnalyzer/Checkers/UninitializedObjectChecker.cpp
@@ -133,12 +133,10 @@
   // - a non-union record
   // - a pointer/reference
   // - an array
-  // - of a member pointer type
-  // - of a primitive type, which we'll define as either a BuiltinType or
-  //   EnumeralType.
+  // - of a primitive type, which we'll define later in a helper function.
   //   * the parent of each node is the object that contains it
-  //   * every leaf is an array, a primitive object, a member pointer, a nullptr
-  // or an undefined pointer.
+  //   * every leaf is an array, a primitive object, a nullptr or an undefined
+  //   pointer.
   //
   // Example:
   //
@@ -165,8 +163,8 @@
   //
   // From this we'll construct a vector of fieldchains, where each fieldchain
   // represents an uninitialized field. An uninitialized field may be a
-  // primitive object, a member pointer, a pointer, a pointee or a union without
-  // a single initialized field.
+  // primitive object, a pointer, a pointee or a union without a single
+  // initialized field.
   // In the above example, for the default constructor call we'll end up with
   // these fieldchains:
   //
@@ -191,10 +189,6 @@
   bool isPointerOrReferenceUninit(const FieldRegion *FR,
   FieldChainInfo LocalChain);
 
-  /// This method checks a region of MemberPointerType, and returns true if the
-  /// the pointer is uninitialized.
-  bool isMemberPointerUninit(const FieldRegion *FR, FieldChainInfo LocalChain);
-
   /// This method returns true if the value of a primitive object is
   /// uninitialized.
   bool isPrimitiveUninit(const SVal );
@@ -221,10 +215,13 @@
 /// known, and thus FD can not be analyzed.
 bool isVoidPointer(const FieldDecl *FD);
 
-/// Returns true if T is a primitive type. We'll call a type primitive if it's
-/// either a BuiltinType or an EnumeralType.
+/// Returns true if T is a primitive type. We defined this type so that for
+/// objects that we'd only like analyze as much as checking whether their
+/// value is undefined or not, such as ints and doubles, can be analyzed with
+/// ease. This also helps ensuring that every special field type is handled
+/// correctly.
 bool isPrimitiveType(const QualType ) {
-  return T->isBuiltinType() || T->isEnumeralType();
+  return T->isBuiltinType() || T->isEnumeralType() || T->isMemberPointerType();
 }
 
 /// Constructs a note message for a given FieldChainInfo object.
@@ -389,13 +386,6 @@
   continue;
 }
 
-if (T->isMemberPointerType()) {
-  if (isMemberPointerUninit(FR, LocalChain))
-ContainsUninitField = true;
-  continue;
-}
-
-// If this is a pointer or reference type.
 if (T->isPointerType() || T->isReferenceType()) {
   if (isPointerOrReferenceUninit(FR, LocalChain))
 ContainsUninitField = true;
@@ -539,14 +529,6 @@
   return false;
 }
 
-bool FindUninitializedFields::isMemberPointerUninit(const FieldRegion *FR,
-FieldChainInfo 

[PATCH] D49008: [clangd] Upgrade logging facilities with levels and formatv.

2018-07-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

still LGTM.

The diff contains unrelated changes now.




Comment at: clangd/tool/ClangdMain.cpp:104
+llvm::cl::values(clEnumVal(Logger::Error, "Error messages only"),
+ clEnumVal(Logger::Info, "High level execution tracing"),
+ clEnumVal(Logger::Debug, "Low level details")),

sammccall wrote:
> hokein wrote:
> > Is it intended not to expose `Verbose` mode?
> dlog is already controlled by -debug/-debug-only flag, so it seems it doesn't 
> need a distinct level here too. WDYT?
> 
> Renamed flag value to "verbose".
Yeah, vlog is controlled by debug flag.  A flag "verbose" is more natural than 
`debug`.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49008



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


[PATCH] D48903: [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name

2018-07-06 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.
Herald added a subscriber: omtcyfz.

The code looks good. I'll let Ben take a final look.




Comment at: lib/Basic/VirtualFileSystem.cpp:485
+  /// \p Status::Name in the return value, to mimic the behavior of \p 
RealFile.
+  Status getStatus(std::string RequestedName) const {
+return Status::copyWithNewName(Stat, RequestedName);

Can we use llvm::StringRef here?



Comment at: unittests/Basic/VirtualFileSystemTest.cpp:950
+  clang::vfs::directory_iterator It = NormalizedFS.dir_begin("../b", EC);
+  clang::vfs::directory_iterator End;
+

This is not used.


Repository:
  rC Clang

https://reviews.llvm.org/D48903



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


[PATCH] D49008: [clangd] Upgrade logging facilities with levels and formatv.

2018-07-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clangd/tool/ClangdMain.cpp:104
+llvm::cl::values(clEnumVal(Logger::Error, "Error messages only"),
+ clEnumVal(Logger::Info, "High level execution tracing"),
+ clEnumVal(Logger::Debug, "Low level details")),

hokein wrote:
> Is it intended not to expose `Verbose` mode?
dlog is already controlled by -debug/-debug-only flag, so it seems it doesn't 
need a distinct level here too. WDYT?

Renamed flag value to "verbose".


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49008



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


[PATCH] D49008: [clangd] Upgrade logging facilities with levels and formatv.

2018-07-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 154391.
sammccall added a comment.
Herald added a subscriber: mgorny.

Name debug->verbose


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49008

Files:
  clang-tidy/cert/CERTTidyModule.cpp
  clang-tidy/cert/CMakeLists.txt
  clang-tidy/cert/ProperlySeededRandomGeneratorCheck.cpp
  clang-tidy/cert/ProperlySeededRandomGeneratorCheck.h
  clang-tidy/misc/UnusedParametersCheck.cpp
  clangd/ClangdLSPServer.cpp
  clangd/ClangdServer.cpp
  clangd/ClangdUnit.cpp
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/Compiler.cpp
  clangd/Diagnostics.cpp
  clangd/FileDistance.cpp
  clangd/FindSymbols.cpp
  clangd/GlobalCompilationDatabase.cpp
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/Logger.cpp
  clangd/Logger.h
  clangd/Protocol.cpp
  clangd/ProtocolHandlers.cpp
  clangd/Quality.cpp
  clangd/TUScheduler.cpp
  clangd/XRefs.cpp
  clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
  clangd/index/FileIndex.cpp
  clangd/index/Index.cpp
  clangd/index/Index.h
  clangd/index/Merge.cpp
  clangd/index/SymbolCollector.cpp
  clangd/index/SymbolCollector.h
  clangd/tool/ClangdMain.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cert-msc32-c.rst
  docs/clang-tidy/checks/cert-msc51-cpp.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/cert-msc32-c.c
  test/clang-tidy/cert-msc51-cpp.cpp
  test/clang-tidy/misc-unused-parameters.cpp
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/IndexTests.cpp
  unittests/clangd/QualityTests.cpp
  unittests/clangd/SymbolCollectorTests.cpp
  unittests/clangd/TestTU.cpp
  unittests/clangd/TestTU.h

Index: unittests/clangd/TestTU.h
===
--- unittests/clangd/TestTU.h
+++ unittests/clangd/TestTU.h
@@ -56,6 +56,9 @@
 const Symbol (const SymbolSlab &, llvm::StringRef QName);
 // Look up an AST symbol by qualified name, which must be unique and top-level.
 const NamedDecl (ParsedAST , llvm::StringRef QName);
+// Look up a main-file AST symbol that satisfies \p Filter.
+const NamedDecl (ParsedAST ,
+ std::function Filter);
 // Look up a main-file AST symbol by unqualified name, which must be unique.
 const NamedDecl (ParsedAST , llvm::StringRef Name);
 
Index: unittests/clangd/TestTU.cpp
===
--- unittests/clangd/TestTU.cpp
+++ unittests/clangd/TestTU.cpp
@@ -93,26 +93,35 @@
   return LookupDecl(*Scope, Components.back());
 }
 
-const NamedDecl (ParsedAST , llvm::StringRef Name) {
+const NamedDecl (ParsedAST ,
+ std::function Callback) {
   struct Visitor : RecursiveASTVisitor {
-llvm::StringRef Name;
+decltype(Callback) CB;
 llvm::SmallVector Decls;
 bool VisitNamedDecl(const NamedDecl *ND) {
-  if (auto *ID = ND->getIdentifier())
-if (ID->getName() == Name)
-  Decls.push_back(ND);
+  if (CB(*ND))
+Decls.push_back(ND);
   return true;
 }
   } Visitor;
-  Visitor.Name = Name;
+  Visitor.CB = Callback;
   for (Decl *D : AST.getLocalTopLevelDecls())
 Visitor.TraverseDecl(D);
   if (Visitor.Decls.size() != 1) {
-ADD_FAILURE() << Visitor.Decls.size() << " symbols named " << Name;
+ADD_FAILURE() << Visitor.Decls.size() << " symbols matched.";
 assert(Visitor.Decls.size() == 1);
   }
   return *Visitor.Decls.front();
 }
 
+const NamedDecl (ParsedAST , llvm::StringRef Name) {
+  return findAnyDecl(AST, [Name](const NamedDecl ) {
+if (auto *ID = ND.getIdentifier())
+  if (ID->getName() == Name)
+return true;
+return false;
+  });
+}
+
 } // namespace clangd
 } // namespace clang
Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -985,6 +985,13 @@
 AllOf(QName("Y"), Refs(1;
 }
 
+TEST_F(SymbolCollectorTest, Origin) {
+  CollectorOpts.Origin = SymbolOrigin::Static;
+  runSymbolCollector("class Foo {};", /*Main=*/"");
+  EXPECT_THAT(Symbols, UnorderedElementsAre(
+   Field(::Origin, SymbolOrigin::Static)));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: unittests/clangd/QualityTests.cpp
===
--- unittests/clangd/QualityTests.cpp
+++ unittests/clangd/QualityTests.cpp
@@ -21,6 +21,9 @@
 #include "Quality.h"
 #include "TestFS.h"
 #include "TestTU.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
+#include "llvm/Support/Casting.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -199,6 +202,31 @@
   EXPECT_LT(sortText(0, "a"), sortText(0, "z"));
 }
 
+TEST(QualityTests, NoBoostForClassConstructor) {
+  auto Header = TestTU::withHeaderCode(R"cpp(
+class Foo {
+public:
+  Foo(int);
+

[PATCH] D48436: [analyzer][UninitializedObjectChecker] Fixed a false negative by no longer filtering out certain constructor calls

2018-07-06 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus added a comment.

Polite ping ^-^


https://reviews.llvm.org/D48436



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


[PATCH] D49008: [clangd] Upgrade logging facilities with levels and formatv.

2018-07-06 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.

Nice, look good.




Comment at: clangd/tool/ClangdMain.cpp:104
+llvm::cl::values(clEnumVal(Logger::Error, "Error messages only"),
+ clEnumVal(Logger::Info, "High level execution tracing"),
+ clEnumVal(Logger::Debug, "Low level details")),

Is it intended not to expose `Verbose` mode?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49008



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


[PATCH] D48961: [Index] Add indexing support for MACROs.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 154390.
ioeric added a comment.

- removed Undefined parameter.


Repository:
  rC Clang

https://reviews.llvm.org/D48961

Files:
  include/clang/Index/IndexDataConsumer.h
  include/clang/Index/IndexSymbol.h
  include/clang/Index/IndexingAction.h
  lib/Index/IndexSymbol.cpp
  lib/Index/IndexingAction.cpp
  lib/Index/IndexingContext.cpp
  lib/Index/IndexingContext.h
  test/Index/Core/index-macros.c
  tools/c-index-test/core_main.cpp

Index: tools/c-index-test/core_main.cpp
===
--- tools/c-index-test/core_main.cpp
+++ tools/c-index-test/core_main.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 
+#include "clang/Basic/LangOptions.h"
 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
@@ -16,6 +17,7 @@
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/USRGeneration.h"
 #include "clang/Index/CodegenNameGenerator.h"
+#include "clang/Lex/Preprocessor.h"
 #include "clang/Serialization/ASTReader.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Signals.h"
@@ -77,6 +79,7 @@
 class PrintIndexDataConsumer : public IndexDataConsumer {
   raw_ostream 
   std::unique_ptr CGNameGen;
+  std::shared_ptr PP;
 
 public:
   PrintIndexDataConsumer(raw_ostream ) : OS(OS) {
@@ -86,6 +89,10 @@
 CGNameGen.reset(new CodegenNameGenerator(Ctx));
   }
 
+  void setPreprocessor(std::shared_ptr PP) override {
+this->PP = std::move(PP);
+  }
+
   bool handleDeclOccurence(const Decl *D, SymbolRoleSet Roles,
ArrayRef Relations,
SourceLocation Loc, ASTNodeInfo ASTNode) override {
@@ -145,6 +152,37 @@
 
 return true;
   }
+
+  bool handleMacroOccurence(const IdentifierInfo , const MacroInfo ,
+SymbolRoleSet Roles, SourceLocation Loc) override {
+assert(PP);
+SourceManager  = PP->getSourceManager();
+
+Loc = SM.getFileLoc(Loc);
+FileID FID = SM.getFileID(Loc);
+unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
+unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
+OS << Line << ':' << Col << " | ";
+
+printSymbolInfo(getSymbolInfoForMacro(MI), OS);
+OS << " | ";
+
+OS << Name.getName();
+OS << " | ";
+
+SmallString<256> USRBuf;
+if (generateUSRForMacro(Name.getName(), MI.getDefinitionLoc(), SM,
+USRBuf)) {
+  OS << "";
+} else {
+  OS << USRBuf;
+}
+OS << " | ";
+
+printSymbolRoles(Roles, OS);
+OS << " |\n";
+return true;
+  }
 };
 
 } // anonymous namespace
Index: test/Index/Core/index-macros.c
===
--- /dev/null
+++ test/Index/Core/index-macros.c
@@ -0,0 +1,12 @@
+// RUN: c-index-test core -print-source-symbols -- %s | FileCheck %s
+
+// CHECK: [[@LINE+1]]:9 | macro/C | X1 | c:index-macros.c@157@macro@X1 | Def |
+#define X1 1
+// CHECK: [[@LINE+1]]:9 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Def |
+#define DEF(x) int x
+// CHECK: [[@LINE+1]]:8 | macro/C | X1 | c:index-macros.c@157@macro@X1 | Undef |
+#undef X1
+
+// CHECK: [[@LINE+2]]:1 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Ref |
+// CHECK: [[@LINE+1]]:5 | variable/C | i | c:@i | i | Def | rel: 0
+DEF(i);
Index: lib/Index/IndexingContext.h
===
--- lib/Index/IndexingContext.h
+++ lib/Index/IndexingContext.h
@@ -10,9 +10,11 @@
 #ifndef LLVM_CLANG_LIB_INDEX_INDEXINGCONTEXT_H
 #define LLVM_CLANG_LIB_INDEX_INDEXINGCONTEXT_H
 
+#include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Index/IndexingAction.h"
+#include "clang/Lex/MacroInfo.h"
 #include "llvm/ADT/ArrayRef.h"
 
 namespace clang {
@@ -80,6 +82,15 @@
const Expr *RefE = nullptr,
const Decl *RefD = nullptr);
 
+  void handleMacroDefined(const IdentifierInfo , SourceLocation Loc,
+  const MacroInfo );
+
+  void handleMacroUndefined(const IdentifierInfo , SourceLocation Loc,
+const MacroInfo );
+
+  void handleMacroReference(const IdentifierInfo , SourceLocation Loc,
+const MacroInfo );
+
   bool importedModule(const ImportDecl *ImportD);
 
   bool indexDecl(const Decl *D);
Index: lib/Index/IndexingContext.cpp
===
--- lib/Index/IndexingContext.cpp
+++ lib/Index/IndexingContext.cpp
@@ -8,6 +8,7 @@
 //===--===//
 
 #include "IndexingContext.h"
+#include "clang/Basic/SourceLocation.h"
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/AST/ASTContext.h"
 

[PATCH] D48412: [RISCV] Add support for interrupt attribute

2018-07-06 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: test/Sema/riscv-interrupt-attr.c:23
+  // expected-note 
{{repeated RISC-V 'interrupt' attribute is here}}
+__attribute__((interrupt("user"))) void foo8() {}
+__attribute__((interrupt("supervisor"))) void foo9() {}

apazos wrote:
> aaron.ballman wrote:
> > apazos wrote:
> > > aaron.ballman wrote:
> > > > apazos wrote:
> > > > > aaron.ballman wrote:
> > > > > > aaron.ballman wrote:
> > > > > > > Do you intend for functions without a prototype to be accepted? 
> > > > > > > foo8() can be passed an arbitrary number of arguments, which is a 
> > > > > > > bit different than what I thought you wanted the semantic check 
> > > > > > > to be.
> > > > > > This question remains outstanding.
> > > > > The checks are validating both function definitions and function 
> > > > > prototypes like these:
> > > > > _attribute__((interrupt)) void foo1() {} 
> > > > > __attribute__((interrupt)) void foo(void);
> > > > > Not sure what the confusion is.
> > > > Ah, now I see where the confusion is.
> > > > 
> > > > In C, an empty parameter list declares a function without a prototype; 
> > > > functions without prototypes can accept any number of arguments. To 
> > > > declare a function that accepts no arguments, you must have a prototype 
> > > > for the function and the parameter list is void. In C++, all functions 
> > > > are prototyped and an empty parameter list is equivalent to a parameter 
> > > > list of void. The word "prototype" doesn't mean "forward declaration". 
> > > > e.g.,
> > > > ```
> > > > // C code
> > > > void foo1(); // Declaration; no prototype; accepts any number of 
> > > > arguments.
> > > > void foo2() {} // Definition; no prototype; accepts any number of 
> > > > arguments.
> > > > void foo3(void); // Declaration; prototype; accepts no arguments.
> > > > void foo4(void) {} // Definition; prototype; accepts no arguments.
> > > > 
> > > > foo2(1, 2, 3); // ok
> > > > foo4(1, 2, 3); // error
> > > > ```
> > > > Because a function without a prototype can accept any number of 
> > > > arguments, I think you want to diagnose such a function signature.
> > > Thanks for clarifying. 
> > > 
> > > I checked GCC behavior and it is less strict. For the example below, it 
> > > silently accepts the interrupt attribute.
> > > 
> > > extern int foo2();
> > > __attribute__((interrupt)) void foo();
> > > void foo() {
> > >   foo2();
> > > }
> > > 
> > > while in LLVM we would be rejecting with the message: 
> > > RISC-V 'interrupt' attribute only applies to functions that have no 
> > > parameters. 
> > > 
> > > I find the reuse of the message confusing. 
> > > 
> > > If we want stricter rule then we probably also need a specific message 
> > > for the  missing prototype.
> > > 
> > > I checked GCC behavior and it is less strict. For the example below, it 
> > > silently accepts the interrupt attribute.
> > 
> > Does it drop the attribute?
> > 
> > > If we want stricter rule then we probably also need a specific message 
> > > for the missing prototype.
> > 
> > If GCC silently drops the attribute in this case then we definitely want a 
> > more strict rule. We already have a good diagnostic for this: 
> > `warn_attribute_wrong_decl_type` with the expected type diagnostic index 
> > being `ExpectedFunctionWithProtoType`.
> It does not drop, it compiles without warnings and it produces the code that 
> is expected when interrupt attribute is set.
Oh! In that case, it's perfectly reasonable for us to support the construct as 
well. I'm really sorry for the churn this back-and-forth has caused. I just 
wanted to make sure that the runtime behavior matches GCC and that we diagnose 
any circumstance under which we're dropping the attribute.

I like the most of the state of this test file where it uses `(void)` as the 
parameter list for most of the functions, so how about we keep those changes? 
I'd leave `foo4()` without the prototype and just remove the diagnostic I asked 
you to introduce in the last patch.


https://reviews.llvm.org/D48412



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


[clang-tools-extra] r336431 - [clangd] Make SymbolOrigin an enum class, rather than a plain enum.

2018-07-06 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Fri Jul  6 04:50:49 2018
New Revision: 336431

URL: http://llvm.org/viewvc/llvm-project?rev=336431=rev
Log:
[clangd] Make SymbolOrigin an enum class, rather than a plain enum.

I never intended to define namespace pollution like clangd::AST, clangd::Unknown
etc. Oops!

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

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=336431=336430=336431=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Fri Jul  6 04:50:49 2018
@@ -268,8 +268,7 @@ struct CodeCompletionBuilder {
   : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments) {
 add(C, SemaCCS);
 if (C.SemaResult) {
-  Completion.Origin =
-  static_cast(Completion.Origin | SymbolOrigin::AST);
+  Completion.Origin |= SymbolOrigin::AST;
   Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
   if (Completion.Scope.empty())
 if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
@@ -281,8 +280,7 @@ struct CodeCompletionBuilder {
   toCompletionItemKind(C.SemaResult->Kind, C.SemaResult->Declaration);
 }
 if (C.IndexResult) {
-  Completion.Origin =
-  static_cast(Completion.Origin | C.IndexResult->Origin);
+  Completion.Origin |= C.IndexResult->Origin;
   if (Completion.Scope.empty())
 Completion.Scope = C.IndexResult->Scope;
   if (Completion.Kind == CompletionItemKind::Missing)
@@ -1156,17 +1154,18 @@ private:
 else
   return;
 SymbolOrigin Origin = SymbolOrigin::Unknown;
+bool FromIndex = false;
 for (const auto  : Bundle) {
   if (Candidate.IndexResult) {
 Quality.merge(*Candidate.IndexResult);
 Relevance.merge(*Candidate.IndexResult);
-Origin =
-static_cast(Origin | Candidate.IndexResult->Origin);
+Origin |= Candidate.IndexResult->Origin;
+FromIndex = true;
   }
   if (Candidate.SemaResult) {
 Quality.merge(*Candidate.SemaResult);
 Relevance.merge(*Candidate.SemaResult);
-Origin = static_cast(Origin | SymbolOrigin::AST);
+Origin |= SymbolOrigin::AST;
   }
 }
 
@@ -1184,8 +1183,8 @@ private:
 << Quality << Relevance << "\n");
 
 NSema += bool(Origin & SymbolOrigin::AST);
-NIndex += bool(Origin & ~SymbolOrigin::AST);
-NBoth += (Origin & SymbolOrigin::AST) && (Origin & ~SymbolOrigin::AST);
+NIndex += FromIndex;
+NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
 if (Candidates.push({std::move(Bundle), Scores}))
   Incomplete = true;
   }

Modified: clang-tools-extra/trunk/clangd/index/Index.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.cpp?rev=336431=336430=336431=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Index.cpp Fri Jul  6 04:50:49 2018
@@ -49,7 +49,7 @@ raw_ostream <<(raw_ostream ,
 return OS << "unknown";
   constexpr static char Sigils[] = "ADSM4567";
   for (unsigned I = 0; I < sizeof(Sigils); ++I)
-if (O & static_cast(1 << I))
+if (static_cast(O) & 1u << I)
   OS << Sigils[I];
   return OS;
 }

Modified: clang-tools-extra/trunk/clangd/index/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.h?rev=336431=336430=336431=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.h (original)
+++ clang-tools-extra/trunk/clangd/index/Index.h Fri Jul  6 04:50:49 2018
@@ -120,7 +120,7 @@ namespace clangd {
 // Describes the source of information about a symbol.
 // Mainly useful for debugging, e.g. understanding code completion reuslts.
 // This is a bitfield as information can be combined from several sources.
-enum SymbolOrigin : uint8_t {
+enum class SymbolOrigin : uint8_t {
   Unknown = 0,
   AST = 1 << 0, // Directly from the AST (indexes should not set this).
   Dynamic = 1 << 1, // From the dynamic index of opened files.
@@ -128,6 +128,17 @@ enum SymbolOrigin : uint8_t {
   Merge = 1 << 3,   // A non-trivial index merge was performed.
   // Remaining bits reserved for index implementations.
 };
+inline SymbolOrigin operator|(SymbolOrigin A, SymbolOrigin B) {
+  return static_cast(static_cast(A) |
+   static_cast(B));
+}
+inline SymbolOrigin |=(SymbolOrigin , SymbolOrigin 

[PATCH] D48961: [Index] Add indexing support for MACROs.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 154388.
ioeric marked 6 inline comments as done.
ioeric added a comment.

- addressed review comments.


Repository:
  rC Clang

https://reviews.llvm.org/D48961

Files:
  include/clang/Index/IndexDataConsumer.h
  include/clang/Index/IndexSymbol.h
  include/clang/Index/IndexingAction.h
  lib/Index/IndexSymbol.cpp
  lib/Index/IndexingAction.cpp
  lib/Index/IndexingContext.cpp
  lib/Index/IndexingContext.h
  lib/Sema/SemaCodeComplete.cpp
  test/Index/Core/index-macros.c
  tools/c-index-test/core_main.cpp
  unittests/Sema/CodeCompleteTest.cpp

Index: unittests/Sema/CodeCompleteTest.cpp
===
--- unittests/Sema/CodeCompleteTest.cpp
+++ unittests/Sema/CodeCompleteTest.cpp
@@ -131,4 +131,15 @@
   EXPECT_TRUE(VisitedNS.empty());
 }
 
+TEST(SemaCodeCompleteTest, VisitedNSWithoutQualifier) {
+  auto VisitedNS = runCodeCompleteOnCode(R"cpp(
+namespace n1 {
+namespace n2 {
+  void f(^) {}
+}
+}
+  )cpp");
+  EXPECT_THAT(VisitedNS, UnorderedElementsAre("n1", "n1::n2"));
+}
+
 } // namespace
Index: tools/c-index-test/core_main.cpp
===
--- tools/c-index-test/core_main.cpp
+++ tools/c-index-test/core_main.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 
+#include "clang/Basic/LangOptions.h"
 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
@@ -16,6 +17,7 @@
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/USRGeneration.h"
 #include "clang/Index/CodegenNameGenerator.h"
+#include "clang/Lex/Preprocessor.h"
 #include "clang/Serialization/ASTReader.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Signals.h"
@@ -77,6 +79,7 @@
 class PrintIndexDataConsumer : public IndexDataConsumer {
   raw_ostream 
   std::unique_ptr CGNameGen;
+  std::shared_ptr PP;
 
 public:
   PrintIndexDataConsumer(raw_ostream ) : OS(OS) {
@@ -86,6 +89,10 @@
 CGNameGen.reset(new CodegenNameGenerator(Ctx));
   }
 
+  void setPreprocessor(std::shared_ptr PP) override {
+this->PP = std::move(PP);
+  }
+
   bool handleDeclOccurence(const Decl *D, SymbolRoleSet Roles,
ArrayRef Relations,
SourceLocation Loc, ASTNodeInfo ASTNode) override {
@@ -145,6 +152,42 @@
 
 return true;
   }
+
+  bool handleMacroOccurence(const IdentifierInfo , const MacroInfo ,
+SymbolRoleSet Roles, SourceLocation Loc,
+bool Undefined) override {
+assert(PP);
+SourceManager  = PP->getSourceManager();
+
+Loc = SM.getFileLoc(Loc);
+FileID FID = SM.getFileID(Loc);
+unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
+unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
+OS << Line << ':' << Col << " | ";
+
+printSymbolInfo(getSymbolInfoForMacro(MI), OS);
+OS << " | ";
+
+OS << Name.getName();
+OS << " | ";
+
+SmallString<256> USRBuf;
+if (generateUSRForMacro(Name.getName(), MI.getDefinitionLoc(), SM,
+USRBuf)) {
+  OS << "";
+} else {
+  OS << USRBuf;
+}
+
+OS << " | ";
+
+if (Undefined)
+  OS << "(undefined)";
+else
+  printSymbolRoles(Roles, OS);
+OS << " |\n";
+return true;
+  }
 };
 
 } // anonymous namespace
Index: test/Index/Core/index-macros.c
===
--- /dev/null
+++ test/Index/Core/index-macros.c
@@ -0,0 +1,12 @@
+// RUN: c-index-test core -print-source-symbols -- %s | FileCheck %s
+
+// CHECK: [[@LINE+1]]:9 | macro/C | X1 | c:index-macros.c@157@macro@X1 | Def |
+#define X1 1
+// CHECK: [[@LINE+1]]:9 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Def |
+#define DEF(x) int x
+// CHECK: [[@LINE+1]]:8 | macro/C | X1 | c:index-macros.c@157@macro@X1 | (undefined) |
+#undef X1
+
+// CHECK: [[@LINE+2]]:1 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Ref |
+// CHECK: [[@LINE+1]]:5 | variable/C | i | c:@i | i | Def | rel: 0
+DEF(i);
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -3700,9 +3700,11 @@
 /// type we're looking for.
 void Sema::CodeCompleteExpression(Scope *S, 
   const CodeCompleteExpressionData ) {
-  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
-CodeCompleter->getCodeCompletionTUInfo(),
-CodeCompletionContext::CCC_Expression);
+  ResultBuilder Results(
+  *this, CodeCompleter->getAllocator(),
+  CodeCompleter->getCodeCompletionTUInfo(),
+  CodeCompletionContext(CodeCompletionContext::CCC_Expression,
+

[PATCH] D48961: [Index] Add indexing support for MACROs.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: include/clang/Index/IndexDataConsumer.h:48
   /// \returns true to continue indexing, or false to abort.
-  virtual bool handleMacroOccurence(const IdentifierInfo *Name,
-const MacroInfo *MI, SymbolRoleSet Roles,
-SourceLocation Loc);
+  /// \p Undefined is set when the occurrence is in an #undef directive where
+  /// the macro undefined.

sammccall wrote:
> Ah, now I understand :-)
> 
> This doesn't seem like another orthogonal bool parameter, it seems more like 
> a SymbolRole (we have Definition there, logically Undefinition seems like it 
> should be there too, even if it only applies to some symbols).
> 
> It looks like it would be safe to insert this as bit 9, and move all the 
> others down by 1 bit? Only the libclang API needs to be stable, and that ends 
> at bit 8.
Sounds good. Done.



Comment at: include/clang/Index/IndexingAction.h:66
+
+/// Recursively indexes all top-level decls in the module. Note that this does
+/// not index macros.

sammccall wrote:
> are you sure it doesn't index macros? is this a bug? maybe this should be 
> FIXME instead of a note
It looks like so from the current implementation:
```
  for (const Decl *D : Reader.getModuleFileLevelDecls(Mod)) {
IndexCtx.indexTopLevelDecl(D);
  }
```

Changed to `FIXME`.



Comment at: lib/Index/IndexSymbol.cpp:357
+  Info.Properties = SymbolPropertySet();
+  // FIXME: set languages more accurately.
+  Info.Lang = SymbolLanguage::C;

sammccall wrote:
> I'm not sure what the intent of this comment is - what's the behavior you 
> *want* here?
> One principled option is to introduce a new SymbolLanguage for the 
> preprocessor (it's reasonable to consider this a separate language).
> Another is to always consider macros C symbol, but then this shouldn't be a 
> fixme.
> I'm not sure what the intent of this comment is - what's the behavior you 
> *want* here?
I'm not really sure what I want... On one hand, it's possible to get the actual 
language from `LangOptions` of the compiler instance; on the other hand, the 
index library doesn't seem to care about `LangOptions` for decls (maybe 
intentionally?), and I'm a bit hesitant to fix them.
> Another is to always consider macros C symbol, but then this shouldn't be a 
> fixme.
Sounds good. This aligns with the current behavior of the library. Removed 
FIXME.




Comment at: lib/Index/IndexingAction.cpp:52
   std::shared_ptr PP;
-  IndexingContext 
+  std::shared_ptr IndexCtx;
 

sammccall wrote:
> making these shared_ptr everywhere feels a bit like giving up :-)
> Can't we keep this one and IndexPPCallbacks as references?
It's unclear how exactly `IndexingContext` should be used :( In the current 
design, the context is owned by `IndexActionBase` and referenced/shared by AST 
consumer and PPCallbacks for the IndexAction use case. The new 
`indexMacroCallbacks` function would also need to create a context that needs 
to be owned by PPCallbacks. Ideally, the ASTConsumer and PPCallbacks can own 
their own context, but it's unclear whether this would fit into the design of 
IndexingContext. So `shared_ptr` seems to be reasonable given the current 
design.


Repository:
  rC Clang

https://reviews.llvm.org/D48961



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


[PATCH] D49012: [clangd] Uprank delcarations when "using q::name" is present in the main file

2018-07-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/Quality.cpp:48
+  if (R.ShadowDecl) {
+const auto Loc = SourceMgr.getSpellingLoc(R.ShadowDecl->getLocation());
+if (SourceMgr.isWrittenInMainFile(Loc))

ioeric wrote:
> I think we might want to use `getExpansionLoc` here. Consider `DEFINE_string` 
> which is implemented like:
> ```
> #define DEFINE_string(XXX) \
> namespace FLs { \
> SomeType FLAGS_XXX; \
> } \
> using FLs::FLAGS_XXX;
> ```
> When you have `DEFINE_string(X) in the main file, the spelling location will 
> be in the file where the macro is defined, while the expansion location will 
> be in the main file, and I think we would want later.
> 
If you're not motivated to add the test now, I doubt anyone ever will be, so 
just remove the FIXME.



Comment at: clang-tools-extra/unittests/clangd/QualityTests.cpp:116
   EXPECT_FLOAT_EQ(Relevance.SemaProximityScore, 1.0f)
-  << "Current file and header";
+  << "Current file and definition in header";
+

(this still says "definition", which doesn't seem true/relevant)



Comment at: clang-tools-extra/unittests/clangd/QualityTests.cpp:119
+  Relevance = {};
+  const auto SymbolName = "Bar";
+  const auto *Shadow =

nit: inline this?
(or if you really want to name it, give a more specific name)


https://reviews.llvm.org/D49012



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


[PATCH] D48931: [Driver,AArch64] Add support for -mcpu=native.

2018-07-06 Thread Florian Hahn via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC336429: [Driver,AArch64] Add support for -mcpu=native. 
(authored by fhahn, committed by ).
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D48931

Files:
  lib/Driver/ToolChains/Arch/AArch64.cpp
  test/Driver/aarch64-cpus.c


Index: lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- lib/Driver/ToolChains/Arch/AArch64.cpp
+++ lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -69,6 +69,9 @@
   std::pair Split = Mcpu.split("+");
   CPU = Split.first;
 
+  if (CPU == "native")
+CPU = llvm::sys::getHostCPUName();
+
   if (CPU == "generic") {
 Features.push_back("+neon");
   } else {
Index: test/Driver/aarch64-cpus.c
===
--- test/Driver/aarch64-cpus.c
+++ test/Driver/aarch64-cpus.c
@@ -15,6 +15,11 @@
 
 // ARM64-GENERIC: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "generic"
 
+// We cannot check much for -mcpu=native, but it should be replaced by either 
generic or a valid
+// Arm cpu string, depending on the host.
+// RUN: %clang -target arm64 -mcpu=native -### -c %s 2>&1 | FileCheck 
-check-prefix=ARM64-NATIVE %s
+// ARM64-NATIVE-NOT: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" 
"native"
+
 // RUN: %clang -target arm64-apple-darwin -arch arm64 -### -c %s 2>&1 | 
FileCheck -check-prefix=ARM64-DARWIN %s
 // ARM64-DARWIN: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "cyclone"
 


Index: lib/Driver/ToolChains/Arch/AArch64.cpp
===
--- lib/Driver/ToolChains/Arch/AArch64.cpp
+++ lib/Driver/ToolChains/Arch/AArch64.cpp
@@ -69,6 +69,9 @@
   std::pair Split = Mcpu.split("+");
   CPU = Split.first;
 
+  if (CPU == "native")
+CPU = llvm::sys::getHostCPUName();
+
   if (CPU == "generic") {
 Features.push_back("+neon");
   } else {
Index: test/Driver/aarch64-cpus.c
===
--- test/Driver/aarch64-cpus.c
+++ test/Driver/aarch64-cpus.c
@@ -15,6 +15,11 @@
 
 // ARM64-GENERIC: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "generic"
 
+// We cannot check much for -mcpu=native, but it should be replaced by either generic or a valid
+// Arm cpu string, depending on the host.
+// RUN: %clang -target arm64 -mcpu=native -### -c %s 2>&1 | FileCheck -check-prefix=ARM64-NATIVE %s
+// ARM64-NATIVE-NOT: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "native"
+
 // RUN: %clang -target arm64-apple-darwin -arch arm64 -### -c %s 2>&1 | FileCheck -check-prefix=ARM64-DARWIN %s
 // ARM64-DARWIN: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "cyclone"
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r336429 - [Driver,AArch64] Add support for -mcpu=native.

2018-07-06 Thread Florian Hahn via cfe-commits
Author: fhahn
Date: Fri Jul  6 03:49:59 2018
New Revision: 336429

URL: http://llvm.org/viewvc/llvm-project?rev=336429=rev
Log:
[Driver,AArch64] Add support for -mcpu=native.

This patches adds support for passing -mcpu=native for AArch64. It will
get turned into the host CPU name, before we get the target features.

CPU = native is handled in a similar fashion in
getAArch64MicroArchFetauresFromMtune and getAArch64TargetCPU already.

Having a good test case for this is hard, as it depends on the host CPU
of the machine running the test. But we can check that native has been
replaced with something else.

When cross-compiling, we will get a CPU name from the host architecture
and get ` the clang compiler does not support '-mcpu=native'` as error
message, which seems reasonable to me.

Reviewers: rengolin, peter.smith, dlj, javed.absar, t.p.northover

Reviewed By: peter.smith

Tags: #clang

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

Modified:
cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp
cfe/trunk/test/Driver/aarch64-cpus.c

Modified: cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp?rev=336429=336428=336429=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp Fri Jul  6 03:49:59 2018
@@ -69,6 +69,9 @@ static bool DecodeAArch64Mcpu(const Driv
   std::pair Split = Mcpu.split("+");
   CPU = Split.first;
 
+  if (CPU == "native")
+CPU = llvm::sys::getHostCPUName();
+
   if (CPU == "generic") {
 Features.push_back("+neon");
   } else {

Modified: cfe/trunk/test/Driver/aarch64-cpus.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/aarch64-cpus.c?rev=336429=336428=336429=diff
==
--- cfe/trunk/test/Driver/aarch64-cpus.c (original)
+++ cfe/trunk/test/Driver/aarch64-cpus.c Fri Jul  6 03:49:59 2018
@@ -15,6 +15,11 @@
 
 // ARM64-GENERIC: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "generic"
 
+// We cannot check much for -mcpu=native, but it should be replaced by either 
generic or a valid
+// Arm cpu string, depending on the host.
+// RUN: %clang -target arm64 -mcpu=native -### -c %s 2>&1 | FileCheck 
-check-prefix=ARM64-NATIVE %s
+// ARM64-NATIVE-NOT: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" 
"native"
+
 // RUN: %clang -target arm64-apple-darwin -arch arm64 -### -c %s 2>&1 | 
FileCheck -check-prefix=ARM64-DARWIN %s
 // ARM64-DARWIN: "-cc1"{{.*}} "-triple" "arm64{{.*}}" "-target-cpu" "cyclone"
 


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


[PATCH] D49012: [clangd] Uprank delcarations when "using q::name" is present in the main file

2018-07-06 Thread Kirill Bobyrev via Phabricator via cfe-commits
omtcyfz updated this revision to Diff 154383.
omtcyfz marked 10 inline comments as done.
omtcyfz added a comment.

Address the comments, add a couple of FIXMEs for the future.


https://reviews.llvm.org/D49012

Files:
  clang-tools-extra/clangd/Quality.cpp
  clang-tools-extra/unittests/clangd/QualityTests.cpp
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/lib/Sema/SemaCodeComplete.cpp

Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -859,12 +859,12 @@
   }
 
   // Look through using declarations.
-  if (const UsingShadowDecl *Using =
-  dyn_cast(R.Declaration)) {
-MaybeAddResult(Result(Using->getTargetDecl(),
-  getBasePriority(Using->getTargetDecl()),
-  R.Qualifier),
-   CurContext);
+  if (const UsingShadowDecl *Using = dyn_cast(R.Declaration)) {
+CodeCompletionResult Result(Using->getTargetDecl(),
+getBasePriority(Using->getTargetDecl()),
+R.Qualifier);
+Result.ShadowDecl = Using;
+MaybeAddResult(Result, CurContext);
 return;
   }
 
@@ -977,10 +977,11 @@
 
   // Look through using declarations.
   if (const UsingShadowDecl *Using = dyn_cast(R.Declaration)) {
-AddResult(Result(Using->getTargetDecl(),
- getBasePriority(Using->getTargetDecl()),
- R.Qualifier),
-  CurContext, Hiding);
+CodeCompletionResult Result(Using->getTargetDecl(),
+getBasePriority(Using->getTargetDecl()),
+R.Qualifier);
+Result.ShadowDecl = Using;
+AddResult(Result, CurContext, Hiding);
 return;
   }
 
@@ -1004,10 +1005,10 @@
   if (AsNestedNameSpecifier) {
 R.StartsNestedNameSpecifier = true;
 R.Priority = CCP_NestedNameSpecifier;
-  }
-  else if (Filter == ::IsMember && !R.Qualifier && InBaseClass &&
-   isa(R.Declaration->getDeclContext()
-  ->getRedeclContext()))
+  } else if (Filter == ::IsMember && !R.Qualifier &&
+ InBaseClass &&
+ isa(
+ R.Declaration->getDeclContext()->getRedeclContext()))
 R.QualifierIsInformative = true;
 
   // If this result is supposed to have an informative qualifier, add one.
Index: clang/include/clang/Sema/CodeCompleteConsumer.h
===
--- clang/include/clang/Sema/CodeCompleteConsumer.h
+++ clang/include/clang/Sema/CodeCompleteConsumer.h
@@ -45,8 +45,9 @@
 class NamedDecl;
 class NestedNameSpecifier;
 class Preprocessor;
-class Sema;
 class RawComment;
+class Sema;
+class UsingShadowDecl;
 
 /// Default priority values for code-completion results based
 /// on their kind.
@@ -836,6 +837,12 @@
   /// informative rather than required.
   NestedNameSpecifier *Qualifier = nullptr;
 
+  /// If this Decl was unshadowed by using declaration, this can store a
+  /// pointer to the UsingShadowDecl which was used in the unshadowing process.
+  /// This information can be used to uprank CodeCompletionResults / which have
+  /// corresponding `using decl::qualified::name;` nearby.
+  const UsingShadowDecl *ShadowDecl = nullptr;
+
   /// Build a result that refers to a declaration.
   CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority,
NestedNameSpecifier *Qualifier = nullptr,
@@ -847,7 +854,7 @@
 QualifierIsInformative(QualifierIsInformative),
 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
 DeclaringEntity(false), Qualifier(Qualifier) {
-//FIXME: Add assert to check FixIts range requirements.
+// FIXME: Add assert to check FixIts range requirements.
 computeCursorKindAndAvailability(Accessible);
   }
 
Index: clang-tools-extra/unittests/clangd/QualityTests.cpp
===
--- clang-tools-extra/unittests/clangd/QualityTests.cpp
+++ clang-tools-extra/unittests/clangd/QualityTests.cpp
@@ -79,8 +79,12 @@
   Test.HeaderCode = R"cpp(
 int header();
 int header_main();
+
+namespace hdr { class Bar {}; } // namespace hdr
 )cpp";
   Test.Code = R"cpp(
+using hdr::Bar;
+
 int ::header_main() {}
 int main();
 
@@ -109,7 +113,26 @@
   Relevance = {};
   Relevance.merge(CodeCompletionResult((AST, "header_main"), 42));
   EXPECT_FLOAT_EQ(Relevance.SemaProximityScore, 1.0f)
-  << "Current file and header";
+  << "Current file and definition in header";
+
+  Relevance = {};
+  const auto SymbolName = "Bar";
+  const auto *Shadow =
+  *dyn_cast(
+   (AST,
+[&](const NamedDecl ) -> bool {
+  if (const UsingDecl *Using = dyn_cast())
+if 

[PATCH] D49008: [clangd] Upgrade logging facilities with levels and formatv.

2018-07-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This borrows from https://reviews.llvm.org/D44226 (log levels) which got 
stalled for various reasons (@simark - is it OK if I pick this up?).
It doesn't actually split the LSP messages vs LSP message names into different 
levels, but that's a simple followup.

Switching to formatv seems like a nice ergonomic win while we're breaking 
interfaces.
It also in principle allows loggers to extract the format string and args 
separately (formatv doesn't yet provide APIs for this, but architecturally it's 
easy) which can help log analysis.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49008



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


[PATCH] D49012: [clangd] Uprank delcarations when "using q::name" is present in the main file

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

Nice!

Just one caveat regarding locations in addition to Sam's comments :)




Comment at: clang-tools-extra/clangd/Quality.cpp:48
+  if (R.ShadowDecl) {
+const auto Loc = SourceMgr.getSpellingLoc(R.ShadowDecl->getLocation());
+if (SourceMgr.isWrittenInMainFile(Loc))

I think we might want to use `getExpansionLoc` here. Consider `DEFINE_string` 
which is implemented like:
```
#define DEFINE_string(XXX) \
namespace FLs { \
SomeType FLAGS_XXX; \
} \
using FLs::FLAGS_XXX;
```
When you have `DEFINE_string(X) in the main file, the spelling location will be 
in the file where the macro is defined, while the expansion location will be in 
the main file, and I think we would want later.



https://reviews.llvm.org/D49012



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


[PATCH] D49012: [clangd] Uprank delcarations when "using q::name" is present in the main file

2018-07-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Nice! Mostly just a few nits.




Comment at: clang-tools-extra/unittests/clangd/QualityTests.cpp:83
+
+namespace foo {
+class Bar {};

nit: can we have slightly more descriptive names here as this is a long test?
e.g. `namespace hdr { class Used; }`
(I think if you forward-declare the class, clang-format will let you have it on 
one line)



Comment at: clang-tools-extra/unittests/clangd/QualityTests.cpp:88
+namespace bar {
+class Foo {};
+} // namespace bar

this bar::Foo proximity test doesn't seem to be substantially different from 
header(), could you drop it to reduce noise?(



Comment at: clang-tools-extra/unittests/clangd/QualityTests.cpp:122
   EXPECT_FLOAT_EQ(Relevance.SemaProximityScore, 1.0f)
-  << "Current file and header";
+  << "Current file and definition in header";
+

definition is not relevant here, AFAICS, revert this comment?
(and in fact this is defined in the main file, not the header)



Comment at: clang-tools-extra/unittests/clangd/QualityTests.cpp:128
+  UsingShadowDecl *Shadow;
+  auto findUsingDecl = [, ,
+](const NamedDecl ) -> bool {

nit: spelling out the captures and types here adds a lot of noise to the test 
and doesn't seem to gain much in return. What about inlining this, capturing 
`[&]`, and letting the return type be implicit?



Comment at: clang-tools-extra/unittests/clangd/QualityTests.cpp:131
+if (const UsingDecl *Using = dyn_cast()) {
+  if (UsingShadowDecl *ShadowDecl = *Using->shadow_begin()) {
+if (ShadowDecl->getTargetDecl()->getName() == SymbolName) {

doesn't this crash if there are no shadows?



Comment at: clang-tools-extra/unittests/clangd/QualityTests.cpp:133
+if (ShadowDecl->getTargetDecl()->getName() == SymbolName) {
+  Shadow = ShadowDecl;
+  FoundDecl = Shadow->getTargetDecl();

`findAnyDecl` is designed to return the decl you find, idiomatically the filter 
shouldn't have side effects.

What about:
```
auto *Shadow = *findAnyDecl(AST, [&](const NamedDecl& ND) {
  if (... Using = ...)
return Using->getQualifiedNameAsString() == "Bar" && Using->shadow_size();
  return false;
}).shadow_begin();
CodeCompletionResult Result(Shadow->getTargetDecl());
Result.setShadowDecl(Shadow);
```



Comment at: clang-tools-extra/unittests/clangd/QualityTests.cpp:146
+  EXPECT_FLOAT_EQ(Relevance.SemaProximityScore, 1.0f)
+  << "Uprank declaration which has using directive in current directory";
+

nit: "current directory" isn't relevant here, rather "main file"?
nit: "uprank" isn't quite right here - ranking/scoring is a concern of 
extraction, rather evaluate(). Prefer just describing the situation ("Using 
declaration in main file")
nit: these are using declarations, not using directives



Comment at: clang/include/clang/Sema/CodeCompleteConsumer.h:852
+   std::vector FixIts = 
std::vector(),
+   const UsingShadowDecl *ShadowDecl = nullptr)
   : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration),

we don't need both the constructor and the setter/public field - I think the 
constructor param is actually unused. Drop?



Comment at: clang/include/clang/Sema/CodeCompleteConsumer.h:911
 
+  void setShadowDecl(const UsingShadowDecl *Shadow) {
+this->ShadowDecl = Shadow;

the field is already public, no need to add a setter


https://reviews.llvm.org/D49012



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


[PATCH] D48973: [SemaCodeComplete] Expose a method to create CodeCompletionString for macros.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC336427: [SemaCodeComplete] Expose a method to create 
CodeCompletionString for macros. (authored by ioeric, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D48973?vs=154370=154380#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48973

Files:
  include/clang/Sema/CodeCompleteConsumer.h
  lib/Sema/SemaCodeComplete.cpp

Index: include/clang/Sema/CodeCompleteConsumer.h
===
--- include/clang/Sema/CodeCompleteConsumer.h
+++ include/clang/Sema/CodeCompleteConsumer.h
@@ -918,6 +918,13 @@
CodeCompletionAllocator ,
CodeCompletionTUInfo ,
bool IncludeBriefComments);
+  /// Creates a new code-completion string for the macro result. Similar to the
+  /// above overloads, except this only requires preprocessor information.
+  /// The result kind must be `RK_Macro`.
+  CodeCompletionString *
+  CreateCodeCompletionStringForMacro(Preprocessor ,
+ CodeCompletionAllocator ,
+ CodeCompletionTUInfo );
 
   /// Retrieve the name that should be used to order a result.
   ///
Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2745,6 +2745,52 @@
 CCTUInfo, IncludeBriefComments);
 }
 
+CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
+Preprocessor , CodeCompletionAllocator ,
+CodeCompletionTUInfo ) {
+  assert(Kind == RK_Macro);
+  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
+  const MacroInfo *MI = PP.getMacroInfo(Macro);
+  Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
+
+  if (!MI || !MI->isFunctionLike())
+return Result.TakeString();
+
+  // Format a function-like macro with placeholders for the arguments.
+  Result.AddChunk(CodeCompletionString::CK_LeftParen);
+  MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
+
+  // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
+  if (MI->isC99Varargs()) {
+--AEnd;
+
+if (A == AEnd) {
+  Result.AddPlaceholderChunk("...");
+}
+  }
+
+  for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
+if (A != MI->param_begin())
+  Result.AddChunk(CodeCompletionString::CK_Comma);
+
+if (MI->isVariadic() && (A + 1) == AEnd) {
+  SmallString<32> Arg = (*A)->getName();
+  if (MI->isC99Varargs())
+Arg += ", ...";
+  else
+Arg += "...";
+  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
+  break;
+}
+
+// Non-variadic macros are simple.
+Result.AddPlaceholderChunk(
+Result.getAllocator().CopyString((*A)->getName()));
+  }
+  Result.AddChunk(CodeCompletionString::CK_RightParen);
+  return Result.TakeString();
+}
+
 /// If possible, create a new code completion string for the given
 /// result.
 ///
@@ -2758,6 +2804,9 @@
CodeCompletionAllocator ,
CodeCompletionTUInfo ,
bool IncludeBriefComments) {
+  if (Kind == RK_Macro)
+return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
+
   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
 
   PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
@@ -2782,50 +2831,6 @@
 Result.AddTypedTextChunk(Keyword);
 return Result.TakeString();
   }
-
-  if (Kind == RK_Macro) {
-const MacroInfo *MI = PP.getMacroInfo(Macro);
-Result.AddTypedTextChunk(
-Result.getAllocator().CopyString(Macro->getName()));
-
-if (!MI || !MI->isFunctionLike())
-  return Result.TakeString();
-
-// Format a function-like macro with placeholders for the arguments.
-Result.AddChunk(CodeCompletionString::CK_LeftParen);
-MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
-
-// C99 variadic macros add __VA_ARGS__ at the end. Skip it.
-if (MI->isC99Varargs()) {
-  --AEnd;
-
-  if (A == AEnd) {
-Result.AddPlaceholderChunk("...");
-  }
-}
-
-for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
-  if (A != MI->param_begin())
-Result.AddChunk(CodeCompletionString::CK_Comma);
-
-  if (MI->isVariadic() && (A+1) == AEnd) {
-SmallString<32> Arg = (*A)->getName();
-if (MI->isC99Varargs())
-  Arg += ", ...";
-else
-  Arg += "...";
-Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
-break;
-  }
-
-  // 

r336427 - [SemaCodeComplete] Expose a method to create CodeCompletionString for macros.

2018-07-06 Thread Eric Liu via cfe-commits
Author: ioeric
Date: Fri Jul  6 02:43:57 2018
New Revision: 336427

URL: http://llvm.org/viewvc/llvm-project?rev=336427=rev
Log:
[SemaCodeComplete] Expose a method to create CodeCompletionString for macros.

Summary:
The method only takes PPreprocessor and don't require structures that
might not be available (e.g. Sema and ASTContext) when CodeCompletionString
needs to be generated for macros.

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: cfe-commits

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

Modified:
cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
cfe/trunk/lib/Sema/SemaCodeComplete.cpp

Modified: cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h?rev=336427=336426=336427=diff
==
--- cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h (original)
+++ cfe/trunk/include/clang/Sema/CodeCompleteConsumer.h Fri Jul  6 02:43:57 2018
@@ -918,6 +918,13 @@ public:
CodeCompletionAllocator ,
CodeCompletionTUInfo ,
bool IncludeBriefComments);
+  /// Creates a new code-completion string for the macro result. Similar to the
+  /// above overloads, except this only requires preprocessor information.
+  /// The result kind must be `RK_Macro`.
+  CodeCompletionString *
+  CreateCodeCompletionStringForMacro(Preprocessor ,
+ CodeCompletionAllocator ,
+ CodeCompletionTUInfo );
 
   /// Retrieve the name that should be used to order a result.
   ///

Modified: cfe/trunk/lib/Sema/SemaCodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaCodeComplete.cpp?rev=336427=336426=336427=diff
==
--- cfe/trunk/lib/Sema/SemaCodeComplete.cpp (original)
+++ cfe/trunk/lib/Sema/SemaCodeComplete.cpp Fri Jul  6 02:43:57 2018
@@ -2745,6 +2745,52 @@ CodeCompletionString *CodeCompletionResu
 CCTUInfo, IncludeBriefComments);
 }
 
+CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
+Preprocessor , CodeCompletionAllocator ,
+CodeCompletionTUInfo ) {
+  assert(Kind == RK_Macro);
+  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
+  const MacroInfo *MI = PP.getMacroInfo(Macro);
+  Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
+
+  if (!MI || !MI->isFunctionLike())
+return Result.TakeString();
+
+  // Format a function-like macro with placeholders for the arguments.
+  Result.AddChunk(CodeCompletionString::CK_LeftParen);
+  MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
+
+  // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
+  if (MI->isC99Varargs()) {
+--AEnd;
+
+if (A == AEnd) {
+  Result.AddPlaceholderChunk("...");
+}
+  }
+
+  for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
+if (A != MI->param_begin())
+  Result.AddChunk(CodeCompletionString::CK_Comma);
+
+if (MI->isVariadic() && (A + 1) == AEnd) {
+  SmallString<32> Arg = (*A)->getName();
+  if (MI->isC99Varargs())
+Arg += ", ...";
+  else
+Arg += "...";
+  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
+  break;
+}
+
+// Non-variadic macros are simple.
+Result.AddPlaceholderChunk(
+Result.getAllocator().CopyString((*A)->getName()));
+  }
+  Result.AddChunk(CodeCompletionString::CK_RightParen);
+  return Result.TakeString();
+}
+
 /// If possible, create a new code completion string for the given
 /// result.
 ///
@@ -2758,6 +2804,9 @@ CodeCompletionResult::CreateCodeCompleti
CodeCompletionAllocator ,
CodeCompletionTUInfo ,
bool IncludeBriefComments) {
+  if (Kind == RK_Macro)
+return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
+
   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
 
   PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
@@ -2782,50 +2831,6 @@ CodeCompletionResult::CreateCodeCompleti
 Result.AddTypedTextChunk(Keyword);
 return Result.TakeString();
   }
-
-  if (Kind == RK_Macro) {
-const MacroInfo *MI = PP.getMacroInfo(Macro);
-Result.AddTypedTextChunk(
-
Result.getAllocator().CopyString(Macro->getName()));
-
-if (!MI || !MI->isFunctionLike())
-  return Result.TakeString();
-
-// Format a function-like macro with placeholders for the arguments.
-Result.AddChunk(CodeCompletionString::CK_LeftParen);
-MacroInfo::param_iterator A = 

[PATCH] D49012: [clangd] Uprank delcarations when "using q::name" is present in the main file

2018-07-06 Thread Kirill Bobyrev via Phabricator via cfe-commits
omtcyfz updated this revision to Diff 154379.
omtcyfz added a comment.

Add const qualifier to UsingShadowDecl in unit tests.


https://reviews.llvm.org/D49012

Files:
  clang-tools-extra/clangd/Quality.cpp
  clang-tools-extra/unittests/clangd/QualityTests.cpp
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/lib/Sema/SemaCodeComplete.cpp

Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -859,12 +859,12 @@
   }
 
   // Look through using declarations.
-  if (const UsingShadowDecl *Using =
-  dyn_cast(R.Declaration)) {
-MaybeAddResult(Result(Using->getTargetDecl(),
-  getBasePriority(Using->getTargetDecl()),
-  R.Qualifier),
-   CurContext);
+  if (const UsingShadowDecl *Using = dyn_cast(R.Declaration)) {
+CodeCompletionResult Result(Using->getTargetDecl(),
+getBasePriority(Using->getTargetDecl()),
+R.Qualifier);
+Result.setShadowDecl(Using);
+MaybeAddResult(Result, CurContext);
 return;
   }
 
@@ -977,10 +977,11 @@
 
   // Look through using declarations.
   if (const UsingShadowDecl *Using = dyn_cast(R.Declaration)) {
-AddResult(Result(Using->getTargetDecl(),
- getBasePriority(Using->getTargetDecl()),
- R.Qualifier),
-  CurContext, Hiding);
+CodeCompletionResult Result(Using->getTargetDecl(),
+getBasePriority(Using->getTargetDecl()),
+R.Qualifier);
+Result.setShadowDecl(Using);
+AddResult(Result, CurContext, Hiding);
 return;
   }
 
@@ -1004,10 +1005,10 @@
   if (AsNestedNameSpecifier) {
 R.StartsNestedNameSpecifier = true;
 R.Priority = CCP_NestedNameSpecifier;
-  }
-  else if (Filter == ::IsMember && !R.Qualifier && InBaseClass &&
-   isa(R.Declaration->getDeclContext()
-  ->getRedeclContext()))
+  } else if (Filter == ::IsMember && !R.Qualifier &&
+ InBaseClass &&
+ isa(
+ R.Declaration->getDeclContext()->getRedeclContext()))
 R.QualifierIsInformative = true;
 
   // If this result is supposed to have an informative qualifier, add one.
Index: clang/include/clang/Sema/CodeCompleteConsumer.h
===
--- clang/include/clang/Sema/CodeCompleteConsumer.h
+++ clang/include/clang/Sema/CodeCompleteConsumer.h
@@ -45,8 +45,9 @@
 class NamedDecl;
 class NestedNameSpecifier;
 class Preprocessor;
-class Sema;
 class RawComment;
+class Sema;
+class UsingShadowDecl;
 
 /// Default priority values for code-completion results based
 /// on their kind.
@@ -836,18 +837,25 @@
   /// informative rather than required.
   NestedNameSpecifier *Qualifier = nullptr;
 
+  /// If this Decl was unshadowed by using declaration, this would would store
+  /// a pointer to the UsingShadowDecl which was used in the unshadowing
+  /// process. This information can be used to uprank CodeCompletionResults
+  /// which have corresponding `using decl::qualified::name;` nearby.
+  const UsingShadowDecl *ShadowDecl = nullptr;
+
   /// Build a result that refers to a declaration.
   CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority,
NestedNameSpecifier *Qualifier = nullptr,
bool QualifierIsInformative = false,
bool Accessible = true,
-   std::vector FixIts = std::vector())
+   std::vector FixIts = std::vector(),
+   const UsingShadowDecl *ShadowDecl = nullptr)
   : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration),
 FixIts(std::move(FixIts)), Hidden(false),
 QualifierIsInformative(QualifierIsInformative),
 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
-DeclaringEntity(false), Qualifier(Qualifier) {
-//FIXME: Add assert to check FixIts range requirements.
+DeclaringEntity(false), Qualifier(Qualifier), ShadowDecl(ShadowDecl) {
+// FIXME: Add assert to check FixIts range requirements.
 computeCursorKindAndAvailability(Accessible);
   }
 
@@ -900,6 +908,10 @@
 return Keyword;
   }
 
+  void setShadowDecl(const UsingShadowDecl *Shadow) {
+this->ShadowDecl = Shadow;
+  }
+
   /// Create a new code-completion string that describes how to insert
   /// this result into a program.
   ///
Index: clang-tools-extra/unittests/clangd/QualityTests.cpp
===
--- clang-tools-extra/unittests/clangd/QualityTests.cpp
+++ clang-tools-extra/unittests/clangd/QualityTests.cpp
@@ -79,8 +79,18 @@
   Test.HeaderCode = R"cpp(
 int header();
 int 

[PATCH] D49012: [clangd] Uprank delcarations when "using q::name" is present in the main file

2018-07-06 Thread Kirill Bobyrev via Phabricator via cfe-commits
omtcyfz updated this revision to Diff 154377.
omtcyfz added a comment.

Remove comments from TestTU.cpp, both functions are properly documented in the 
corresponding header.


https://reviews.llvm.org/D49012

Files:
  clang-tools-extra/clangd/Quality.cpp
  clang-tools-extra/unittests/clangd/QualityTests.cpp
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/lib/Sema/SemaCodeComplete.cpp

Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -859,12 +859,12 @@
   }
 
   // Look through using declarations.
-  if (const UsingShadowDecl *Using =
-  dyn_cast(R.Declaration)) {
-MaybeAddResult(Result(Using->getTargetDecl(),
-  getBasePriority(Using->getTargetDecl()),
-  R.Qualifier),
-   CurContext);
+  if (const UsingShadowDecl *Using = dyn_cast(R.Declaration)) {
+CodeCompletionResult Result(Using->getTargetDecl(),
+getBasePriority(Using->getTargetDecl()),
+R.Qualifier);
+Result.setShadowDecl(Using);
+MaybeAddResult(Result, CurContext);
 return;
   }
 
@@ -977,10 +977,11 @@
 
   // Look through using declarations.
   if (const UsingShadowDecl *Using = dyn_cast(R.Declaration)) {
-AddResult(Result(Using->getTargetDecl(),
- getBasePriority(Using->getTargetDecl()),
- R.Qualifier),
-  CurContext, Hiding);
+CodeCompletionResult Result(Using->getTargetDecl(),
+getBasePriority(Using->getTargetDecl()),
+R.Qualifier);
+Result.setShadowDecl(Using);
+AddResult(Result, CurContext, Hiding);
 return;
   }
 
@@ -1004,10 +1005,10 @@
   if (AsNestedNameSpecifier) {
 R.StartsNestedNameSpecifier = true;
 R.Priority = CCP_NestedNameSpecifier;
-  }
-  else if (Filter == ::IsMember && !R.Qualifier && InBaseClass &&
-   isa(R.Declaration->getDeclContext()
-  ->getRedeclContext()))
+  } else if (Filter == ::IsMember && !R.Qualifier &&
+ InBaseClass &&
+ isa(
+ R.Declaration->getDeclContext()->getRedeclContext()))
 R.QualifierIsInformative = true;
 
   // If this result is supposed to have an informative qualifier, add one.
Index: clang/include/clang/Sema/CodeCompleteConsumer.h
===
--- clang/include/clang/Sema/CodeCompleteConsumer.h
+++ clang/include/clang/Sema/CodeCompleteConsumer.h
@@ -45,8 +45,9 @@
 class NamedDecl;
 class NestedNameSpecifier;
 class Preprocessor;
-class Sema;
 class RawComment;
+class Sema;
+class UsingShadowDecl;
 
 /// Default priority values for code-completion results based
 /// on their kind.
@@ -836,18 +837,25 @@
   /// informative rather than required.
   NestedNameSpecifier *Qualifier = nullptr;
 
+  /// If this Decl was unshadowed by using declaration, this would would store
+  /// a pointer to the UsingShadowDecl which was used in the unshadowing
+  /// process. This information can be used to uprank CodeCompletionResults
+  /// which have corresponding `using decl::qualified::name;` nearby.
+  const UsingShadowDecl *ShadowDecl = nullptr;
+
   /// Build a result that refers to a declaration.
   CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority,
NestedNameSpecifier *Qualifier = nullptr,
bool QualifierIsInformative = false,
bool Accessible = true,
-   std::vector FixIts = std::vector())
+   std::vector FixIts = std::vector(),
+   const UsingShadowDecl *ShadowDecl = nullptr)
   : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration),
 FixIts(std::move(FixIts)), Hidden(false),
 QualifierIsInformative(QualifierIsInformative),
 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
-DeclaringEntity(false), Qualifier(Qualifier) {
-//FIXME: Add assert to check FixIts range requirements.
+DeclaringEntity(false), Qualifier(Qualifier), ShadowDecl(ShadowDecl) {
+// FIXME: Add assert to check FixIts range requirements.
 computeCursorKindAndAvailability(Accessible);
   }
 
@@ -900,6 +908,10 @@
 return Keyword;
   }
 
+  void setShadowDecl(const UsingShadowDecl *Shadow) {
+this->ShadowDecl = Shadow;
+  }
+
   /// Create a new code-completion string that describes how to insert
   /// this result into a program.
   ///
Index: clang-tools-extra/unittests/clangd/QualityTests.cpp
===
--- clang-tools-extra/unittests/clangd/QualityTests.cpp
+++ clang-tools-extra/unittests/clangd/QualityTests.cpp
@@ -79,8 +79,18 @@
   

[PATCH] D49012: [clangd] Uprank delcarations when "using q::name" is present in the main file

2018-07-06 Thread Kirill Bobyrev via Phabricator via cfe-commits
omtcyfz created this revision.
omtcyfz added reviewers: ioeric, sammccall, ilya-biryukov.
omtcyfz added a project: clang-tools-extra.
Herald added subscribers: jkorous, MaskRay.

Having `using qualified::name;` for some symbol is an important signal for 
clangd code completion as the user is more likely to use such symbol. This 
patch helps to uprank the relevant symbols by saving UsingShadowDecl in the new 
field of CodeCompletionResult and checking whether the corresponding 
UsingShadowDecl is located in the main file later in ClangD code completion 
routine. While the relative importance of such signal is a subject to change in 
the future, this patch simply bumps DeclProximity score to the value of 1.0 
which should be enough for now.

The patch was tested using

$ ninja check-clang check-clang-tools

No unexpected failures were noticed after running the relevant testsets.


https://reviews.llvm.org/D49012

Files:
  clang-tools-extra/clangd/Quality.cpp
  clang-tools-extra/unittests/clangd/QualityTests.cpp
  clang-tools-extra/unittests/clangd/TestTU.cpp
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/lib/Sema/SemaCodeComplete.cpp

Index: clang/lib/Sema/SemaCodeComplete.cpp
===
--- clang/lib/Sema/SemaCodeComplete.cpp
+++ clang/lib/Sema/SemaCodeComplete.cpp
@@ -859,12 +859,12 @@
   }
 
   // Look through using declarations.
-  if (const UsingShadowDecl *Using =
-  dyn_cast(R.Declaration)) {
-MaybeAddResult(Result(Using->getTargetDecl(),
-  getBasePriority(Using->getTargetDecl()),
-  R.Qualifier),
-   CurContext);
+  if (const UsingShadowDecl *Using = dyn_cast(R.Declaration)) {
+CodeCompletionResult Result(Using->getTargetDecl(),
+getBasePriority(Using->getTargetDecl()),
+R.Qualifier);
+Result.setShadowDecl(Using);
+MaybeAddResult(Result, CurContext);
 return;
   }
 
@@ -977,10 +977,11 @@
 
   // Look through using declarations.
   if (const UsingShadowDecl *Using = dyn_cast(R.Declaration)) {
-AddResult(Result(Using->getTargetDecl(),
- getBasePriority(Using->getTargetDecl()),
- R.Qualifier),
-  CurContext, Hiding);
+CodeCompletionResult Result(Using->getTargetDecl(),
+getBasePriority(Using->getTargetDecl()),
+R.Qualifier);
+Result.setShadowDecl(Using);
+AddResult(Result, CurContext, Hiding);
 return;
   }
 
@@ -1004,10 +1005,10 @@
   if (AsNestedNameSpecifier) {
 R.StartsNestedNameSpecifier = true;
 R.Priority = CCP_NestedNameSpecifier;
-  }
-  else if (Filter == ::IsMember && !R.Qualifier && InBaseClass &&
-   isa(R.Declaration->getDeclContext()
-  ->getRedeclContext()))
+  } else if (Filter == ::IsMember && !R.Qualifier &&
+ InBaseClass &&
+ isa(
+ R.Declaration->getDeclContext()->getRedeclContext()))
 R.QualifierIsInformative = true;
 
   // If this result is supposed to have an informative qualifier, add one.
Index: clang/include/clang/Sema/CodeCompleteConsumer.h
===
--- clang/include/clang/Sema/CodeCompleteConsumer.h
+++ clang/include/clang/Sema/CodeCompleteConsumer.h
@@ -45,8 +45,9 @@
 class NamedDecl;
 class NestedNameSpecifier;
 class Preprocessor;
-class Sema;
 class RawComment;
+class Sema;
+class UsingShadowDecl;
 
 /// Default priority values for code-completion results based
 /// on their kind.
@@ -836,18 +837,25 @@
   /// informative rather than required.
   NestedNameSpecifier *Qualifier = nullptr;
 
+  /// If this Decl was unshadowed by using declaration, this would would store
+  /// a pointer to the UsingShadowDecl which was used in the unshadowing
+  /// process. This information can be used to uprank CodeCompletionResults
+  /// which have corresponding `using decl::qualified::name;` nearby.
+  const UsingShadowDecl *ShadowDecl = nullptr;
+
   /// Build a result that refers to a declaration.
   CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority,
NestedNameSpecifier *Qualifier = nullptr,
bool QualifierIsInformative = false,
bool Accessible = true,
-   std::vector FixIts = std::vector())
+   std::vector FixIts = std::vector(),
+   const UsingShadowDecl *ShadowDecl = nullptr)
   : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration),
 FixIts(std::move(FixIts)), Hidden(false),
 QualifierIsInformative(QualifierIsInformative),
 StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
-DeclaringEntity(false), Qualifier(Qualifier) {
-//FIXME: Add assert 

[PATCH] D48961: [Index] Add indexing support for MACROs.

2018-07-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: include/clang/Index/IndexDataConsumer.h:48
   /// \returns true to continue indexing, or false to abort.
-  virtual bool handleMacroOccurence(const IdentifierInfo *Name,
-const MacroInfo *MI, SymbolRoleSet Roles,
-SourceLocation Loc);
+  /// \p Undefined is set when the occurrence is in an #undef directive where
+  /// the macro undefined.

Ah, now I understand :-)

This doesn't seem like another orthogonal bool parameter, it seems more like a 
SymbolRole (we have Definition there, logically Undefinition seems like it 
should be there too, even if it only applies to some symbols).

It looks like it would be safe to insert this as bit 9, and move all the others 
down by 1 bit? Only the libclang API needs to be stable, and that ends at bit 8.



Comment at: include/clang/Index/IndexingAction.h:44
 
+/// Creates a frontend action that indexes macros and AST decls.
 /// \param WrappedAction another frontend action to wrap over or null.

nit: indexes all symbols (macros and AST decls).
i.e. if there were other types in the future, they'd get indexed too.



Comment at: include/clang/Index/IndexingAction.h:51
 
+/// Recursively indexes all decls in the AST. Note that this does not index
+/// macros.

nit: can you break before the "Note" here and below, to make this easier to 
find?



Comment at: include/clang/Index/IndexingAction.h:61
+/// Creates a PPCallbacks that indexes macros and feeds macros to \p Consumer.
+/// Note that this does not set the preprocesssor in \p Consumer. If \p 
Consumer
+/// needs Preprocessor, it has to be set separately before callback is invoked.

I found this second part hard to understand - I think it's what I'd expect 
(Preprocessor knows about PPCallbacks, but not the other way around), but I had 
to look up what "set the preprocessor" meant.

Maybe "The caller is responsible for calling Consumer.setPreprocessor()"?



Comment at: include/clang/Index/IndexingAction.h:66
+
+/// Recursively indexes all top-level decls in the module. Note that this does
+/// not index macros.

are you sure it doesn't index macros? is this a bug? maybe this should be FIXME 
instead of a note



Comment at: lib/Index/IndexSymbol.cpp:357
+  Info.Properties = SymbolPropertySet();
+  // FIXME: set languages more accurately.
+  Info.Lang = SymbolLanguage::C;

I'm not sure what the intent of this comment is - what's the behavior you 
*want* here?
One principled option is to introduce a new SymbolLanguage for the preprocessor 
(it's reasonable to consider this a separate language).
Another is to always consider macros C symbol, but then this shouldn't be a 
fixme.



Comment at: lib/Index/IndexingAction.cpp:52
   std::shared_ptr PP;
-  IndexingContext 
+  std::shared_ptr IndexCtx;
 

making these shared_ptr everywhere feels a bit like giving up :-)
Can't we keep this one and IndexPPCallbacks as references?


Repository:
  rC Clang

https://reviews.llvm.org/D48961



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


[PATCH] D48921: NFC - type fix in test/CodeGenCXX/runtime-dllstorage.cpp

2018-07-06 Thread Gabor Buella via Phabricator via cfe-commits
GBuella requested review of this revision.
GBuella added a comment.

Well, apparently the test fails with the typo fix.
There is no  `declare dllimport void @_ZSt9terminatev()` line that could be 
matched for `CHECK-DYNAMIC-IA-DAG`.


Repository:
  rC Clang

https://reviews.llvm.org/D48921



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


[PATCH] D49010: YAML output for index-while-building

2018-07-06 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan created this revision.
yvvan added a reviewer: nathawes.
Herald added subscribers: ioeric, ilya-biryukov.

Should be compatible with the current index format accepted by clangd


https://reviews.llvm.org/D49010

Files:
  include/clang/Index/IndexRecordReader.h
  include/clang/Index/IndexRecordWriter.h
  include/indexstore/IndexStoreCXX.h
  include/indexstore/indexstore.h
  lib/Index/ClangIndexRecordWriter.cpp
  lib/Index/IndexRecordReader.cpp
  lib/Index/IndexRecordWriter.cpp
  tools/IndexStore/IndexStore.cpp
  tools/c-index-test/JSONAggregation.cpp
  tools/c-index-test/JSONAggregation.h
  tools/c-index-test/core_main.cpp

Index: tools/c-index-test/core_main.cpp
===
--- tools/c-index-test/core_main.cpp
+++ tools/c-index-test/core_main.cpp
@@ -59,6 +59,7 @@
   PrintUnit,
   PrintStoreFormatVersion,
   AggregateAsJSON,
+  AggregateAsYAML,
   WatchDir,
 };
 
@@ -80,6 +81,8 @@
"print-store-format-version", "Print store format version"),
 clEnumValN(ActionType::AggregateAsJSON, "aggregate-json",
"Aggregate index data in JSON format"),
+clEnumValN(ActionType::AggregateAsYAML, "aggregate-yaml",
+   "Aggregate index data in YAML format"),
 clEnumValN(ActionType::WatchDir, "watch-dir",
"Watch directory for file events")),
 cl::cat(IndexTestCoreCategory));
@@ -1063,7 +1066,8 @@
 outs() << indexstore::IndexStore::formatVersion() << '\n';
   }
 
-  if (options::Action == ActionType::AggregateAsJSON) {
+  if (options::Action == ActionType::AggregateAsJSON ||
+  options::Action == ActionType::AggregateAsYAML) {
 if (options::InputFiles.empty()) {
   errs() << "error: missing input data store directory\n";
   return 1;
@@ -1077,7 +1081,10 @@
   errs() << "failed to open output file: " << EC.message() << '\n';
   return 1;
 }
-return aggregateDataAsJSON(storePath, OS);
+if (options::Action == ActionType::AggregateAsJSON)
+  return aggregateDataAsJSON(storePath, OS);
+else
+  return aggregateDataAsYAML(storePath, OS);
   }
 
   if (options::Action == ActionType::WatchDir) {
Index: tools/c-index-test/JSONAggregation.h
===
--- tools/c-index-test/JSONAggregation.h
+++ tools/c-index-test/JSONAggregation.h
@@ -18,6 +18,9 @@
 /// Returns true if an error occurred, false otherwise.
 bool aggregateDataAsJSON(StringRef StorePath, raw_ostream );
 
+/// Returns true if an error occurred, false otherwise.
+bool aggregateDataAsYAML(StringRef StorePath, raw_ostream );
+
 } // end namespace index
 } // end namespace clang
 
Index: tools/c-index-test/JSONAggregation.cpp
===
--- tools/c-index-test/JSONAggregation.cpp
+++ tools/c-index-test/JSONAggregation.cpp
@@ -10,11 +10,16 @@
 #include "JSONAggregation.h"
 #include "indexstore/IndexStoreCXX.h"
 #include "clang/Index/IndexDataStoreSymbolUtils.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/SHA1.h"
 #include "llvm/Support/raw_ostream.h"
 
+#include 
+#include 
+
 using namespace clang;
 using namespace clang::index;
 using namespace indexstore;
@@ -44,6 +49,7 @@
   SymbolLanguage Lang;
   StringRef USR;
   StringRef Name;
+  StringRef Scope;
   StringRef CodegenName;
   SymbolRoleSet Roles = 0;
   SymbolRoleSet RelatedRoles = 0;
@@ -62,6 +68,8 @@
   std::vector Relations;
   unsigned Line;
   unsigned Column;
+  unsigned EndLine;
+  unsigned EndColumn;
 };
 
 struct RecordInfo {
@@ -93,6 +101,7 @@
   bool process();
   void processUnit(StringRef name, IndexUnitReader );
   void dumpJSON(raw_ostream );
+  void dumpYAML(raw_ostream );
 
 private:
   StringRef copyStr(StringRef str) {
@@ -232,6 +241,7 @@
 });
 occurInfo.Roles = idxOccur.getRoles();
 std::tie(occurInfo.Line, occurInfo.Column) = idxOccur.getLineCol();
+std::tie(occurInfo.EndLine, occurInfo.EndColumn) = idxOccur.getEndLineCol();
 record->Occurrences.push_back(std::move(occurInfo));
 return true;
   });
@@ -248,6 +258,7 @@
 symInfo.Lang = getSymbolLanguage(sym.getLanguage());
 symInfo.USR = pair.first->first();
 symInfo.Name = copyStr(sym.getName());
+symInfo.Scope = copyStr(sym.getScope());
 symInfo.CodegenName = copyStr(sym.getCodegenName());
 Symbols.push_back(std::move(symInfo));
   }
@@ -392,6 +403,84 @@
   OS << "}\n";
 }
 
+static StringRef getSymbolKindForYAML(SymbolKind K) {
+  switch (K) {
+  case SymbolKind::Unknown: return "";
+  case SymbolKind::Module: return "Module";
+  case SymbolKind::Namespace: return "Namespace";
+  case SymbolKind::NamespaceAlias: return "NamespaceAlias";
+  case SymbolKind::Macro: return "Macro";
+  case SymbolKind::Enum: return "Enum";
+  case SymbolKind::Struct: return "Struct";

[PATCH] D49008: [clangd] Upgrade logging facilities with levels and formatv.

2018-07-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
Herald added subscribers: cfe-commits, jkorous, MaskRay, ioeric, javed.absar, 
ilya-biryukov.

log() is split into four functions:

- elog()/log()/vlog() have different severity levels, allowing filtering
- dlog() is a lazy macro which uses LLVM_DEBUG - it logs to the logger, but 
conditionally based on -debug-only flag and is omitted in release builds

All logging functions use formatv-style format strings now, e.g:

  log("Could not resolve URI {0}: {1}", URI, Result.takeError());

Existing log sites have been split between elog/log/vlog by best guess.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49008

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdServer.cpp
  clangd/ClangdUnit.cpp
  clangd/CodeComplete.cpp
  clangd/Compiler.cpp
  clangd/Diagnostics.cpp
  clangd/FileDistance.cpp
  clangd/FindSymbols.cpp
  clangd/GlobalCompilationDatabase.cpp
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/Logger.cpp
  clangd/Logger.h
  clangd/Protocol.cpp
  clangd/ProtocolHandlers.cpp
  clangd/TUScheduler.cpp
  clangd/XRefs.cpp
  clangd/index/SymbolCollector.cpp
  clangd/tool/ClangdMain.cpp

Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -98,6 +98,13 @@
 PrettyPrint("pretty", llvm::cl::desc("Pretty-print JSON output"),
 llvm::cl::init(false));
 
+static llvm::cl::opt LogLevel(
+"log", llvm::cl::desc("Verbosity of log messages written to stderr"),
+llvm::cl::values(clEnumVal(Logger::Error, "Error messages only"),
+ clEnumVal(Logger::Info, "High level execution tracing"),
+ clEnumVal(Logger::Debug, "Low level details")),
+llvm::cl::init(Logger::Info));
+
 static llvm::cl::opt Test(
 "lit-test",
 llvm::cl::desc(
@@ -223,7 +230,7 @@
   if (Tracer)
 TracingSession.emplace(*Tracer);
 
-  JSONOutput Out(llvm::outs(), llvm::errs(),
+  JSONOutput Out(llvm::outs(), llvm::errs(), LogLevel,
  InputMirrorStream ? InputMirrorStream.getPointer() : nullptr,
  PrettyPrint);
 
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -52,7 +52,7 @@
   if (std::error_code EC =
   SM.getFileManager().getVirtualFileSystem()->makeAbsolute(
   AbsolutePath))
-log("Warning: could not make absolute file: " + EC.message());
+log("Warning: could not make absolute file: {0}", EC.message());
   if (llvm::sys::path::is_absolute(AbsolutePath)) {
 // Handle the symbolic link path case where the current working directory
 // (getCurrentWorkingDirectory) is a symlink./ We always want to the real
@@ -86,8 +86,7 @@
   return U->toString();
 ErrMsg += llvm::toString(U.takeError()) + "\n";
   }
-  log(llvm::Twine("Failed to create an URI for file ") + AbsolutePath + ": " +
-  ErrMsg);
+  log("Failed to create an URI for file {0}: {1}", AbsolutePath, ErrMsg);
   return llvm::None;
 }
 
Index: clangd/XRefs.cpp
===
--- clangd/XRefs.cpp
+++ clangd/XRefs.cpp
@@ -46,12 +46,12 @@
 return llvm::None;
   auto Uri = URI::parse(Loc.FileURI);
   if (!Uri) {
-log("Could not parse URI: " + Loc.FileURI);
+log("Could not parse URI: {0}", Loc.FileURI);
 return llvm::None;
   }
   auto Path = URI::resolve(*Uri, HintPath);
   if (!Path) {
-log("Could not resolve URI: " + Loc.FileURI);
+log("Could not resolve URI: {0}", Loc.FileURI);
 return llvm::None;
   }
   Location LSPLoc;
@@ -182,7 +182,7 @@
 FilePath = F->getName();
   if (!llvm::sys::path::is_absolute(FilePath)) {
 if (!SourceMgr.getFileManager().makeAbsolutePath(FilePath)) {
-  log("Could not turn relative path to absolute: " + FilePath);
+  log("Could not turn relative path to absolute: {0}", FilePath);
   return llvm::None;
 }
   }
Index: clangd/TUScheduler.cpp
===
--- clangd/TUScheduler.cpp
+++ clangd/TUScheduler.cpp
@@ -321,14 +321,14 @@
 // Remove the old AST if it's still in cache.
 IdleASTs.take(this);
 
-log("Updating file " + FileName + " with command [" +
-Inputs.CompileCommand.Directory + "] " +
+log("Updating file {0} with command [{1}] {2}", FileName,
+Inputs.CompileCommand.Directory,
 llvm::join(Inputs.CompileCommand.CommandLine, " "));
 // Rebuild the preamble and the AST.
 std::unique_ptr Invocation =
 buildCompilerInvocation(Inputs);
 if (!Invocation) {
-  log("Could not build CompilerInvocation for file " + FileName);
+  elog("Could not build CompilerInvocation for file {0}", FileName);
   return;
 }
 
@@ -611,8 +611,8 @@
 void TUScheduler::remove(PathRef File) {
   

[PATCH] D48973: [SemaCodeComplete] Expose a method to create CodeCompletionString for macros.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 154370.
ioeric added a comment.

- Merged with orgin/master


Repository:
  rC Clang

https://reviews.llvm.org/D48973

Files:
  include/clang/Sema/CodeCompleteConsumer.h
  lib/Sema/SemaCodeComplete.cpp

Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2745,6 +2745,52 @@
 CCTUInfo, IncludeBriefComments);
 }
 
+CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
+Preprocessor , CodeCompletionAllocator ,
+CodeCompletionTUInfo ) {
+  assert(Kind == RK_Macro);
+  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
+  const MacroInfo *MI = PP.getMacroInfo(Macro);
+  Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
+
+  if (!MI || !MI->isFunctionLike())
+return Result.TakeString();
+
+  // Format a function-like macro with placeholders for the arguments.
+  Result.AddChunk(CodeCompletionString::CK_LeftParen);
+  MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
+
+  // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
+  if (MI->isC99Varargs()) {
+--AEnd;
+
+if (A == AEnd) {
+  Result.AddPlaceholderChunk("...");
+}
+  }
+
+  for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
+if (A != MI->param_begin())
+  Result.AddChunk(CodeCompletionString::CK_Comma);
+
+if (MI->isVariadic() && (A + 1) == AEnd) {
+  SmallString<32> Arg = (*A)->getName();
+  if (MI->isC99Varargs())
+Arg += ", ...";
+  else
+Arg += "...";
+  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
+  break;
+}
+
+// Non-variadic macros are simple.
+Result.AddPlaceholderChunk(
+Result.getAllocator().CopyString((*A)->getName()));
+  }
+  Result.AddChunk(CodeCompletionString::CK_RightParen);
+  return Result.TakeString();
+}
+
 /// If possible, create a new code completion string for the given
 /// result.
 ///
@@ -2758,6 +2804,9 @@
CodeCompletionAllocator ,
CodeCompletionTUInfo ,
bool IncludeBriefComments) {
+  if (Kind == RK_Macro)
+return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
+
   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
 
   PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
@@ -2782,50 +2831,6 @@
 Result.AddTypedTextChunk(Keyword);
 return Result.TakeString();
   }
-
-  if (Kind == RK_Macro) {
-const MacroInfo *MI = PP.getMacroInfo(Macro);
-Result.AddTypedTextChunk(
-Result.getAllocator().CopyString(Macro->getName()));
-
-if (!MI || !MI->isFunctionLike())
-  return Result.TakeString();
-
-// Format a function-like macro with placeholders for the arguments.
-Result.AddChunk(CodeCompletionString::CK_LeftParen);
-MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
-
-// C99 variadic macros add __VA_ARGS__ at the end. Skip it.
-if (MI->isC99Varargs()) {
-  --AEnd;
-
-  if (A == AEnd) {
-Result.AddPlaceholderChunk("...");
-  }
-}
-
-for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
-  if (A != MI->param_begin())
-Result.AddChunk(CodeCompletionString::CK_Comma);
-
-  if (MI->isVariadic() && (A+1) == AEnd) {
-SmallString<32> Arg = (*A)->getName();
-if (MI->isC99Varargs())
-  Arg += ", ...";
-else
-  Arg += "...";
-Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
-break;
-  }
-
-  // Non-variadic macros are simple.
-  Result.AddPlaceholderChunk(
-  Result.getAllocator().CopyString((*A)->getName()));
-}
-Result.AddChunk(CodeCompletionString::CK_RightParen);
-return Result.TakeString();
-  }
-
   assert(Kind == RK_Declaration && "Missed a result kind?");
   const NamedDecl *ND = Declaration;
   Result.addParentContext(ND->getDeclContext());
Index: include/clang/Sema/CodeCompleteConsumer.h
===
--- include/clang/Sema/CodeCompleteConsumer.h
+++ include/clang/Sema/CodeCompleteConsumer.h
@@ -918,6 +918,13 @@
CodeCompletionAllocator ,
CodeCompletionTUInfo ,
bool IncludeBriefComments);
+  /// Creates a new code-completion string for the macro result. Similar to the
+  /// above overloads, except this only requires preprocessor information.
+  /// The result kind must be `RK_Macro`.
+  CodeCompletionString *
+  CreateCodeCompletionStringForMacro(Preprocessor ,
+  

[PATCH] D48973: [SemaCodeComplete] Expose a method to create CodeCompletionString for macros.

2018-07-06 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Thanks for the explanation!


Repository:
  rC Clang

https://reviews.llvm.org/D48973



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


[PATCH] D48973: [SemaCodeComplete] Expose a method to create CodeCompletionString for macros.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 154369.
ioeric added a comment.

- Addressed review comments.


Repository:
  rC Clang

https://reviews.llvm.org/D48973

Files:
  include/clang/Sema/CodeCompleteConsumer.h
  lib/Sema/SemaCodeComplete.cpp

Index: lib/Sema/SemaCodeComplete.cpp
===
--- lib/Sema/SemaCodeComplete.cpp
+++ lib/Sema/SemaCodeComplete.cpp
@@ -2745,6 +2745,52 @@
 CCTUInfo, IncludeBriefComments);
 }
 
+CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
+Preprocessor , CodeCompletionAllocator ,
+CodeCompletionTUInfo ) {
+  assert(Kind == RK_Macro);
+  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
+  const MacroInfo *MI = PP.getMacroInfo(Macro);
+  Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
+
+  if (!MI || !MI->isFunctionLike())
+return Result.TakeString();
+
+  // Format a function-like macro with placeholders for the arguments.
+  Result.AddChunk(CodeCompletionString::CK_LeftParen);
+  MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
+
+  // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
+  if (MI->isC99Varargs()) {
+--AEnd;
+
+if (A == AEnd) {
+  Result.AddPlaceholderChunk("...");
+}
+  }
+
+  for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
+if (A != MI->param_begin())
+  Result.AddChunk(CodeCompletionString::CK_Comma);
+
+if (MI->isVariadic() && (A + 1) == AEnd) {
+  SmallString<32> Arg = (*A)->getName();
+  if (MI->isC99Varargs())
+Arg += ", ...";
+  else
+Arg += "...";
+  Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
+  break;
+}
+
+// Non-variadic macros are simple.
+Result.AddPlaceholderChunk(
+Result.getAllocator().CopyString((*A)->getName()));
+  }
+  Result.AddChunk(CodeCompletionString::CK_RightParen);
+  return Result.TakeString();
+}
+
 /// If possible, create a new code completion string for the given
 /// result.
 ///
@@ -2758,6 +2804,9 @@
CodeCompletionAllocator ,
CodeCompletionTUInfo ,
bool IncludeBriefComments) {
+  if (Kind == RK_Macro)
+return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
+
   CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
   
   PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
@@ -2783,49 +2832,6 @@
 return Result.TakeString();
   }
   
-  if (Kind == RK_Macro) {
-const MacroInfo *MI = PP.getMacroInfo(Macro);
-Result.AddTypedTextChunk(
-Result.getAllocator().CopyString(Macro->getName()));
-
-if (!MI || !MI->isFunctionLike())
-  return Result.TakeString();
-
-// Format a function-like macro with placeholders for the arguments.
-Result.AddChunk(CodeCompletionString::CK_LeftParen);
-MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
-
-// C99 variadic macros add __VA_ARGS__ at the end. Skip it.
-if (MI->isC99Varargs()) {
-  --AEnd;
-  
-  if (A == AEnd) {
-Result.AddPlaceholderChunk("...");
-  }
-}
-
-for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
-  if (A != MI->param_begin())
-Result.AddChunk(CodeCompletionString::CK_Comma);
-
-  if (MI->isVariadic() && (A+1) == AEnd) {
-SmallString<32> Arg = (*A)->getName();
-if (MI->isC99Varargs())
-  Arg += ", ...";
-else
-  Arg += "...";
-Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
-break;
-  }
-
-  // Non-variadic macros are simple.
-  Result.AddPlaceholderChunk(
-  Result.getAllocator().CopyString((*A)->getName()));
-}
-Result.AddChunk(CodeCompletionString::CK_RightParen);
-return Result.TakeString();
-  }
-  
   assert(Kind == RK_Declaration && "Missed a result kind?");
   const NamedDecl *ND = Declaration;
   Result.addParentContext(ND->getDeclContext());
Index: include/clang/Sema/CodeCompleteConsumer.h
===
--- include/clang/Sema/CodeCompleteConsumer.h
+++ include/clang/Sema/CodeCompleteConsumer.h
@@ -918,6 +918,13 @@
CodeCompletionAllocator ,
CodeCompletionTUInfo ,
bool IncludeBriefComments);
+  /// Creates a new code-completion string for the macro result. Similar to the
+  /// above overloads, except this only requires preprocessor information.
+  /// The result kind must be `RK_Macro`.
+  CodeCompletionString *
+  CreateCodeCompletionStringForMacro(Preprocessor ,
+

[PATCH] D48973: [SemaCodeComplete] Expose a method to create CodeCompletionString for macros.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: include/clang/Sema/CodeCompleteConsumer.h:921
bool IncludeBriefComments);
+  CodeCompletionString *
+  CreateCodeCompletionStringForMacro(Preprocessor ,

sammccall wrote:
> please document the new function - particularly why it's different and what's 
> the use case it supports
> (if I understand right, it's to allow storing CodeCompletionResult instances 
> for later stringification only when they're for macros - why?)
> 
> One of the args you're *not* taking here is ASTContext, but if I understand 
> right it must still be alive: `this->Macro` points into the IdentifierTable 
> which is owned by ASTContext.
> In some sense taking this arg seems like a safety feature!
Done. Added documentation.

>One of the args you're *not* taking here is ASTContext, but if I understand 
>right it must still be alive: this->Macro points into the IdentifierTable 
>which is owned by ASTContext.
ASTContext might not be available during preprocessing. It turned out that 
ASTContext only holds a reference to the `IdentifierTable` which is owned by 
the Preprocessor, so requiring a Preprocessor should be safe.


Repository:
  rC Clang

https://reviews.llvm.org/D48973



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


[PATCH] D48961: [Index] Add indexing support for MACROs.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

Thanks for the review!

In https://reviews.llvm.org/D48961#1152999, @sammccall wrote:

> I worry this is a trap: the indexing infrastructure here is designed so you 
> can run it as a frontendaction, on an ASTUnit, or by passing a set of top 
> level decls.
>  However the macro functionality necessarily only works when running as a 
> frontend action, so the same consumer would have different semantics when 
> using these functions.
>  Moreover, clangd does call indexTopLevelDecls(), so this API might actually 
> be awkward for us to use.
>
> Alternatives would be:
>
> - write lots of loud documentation and hope people read it
> - punt on generalization and just do what we need in clangd with PPCallbacks 
> directly
> - offer a peer API here for consuming macros, and have the 
> indexTopLevelDecls() etc only take the symbol consumer, 
> createIndexingAction() would create both (and you could have a 
> createIndexingPPCallbacks() that takes only the macro consumer).
>
>   WDYT?


As chatted offline, the fact that `indexTopLevelDecls` etc can't index macros 
is unfortunate, but it seems to be by the current design and probably due to 
how preprocessor  and AST work. As you suggested, I added some comments to make 
this more explicit and also exposed a function that returns a PPCallbacks for 
indexing macros, which should be useful for clangd's dynamic index. Hope this 
would make these functions harder to misuse.


Repository:
  rC Clang

https://reviews.llvm.org/D48961



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


[PATCH] D48961: [Index] Add indexing support for MACROs.

2018-07-06 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 154367.
ioeric marked 2 inline comments as done.
ioeric added a comment.

- Addressed review comments. Expose create a PPCallbacks for indexing macros.


Repository:
  rC Clang

https://reviews.llvm.org/D48961

Files:
  include/clang/Index/IndexDataConsumer.h
  include/clang/Index/IndexSymbol.h
  include/clang/Index/IndexingAction.h
  lib/Index/IndexSymbol.cpp
  lib/Index/IndexingAction.cpp
  lib/Index/IndexingContext.cpp
  lib/Index/IndexingContext.h
  test/Index/Core/index-macros.c
  tools/c-index-test/core_main.cpp

Index: tools/c-index-test/core_main.cpp
===
--- tools/c-index-test/core_main.cpp
+++ tools/c-index-test/core_main.cpp
@@ -7,6 +7,7 @@
 //
 //===--===//
 
+#include "clang/Basic/LangOptions.h"
 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
@@ -16,6 +17,7 @@
 #include "clang/Index/IndexDataConsumer.h"
 #include "clang/Index/USRGeneration.h"
 #include "clang/Index/CodegenNameGenerator.h"
+#include "clang/Lex/Preprocessor.h"
 #include "clang/Serialization/ASTReader.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Signals.h"
@@ -77,6 +79,7 @@
 class PrintIndexDataConsumer : public IndexDataConsumer {
   raw_ostream 
   std::unique_ptr CGNameGen;
+  std::shared_ptr PP;
 
 public:
   PrintIndexDataConsumer(raw_ostream ) : OS(OS) {
@@ -86,6 +89,10 @@
 CGNameGen.reset(new CodegenNameGenerator(Ctx));
   }
 
+  void setPreprocessor(std::shared_ptr PP) override {
+this->PP = std::move(PP);
+  }
+
   bool handleDeclOccurence(const Decl *D, SymbolRoleSet Roles,
ArrayRef Relations,
SourceLocation Loc, ASTNodeInfo ASTNode) override {
@@ -145,6 +152,42 @@
 
 return true;
   }
+
+  bool handleMacroOccurence(const IdentifierInfo , const MacroInfo ,
+SymbolRoleSet Roles, SourceLocation Loc,
+bool Undefined) override {
+assert(PP);
+SourceManager  = PP->getSourceManager();
+
+Loc = SM.getFileLoc(Loc);
+FileID FID = SM.getFileID(Loc);
+unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
+unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
+OS << Line << ':' << Col << " | ";
+
+printSymbolInfo(getSymbolInfoForMacro(MI), OS);
+OS << " | ";
+
+OS << Name.getName();
+OS << " | ";
+
+SmallString<256> USRBuf;
+if (generateUSRForMacro(Name.getName(), MI.getDefinitionLoc(), SM,
+USRBuf)) {
+  OS << "";
+} else {
+  OS << USRBuf;
+}
+
+OS << " | ";
+
+if (Undefined)
+  OS << "(undefined)";
+else
+  printSymbolRoles(Roles, OS);
+OS << " |\n";
+return true;
+  }
 };
 
 } // anonymous namespace
Index: test/Index/Core/index-macros.c
===
--- /dev/null
+++ test/Index/Core/index-macros.c
@@ -0,0 +1,12 @@
+// RUN: c-index-test core -print-source-symbols -- %s | FileCheck %s
+
+// CHECK: [[@LINE+1]]:9 | macro/C | X1 | c:index-macros.c@157@macro@X1 | Def |
+#define X1 1
+// CHECK: [[@LINE+1]]:9 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Def |
+#define DEF(x) int x
+// CHECK: [[@LINE+1]]:8 | macro/C | X1 | c:index-macros.c@157@macro@X1 | (undefined) |
+#undef X1
+
+// CHECK: [[@LINE+2]]:1 | macro/C | DEF | c:index-macros.c@251@macro@DEF | Ref |
+// CHECK: [[@LINE+1]]:5 | variable/C | i | c:@i | i | Def | rel: 0
+DEF(i);
Index: lib/Index/IndexingContext.h
===
--- lib/Index/IndexingContext.h
+++ lib/Index/IndexingContext.h
@@ -10,9 +10,11 @@
 #ifndef LLVM_CLANG_LIB_INDEX_INDEXINGCONTEXT_H
 #define LLVM_CLANG_LIB_INDEX_INDEXINGCONTEXT_H
 
+#include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Index/IndexSymbol.h"
 #include "clang/Index/IndexingAction.h"
+#include "clang/Lex/MacroInfo.h"
 #include "llvm/ADT/ArrayRef.h"
 
 namespace clang {
@@ -80,6 +82,15 @@
const Expr *RefE = nullptr,
const Decl *RefD = nullptr);
 
+  void handleMacroDefined(const IdentifierInfo , SourceLocation Loc,
+  const MacroInfo );
+
+  void handleMacroUndefined(const IdentifierInfo , SourceLocation Loc,
+const MacroInfo );
+
+  void handleMacroReference(const IdentifierInfo , SourceLocation Loc,
+const MacroInfo );
+
   bool importedModule(const ImportDecl *ImportD);
 
   bool indexDecl(const Decl *D);
Index: lib/Index/IndexingContext.cpp
===
--- lib/Index/IndexingContext.cpp
+++ lib/Index/IndexingContext.cpp
@@ -8,6 +8,7 @@
 

[PATCH] D48941: [ASTImporter] import FunctionDecl end locations

2018-07-06 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rC Clang

https://reviews.llvm.org/D48941



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


r336417 - [X86] Implement _builtin_ia32_vfmaddss and _builtin_ia32_vfmaddsd with native IR using llvm.fma intrinsic.

2018-07-06 Thread Craig Topper via cfe-commits
Author: ctopper
Date: Fri Jul  6 00:14:47 2018
New Revision: 336417

URL: http://llvm.org/viewvc/llvm-project?rev=336417=rev
Log:
[X86] Implement _builtin_ia32_vfmaddss and _builtin_ia32_vfmaddsd with native 
IR using llvm.fma intrinsic.

This generates some extra zeroing currently, but we should be able to quickly 
address that with some isel patterns.

Modified:
cfe/trunk/lib/CodeGen/CGBuiltin.cpp
cfe/trunk/test/CodeGen/fma4-builtins.c

Modified: cfe/trunk/lib/CodeGen/CGBuiltin.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGBuiltin.cpp?rev=336417=336416=336417=diff
==
--- cfe/trunk/lib/CodeGen/CGBuiltin.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGBuiltin.cpp Fri Jul  6 00:14:47 2018
@@ -9134,6 +9134,16 @@ Value *CodeGenFunction::EmitX86BuiltinEx
 Value *Res = Builder.CreateCall(FMA, {A, B, C} );
 return Builder.CreateInsertElement(Ops[0], Res, (uint64_t)0);
   }
+  case X86::BI__builtin_ia32_vfmaddss:
+  case X86::BI__builtin_ia32_vfmaddsd: {
+Value *A = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
+Value *B = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
+Value *C = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
+Function *FMA = CGM.getIntrinsic(Intrinsic::fma, A->getType());
+Value *Res = Builder.CreateCall(FMA, {A, B, C} );
+Value *Zero = Constant::getNullValue(Ops[0]->getType());
+return Builder.CreateInsertElement(Zero, Res, (uint64_t)0);
+  }
   case X86::BI__builtin_ia32_vfmaddps:
   case X86::BI__builtin_ia32_vfmaddpd:
   case X86::BI__builtin_ia32_vfmaddps256:

Modified: cfe/trunk/test/CodeGen/fma4-builtins.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/fma4-builtins.c?rev=336417=336416=336417=diff
==
--- cfe/trunk/test/CodeGen/fma4-builtins.c (original)
+++ cfe/trunk/test/CodeGen/fma4-builtins.c Fri Jul  6 00:14:47 2018
@@ -17,13 +17,21 @@ __m128d test_mm_macc_pd(__m128d a, __m12
 
 __m128 test_mm_macc_ss(__m128 a, __m128 b, __m128 c) {
   // CHECK-LABEL: test_mm_macc_ss
-  // CHECK: @llvm.x86.fma4.vfmadd.ss
+  // CHECK: extractelement <4 x float> %{{.*}}, i64 0
+  // CHECK: extractelement <4 x float> %{{.*}}, i64 0
+  // CHECK: extractelement <4 x float> %{{.*}}, i64 0
+  // CHECK: call float @llvm.fma.f32(float %{{.*}}, float %{{.*}}, float 
%{{.*}})
+  // CHECK: insertelement <4 x float> zeroinitializer, float %{{.*}}, i64 0
   return _mm_macc_ss(a, b, c);
 }
 
 __m128d test_mm_macc_sd(__m128d a, __m128d b, __m128d c) {
   // CHECK-LABEL: test_mm_macc_sd
-  // CHECK: @llvm.x86.fma4.vfmadd.sd
+  // CHECK: extractelement <2 x double> %{{.*}}, i64 0
+  // CHECK: extractelement <2 x double> %{{.*}}, i64 0
+  // CHECK: extractelement <2 x double> %{{.*}}, i64 0
+  // CHECK: call double @llvm.fma.f64(double %{{.*}}, double %{{.*}}, double 
%{{.*}})
+  // CHECK: insertelement <2 x double> zeroinitializer, double %{{.*}}, i64 0
   return _mm_macc_sd(a, b, c);
 }
 
@@ -44,14 +52,22 @@ __m128d test_mm_msub_pd(__m128d a, __m12
 __m128 test_mm_msub_ss(__m128 a, __m128 b, __m128 c) {
   // CHECK-LABEL: test_mm_msub_ss
   // CHECK: [[NEG:%.+]] = fsub <4 x float> , %{{.+}}
-  // CHECK: @llvm.x86.fma4.vfmadd.ss(<4 x float> %{{.+}}, <4 x float> %{{.+}}, 
<4 x float> [[NEG]])
+  // CHECK: extractelement <4 x float> %{{.*}}, i64 0
+  // CHECK: extractelement <4 x float> %{{.*}}, i64 0
+  // CHECK: [[C:%.+]] = extractelement <4 x float> [[NEG]], i64 0
+  // CHECK: call float @llvm.fma.f32(float %{{.*}}, float %{{.*}}, float [[C]])
+  // CHECK: insertelement <4 x float> zeroinitializer, float %{{.*}}, i64 0
   return _mm_msub_ss(a, b, c);
 }
 
 __m128d test_mm_msub_sd(__m128d a, __m128d b, __m128d c) {
   // CHECK-LABEL: test_mm_msub_sd
   // CHECK: [[NEG:%.+]] = fsub <2 x double> , %{{.+}}
-  // CHECK: @llvm.x86.fma4.vfmadd.sd(<2 x double> %{{.+}}, <2 x double> 
%{{.+}}, <2 x double> [[NEG]])
+  // CHECK: extractelement <2 x double> %{{.*}}, i64 0
+  // CHECK: extractelement <2 x double> %{{.*}}, i64 0
+  // CHECK: [[C:%.+]] = extractelement <2 x double> [[NEG]], i64 0
+  // CHECK: call double @llvm.fma.f64(double %{{.*}}, double %{{.*}}, double 
[[C]])
+  // CHECK: insertelement <2 x double> zeroinitializer, double %{{.*}}, i64 0
   return _mm_msub_sd(a, b, c);
 }
 
@@ -72,14 +88,22 @@ __m128d test_mm_nmacc_pd(__m128d a, __m1
 __m128 test_mm_nmacc_ss(__m128 a, __m128 b, __m128 c) {
   // CHECK-LABEL: test_mm_nmacc_ss
   // CHECK: [[NEG:%.+]] = fsub <4 x float> , %{{.+}}
-  // CHECK: @llvm.x86.fma4.vfmadd.ss(<4 x float> [[NEG]], <4 x float> %{{.+}}, 
<4 x float> %{{.+}})
+  // CHECK: [[A:%.+]] = extractelement <4 x float> [[NEG]], i64 0
+  // CHECK: extractelement <4 x float> %{{.*}}, i64 0
+  // CHECK: extractelement <4 x float> %{{.*}}, i64 0
+  // CHECK: call float @llvm.fma.f32(float [[A]], float %{{.*}}, float %{{.*}})
+  // CHECK: insertelement <4 x float> 

r336415 - [ms] Fix mangling of string literals used to initialize arrays larger or smaller than the literal

2018-07-06 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Thu Jul  5 23:54:16 2018
New Revision: 336415

URL: http://llvm.org/viewvc/llvm-project?rev=336415=rev
Log:
[ms] Fix mangling of string literals used to initialize arrays larger or 
smaller than the literal

A Chromium developer reported a bug which turned out to be a mangling
collision between these two literals:

  char s[] = "foo";
  char t[32] = "foo";

They may look the same, but for the initialization of t we will (under
some circumstances) use a literal that's extended with zeros, and
both the length and those zeros should be accounted for by the mangling.

This actually makes the mangling code simpler: where it previously had
special logic for null terminators, which are not part of the
StringLiteral, that is now covered by the general algorithm.

(The problem was reported at https://crbug.com/857442)

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

Added:
cfe/trunk/test/CodeGen/mangle-ms-string-literals.c
Modified:
cfe/trunk/lib/AST/MicrosoftMangle.cpp

Modified: cfe/trunk/lib/AST/MicrosoftMangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/MicrosoftMangle.cpp?rev=336415=336414=336415=diff
==
--- cfe/trunk/lib/AST/MicrosoftMangle.cpp (original)
+++ cfe/trunk/lib/AST/MicrosoftMangle.cpp Thu Jul  5 23:54:16 2018
@@ -3171,7 +3171,7 @@ void MicrosoftMangleContextImpl::mangleS
   //  ::=   # the length of the literal
   //
   // ::= + @  # crc of the literal 
including
-  //  # null-terminator
+  //  # trailing null bytes
   //
   //  ::=# uninteresting 
character
   //  ::= '?$'   # these two nibbles
@@ -3186,6 +3186,18 @@ void MicrosoftMangleContextImpl::mangleS
   MicrosoftCXXNameMangler Mangler(*this, Out);
   Mangler.getStream() << "??_C@_";
 
+  // The actual string length might be different from that of the string 
literal
+  // in cases like:
+  // char foo[3] = "foobar";
+  // char bar[42] = "foobar";
+  // Where it is truncated or zero-padded to fit the array. This is the length
+  // used for mangling, and any trailing null-bytes also need to be mangled.
+  unsigned StringLength = getASTContext()
+  .getAsConstantArrayType(SL->getType())
+  ->getSize()
+  .getZExtValue();
+  unsigned StringByteLength = StringLength * SL->getCharByteWidth();
+
   // : The "kind" of string literal is encoded into the mangled 
name.
   if (SL->isWide())
 Mangler.getStream() << '1';
@@ -3193,14 +3205,13 @@ void MicrosoftMangleContextImpl::mangleS
 Mangler.getStream() << '0';
 
   // : The next part of the mangled name consists of the length
-  // of the string.
-  // The StringLiteral does not consider the NUL terminator byte(s) but the
-  // mangling does.
-  // N.B. The length is in terms of bytes, not characters.
-  Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
+  // of the string in bytes.
+  Mangler.mangleNumber(StringByteLength);
 
   auto GetLittleEndianByte = [](unsigned Index) {
 unsigned CharByteWidth = SL->getCharByteWidth();
+if (Index / CharByteWidth >= SL->getLength())
+  return static_cast(0);
 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
 unsigned OffsetInCodeUnit = Index % CharByteWidth;
 return static_cast((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
@@ -3208,6 +3219,8 @@ void MicrosoftMangleContextImpl::mangleS
 
   auto GetBigEndianByte = [](unsigned Index) {
 unsigned CharByteWidth = SL->getCharByteWidth();
+if (Index / CharByteWidth >= SL->getLength())
+  return static_cast(0);
 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
 unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
 return static_cast((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
@@ -3215,15 +3228,9 @@ void MicrosoftMangleContextImpl::mangleS
 
   // CRC all the bytes of the StringLiteral.
   llvm::JamCRC JC;
-  for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
+  for (unsigned I = 0, E = StringByteLength; I != E; ++I)
 JC.update(GetLittleEndianByte(I));
 
-  // The NUL terminator byte(s) were not present earlier,
-  // we need to manually process those bytes into the CRC.
-  for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
-   ++NullTerminator)
-JC.update('\x00');
-
   // : The CRC is encoded utilizing the standard number mangling
   // scheme.
   Mangler.mangleNumber(JC.getCRC());
@@ -3260,18 +3267,13 @@ void MicrosoftMangleContextImpl::mangleS
 
   // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
   unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
-  unsigned NumBytesToMangle = std::min(MaxBytesToMangle, SL->getByteLength());
-  for (unsigned I = 0; I != NumBytesToMangle; ++I)
+  

[PATCH] D48928: [ms] Fix mangling of string literals used to initialize arrays larger or smaller than the literal

2018-07-06 Thread Hans Wennborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
hans marked 2 inline comments as done.
Closed by commit rC336415: [ms] Fix mangling of string literals used to 
initialize arrays larger or… (authored by hans, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D48928?vs=154082=154359#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48928

Files:
  lib/AST/MicrosoftMangle.cpp
  test/CodeGen/mangle-ms-string-literals.c

Index: lib/AST/MicrosoftMangle.cpp
===
--- lib/AST/MicrosoftMangle.cpp
+++ lib/AST/MicrosoftMangle.cpp
@@ -3171,7 +3171,7 @@
   //  ::=   # the length of the literal
   //
   // ::= + @  # crc of the literal including
-  //  # null-terminator
+  //  # trailing null bytes
   //
   //  ::=# uninteresting character
   //  ::= '?$'   # these two nibbles
@@ -3186,44 +3186,51 @@
   MicrosoftCXXNameMangler Mangler(*this, Out);
   Mangler.getStream() << "??_C@_";
 
+  // The actual string length might be different from that of the string literal
+  // in cases like:
+  // char foo[3] = "foobar";
+  // char bar[42] = "foobar";
+  // Where it is truncated or zero-padded to fit the array. This is the length
+  // used for mangling, and any trailing null-bytes also need to be mangled.
+  unsigned StringLength = getASTContext()
+  .getAsConstantArrayType(SL->getType())
+  ->getSize()
+  .getZExtValue();
+  unsigned StringByteLength = StringLength * SL->getCharByteWidth();
+
   // : The "kind" of string literal is encoded into the mangled name.
   if (SL->isWide())
 Mangler.getStream() << '1';
   else
 Mangler.getStream() << '0';
 
   // : The next part of the mangled name consists of the length
-  // of the string.
-  // The StringLiteral does not consider the NUL terminator byte(s) but the
-  // mangling does.
-  // N.B. The length is in terms of bytes, not characters.
-  Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
+  // of the string in bytes.
+  Mangler.mangleNumber(StringByteLength);
 
   auto GetLittleEndianByte = [](unsigned Index) {
 unsigned CharByteWidth = SL->getCharByteWidth();
+if (Index / CharByteWidth >= SL->getLength())
+  return static_cast(0);
 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
 unsigned OffsetInCodeUnit = Index % CharByteWidth;
 return static_cast((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
   };
 
   auto GetBigEndianByte = [](unsigned Index) {
 unsigned CharByteWidth = SL->getCharByteWidth();
+if (Index / CharByteWidth >= SL->getLength())
+  return static_cast(0);
 uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
 unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
 return static_cast((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
   };
 
   // CRC all the bytes of the StringLiteral.
   llvm::JamCRC JC;
-  for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
+  for (unsigned I = 0, E = StringByteLength; I != E; ++I)
 JC.update(GetLittleEndianByte(I));
 
-  // The NUL terminator byte(s) were not present earlier,
-  // we need to manually process those bytes into the CRC.
-  for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
-   ++NullTerminator)
-JC.update('\x00');
-
   // : The CRC is encoded utilizing the standard number mangling
   // scheme.
   Mangler.mangleNumber(JC.getCRC());
@@ -3260,18 +3267,13 @@
 
   // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
   unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
-  unsigned NumBytesToMangle = std::min(MaxBytesToMangle, SL->getByteLength());
-  for (unsigned I = 0; I != NumBytesToMangle; ++I)
+  unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
+  for (unsigned I = 0; I != NumBytesToMangle; ++I) {
 if (SL->isWide())
   MangleByte(GetBigEndianByte(I));
 else
   MangleByte(GetLittleEndianByte(I));
-
-  // Encode the NUL terminator if there is room.
-  if (NumBytesToMangle < MaxBytesToMangle)
-for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
- ++NullTerminator)
-  MangleByte(0);
+  }
 
   Mangler.getStream() << '@';
 }
Index: test/CodeGen/mangle-ms-string-literals.c
===
--- test/CodeGen/mangle-ms-string-literals.c
+++ test/CodeGen/mangle-ms-string-literals.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -x c -emit-llvm %s -o - -triple=i386-pc-win32 | FileCheck %s
+// RUN: %clang_cc1 -x c -emit-llvm %s -o - -triple=x86_64-pc-win32 | FileCheck %s
+
+void crbug857442(int x) {
+  // Make sure to handle truncated or padded literals. The truncation is only valid in C.
+  struct {int x; 

[PATCH] D48827: [clang-format ]Extend IncludeCategories regex documentation

2018-07-06 Thread Wim Leflere via Phabricator via cfe-commits
WimLeflere added a comment.

Who can merge these changes?
Or does this happen automatically?


Repository:
  rC Clang

https://reviews.llvm.org/D48827



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


[PATCH] D48928: [ms] Fix mangling of string literals used to initialize arrays larger or smaller than the literal

2018-07-06 Thread Hans Wennborg via Phabricator via cfe-commits
hans marked 3 inline comments as done.
hans added inline comments.



Comment at: lib/AST/MicrosoftMangle.cpp:3198
+  ->getSize()
+  .getZExtValue();
+

thakis wrote:
> nit: Also do `unsigned StingByteLength = StringLength * 
> SL->getCharByteWidth()` here and use it the 3 times you have that computation 
> below
Good idea, thanks!



Comment at: lib/AST/MicrosoftMangle.cpp:3210
 
-  auto GetLittleEndianByte = [](unsigned Index) {
+  auto GetLittleEndianByte = [, StringLength](unsigned Index) {
 unsigned CharByteWidth = SL->getCharByteWidth();

thakis wrote:
> You're capturing StringLength here, but then you don't use it in the lambda 
> body.
Oops, a leftover from an older version of the patch. Removed.


https://reviews.llvm.org/D48928



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


[PATCH] D32747: [Analyzer] Iterator Checker - Part 3: Invalidation check, first for (copy) assignments

2018-07-06 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware marked an inline comment as not done.
baloghadamsoftware added inline comments.



Comment at: test/Analysis/invalidated-iterator.cpp:32
+  *i0; // expected-warning{{Invalidated iterator accessed}}
+}

whisperity wrote:
> This might not be applicable here, but isn't there a test case for copy 
> operations where the iterator isn't invalidated? Something of a positive test 
> to be added here. My only idea is something with weird reference-to-pointer 
> magic. Might not worth the hassle.
Accoring to the rules (on STL containers) if a container is overwritten using a 
copy assignment,  all its iterators become invalidated. So I cannot imagine a 
positive test case here.


https://reviews.llvm.org/D32747



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


[PATCH] D32747: [Analyzer] Iterator Checker - Part 3: Invalidation check, first for (copy) assignments

2018-07-06 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware updated this revision to Diff 154358.
baloghadamsoftware marked 2 inline comments as done.
baloghadamsoftware added a comment.

Re-upload because of a mistake.


https://reviews.llvm.org/D32747

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
  test/Analysis/Inputs/system-header-simulator-cxx.h
  test/Analysis/diagnostics/explicit-suppression.cpp
  test/Analysis/invalidated-iterator.cpp

Index: test/Analysis/invalidated-iterator.cpp
===
--- /dev/null
+++ test/Analysis/invalidated-iterator.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,cplusplus,alpha.cplusplus.InvalidatedIterator -analyzer-eagerly-assume -analyzer-config aggressive-relational-comparison-simplification=true -analyzer-config c++-container-inlining=false %s -verify
+// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,cplusplus,alpha.cplusplus.InvalidatedIterator -analyzer-eagerly-assume -analyzer-config aggressive-relational-comparison-simplification=true -analyzer-config c++-container-inlining=true -DINLINE=1 %s -verify
+
+#include "Inputs/system-header-simulator-cxx.h"
+
+void bad_copy_assign_operator_list1(std::list ,
+const std::list ) {
+  auto i0 = L1.cbegin();
+  L1 = L2;
+  *i0; // expected-warning{{Invalidated iterator accessed}}
+}
+
+void bad_copy_assign_operator_vector1(std::vector ,
+  const std::vector ) {
+  auto i0 = V1.cbegin();
+  V1 = V2;
+  *i0; // expected-warning{{Invalidated iterator accessed}}
+}
+
+void bad_copy_assign_operator_deque1(std::deque ,
+ const std::deque ) {
+  auto i0 = D1.cbegin();
+  D1 = D2;
+  *i0; // expected-warning{{Invalidated iterator accessed}}
+}
+
+void bad_copy_assign_operator_forward_list1(std::forward_list ,
+const std::forward_list ) {
+  auto i0 = FL1.cbegin();
+  FL1 = FL2;
+  *i0; // expected-warning{{Invalidated iterator accessed}}
+}
Index: test/Analysis/diagnostics/explicit-suppression.cpp
===
--- test/Analysis/diagnostics/explicit-suppression.cpp
+++ test/Analysis/diagnostics/explicit-suppression.cpp
@@ -19,6 +19,6 @@
 void testCopyNull(C *I, C *E) {
   std::copy(I, E, (C *)0);
 #ifndef SUPPRESSED
-  // expected-warning@../Inputs/system-header-simulator-cxx.h:514 {{Called C++ object pointer is null}}
+  // expected-warning@../Inputs/system-header-simulator-cxx.h:554 {{Called C++ object pointer is null}}
 #endif
 }
Index: test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- test/Analysis/Inputs/system-header-simulator-cxx.h
+++ test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -252,6 +252,15 @@
   return size_t(_finish - _start);
 }
 
+vector& operator=(const vector );
+vector& operator=(vector &);
+vector& operator=(std::initializer_list ilist);
+
+void assign(size_type count, const T );
+template 
+void assign(InputIterator first, InputIterator last);
+void assign(std::initializer_list ilist);
+
 void clear();
 
 void push_back(const T );
@@ -301,8 +310,21 @@
 list& operator=(list &);
 list& operator=(std::initializer_list ilist);
 
+void assign(size_type count, const T );
+template 
+void assign(InputIterator first, InputIterator last);
+void assign(std::initializer_list ilist);
+
 void clear();
 
+void push_back(const T );
+void push_back(T &);
+void pop_back();
+
+void push_front(const T );
+void push_front(T &);
+void pop_front();
+
 iterator begin() { return iterator(_start); }
 const_iterator begin() const { return const_iterator(_start); }
 const_iterator cbegin() const { return const_iterator(_start); }
@@ -338,6 +360,15 @@
   return size_t(_finish - _start);
 }
 
+deque& operator=(const deque );
+deque& operator=(deque &);
+deque& operator=(std::initializer_list ilist);
+
+void assign(size_type count, const T );
+template 
+void assign(InputIterator first, InputIterator last);
+void assign(std::initializer_list ilist);
+
 void clear();
 
 void push_back(const T );
@@ -351,11 +382,11 @@
 T [](size_t n) {
   return _start[n];
 }
-
+
 const T [](size_t n) const {
   return _start[n];
 }
-
+
 iterator begin() { return iterator(_start); }
 const_iterator begin() const { return const_iterator(_start); }
 const_iterator cbegin() const { return const_iterator(_start); }
@@ -367,7 +398,7 @@
 T& back() { return *(end() - 1); }
 const T& back() const { return *(end() - 1); }
   };
-  
+
   template
   class forward_list {
 struct __item {
@@ -387,6 +418,15 @@
 forward_list(forward_list &);
 

[PATCH] D48831: alpha.unix.cstring.OutOfBounds checker enable/disable fix

2018-07-06 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware accepted this revision.
baloghadamsoftware added a comment.
This revision is now accepted and ready to land.

LGTM! But wait for Artem's acceptance before submitting.




Comment at: lib/StaticAnalyzer/Checkers/CStringChecker.cpp:311
+if (!Filter.CheckCStringOutOfBounds)
+  return StOutBound;
 

dkrupp wrote:
> NoQ wrote:
> > Could we preserve the other portion of the assertion on this branch? I.e., 
> > `assert(Filter.CheckCStringNullArg)`.
> > 
> > Additionally, do you really want to continue analysis on this path? Maybe 
> > `return nullptr` to sink?
> I was unsure whether to return nullptr or StOutBound. I thought that 
> alpha.unix.cstring.OutOfBounds is in alpha because it may falsely detect 
> buffer overflows and then we would cut the path unnecessarily.  
> But OK, it is safer this way.
> 
> I could not put back the assertion, because if only unix.Malloc checker is 
> enabled (and CStringOutOfBounds and CStringNullArg are not) the assertion is 
> not true.
> 
I think the assertion could be preserved after the early exit, but it has no 
point to repeat the same condition in subsequent lines.


https://reviews.llvm.org/D48831



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


[PATCH] D32747: [Analyzer] Iterator Checker - Part 3: Invalidation check, first for (copy) assignments

2018-07-06 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware updated this revision to Diff 154357.
baloghadamsoftware added a comment.

Updated according to the comments.


https://reviews.llvm.org/D32747

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/IteratorChecker.cpp
  test/Analysis/Inputs/system-header-simulator-cxx.h
  test/Analysis/diagnostics/explicit-suppression.cpp
  test/Analysis/invalidated-iterator.cpp
  test/Analysis/iterator-range.cpp

Index: test/Analysis/iterator-range.cpp
===
--- test/Analysis/iterator-range.cpp
+++ test/Analysis/iterator-range.cpp
@@ -47,7 +47,13 @@
   *--i; // expected-warning{{Iterator accessed outside of its range}}
 }
 
-void copy(const std::vector ) {
+void good_copy(const std::vector ) {
+  auto i1 = v.begin();
+  auto i2 = i1;
+  *i2; // no-warning
+}
+
+void bad_copy(const std::vector ) {
   auto i1 = v.end();
   auto i2 = i1;
   *i2; // expected-warning{{Iterator accessed outside of its range}}
Index: test/Analysis/invalidated-iterator.cpp
===
--- /dev/null
+++ test/Analysis/invalidated-iterator.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,cplusplus,alpha.cplusplus.InvalidatedIterator -analyzer-eagerly-assume -analyzer-config aggressive-relational-comparison-simplification=true -analyzer-config c++-container-inlining=false %s -verify
+// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,cplusplus,alpha.cplusplus.InvalidatedIterator -analyzer-eagerly-assume -analyzer-config aggressive-relational-comparison-simplification=true -analyzer-config c++-container-inlining=true -DINLINE=1 %s -verify
+
+#include "Inputs/system-header-simulator-cxx.h"
+
+void bad_copy_assign_operator_list1(std::list ,
+const std::list ) {
+  auto i0 = L1.cbegin();
+  L1 = L2;
+  *i0; // expected-warning{{Invalidated iterator accessed}}
+}
+
+void bad_copy_assign_operator_vector1(std::vector ,
+  const std::vector ) {
+  auto i0 = V1.cbegin();
+  V1 = V2;
+  *i0; // expected-warning{{Invalidated iterator accessed}}
+}
+
+void bad_copy_assign_operator_deque1(std::deque ,
+ const std::deque ) {
+  auto i0 = D1.cbegin();
+  D1 = D2;
+  *i0; // expected-warning{{Invalidated iterator accessed}}
+}
+
+void bad_copy_assign_operator_forward_list1(std::forward_list ,
+const std::forward_list ) {
+  auto i0 = FL1.cbegin();
+  FL1 = FL2;
+  *i0; // expected-warning{{Invalidated iterator accessed}}
+}
Index: test/Analysis/diagnostics/explicit-suppression.cpp
===
--- test/Analysis/diagnostics/explicit-suppression.cpp
+++ test/Analysis/diagnostics/explicit-suppression.cpp
@@ -19,6 +19,6 @@
 void testCopyNull(C *I, C *E) {
   std::copy(I, E, (C *)0);
 #ifndef SUPPRESSED
-  // expected-warning@../Inputs/system-header-simulator-cxx.h:514 {{Called C++ object pointer is null}}
+  // expected-warning@../Inputs/system-header-simulator-cxx.h:554 {{Called C++ object pointer is null}}
 #endif
 }
Index: test/Analysis/Inputs/system-header-simulator-cxx.h
===
--- test/Analysis/Inputs/system-header-simulator-cxx.h
+++ test/Analysis/Inputs/system-header-simulator-cxx.h
@@ -252,6 +252,15 @@
   return size_t(_finish - _start);
 }
 
+vector& operator=(const vector );
+vector& operator=(vector &);
+vector& operator=(std::initializer_list ilist);
+
+void assign(size_type count, const T );
+template 
+void assign(InputIterator first, InputIterator last);
+void assign(std::initializer_list ilist);
+
 void clear();
 
 void push_back(const T );
@@ -301,8 +310,21 @@
 list& operator=(list &);
 list& operator=(std::initializer_list ilist);
 
+void assign(size_type count, const T );
+template 
+void assign(InputIterator first, InputIterator last);
+void assign(std::initializer_list ilist);
+
 void clear();
 
+void push_back(const T );
+void push_back(T &);
+void pop_back();
+
+void push_front(const T );
+void push_front(T &);
+void pop_front();
+
 iterator begin() { return iterator(_start); }
 const_iterator begin() const { return const_iterator(_start); }
 const_iterator cbegin() const { return const_iterator(_start); }
@@ -338,6 +360,15 @@
   return size_t(_finish - _start);
 }
 
+deque& operator=(const deque );
+deque& operator=(deque &);
+deque& operator=(std::initializer_list ilist);
+
+void assign(size_type count, const T );
+template 
+void assign(InputIterator first, InputIterator last);
+void assign(std::initializer_list ilist);
+
 void clear();
 
 void push_back(const T );
@@ -351,11 +382,11 @@
 T [](size_t n) {