[PATCH] D59812: [analyzer] PR41185: Fix regression where __builtin_* functions weren't recognized

2019-04-17 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus updated this revision to Diff 195617.
Szelethus retitled this revision from "[analyzer] Detect usages of unsafe I/O 
functions - Bug fixing" to "[analyzer] PR41185: Fix regression where 
__builtin_* functions weren't recognized".
Szelethus edited the summary of this revision.
Szelethus edited reviewers, added: baloghadamsoftware, alexfh; removed: 
zaks.anna.
Szelethus set the repository for this revision to rC Clang.
Szelethus edited projects, added clang; removed LLVM.
Szelethus added a comment.
Herald added subscribers: cfe-commits, kristina.

Implemented the fix I proposed in my earlier comment. While I was there, I 
prettified some of the other tests, and also made sure that the core package is 
enabled in their run lines.


Repository:
  rC Clang

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

https://reviews.llvm.org/D59812

Files:
  lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
  test/Analysis/security-syntax-checks-no-emit.c
  test/Analysis/security-syntax-checks.c
  test/Analysis/security-syntax-checks.m

Index: test/Analysis/security-syntax-checks.m
===
--- test/Analysis/security-syntax-checks.m
+++ test/Analysis/security-syntax-checks.m
@@ -1,11 +1,48 @@
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DUSE_BUILTINS -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DVARIANT -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DUSE_BUILTINS -DVARIANT -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -DUSE_BUILTINS -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -DVARIANT -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -DUSE_BUILTINS -DVARIANT -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -DVARIANT \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -DUSE_BUILTINS -DVARIANT \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -DVARIANT \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -DUSE_BUILTINS -DVARIANT \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
 
 #ifdef USE_BUILTINS
 # define BUILTIN(f) __builtin_ ## f
@@ -165,7 +202,7 @@
 
 void test_strcpy() {
   char x[4];
-  char *y;
+  char *y = 0;
 
   strcpy(x, y); //expected-warning{{Call to function 'strcpy' is insecure as it does not provide bounding of the memory buffer. Replace unbounded copy functions with analogous functions that support length arguments such as 'strlcpy'. CWE-119}}
 }
@@ -204,7 +241,7 @@
 
 void test_strcat() {
   char x[4];
-  char *y;
+  char *y = 0;
 
   strcat(x, y); //expected-warning{{Call to function 'strcat' is insecure as it does not provide bounding of the memory buffer. Replace unbounded 

[PATCH] D60819: [clangd] Strip the ' [some-check-name]' suffix from clang-tidy diagnostics. The check name is reported in Diagnostic.code.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE358612: [clangd] Strip the  [some-check-name] 
suffix from clang-tidy diagnostics. The… (authored by sammccall, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60819?vs=195548=195625#toc

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60819

Files:
  clangd/Diagnostics.cpp
  test/clangd/diagnostics.test
  unittests/clangd/DiagnosticsTests.cpp


Index: clangd/Diagnostics.cpp
===
--- clangd/Diagnostics.cpp
+++ clangd/Diagnostics.cpp
@@ -350,6 +350,17 @@
   if (!TidyDiag.empty()) {
 Diag.Name = std::move(TidyDiag);
 Diag.Source = Diag::ClangTidy;
+// clang-tidy bakes the name into diagnostic messages. Strip it out.
+// It would be much nicer to make clang-tidy not do this.
+auto CleanMessage = [&](std::string ) {
+  StringRef Rest(Msg);
+  if (Rest.consume_back("]") && Rest.consume_back(Diag.Name) &&
+  Rest.consume_back(" ["))
+Msg.resize(Rest.size());
+};
+CleanMessage(Diag.Message);
+for (auto& Note : Diag.Notes)
+  CleanMessage(Note.Message);
 continue;
   }
 }
Index: test/clangd/diagnostics.test
===
--- test/clangd/diagnostics.test
+++ test/clangd/diagnostics.test
@@ -23,7 +23,7 @@
 # CHECK-NEXT:  },
 # CHECK-NEXT:  {
 # CHECK-NEXT:"code": "bugprone-sizeof-expression",
-# CHECK-NEXT:"message": "Suspicious usage of 'sizeof(K)'; did you mean 
'K'? [bugprone-sizeof-expression]",
+# CHECK-NEXT:"message": "Suspicious usage of 'sizeof(K)'; did you mean 
'K'?",
 # CHECK-NEXT:"range": {
 # CHECK-NEXT:  "end": {
 # CHECK-NEXT:"character": 12,
Index: unittests/clangd/DiagnosticsTests.cpp
===
--- unittests/clangd/DiagnosticsTests.cpp
+++ unittests/clangd/DiagnosticsTests.cpp
@@ -176,23 +176,21 @@
   UnorderedElementsAre(
   AllOf(Diag(Test.range("deprecated"),
  "inclusion of deprecated C++ header 'assert.h'; consider "
- "using 'cassert' instead [modernize-deprecated-headers]"),
+ "using 'cassert' instead"),
 DiagSource(Diag::ClangTidy),
 DiagName("modernize-deprecated-headers"),
 WithFix(Fix(Test.range("deprecated"), "",
 "change '\"assert.h\"' to ''"))),
   Diag(Test.range("doubled"),
-   "suspicious usage of 'sizeof(sizeof(...))' "
-   "[bugprone-sizeof-expression]"),
+   "suspicious usage of 'sizeof(sizeof(...))'"),
   AllOf(
   Diag(Test.range("macroarg"),
"side effects in the 1st macro argument 'X' are repeated in 
"
-   "macro expansion [bugprone-macro-repeated-side-effects]"),
+   "macro expansion"),
   DiagSource(Diag::ClangTidy),
   DiagName("bugprone-macro-repeated-side-effects"),
-  WithNote(Diag(Test.range("macrodef"),
-"macro 'SQUARE' defined here "
-"[bugprone-macro-repeated-side-effects]"))),
+  WithNote(
+  Diag(Test.range("macrodef"), "macro 'SQUARE' defined 
here"))),
   Diag(Test.range("macroarg"),
"multiple unsequenced modifications to 'y'")));
 }


Index: clangd/Diagnostics.cpp
===
--- clangd/Diagnostics.cpp
+++ clangd/Diagnostics.cpp
@@ -350,6 +350,17 @@
   if (!TidyDiag.empty()) {
 Diag.Name = std::move(TidyDiag);
 Diag.Source = Diag::ClangTidy;
+// clang-tidy bakes the name into diagnostic messages. Strip it out.
+// It would be much nicer to make clang-tidy not do this.
+auto CleanMessage = [&](std::string ) {
+  StringRef Rest(Msg);
+  if (Rest.consume_back("]") && Rest.consume_back(Diag.Name) &&
+  Rest.consume_back(" ["))
+Msg.resize(Rest.size());
+};
+CleanMessage(Diag.Message);
+for (auto& Note : Diag.Notes)
+  CleanMessage(Note.Message);
 continue;
   }
 }
Index: test/clangd/diagnostics.test
===
--- test/clangd/diagnostics.test
+++ test/clangd/diagnostics.test
@@ -23,7 +23,7 @@
 # CHECK-NEXT:  },
 # CHECK-NEXT:  {
 # CHECK-NEXT:"code": "bugprone-sizeof-expression",
-# CHECK-NEXT:"message": "Suspicious usage of 'sizeof(K)'; did you mean 'K'? [bugprone-sizeof-expression]",
+# CHECK-NEXT:"message": "Suspicious usage of 

[clang-tools-extra] r358612 - [clangd] Strip the ' [some-check-name]' suffix from clang-tidy diagnostics. The check name is reported in Diagnostic.code.

2019-04-17 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Wed Apr 17 13:15:08 2019
New Revision: 358612

URL: http://llvm.org/viewvc/llvm-project?rev=358612=rev
Log:
[clangd] Strip the ' [some-check-name]' suffix from clang-tidy diagnostics. The 
check name is reported in Diagnostic.code.

Reviewers: kadircet

Subscribers: ilya-biryukov, ioeric, MaskRay, jkorous, arphaman, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/Diagnostics.cpp
clang-tools-extra/trunk/test/clangd/diagnostics.test
clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp

Modified: clang-tools-extra/trunk/clangd/Diagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Diagnostics.cpp?rev=358612=358611=358612=diff
==
--- clang-tools-extra/trunk/clangd/Diagnostics.cpp (original)
+++ clang-tools-extra/trunk/clangd/Diagnostics.cpp Wed Apr 17 13:15:08 2019
@@ -350,6 +350,17 @@ std::vector StoreDiags::take(const
   if (!TidyDiag.empty()) {
 Diag.Name = std::move(TidyDiag);
 Diag.Source = Diag::ClangTidy;
+// clang-tidy bakes the name into diagnostic messages. Strip it out.
+// It would be much nicer to make clang-tidy not do this.
+auto CleanMessage = [&](std::string ) {
+  StringRef Rest(Msg);
+  if (Rest.consume_back("]") && Rest.consume_back(Diag.Name) &&
+  Rest.consume_back(" ["))
+Msg.resize(Rest.size());
+};
+CleanMessage(Diag.Message);
+for (auto& Note : Diag.Notes)
+  CleanMessage(Note.Message);
 continue;
   }
 }

Modified: clang-tools-extra/trunk/test/clangd/diagnostics.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/diagnostics.test?rev=358612=358611=358612=diff
==
--- clang-tools-extra/trunk/test/clangd/diagnostics.test (original)
+++ clang-tools-extra/trunk/test/clangd/diagnostics.test Wed Apr 17 13:15:08 
2019
@@ -23,7 +23,7 @@
 # CHECK-NEXT:  },
 # CHECK-NEXT:  {
 # CHECK-NEXT:"code": "bugprone-sizeof-expression",
-# CHECK-NEXT:"message": "Suspicious usage of 'sizeof(K)'; did you mean 
'K'? [bugprone-sizeof-expression]",
+# CHECK-NEXT:"message": "Suspicious usage of 'sizeof(K)'; did you mean 
'K'?",
 # CHECK-NEXT:"range": {
 # CHECK-NEXT:  "end": {
 # CHECK-NEXT:"character": 12,

Modified: clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp?rev=358612=358611=358612=diff
==
--- clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp Wed Apr 17 
13:15:08 2019
@@ -176,23 +176,21 @@ TEST(DiagnosticsTest, ClangTidy) {
   UnorderedElementsAre(
   AllOf(Diag(Test.range("deprecated"),
  "inclusion of deprecated C++ header 'assert.h'; consider "
- "using 'cassert' instead [modernize-deprecated-headers]"),
+ "using 'cassert' instead"),
 DiagSource(Diag::ClangTidy),
 DiagName("modernize-deprecated-headers"),
 WithFix(Fix(Test.range("deprecated"), "",
 "change '\"assert.h\"' to ''"))),
   Diag(Test.range("doubled"),
-   "suspicious usage of 'sizeof(sizeof(...))' "
-   "[bugprone-sizeof-expression]"),
+   "suspicious usage of 'sizeof(sizeof(...))'"),
   AllOf(
   Diag(Test.range("macroarg"),
"side effects in the 1st macro argument 'X' are repeated in 
"
-   "macro expansion [bugprone-macro-repeated-side-effects]"),
+   "macro expansion"),
   DiagSource(Diag::ClangTidy),
   DiagName("bugprone-macro-repeated-side-effects"),
-  WithNote(Diag(Test.range("macrodef"),
-"macro 'SQUARE' defined here "
-"[bugprone-macro-repeated-side-effects]"))),
+  WithNote(
+  Diag(Test.range("macrodef"), "macro 'SQUARE' defined 
here"))),
   Diag(Test.range("macroarg"),
"multiple unsequenced modifications to 'y'")));
 }


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


[PATCH] D60822: [clangd] Use shorter, more recognizable codes for diagnostics.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE358611: [clangd] Use shorter, more recognizable codes for 
diagnostics. (authored by sammccall, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60822?vs=195623=195624#toc

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60822

Files:
  clangd/Diagnostics.cpp
  test/clangd/compile-commands-path-in-initialize.test
  test/clangd/diagnostic-category.test
  test/clangd/diagnostics.test
  test/clangd/did-change-configuration-params.test
  test/clangd/execute-command.test
  test/clangd/fixits-codeaction.test
  test/clangd/fixits-command.test
  test/clangd/fixits-embed-in-diagnostic.test
  unittests/clangd/DiagnosticsTests.cpp

Index: clangd/Diagnostics.cpp
===
--- clangd/Diagnostics.cpp
+++ clangd/Diagnostics.cpp
@@ -331,7 +331,17 @@
   // Fill in name/source now that we have all the context needed to map them.
   for (auto  : Output) {
 if (const char *ClangDiag = getDiagnosticCode(Diag.ID)) {
-  Diag.Name = ClangDiag;
+  // Warnings controlled by -Wfoo are better recognized by that name.
+  StringRef Warning = DiagnosticIDs::getWarningOptionForDiag(Diag.ID);
+  if (!Warning.empty()) {
+Diag.Name = ("-W" + Warning).str();
+  } else {
+StringRef Name(ClangDiag);
+// Almost always an error, with a name like err_enum_class_reference.
+// Drop the err_ prefix for brevity.
+Name.consume_front("err_");
+Diag.Name = Name;
+  }
   Diag.Source = Diag::Clang;
   continue;
 }
Index: test/clangd/fixits-codeaction.test
===
--- test/clangd/fixits-codeaction.test
+++ test/clangd/fixits-codeaction.test
@@ -6,7 +6,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"diagnostics": [
 # CHECK-NEXT:  {
-# CHECK-NEXT:"code": "warn_condition_is_assignment",
+# CHECK-NEXT:"code": "-Wparentheses",
 # CHECK-NEXT:"message": "Using the result of an assignment as a condition without parentheses (fixes available)",
 # CHECK-NEXT:"range": {
 # CHECK-NEXT:  "end": {
@@ -25,14 +25,14 @@
 # CHECK-NEXT:"uri": "file://{{.*}}/foo.c"
 # CHECK-NEXT:  }
 ---
-{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{"textDocument":{"uri":"test:///foo.c"},"range":{"start":{"line":0,"character":13},"end":{"line":0,"character":35}},"context":{"diagnostics":[{"range":{"start": {"line": 0, "character": 32}, "end": {"line": 0, "character": 37}},"severity":2,"message":"Using the result of an assignment as a condition without parentheses (fixes available)", "code": "warn_condition_is_assignment", "source": "clang"}]}}}
+{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{"textDocument":{"uri":"test:///foo.c"},"range":{"start":{"line":0,"character":13},"end":{"line":0,"character":35}},"context":{"diagnostics":[{"range":{"start": {"line": 0, "character": 32}, "end": {"line": 0, "character": 37}},"severity":2,"message":"Using the result of an assignment as a condition without parentheses (fixes available)", "code": "-Wparentheses", "source": "clang"}]}}}
 #  CHECK:  "id": 2,
 # CHECK-NEXT:  "jsonrpc": "2.0",
 # CHECK-NEXT:  "result": [
 # CHECK-NEXT:{
 # CHECK-NEXT:  "diagnostics": [
 # CHECK-NEXT:{
-# CHECK-NEXT:  "code": "warn_condition_is_assignment",
+# CHECK-NEXT:  "code": "-Wparentheses",
 # CHECK-NEXT:  "message": "Using the result of an assignment as a condition without parentheses (fixes available)",
 # CHECK-NEXT:  "range": {
 # CHECK-NEXT:"end": {
@@ -86,7 +86,7 @@
 # CHECK-NEXT:{
 # CHECK-NEXT:  "diagnostics": [
 # CHECK-NEXT:{
-# CHECK-NEXT:  "code": "warn_condition_is_assignment",
+# CHECK-NEXT:  "code": "-Wparentheses",
 # CHECK-NEXT:  "message": "Using the result of an assignment as a condition without parentheses (fixes available)",
 # CHECK-NEXT:  "range": {
 # CHECK-NEXT:"end": {
Index: test/clangd/did-change-configuration-params.test
===
--- test/clangd/did-change-configuration-params.test
+++ test/clangd/did-change-configuration-params.test
@@ -24,7 +24,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"diagnostics": [
 # CHECK-NEXT:  {
-# CHECK-NEXT:"code": "warn_uninit_var",
+# CHECK-NEXT:"code": "-Wuninitialized",
 # CHECK-NEXT:"message": "Variable 'i' is uninitialized when used here (fix available)",
 # CHECK-NEXT:"range": {
 # CHECK-NEXT:  "end": {
Index: test/clangd/diagnostic-category.test
===
--- test/clangd/diagnostic-category.test
+++ 

[PATCH] D60822: [clangd] Use shorter, more recognizable codes for diagnostics.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D60822#1470227 , @kadircet wrote:

> I agree that these are more useful. What about also adding "-W" in front of 
> warning flags to make them more explicit and stand out from "non-flag" error 
> names?


I went back and forth on this, I think you're probably right. It's consistent 
with how clang-tidy check names vs warnings are exposed to users: "Diag text 
[-Wfoo]" and "Diag text [check-name]".
Let's see how it goes.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60822



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


[PATCH] D59168: [runtimes] Move libunwind, libc++abi and libc++ to lib/clang/ and include/

2019-04-17 Thread Petr Hosek via Phabricator via cfe-commits
phosek added a comment.

In D59168#1469186 , @jdenny wrote:

> Is there anything I can do to help this patch make progress?


I think it's ready to land. I was just waiting if anyone else wants to chime 
in, but it doesn't seem like.

I was also thinking about alternative names for the library path, specifically 
for headers we use `include/c++` but for libraries we'll now use 
`lib/clang/` which is not very consistent. I was considering 
`lib/c++/` instead but that wouldn't work for libomp and I didn't come 
up with any other better alternatives.


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

https://reviews.llvm.org/D59168



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


[PATCH] D60736: [Sema][ObjC] Don't warn about a block implicitly retaining self if the block is marked noescape

2019-04-17 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 195601.
ahatanak marked an inline comment as done.
ahatanak added a comment.

Rename function.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60736

Files:
  include/clang/AST/DeclBase.h
  include/clang/Sema/Sema.h
  lib/Parse/ParseObjc.cpp
  lib/Sema/SemaDeclObjC.cpp
  lib/Sema/SemaExpr.cpp
  test/SemaObjC/warn-implicit-self-in-block.m
  test/SemaObjCXX/warn-implicit-self-in-block.mm

Index: test/SemaObjCXX/warn-implicit-self-in-block.mm
===
--- /dev/null
+++ test/SemaObjCXX/warn-implicit-self-in-block.mm
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -x objective-c++ -std=c++11 -fobjc-arc -fblocks -Wimplicit-retain-self -verify %s
+// rdar://11194874
+
+typedef void (^BlockTy)();
+
+void noescapeFunc(__attribute__((noescape)) BlockTy);
+void escapeFunc(BlockTy);
+
+@interface Root @end
+
+@interface I : Root
+{
+  int _bar;
+}
+@end
+
+@implementation I
+  - (void)foo{
+  ^{
+   _bar = 3; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+   }();
+  }
+
+  - (void)testNested{
+noescapeFunc(^{
+  (void)_bar;
+  escapeFunc(^{
+(void)_bar; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+noescapeFunc(^{
+  (void)_bar; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+});
+(void)_bar; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+  });
+  (void)_bar;
+});
+  }
+
+  - (void)testLambdaInBlock{
+noescapeFunc(^{ [&](){ (void)_bar; }(); });
+escapeFunc(^{ [&](){ (void)_bar; }(); }); // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+  }
+@end
Index: test/SemaObjC/warn-implicit-self-in-block.m
===
--- test/SemaObjC/warn-implicit-self-in-block.m
+++ /dev/null
@@ -1,18 +0,0 @@
-// RUN: %clang_cc1 -x objective-c -fobjc-arc -fblocks -Wimplicit-retain-self -verify %s
-// rdar://11194874
-
-@interface Root @end
-
-@interface I : Root
-{
-  int _bar;
-}
-@end
-
-@implementation I
-  - (void)foo{
-  ^{
-   _bar = 3; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
-   }();
-  }
-@end
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -2575,11 +2575,9 @@
 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
   getCurFunction()->recordUseOfWeak(Result);
   }
-  if (getLangOpts().ObjCAutoRefCount) {
-if (CurContext->isClosure())
-  Diag(Loc, diag::warn_implicitly_retains_self)
-<< FixItHint::CreateInsertion(Loc, "self->");
-  }
+  if (getLangOpts().ObjCAutoRefCount)
+if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
+  ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
 
   return Result;
 }
Index: lib/Sema/SemaDeclObjC.cpp
===
--- lib/Sema/SemaDeclObjC.cpp
+++ lib/Sema/SemaDeclObjC.cpp
@@ -359,6 +359,7 @@
 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
 /// and user declared, in the method definition's AST.
 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
+  ImplicitlyRetainedSelfLocs.clear();
   assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
   ObjCMethodDecl *MDecl = dyn_cast_or_null(D);
 
@@ -494,6 +495,35 @@
   }
 }
 
+void Sema::ActOnEndOfObjCMethodDef() {
+  llvm::DenseMap EscapeInfo;
+
+  auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
+if (EscapeInfo.count(BD))
+  return EscapeInfo[BD];
+
+bool R = false;
+const BlockDecl *CurBD = BD;
+
+do {
+  R = R || !CurBD->doesNotEscape();
+  if (R)
+break;
+  CurBD = CurBD->getParent()->getInnermostBlockDecl();
+} while (CurBD);
+
+return EscapeInfo[BD] = R;
+  };
+
+  // If the location where 'self' is implicitly retained is inside a escaping
+  // block, emit a diagnostic.
+  for (const std::pair  :
+   ImplicitlyRetainedSelfLocs)
+if (IsOrNestedInEscapingBlock(P.second))
+  Diag(P.first, diag::warn_implicitly_retains_self)
+  << FixItHint::CreateInsertion(P.first, "self->");
+}
+
 namespace {
 
 // Callback to only accept typo corrections that are Objective-C classes.
Index: lib/Parse/ParseObjc.cpp
===
--- lib/Parse/ParseObjc.cpp
+++ 

[PATCH] D60543: [clang] Add matcher for subclasses of Objective-C interfaces 

2019-04-17 Thread Jordan Rose via Phabricator via cfe-commits
jordan_rose added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:1479
+/// \endcode
+AST_MATCHER_P(ObjCInterfaceDecl, isSubclassOfInterface,
+  internal::Matcher,

aaron.ballman wrote:
> jordan_rose wrote:
> > aaron.ballman wrote:
> > > stephanemoore wrote:
> > > > aaron.ballman wrote:
> > > > > stephanemoore wrote:
> > > > > > I am still uncertain about the naming.
> > > > > > 
> > > > > > `isSubclassOf` seemed too generic as that could apply to C++ 
> > > > > > classes.
> > > > > > `objcIsSubclassOf` seemed unconventional as a matcher name.
> > > > > > `isSubclassOfObjCInterface` and `isSubclassOfObjCClass` seemed 
> > > > > > awkwardly lengthy.
> > > > > > Creating a new namespace `clang::ast_matchers::objc` seemed 
> > > > > > unprecedented.
> > > > > > 
> > > > > > I am happy to change the name if you think another name would be 
> > > > > > more appropriate.
> > > > > Does ObjC use the term "derived" by any chance? We already have 
> > > > > `isDerivedFrom`, so I'm wondering if we can use that to also match on 
> > > > > an `ObjCInterfaceDecl`?
> > > > Objective-C doesn't generally use the term "derived" (for example, see 
> > > > archive of [Programming With Objective-C > Defining 
> > > > Classes](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW1)).
> > > >  With that said, I don't think it's unreasonable or incorrect to use 
> > > > the term "derived" to describe inheritance in Objective-C. The behavior 
> > > > of this matcher is also consistent with the behavior of 
> > > > `isDerivedFrom`. In order to change `isDerivedFrom`, I would also need 
> > > > to update `isSameOrDerivedFrom`. That would probably be a good thing so 
> > > > that derivation matching feature set is consistent for C++ and 
> > > > Objective-C language variants.
> > > > 
> > > > Let me take a crack at merging this into `isDerivedFrom`.
> > > I agree that if we go with `isDerivedFrom`, you should update 
> > > `isSameOrDerivedFrom` at the same time.
> > `isSubclassOf` sounds right to me, and since ObjC and C++ class hierarchies 
> > can't mix, it _should_ be okay, right? They're analogous concepts.
> > isSubclassOf sounds right to me, and since ObjC and C++ class hierarchies 
> > can't mix, it _should_ be okay, right? They're analogous concepts.
> 
> In the AST matchers, we try to overload the matchers that have similar 
> behavior. My concern is that a user will reach for `isSubclassOf()` when they 
> really mean `isDerivedFrom()` or vice versa, and only through annoying error 
> messages learns about their mistake. Given that we already have 
> `isDerivedFrom()` and renaming it would break code, I was trying to determine 
> whether using that name for both C++ derivation and ObjC derivation would be 
> acceptable.
Ah, I see what you mean. Yes, I guess it's more important to be consistent than 
to perfectly match the terminology. You will certainly confuse an ObjC-only 
developer at first by using "non-standard" terminology, but any developer has 
to learn a certain amount of compiler-isms anyway using AST matchers.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60543



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


[PATCH] D60543: [clang] Add matcher for subclasses of Objective-C interfaces 

2019-04-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:1479
+/// \endcode
+AST_MATCHER_P(ObjCInterfaceDecl, isSubclassOfInterface,
+  internal::Matcher,

jordan_rose wrote:
> aaron.ballman wrote:
> > jordan_rose wrote:
> > > aaron.ballman wrote:
> > > > jordan_rose wrote:
> > > > > aaron.ballman wrote:
> > > > > > stephanemoore wrote:
> > > > > > > aaron.ballman wrote:
> > > > > > > > stephanemoore wrote:
> > > > > > > > > I am still uncertain about the naming.
> > > > > > > > > 
> > > > > > > > > `isSubclassOf` seemed too generic as that could apply to C++ 
> > > > > > > > > classes.
> > > > > > > > > `objcIsSubclassOf` seemed unconventional as a matcher name.
> > > > > > > > > `isSubclassOfObjCInterface` and `isSubclassOfObjCClass` 
> > > > > > > > > seemed awkwardly lengthy.
> > > > > > > > > Creating a new namespace `clang::ast_matchers::objc` seemed 
> > > > > > > > > unprecedented.
> > > > > > > > > 
> > > > > > > > > I am happy to change the name if you think another name would 
> > > > > > > > > be more appropriate.
> > > > > > > > Does ObjC use the term "derived" by any chance? We already have 
> > > > > > > > `isDerivedFrom`, so I'm wondering if we can use that to also 
> > > > > > > > match on an `ObjCInterfaceDecl`?
> > > > > > > Objective-C doesn't generally use the term "derived" (for 
> > > > > > > example, see archive of [Programming With Objective-C > Defining 
> > > > > > > Classes](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW1)).
> > > > > > >  With that said, I don't think it's unreasonable or incorrect to 
> > > > > > > use the term "derived" to describe inheritance in Objective-C. 
> > > > > > > The behavior of this matcher is also consistent with the behavior 
> > > > > > > of `isDerivedFrom`. In order to change `isDerivedFrom`, I would 
> > > > > > > also need to update `isSameOrDerivedFrom`. That would probably be 
> > > > > > > a good thing so that derivation matching feature set is 
> > > > > > > consistent for C++ and Objective-C language variants.
> > > > > > > 
> > > > > > > Let me take a crack at merging this into `isDerivedFrom`.
> > > > > > I agree that if we go with `isDerivedFrom`, you should update 
> > > > > > `isSameOrDerivedFrom` at the same time.
> > > > > `isSubclassOf` sounds right to me, and since ObjC and C++ class 
> > > > > hierarchies can't mix, it _should_ be okay, right? They're analogous 
> > > > > concepts.
> > > > > isSubclassOf sounds right to me, and since ObjC and C++ class 
> > > > > hierarchies can't mix, it _should_ be okay, right? They're analogous 
> > > > > concepts.
> > > > 
> > > > In the AST matchers, we try to overload the matchers that have similar 
> > > > behavior. My concern is that a user will reach for `isSubclassOf()` 
> > > > when they really mean `isDerivedFrom()` or vice versa, and only through 
> > > > annoying error messages learns about their mistake. Given that we 
> > > > already have `isDerivedFrom()` and renaming it would break code, I was 
> > > > trying to determine whether using that name for both C++ derivation and 
> > > > ObjC derivation would be acceptable.
> > > Ah, I see what you mean. Yes, I guess it's more important to be 
> > > consistent than to perfectly match the terminology. You will certainly 
> > > confuse an ObjC-only developer at first by using "non-standard" 
> > > terminology, but any developer has to learn a certain amount of 
> > > compiler-isms anyway using AST matchers.
> > Okay, so it sounds like it wouldn't be hugely problematic to go with 
> > `isDerivedFrom()`, just that it may sound a bit confusing at first to an 
> > ObjC developer. Are there some words you think we should add to the 
> > documentation to help an ObjC developer searching for this functionality?
> I think just including "subclass" is sufficient. For example, the current doc 
> comment is
> 
> ```
> /// Matches C++ classes that are directly or indirectly derived from
> /// a class matching \c Base.
> ```
> 
> and it could be changed to something like
> 
> ```
> /// Matches C++ classes that are directly or indirectly derived from
> /// a class matching \c Base, or Objective-C classes that directly or
> /// indirectly subclass a class matching \c Base.
> ```
> 
> A little clunky, but you get what I mean.
> 
Fantastic, that makes sense to me. Thank you for weighing in!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60543



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


[PATCH] D59812: [analyzer] PR41185: Fix regression where __builtin_* functions weren't recognized

2019-04-17 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

Awesome, thanks!
LG


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

https://reviews.llvm.org/D59812



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


[PATCH] D59812: [analyzer] PR41185: Fix regression where __builtin_* functions weren't recognized

2019-04-17 Thread Kristóf Umann via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358609: [analyzer] PR41185: Fix regression where __builtin_* 
functions werent… (authored by Szelethus, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59812?vs=195619=195622#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59812

Files:
  cfe/trunk/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
  cfe/trunk/test/Analysis/security-syntax-checks-no-emit.c
  cfe/trunk/test/Analysis/security-syntax-checks.c
  cfe/trunk/test/Analysis/security-syntax-checks.m


Index: cfe/trunk/test/Analysis/security-syntax-checks-no-emit.c
===
--- cfe/trunk/test/Analysis/security-syntax-checks-no-emit.c
+++ cfe/trunk/test/Analysis/security-syntax-checks-no-emit.c
@@ -1,4 +1,7 @@
-// RUN: %clang_analyze_cc1 -triple i686-pc-linux-gnu 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
+// RUN: %clang_analyze_cc1 -triple i686-pc-linux-gnu %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
 // expected-no-diagnostics
 
 // This file complements 'security-syntax-checks.m', but tests that we omit
Index: cfe/trunk/test/Analysis/security-syntax-checks.m
===
--- cfe/trunk/test/Analysis/security-syntax-checks.m
+++ cfe/trunk/test/Analysis/security-syntax-checks.m
@@ -1,11 +1,40 @@
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DUSE_BUILTINS 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DVARIANT 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DUSE_BUILTINS 
-DVARIANT -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s 
-verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -DUSE_BUILTINS 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -DVARIANT 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -DUSE_BUILTINS 
-DVARIANT -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s 
-verify
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -DVARIANT \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -DUSE_BUILTINS -DVARIANT \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -DVARIANT \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -DUSE_BUILTINS -DVARIANT \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
 
 #ifdef USE_BUILTINS
 # define BUILTIN(f) __builtin_ ## f
Index: cfe/trunk/test/Analysis/security-syntax-checks.c
===
--- cfe/trunk/test/Analysis/security-syntax-checks.c
+++ cfe/trunk/test/Analysis/security-syntax-checks.c
@@ -0,0 +1,8 @@
+// RUN: %clang_analyze_cc1 %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI
+
+void builtin_function_call_crash_fixes(char *c) {
+  __builtin_strncpy(c, "", 6); // expected-warning{{Call to function 'strncpy' 
is insecure 

[PATCH] D60417: [libunwind] Add support for ARMv7-M architecture which uses the Thumb 2 ISA (unified syntax)

2019-04-17 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D60417#1464070 , @mstorsjo wrote:

> In D60417#1459249 , @mstorsjo wrote:
>
> > Given that, the suggested form of this patch is indeed correct - sorry for 
> > the noise.
> >
> > I can commit the patch for you, but I'd need approval by either of @EricWF, 
> > @ldionne or @mclow.lists first.
>
>
> Ping @EricWF @ldionne @mclow.lists


Ping @EricWF @ldionne @mclow.lists


Repository:
  rUNW libunwind

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

https://reviews.llvm.org/D60417



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


[PATCH] D60605: [clangd] Revamp textDocument/onTypeFormatting.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

@kadircet if you're interested in the behavior here, you can patch this in and 
try out with vscode.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60605



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


[PATCH] D60808: [analyzer] pr41335: NoStoreFuncVisitor: Fix crash when no-store event is in a body-farmed function.

2019-04-17 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

LG with a couple of nits.




Comment at: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp:582
+if (!L.hasValidLocation()) {
+  // Do we need to suppress our report for body-farmed functions as well?
+  // Or maybe attach the note to the call site instead?

Should this be marked with a FIXME?



Comment at: clang/test/Analysis/diagnostics/body-farm-crashes.c:1
+// RUN: %clang_analyze_cc1 -w -analyzer-checker=core\
+// RUN:-analyzer-output=text -verify %s

Add a space before the backslash.


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

https://reviews.llvm.org/D60808



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


[PATCH] D60736: [Sema][ObjC] Don't warn about a block implicitly retaining self if the block is marked noescape

2019-04-17 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington accepted this revision.
erik.pilkington added a comment.

LGTM too, thanks!




Comment at: lib/Sema/SemaDecl.cpp:13169
+do {
+  R = R || !CurBD->doesNotEscape();
+  if (R)

This can just be R = !CurBD->doesNotEscape();


Repository:
  rC Clang

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

https://reviews.llvm.org/D60736



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


[PATCH] D59806: [clang-tidy] Add a check for [super self] in initializers 

2019-04-17 Thread Stephane Moore via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358620: [clang-tidy] Add a check for [super self] in 
initializers  (authored by stephanemoore, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D59806?vs=194998=195643#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D59806

Files:
  clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt
  clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp
  clang-tools-extra/trunk/clang-tidy/objc/SuperSelfCheck.cpp
  clang-tools-extra/trunk/clang-tidy/objc/SuperSelfCheck.h
  clang-tools-extra/trunk/docs/ReleaseNotes.rst
  clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst
  clang-tools-extra/trunk/docs/clang-tidy/checks/objc-super-self.rst
  clang-tools-extra/trunk/test/clang-tidy/objc-super-self.m

Index: clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp
===
--- clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp
+++ clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp
@@ -13,6 +13,7 @@
 #include "AvoidSpinlockCheck.h"
 #include "ForbiddenSubclassingCheck.h"
 #include "PropertyDeclarationCheck.h"
+#include "SuperSelfCheck.h"
 
 using namespace clang::ast_matchers;
 
@@ -31,6 +32,8 @@
 "objc-forbidden-subclassing");
 CheckFactories.registerCheck(
 "objc-property-declaration");
+CheckFactories.registerCheck(
+"objc-super-self");
   }
 };
 
Index: clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt
===
--- clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt
+++ clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt
@@ -6,6 +6,7 @@
   ForbiddenSubclassingCheck.cpp
   ObjCTidyModule.cpp
   PropertyDeclarationCheck.cpp
+  SuperSelfCheck.cpp
 
   LINK_LIBS
   clangAST
Index: clang-tools-extra/trunk/clang-tidy/objc/SuperSelfCheck.h
===
--- clang-tools-extra/trunk/clang-tidy/objc/SuperSelfCheck.h
+++ clang-tools-extra/trunk/clang-tidy/objc/SuperSelfCheck.h
@@ -0,0 +1,36 @@
+//===--- SuperSelfCheck.h - clang-tidy --*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_SUPERSELFCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_SUPERSELFCHECK_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace objc {
+
+/// Finds invocations of -self on super instances in initializers of subclasses
+/// of NSObject and recommends calling a superclass initializer instead.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/objc-super-self.html
+class SuperSelfCheck : public ClangTidyCheck {
+public:
+  SuperSelfCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+};
+
+} // namespace objc
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_SUPERSELFCHECK_H
Index: clang-tools-extra/trunk/clang-tidy/objc/SuperSelfCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/objc/SuperSelfCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/objc/SuperSelfCheck.cpp
@@ -0,0 +1,127 @@
+//===--- SuperSelfCheck.cpp - clang-tidy --===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "SuperSelfCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace objc {
+
+namespace {
+
+/// \brief Matches Objective-C methods in the initializer family.
+///
+/// Example matches -init and -initWithInt:.
+///   (matcher = objcMethodDecl(isInitializer()))
+/// \code
+///   @interface Foo
+///   - (instancetype)init;
+///   - (instancetype)initWithInt:(int)i;
+///   + (instancetype)init;
+///   - (void)bar;
+///   @end
+/// \endcode
+AST_MATCHER(ObjCMethodDecl, isInitializer) {
+  return Node.getMethodFamily() == OMF_init;
+}
+
+/// \brief Matches Objective-C implementations of classes that directly or
+/// indirectly have a superclass 

[PATCH] D60516: [LTO] Add plumbing to save stats during LTO on Darwin.

2019-04-17 Thread Steven Wu via Phabricator via cfe-commits
steven_wu added a comment.

forgot to save the inline comments.




Comment at: llvm/lib/LTO/LTOCodeGenerator.cpp:601
   // If statistics were requested, print them out after codegen.
-  if (llvm::AreStatisticsEnabled())
+  if (llvm::AreStatisticsEnabled() && !StatsFile)
 llvm::PrintStatistics();

You can simplify the logic a bit here.
```
if (StatsFile)
...
else if (llvm::AreStatisticsEnabled())
...
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60516



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


[PATCH] D59754: [Sema] Add c++2a designated initializer warnings

2019-04-17 Thread Don Hinton via Phabricator via cfe-commits
hintonda updated this revision to Diff 195611.
hintonda added a comment.

- Fix typo.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59754

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaInit.cpp
  clang/test/SemaCXX/cxx2a-initializer-aggregates.cpp

Index: clang/test/SemaCXX/cxx2a-initializer-aggregates.cpp
===
--- clang/test/SemaCXX/cxx2a-initializer-aggregates.cpp
+++ clang/test/SemaCXX/cxx2a-initializer-aggregates.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++2a %s -verify
+// RUN: %clang_cc1 -std=c++2a %s -verify -pedantic
 
 namespace class_with_ctor {
   struct A { // expected-note 6{{candidate}}
@@ -21,3 +21,14 @@
   C c1 = {{}, {}}; // ok, call default ctor twice
   C c2 = {{1, 2}, {3, 4}}; // expected-error 2{{no matching constructor}}
 }
+
+namespace designator {
+struct A { int x, y; };
+struct B { A a; };
+
+A a1 = {.y = 1, .x = 2}; // expected-warning {{C99 out of order designated initializers are a C++20 extension}}
+int arr[3] = {[1] = 5}; // expected-warning {{C99 array designated initializers are a C++20 extension}}
+B b = {.a.x = 0}; // expected-warning {{C99 nested designated initializers are a C++20 extension}}
+A a2 = {.x = 1, 2}; // expected-warning {{C99 mixed designated initializers are a C++20 extension}}
+A a3 = {1, .y = 2}; // expected-warning {{C99 mixed designated initializers are a C++20 extension}}
+}
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -1999,6 +1999,7 @@
   bool CheckForMissingFields =
 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
   bool HasDesignatedInit = false;
+  bool HasNonDesignatedInit = false;
 
   while (Index < IList->getNumInits()) {
 Expr *Init = IList->getInit(Index);
@@ -2013,6 +2014,10 @@
 
   HasDesignatedInit = true;
 
+  unsigned LastIdx =
+  Field != FieldEnd ? Field->getFieldIndex()
+: std::distance(RD->field_begin(), RD->field_end());
+
   // Handle this designated initializer. Field will be updated to
   // the next field that we'll be initializing.
   if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
@@ -2032,6 +2037,20 @@
 }
   }
 
+  unsigned NextIdx =
+  Field != FieldEnd ? Field->getFieldIndex()
+: std::distance(RD->field_begin(), RD->field_end());
+  if (!VerifyOnly && SemaRef.getLangOpts().CPlusPlus2a) {
+if (LastIdx >= NextIdx) {
+  SemaRef.Diag(Init->getBeginLoc(), diag::ext_c20_designated_init)
+  << "out of order" << Init->getSourceRange();
+}
+if (HasNonDesignatedInit) {
+  SemaRef.Diag(Init->getBeginLoc(), diag::ext_c20_designated_init)
+  << "mixed" << Init->getSourceRange();
+}
+  }
+
   InitializedSomething = true;
 
   // Disable check for missing fields when designators are used.
@@ -2045,6 +2064,13 @@
   break;
 }
 
+HasNonDesignatedInit = true;
+
+if (!VerifyOnly && HasDesignatedInit && SemaRef.getLangOpts().CPlusPlus2a) {
+  SemaRef.Diag(Init->getBeginLoc(), diag::ext_c20_designated_init)
+  << "mixed" << Init->getSourceRange();
+}
+
 // We've already initialized a member of a union. We're done.
 if (InitializedSomething && DeclType->isUnionType())
   break;
@@ -2980,6 +3006,7 @@
   bool Invalid = false;
   SmallVector Designators;
   SmallVector InitExpressions;
+  bool HasArrayDesignator = false;
 
   // Build designators and check array designator expressions.
   for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
@@ -3003,6 +3030,7 @@
 D.getRBracketLoc()));
 InitExpressions.push_back(Index);
   }
+  HasArrayDesignator = true;
   break;
 }
 
@@ -3046,6 +3074,7 @@
   InitExpressions.push_back(EndIndex);
 }
   }
+  HasArrayDesignator = true;
   break;
 }
 }
@@ -3063,9 +3092,19 @@
  InitExpressions, Loc, GNUSyntax,
  Init.getAs());
 
-  if (!getLangOpts().C99)
+  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus2a) {
 Diag(DIE->getBeginLoc(), diag::ext_designated_init)
 << DIE->getSourceRange();
+  } else if (getLangOpts().CPlusPlus2a) {
+if (Desig.getNumDesignators() > 1) {
+  Diag(DIE->getBeginLoc(), diag::ext_c20_designated_init)
+  << "nested" << DIE->getSourceRange();
+}
+if (HasArrayDesignator) {
+  Diag(DIE->getBeginLoc(), diag::ext_c20_designated_init)
+  << "array" << DIE->getSourceRange();
+}
+  }
 
   return DIE;
 }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td

[PATCH] D60629: [clang-tidy] Change the namespace for llvm checkers from 'llvm' to 'llvm_check'

2019-04-17 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added inline comments.



Comment at: clang-tools-extra/clang-tidy/add_new_check.py:382
+  if module == 'llvm' or module == 'clang':
+namespace = module + '_checker'
+  else:

hintonda wrote:
> aaron.ballman wrote:
> > I thought we were going with `llvm_check`?
> Just typo on my part.  I the options mentioned before where things like 
> `llvm_project` or `llvm_proj`, etc.  I just settled on `llvm_check` because 
> it sounded better -- then actually typed `checker`.  
> 
> I'll fix it this afternoon.
I have another suggestion re: the color of this bike shed, namely: 
`llvm_checks`. But I don't feel strongly about this.



Comment at: clang-tools-extra/clang-tidy/add_new_check.py:381
+
+  # Don't allow 'clang' or 'llvm' namespaces
+  if module == 'llvm':

I'd add an explanation: `# Map module names to namespace names that don't 
conflict with widely used top-level namespaces.`

And again, no need to mention `clang` here.



Comment at: clang-tools-extra/clang-tidy/rename_check.py:218
   header_guard_variants = [
+  (args.old_check_name.replace('-', '_') + '_Check').upper(),
+  (old_module + '_' + check_name_camel).upper(),

s/_Check/_CHECK/, maybe?



Comment at: clang-tools-extra/clang-tidy/rename_check.py:267
 
-  if old_module != new_module:
+  if old_module != new_module or new_module == 'llvm':
+if new_module == 'llvm':

I believe, we should first construct the new namespace name (using exactly the 
same code as in add_new_check.py) and then check if it differs from the old one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60629



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


[PATCH] D60822: [clangd] Use shorter, more recognizable codes for diagnostics.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 195623.
sammccall added a comment.

-Wfoo instead of foo


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60822

Files:
  clangd/Diagnostics.cpp
  test/clangd/compile-commands-path-in-initialize.test
  test/clangd/diagnostic-category.test
  test/clangd/diagnostics.test
  test/clangd/did-change-configuration-params.test
  test/clangd/execute-command.test
  test/clangd/fixits-codeaction.test
  test/clangd/fixits-command.test
  test/clangd/fixits-embed-in-diagnostic.test
  unittests/clangd/DiagnosticsTests.cpp

Index: unittests/clangd/DiagnosticsTests.cpp
===
--- unittests/clangd/DiagnosticsTests.cpp
+++ unittests/clangd/DiagnosticsTests.cpp
@@ -107,7 +107,7 @@
   AllOf(Diag(Test.range("typo"),
  "use of undeclared identifier 'goo'; did you mean 'foo'?"),
 DiagSource(Diag::Clang),
-DiagName("err_undeclared_var_use_suggest"),
+DiagName("undeclared_var_use_suggest"),
 WithFix(
 Fix(Test.range("typo"), "foo", "change 'go\\ o' to 'foo'")),
 // This is a pretty normal range.
@@ -152,7 +152,7 @@
   EXPECT_THAT(TU.build().getDiagnostics(),
   ElementsAre(testing::AllOf(
   Diag(Test.range(), "'not-found.h' file not found"),
-  DiagSource(Diag::Clang), DiagName("err_pp_file_not_found";
+  DiagSource(Diag::Clang), DiagName("pp_file_not_found";
 }
 
 TEST(DiagnosticsTest, ClangTidy) {
@@ -252,7 +252,7 @@
 TEST(DiagnosticsTest, ToLSP) {
   clangd::Diag D;
   D.ID = clang::diag::err_enum_class_reference;
-  D.Name = "err_enum_class_reference";
+  D.Name = "enum_class_reference";
   D.Source = clangd::Diag::Clang;
   D.Message = "something terrible happened";
   D.Range = {pos(1, 2), pos(3, 4)};
@@ -322,7 +322,7 @@
   LSPDiags,
   ElementsAre(Pair(EqualToLSPDiag(MainLSP), ElementsAre(EqualToFix(F))),
   Pair(EqualToLSPDiag(NoteInMainLSP), IsEmpty(;
-  EXPECT_EQ(LSPDiags[0].first.code, "err_enum_class_reference");
+  EXPECT_EQ(LSPDiags[0].first.code, "enum_class_reference");
   EXPECT_EQ(LSPDiags[0].first.source, "clang");
   EXPECT_EQ(LSPDiags[1].first.code, "");
   EXPECT_EQ(LSPDiags[1].first.source, "");
Index: test/clangd/fixits-embed-in-diagnostic.test
===
--- test/clangd/fixits-embed-in-diagnostic.test
+++ test/clangd/fixits-embed-in-diagnostic.test
@@ -6,7 +6,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"diagnostics": [
 # CHECK-NEXT:  {
-# CHECK-NEXT:"code": "err_use_with_wrong_tag",
+# CHECK-NEXT:"code": "use_with_wrong_tag",
 # CHECK-NEXT:"codeActions": [
 # CHECK-NEXT:  {
 # CHECK-NEXT:"edit": {
Index: test/clangd/fixits-command.test
===
--- test/clangd/fixits-command.test
+++ test/clangd/fixits-command.test
@@ -6,7 +6,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"diagnostics": [
 # CHECK-NEXT:  {
-# CHECK-NEXT:"code": "warn_condition_is_assignment",
+# CHECK-NEXT:"code": "-Wparentheses",
 # CHECK-NEXT:"message": "Using the result of an assignment as a condition without parentheses (fixes available)",
 # CHECK-NEXT:"range": {
 # CHECK-NEXT:  "end": {
Index: test/clangd/fixits-codeaction.test
===
--- test/clangd/fixits-codeaction.test
+++ test/clangd/fixits-codeaction.test
@@ -6,7 +6,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"diagnostics": [
 # CHECK-NEXT:  {
-# CHECK-NEXT:"code": "warn_condition_is_assignment",
+# CHECK-NEXT:"code": "-Wparentheses",
 # CHECK-NEXT:"message": "Using the result of an assignment as a condition without parentheses (fixes available)",
 # CHECK-NEXT:"range": {
 # CHECK-NEXT:  "end": {
@@ -25,14 +25,14 @@
 # CHECK-NEXT:"uri": "file://{{.*}}/foo.c"
 # CHECK-NEXT:  }
 ---
-{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{"textDocument":{"uri":"test:///foo.c"},"range":{"start":{"line":0,"character":13},"end":{"line":0,"character":35}},"context":{"diagnostics":[{"range":{"start": {"line": 0, "character": 32}, "end": {"line": 0, "character": 37}},"severity":2,"message":"Using the result of an assignment as a condition without parentheses (fixes available)", "code": "warn_condition_is_assignment", "source": "clang"}]}}}
+{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{"textDocument":{"uri":"test:///foo.c"},"range":{"start":{"line":0,"character":13},"end":{"line":0,"character":35}},"context":{"diagnostics":[{"range":{"start": {"line": 0, "character": 32}, "end": {"line": 0, "character": 

[PATCH] D60835: [Serialization] Stable serialization order for OpenCLTypeExtMap and OpenCLDeclExtMap

2019-04-17 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added a comment.

By the way, I am wondering about how much this is tested. I did look quickly in 
`test/PCH` and it appears that there are only 3 (short) tests : `ocl_types.cl`, 
`opencl-extensions.cl` and `no-validate-pch`.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60835



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


[PATCH] D59754: [Sema] Add c++2a designated initializer warnings

2019-04-17 Thread Don Hinton via Phabricator via cfe-commits
hintonda updated this revision to Diff 195610.
hintonda added a comment.

- Removed auto and added specific warnings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59754

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaInit.cpp
  clang/test/SemaCXX/cxx2a-initializer-aggregates.cpp

Index: clang/test/SemaCXX/cxx2a-initializer-aggregates.cpp
===
--- clang/test/SemaCXX/cxx2a-initializer-aggregates.cpp
+++ clang/test/SemaCXX/cxx2a-initializer-aggregates.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++2a %s -verify
+// RUN: %clang_cc1 -std=c++2a %s -verify -pedantic
 
 namespace class_with_ctor {
   struct A { // expected-note 6{{candidate}}
@@ -21,3 +21,14 @@
   C c1 = {{}, {}}; // ok, call default ctor twice
   C c2 = {{1, 2}, {3, 4}}; // expected-error 2{{no matching constructor}}
 }
+
+namespace designator {
+struct A { int x, y; };
+struct B { A a; };
+
+A a1 = {.y = 1, .x = 2}; // expected-warning {{C99 out of order designated initializers are a C++20 extention}}
+int arr[3] = {[1] = 5}; // expected-warning {{C99 array designated initializers are a C++20 extention}}
+B b = {.a.x = 0}; // expected-warning {{C99 nested designated initializers are a C++20 extention}}
+A a2 = {.x = 1, 2}; // expected-warning {{C99 mixed designated initializers are a C++20 extention}}
+A a3 = {1, .y = 2}; // expected-warning {{C99 mixed designated initializers are a C++20 extention}}
+}
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -1999,6 +1999,7 @@
   bool CheckForMissingFields =
 !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
   bool HasDesignatedInit = false;
+  bool HasNonDesignatedInit = false;
 
   while (Index < IList->getNumInits()) {
 Expr *Init = IList->getInit(Index);
@@ -2013,6 +2014,10 @@
 
   HasDesignatedInit = true;
 
+  unsigned LastIdx =
+  Field != FieldEnd ? Field->getFieldIndex()
+: std::distance(RD->field_begin(), RD->field_end());
+
   // Handle this designated initializer. Field will be updated to
   // the next field that we'll be initializing.
   if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
@@ -2032,6 +2037,20 @@
 }
   }
 
+  unsigned NextIdx =
+  Field != FieldEnd ? Field->getFieldIndex()
+: std::distance(RD->field_begin(), RD->field_end());
+  if (!VerifyOnly && SemaRef.getLangOpts().CPlusPlus2a) {
+if (LastIdx >= NextIdx) {
+  SemaRef.Diag(Init->getBeginLoc(), diag::ext_c20_designated_init)
+  << "out of order" << Init->getSourceRange();
+}
+if (HasNonDesignatedInit) {
+  SemaRef.Diag(Init->getBeginLoc(), diag::ext_c20_designated_init)
+  << "mixed" << Init->getSourceRange();
+}
+  }
+
   InitializedSomething = true;
 
   // Disable check for missing fields when designators are used.
@@ -2045,6 +2064,13 @@
   break;
 }
 
+HasNonDesignatedInit = true;
+
+if (!VerifyOnly && HasDesignatedInit && SemaRef.getLangOpts().CPlusPlus2a) {
+  SemaRef.Diag(Init->getBeginLoc(), diag::ext_c20_designated_init)
+  << "mixed" << Init->getSourceRange();
+}
+
 // We've already initialized a member of a union. We're done.
 if (InitializedSomething && DeclType->isUnionType())
   break;
@@ -2980,6 +3006,7 @@
   bool Invalid = false;
   SmallVector Designators;
   SmallVector InitExpressions;
+  bool HasArrayDesignator = false;
 
   // Build designators and check array designator expressions.
   for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
@@ -3003,6 +3030,7 @@
 D.getRBracketLoc()));
 InitExpressions.push_back(Index);
   }
+  HasArrayDesignator = true;
   break;
 }
 
@@ -3046,6 +3074,7 @@
   InitExpressions.push_back(EndIndex);
 }
   }
+  HasArrayDesignator = true;
   break;
 }
 }
@@ -3063,9 +3092,19 @@
  InitExpressions, Loc, GNUSyntax,
  Init.getAs());
 
-  if (!getLangOpts().C99)
+  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus2a) {
 Diag(DIE->getBeginLoc(), diag::ext_designated_init)
 << DIE->getSourceRange();
+  } else if (getLangOpts().CPlusPlus2a) {
+if (Desig.getNumDesignators() > 1) {
+  Diag(DIE->getBeginLoc(), diag::ext_c20_designated_init)
+  << "nested" << DIE->getSourceRange();
+}
+if (HasArrayDesignator) {
+  Diag(DIE->getBeginLoc(), diag::ext_c20_designated_init)
+  << "array" << DIE->getSourceRange();
+}
+  }
 
   return DIE;
 }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td

[PATCH] D59812: [analyzer] PR41185: Fix regression where __builtin_* functions weren't recognized

2019-04-17 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus updated this revision to Diff 195619.
Szelethus edited the summary of this revision.
Szelethus added a comment.

Uhh, sorry for the spam. Realized that these are not path sensitive checkers. 
Removed the core packages from the invocations. Actual logic of the patch is 
untouched.


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

https://reviews.llvm.org/D59812

Files:
  lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
  test/Analysis/security-syntax-checks-no-emit.c
  test/Analysis/security-syntax-checks.c
  test/Analysis/security-syntax-checks.m


Index: test/Analysis/security-syntax-checks.m
===
--- test/Analysis/security-syntax-checks.m
+++ test/Analysis/security-syntax-checks.m
@@ -1,11 +1,40 @@
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DUSE_BUILTINS 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DVARIANT 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DUSE_BUILTINS 
-DVARIANT -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s 
-verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -DUSE_BUILTINS 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -DVARIANT 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi -DUSE_BUILTINS 
-DVARIANT -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s 
-verify
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -DVARIANT \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 %s -verify \
+// RUN:   -DUSE_BUILTINS -DVARIANT \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -DUSE_BUILTINS \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -DVARIANT \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi %s -verify \
+// RUN:   -DUSE_BUILTINS -DVARIANT \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
 
 #ifdef USE_BUILTINS
 # define BUILTIN(f) __builtin_ ## f
Index: test/Analysis/security-syntax-checks.c
===
--- /dev/null
+++ test/Analysis/security-syntax-checks.c
@@ -0,0 +1,8 @@
+// RUN: %clang_analyze_cc1 %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI
+
+void builtin_function_call_crash_fixes(char *c) {
+  __builtin_strncpy(c, "", 6); // expected-warning{{Call to function 'strncpy' 
is insecure as it does not provide security checks introduced in the C11 
standard.}}
+  __builtin_memset(c, '\0', (0)); // expected-warning{{Call to function 
'memset' is insecure as it does not provide security checks introduced in the 
C11 standard.}}
+  __builtin_memcpy(c, c, 0); // expected-warning{{Call to function 'memcpy' is 
insecure as it does not provide security checks introduced in the C11 
standard.}}
+}
Index: test/Analysis/security-syntax-checks-no-emit.c
===
--- test/Analysis/security-syntax-checks-no-emit.c
+++ test/Analysis/security-syntax-checks-no-emit.c
@@ -1,4 +1,7 @@
-// RUN: %clang_analyze_cc1 -triple i686-pc-linux-gnu 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
+// RUN: %clang_analyze_cc1 -triple i686-pc-linux-gnu %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN: 

[PATCH] D60186: Support CLANG_ENABLE_DEFAULT_PIE like gcc --enable-default-pie

2019-04-17 Thread Jiang Yi via Phabricator via cfe-commits
jiangyi added a comment.

Ping.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60186



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


[clang-tools-extra] r358621 - [clang-tidy] Don't issue cppcoreguidelines-macro-usage on builtin macros

2019-04-17 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Wed Apr 17 15:35:36 2019
New Revision: 358621

URL: http://llvm.org/viewvc/llvm-project?rev=358621=rev
Log:
[clang-tidy] Don't issue cppcoreguidelines-macro-usage on builtin macros

Before the patch calling clang-tidy with -header-filter=.* -system-headers would
result in a few hundred useless warnings:
  warning: macro '_GNU_SOURCE' used to declare a constant; consider using a 
'constexpr' constant [cppcoreguidelines-macro-usage]
  warning: macro '_LP64' used to declare a constant; consider using a 
'constexpr' constant [cppcoreguidelines-macro-usage]
  warning: macro '__ATOMIC_ACQUIRE' used to declare a constant; consider using 
a 'constexpr' constant [cppcoreguidelines-macro-usage]
  warning: macro '__ATOMIC_ACQ_REL' used to declare a constant; consider using 
a 'constexpr' constant [cppcoreguidelines-macro-usage]
  warning: macro '__ATOMIC_CONSUME' used to declare a constant; consider using 
a 'constexpr' constant [cppcoreguidelines-macro-usage]
  warning: macro '__ATOMIC_RELAXED' used to declare a constant; consider using 
a 'constexpr' constant [cppcoreguidelines-macro-usage]
  warning: macro '__ATOMIC_RELEASE' used to declare a constant; consider using 
a 'constexpr' constant [cppcoreguidelines-macro-usage]
  warning: macro '__ATOMIC_SEQ_CST' used to declare a constant; consider using 
a 'constexpr' constant [cppcoreguidelines-macro-usage]
  warning: macro '__BIGGEST_ALIGNMENT__' used to declare a constant; consider 
using a 'constexpr' constant [cppcoreguidelines-macro-usage]
  ... and so on

Modified:
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-macro-usage.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp?rev=358621=358620=358621=diff
==
--- clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/cppcoreguidelines/MacroUsageCheck.cpp 
Wed Apr 17 15:35:36 2019
@@ -36,7 +36,8 @@ public:
 IgnoreCommandLineMacros(IgnoreCommandLine) {}
   void MacroDefined(const Token ,
 const MacroDirective *MD) override {
-if (MD->getMacroInfo()->isUsedForHeaderGuard() ||
+if (SM.isWrittenInBuiltinFile(MD->getLocation()) ||
+MD->getMacroInfo()->isUsedForHeaderGuard() ||
 MD->getMacroInfo()->getNumTokens() == 0)
   return;
 

Modified: 
clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-macro-usage.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-macro-usage.cpp?rev=358621=358620=358621=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-macro-usage.cpp 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/cppcoreguidelines-macro-usage.cpp 
Wed Apr 17 15:35:36 2019
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s cppcoreguidelines-macro-usage %t
+// RUN: %check_clang_tidy %s cppcoreguidelines-macro-usage %t -- 
-header-filter=.* -system-headers --
 
 #ifndef INCLUDE_GUARD
 #define INCLUDE_GUARD


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


[PATCH] D60543: [clang] Add matcher for subclasses of Objective-C interfaces 

2019-04-17 Thread Jordan Rose via Phabricator via cfe-commits
jordan_rose added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:1479
+/// \endcode
+AST_MATCHER_P(ObjCInterfaceDecl, isSubclassOfInterface,
+  internal::Matcher,

aaron.ballman wrote:
> stephanemoore wrote:
> > aaron.ballman wrote:
> > > stephanemoore wrote:
> > > > I am still uncertain about the naming.
> > > > 
> > > > `isSubclassOf` seemed too generic as that could apply to C++ classes.
> > > > `objcIsSubclassOf` seemed unconventional as a matcher name.
> > > > `isSubclassOfObjCInterface` and `isSubclassOfObjCClass` seemed 
> > > > awkwardly lengthy.
> > > > Creating a new namespace `clang::ast_matchers::objc` seemed 
> > > > unprecedented.
> > > > 
> > > > I am happy to change the name if you think another name would be more 
> > > > appropriate.
> > > Does ObjC use the term "derived" by any chance? We already have 
> > > `isDerivedFrom`, so I'm wondering if we can use that to also match on an 
> > > `ObjCInterfaceDecl`?
> > Objective-C doesn't generally use the term "derived" (for example, see 
> > archive of [Programming With Objective-C > Defining 
> > Classes](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW1)).
> >  With that said, I don't think it's unreasonable or incorrect to use the 
> > term "derived" to describe inheritance in Objective-C. The behavior of this 
> > matcher is also consistent with the behavior of `isDerivedFrom`. In order 
> > to change `isDerivedFrom`, I would also need to update 
> > `isSameOrDerivedFrom`. That would probably be a good thing so that 
> > derivation matching feature set is consistent for C++ and Objective-C 
> > language variants.
> > 
> > Let me take a crack at merging this into `isDerivedFrom`.
> I agree that if we go with `isDerivedFrom`, you should update 
> `isSameOrDerivedFrom` at the same time.
`isSubclassOf` sounds right to me, and since ObjC and C++ class hierarchies 
can't mix, it _should_ be okay, right? They're analogous concepts.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60543



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


[PATCH] D60736: [Sema][ObjC] Don't warn about a block implicitly retaining self if the block is marked noescape

2019-04-17 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington added inline comments.



Comment at: lib/Parse/ParseObjc.cpp:3696-3699
+
+  Actions.ActOnEndOfObjCMethodDef();
+
   // Clean up the remaining EOF token.

Any reason not to do this check in `ActOnFinishFunctionBody` (which is called 
by ParseFunctionStatementBody)? Seems like there are some similar diagnostics 
implemented there.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60736



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


[PATCH] D59371: [LibTooling] Add Stencil library for format-string style codegen.

2019-04-17 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: clang/include/clang/Tooling/Refactoring/Stencil.h:127
+  // Allow Stencils to operate as std::function, for compatibility with
+  // Transformer's TextGenerator. Calls `eval()` and asserts on failure.
+  std::string operator()(const ast_matchers::MatchFinder::MatchResult &) const;

sbenza wrote:
> ymandel wrote:
> > sbenza wrote:
> > > "asserts" as it only fails in debug mode?
> > I thought `assert()` also fails in normal mode, based on my reading of the 
> > llvm docs, but it's not explicit about this: 
> > http://llvm.org/docs/ProgrammersManual.html#programmatic-errors
> > 
> > FWIW, I'm on the fence whether `eval()` should actually have the same 
> > signature and similarly just crash the program on errors. Its not clear 
> > there's any value to propogating the errors up the stack via `Expected`.
> `assert` follows `NDEBUG`, which is not explicitly related to `-Ox`, but they 
> usually go together.
> 
> Don't make it crash, please.
> Otherwise it would be hard to have a refactoring service or alike.
Right, you've convinced me. For some background: TextGenerator (in Transformer) 
originally return an Expected, but Ilya suggested that I simplify 
to just a string and use assertions.  The logic being that these are 
compiler-style tools. However, I agree that this simply doesn't work for 
running these in servers, which is a very real concern. It's also trivial to 
imagine a user mistyping a stencil (say, in web UI) which results in a failure 
in stencil eval. We want to return a nice error to the user, not crash the 
server.

So, I've adjusted the signature. I will (separately) change the definition of 
TextGenerator in Transformer.



Comment at: clang/include/clang/Tooling/Refactoring/Stencil.h:101
+S.Parts.reserve(sizeof...(Parts));
+auto Unused = {(S.push(std::forward(Parts)), true)...};
+(void)Unused;

sbenza wrote:
> We could simplify this code if you change `void push(T)` to instead 
> `StencilPart wrap(T)`.
> Then this could be:
> 
> 
> ```
> Stencil S;
> S.Parts = {wrap(std::forward(Parts))...};
> return S;
> ```
Much better. I believe the current design came about when StencilPart was move 
only. Thanks!



Comment at: clang/lib/Tooling/Refactoring/Stencil.cpp:78
+
+template <> bool isEqualData(const RawTextData , const RawTextData ) {
+  return A.Text == B.Text;

sbenza wrote:
> Any particular reason to use function template specialization instead of 
> function overloading?
> The former is rare and thus harder to reason about.
> 
> (same for `evalData` below)
Stylistic -- it forces you to explicitly declare the "overload set" so to 
speak.  However, i'm not particularly attached -- if you think this a bad idea 
given its rarity, I'm happy to use overload sets. WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59371



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


[PATCH] D59371: [LibTooling] Add Stencil library for format-string style codegen.

2019-04-17 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 195606.
ymandel added a comment.

Convert template specialization to overload sets.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59371

Files:
  clang/include/clang/Tooling/Refactoring/Stencil.h
  clang/lib/Tooling/Refactoring/CMakeLists.txt
  clang/lib/Tooling/Refactoring/Stencil.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -0,0 +1,223 @@
+//===- unittest/Tooling/StencilTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Refactoring/Stencil.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/FixIt.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace tooling;
+using namespace ast_matchers;
+
+namespace {
+using ::testing::AllOf;
+using ::testing::Eq;
+using ::testing::HasSubstr;
+using MatchResult = MatchFinder::MatchResult;
+using tooling::stencil::node;
+using tooling::stencil::sNode;
+using tooling::stencil::text;
+
+// In tests, we can't directly match on llvm::Expected since its accessors
+// mutate the object. So, we collapse it to an Optional.
+static llvm::Optional toOptional(llvm::Expected V) {
+  if (V)
+return *V;
+  ADD_FAILURE() << "Losing error in conversion to IsSomething: "
+<< llvm::toString(V.takeError());
+  return llvm::None;
+}
+
+// A very simple matcher for llvm::Optional values.
+MATCHER_P(IsSomething, ValueMatcher, "") {
+  if (!arg)
+return false;
+  return ::testing::ExplainMatchResult(ValueMatcher, *arg, result_listener);
+}
+
+// Create a valid translation-unit from a statement.
+static std::string wrapSnippet(llvm::Twine StatementCode) {
+  return ("auto stencil_test_snippet = []{" + StatementCode + "};").str();
+}
+
+static DeclarationMatcher wrapMatcher(const StatementMatcher ) {
+  return varDecl(hasName("stencil_test_snippet"),
+ hasDescendant(compoundStmt(hasAnySubstatement(Matcher;
+}
+
+struct TestMatch {
+  // The AST unit from which `result` is built. We bundle it because it backs
+  // the result. Users are not expected to access it.
+  std::unique_ptr AstUnit;
+  // The result to use in the test. References `ast_unit`.
+  MatchResult Result;
+};
+
+// Matches `Matcher` against the statement `StatementCode` and returns the
+// result. Handles putting the statement inside a function and modifying the
+// matcher correspondingly. `Matcher` should match `StatementCode` exactly --
+// that is, produce exactly one match.
+static llvm::Optional matchStmt(llvm::Twine StatementCode,
+   StatementMatcher Matcher) {
+  auto AstUnit = buildASTFromCode(wrapSnippet(StatementCode));
+  if (AstUnit == nullptr) {
+ADD_FAILURE() << "AST construction failed";
+return llvm::None;
+  }
+  ASTContext  = AstUnit->getASTContext();
+  auto Matches = ast_matchers::match(wrapMatcher(Matcher), Context);
+  // We expect a single, exact match for the statement.
+  if (Matches.size() != 1) {
+ADD_FAILURE() << "Wrong number of matches: " << Matches.size();
+return llvm::None;
+  }
+  return TestMatch{std::move(AstUnit), MatchResult(Matches[0], )};
+}
+
+class StencilTest : public ::testing::Test {
+protected:
+  // Verifies that the given stencil fails when evaluated on a valid match
+  // result. Binds a statement to "stmt", a (non-member) ctor-initializer to
+  // "init", an expression to "expr" and a (nameless) declaration to "decl".
+  void testError(const Stencil ,
+ ::testing::Matcher Matcher) {
+const std::string Snippet = R"cc(
+  struct A {};
+  class F : public A {
+   public:
+F(int) {}
+  };
+  F(1);
+)cc";
+auto StmtMatch = matchStmt(
+Snippet,
+stmt(hasDescendant(
+ cxxConstructExpr(
+ hasDeclaration(decl(hasDescendant(cxxCtorInitializer(
+   isBaseInitializer())
+   .bind("init")))
+.bind("decl")))
+ .bind("expr")))
+.bind("stmt"));
+ASSERT_TRUE(StmtMatch);
+if (auto ResultOrErr = Stencil.eval(StmtMatch->Result)) {
+  ADD_FAILURE() << "Expected failure but succeeded: " << *ResultOrErr;
+} else {
+  auto Err = 

[clang-tools-extra] r358605 - [clangd] Recognize "don't include me directly" pattern, and suppress include insertion.

2019-04-17 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Wed Apr 17 11:33:07 2019
New Revision: 358605

URL: http://llvm.org/viewvc/llvm-project?rev=358605=rev
Log:
[clangd] Recognize "don't include me directly" pattern, and suppress include 
insertion.

Summary:
Typically used with umbrella headers, e.g. GTK:

 #if !defined (__GTK_H_INSIDE__) && !defined (GTK_COMPILATION)
 #error "Only  can be included directly."
 #endif

Heuristic is fairly conservative, a quick code search over github showed
a fair number of hits and few/no false positives. (Not all were umbrella
headers, but I'd be happy avoiding include insertion for all of them).

We may want to relax the heuristic later to catch more cases.

Reviewers: ioeric

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

Tags: #clang

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

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

Modified: clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp?rev=358605=358604=358605=diff
==
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.cpp Wed Apr 17 
11:33:07 2019
@@ -128,48 +128,6 @@ bool shouldCollectIncludePath(index::Sym
   }
 }
 
-bool isSelfContainedHeader(FileID FID, const SourceManager ,
-   const Preprocessor ) {
-  const FileEntry *FE = SM.getFileEntryForID(FID);
-  if (!FE)
-return false;
-  return PP.getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE);
-}
-
-/// Gets a canonical include (URI of the header or  or "header") for
-/// header of \p FID (which should usually be the *expansion* file).
-/// Returns None if includes should not be inserted for this file.
-llvm::Optional
-getIncludeHeader(llvm::StringRef QName, const SourceManager ,
- const Preprocessor , FileID FID,
- const SymbolCollector::Options ) {
-  const FileEntry *FE = SM.getFileEntryForID(FID);
-  if (!FE || FE->getName().empty())
-return llvm::None;
-  llvm::StringRef Filename = FE->getName();
-  // If a file is mapped by canonical headers, use that mapping, regardless
-  // of whether it's an otherwise-good header (header guards etc).
-  if (Opts.Includes) {
-llvm::StringRef Canonical = Opts.Includes->mapHeader(Filename, QName);
-// If we had a mapping, always use it.
-if (Canonical.startswith("<") || Canonical.startswith("\""))
-  return Canonical.str();
-if (Canonical != Filename)
-  return toURI(SM, Canonical, Opts);
-  }
-  if (!isSelfContainedHeader(FID, SM, PP)) {
-// A .inc or .def file is often included into a real header to define
-// symbols (e.g. LLVM tablegen files).
-if (Filename.endswith(".inc") || Filename.endswith(".def"))
-  return getIncludeHeader(QName, SM, PP,
-  SM.getFileID(SM.getIncludeLoc(FID)), Opts);
-// Conservatively refuse to insert #includes to files without guards.
-return llvm::None;
-  }
-  // Standard case: just insert the file itself.
-  return toURI(SM, Filename, Opts);
-}
-
 // Return the symbol range of the token at \p TokLoc.
 std::pair
 getTokenRange(SourceLocation TokLoc, const SourceManager ,
@@ -452,9 +410,8 @@ bool SymbolCollector::handleMacroOccuren
 
   std::string Include;
   if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
-if (auto Header =
-getIncludeHeader(Name->getName(), SM, *PP,
- SM.getDecomposedExpansionLoc(DefLoc).first, Opts))
+if (auto Header = getIncludeHeader(
+Name->getName(), SM.getDecomposedExpansionLoc(DefLoc).first))
   Include = std::move(*Header);
   }
   S.Signature = Signature;
@@ -533,6 +490,7 @@ void SymbolCollector::finish() {
   ReferencedMacros.clear();
   DeclRefs.clear();
   FilesToIndexCache.clear();
+  HeaderIsSelfContainedCache.clear();
 }
 
 const Symbol *SymbolCollector::addDeclaration(const NamedDecl , SymbolID ID,
@@ -602,8 +560,7 @@ const Symbol *SymbolCollector::addDeclar
 // Use the expansion location to get the #include header since this is
 // where the symbol is exposed.
 if (auto Header = getIncludeHeader(
-QName, SM, *PP,
-SM.getDecomposedExpansionLoc(ND.getLocation()).first, Opts))
+QName, SM.getDecomposedExpansionLoc(ND.getLocation()).first))
   Include = std::move(*Header);
   }
   if (!Include.empty())
@@ -639,5 +596,59 @@ void SymbolCollector::addDefinition(cons
   Symbols.insert(S);
 }
 
+/// Gets a canonical include (URI of the header or  or "header") for
+/// header of \p FID (which should usually be the *expansion* file).
+/// Returns None if includes should 

[PATCH] D60815: [clangd] Recognize "don't include me directly" pattern, and suppress include insertion.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE358605: [clangd] Recognize dont include me 
directly pattern, and suppress include… (authored by sammccall, committed 
by ).

Changed prior to commit:
  https://reviews.llvm.org/D60815?vs=195562=195607#toc

Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60815

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

Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -128,48 +128,6 @@
   }
 }
 
-bool isSelfContainedHeader(FileID FID, const SourceManager ,
-   const Preprocessor ) {
-  const FileEntry *FE = SM.getFileEntryForID(FID);
-  if (!FE)
-return false;
-  return PP.getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE);
-}
-
-/// Gets a canonical include (URI of the header or  or "header") for
-/// header of \p FID (which should usually be the *expansion* file).
-/// Returns None if includes should not be inserted for this file.
-llvm::Optional
-getIncludeHeader(llvm::StringRef QName, const SourceManager ,
- const Preprocessor , FileID FID,
- const SymbolCollector::Options ) {
-  const FileEntry *FE = SM.getFileEntryForID(FID);
-  if (!FE || FE->getName().empty())
-return llvm::None;
-  llvm::StringRef Filename = FE->getName();
-  // If a file is mapped by canonical headers, use that mapping, regardless
-  // of whether it's an otherwise-good header (header guards etc).
-  if (Opts.Includes) {
-llvm::StringRef Canonical = Opts.Includes->mapHeader(Filename, QName);
-// If we had a mapping, always use it.
-if (Canonical.startswith("<") || Canonical.startswith("\""))
-  return Canonical.str();
-if (Canonical != Filename)
-  return toURI(SM, Canonical, Opts);
-  }
-  if (!isSelfContainedHeader(FID, SM, PP)) {
-// A .inc or .def file is often included into a real header to define
-// symbols (e.g. LLVM tablegen files).
-if (Filename.endswith(".inc") || Filename.endswith(".def"))
-  return getIncludeHeader(QName, SM, PP,
-  SM.getFileID(SM.getIncludeLoc(FID)), Opts);
-// Conservatively refuse to insert #includes to files without guards.
-return llvm::None;
-  }
-  // Standard case: just insert the file itself.
-  return toURI(SM, Filename, Opts);
-}
-
 // Return the symbol range of the token at \p TokLoc.
 std::pair
 getTokenRange(SourceLocation TokLoc, const SourceManager ,
@@ -452,9 +410,8 @@
 
   std::string Include;
   if (Opts.CollectIncludePath && shouldCollectIncludePath(S.SymInfo.Kind)) {
-if (auto Header =
-getIncludeHeader(Name->getName(), SM, *PP,
- SM.getDecomposedExpansionLoc(DefLoc).first, Opts))
+if (auto Header = getIncludeHeader(
+Name->getName(), SM.getDecomposedExpansionLoc(DefLoc).first))
   Include = std::move(*Header);
   }
   S.Signature = Signature;
@@ -533,6 +490,7 @@
   ReferencedMacros.clear();
   DeclRefs.clear();
   FilesToIndexCache.clear();
+  HeaderIsSelfContainedCache.clear();
 }
 
 const Symbol *SymbolCollector::addDeclaration(const NamedDecl , SymbolID ID,
@@ -602,8 +560,7 @@
 // Use the expansion location to get the #include header since this is
 // where the symbol is exposed.
 if (auto Header = getIncludeHeader(
-QName, SM, *PP,
-SM.getDecomposedExpansionLoc(ND.getLocation()).first, Opts))
+QName, SM.getDecomposedExpansionLoc(ND.getLocation()).first))
   Include = std::move(*Header);
   }
   if (!Include.empty())
@@ -639,5 +596,59 @@
   Symbols.insert(S);
 }
 
+/// Gets a canonical include (URI of the header or  or "header") for
+/// header of \p FID (which should usually be the *expansion* file).
+/// Returns None if includes should not be inserted for this file.
+llvm::Optional
+SymbolCollector::getIncludeHeader(llvm::StringRef QName, FileID FID) {
+  const SourceManager  = ASTCtx->getSourceManager();
+  const FileEntry *FE = SM.getFileEntryForID(FID);
+  if (!FE || FE->getName().empty())
+return llvm::None;
+  llvm::StringRef Filename = FE->getName();
+  // If a file is mapped by canonical headers, use that mapping, regardless
+  // of whether it's an otherwise-good header (header guards etc).
+  if (Opts.Includes) {
+llvm::StringRef Canonical = Opts.Includes->mapHeader(Filename, QName);
+// If we had a mapping, always use it.
+if (Canonical.startswith("<") || Canonical.startswith("\""))
+  return Canonical.str();
+if (Canonical != Filename)
+  return toURI(SM, Canonical, Opts);
+  }
+  if (!isSelfContainedHeader(FID)) {
+// A .inc or .def file is often included into a real header to define
+// symbols (e.g. 

[PATCH] D60719: Demonstrate how to fix freestanding for memcpy

2019-04-17 Thread Tim Northover via Phabricator via cfe-commits
t.p.northover added a comment.

> IIUC freestanding environment should not rely on memcpy being present so my 
> take on it was that by "fixing" freestanding I could have my cake and eat it 
> too.

The formal situation is that freestanding implementations are only required to 
provide language support stuff like `va_list`. They're allowed to give more of 
the standard library if they want though, as implementation defined behaviour.

In practice, everyone I know provides the basic `string.h` functions and the 
compiler is pretty explicit about relying on them being present for 
correctness. They're part of the surrounding environment a user is expected to 
supply (much like the various exception handling callbacks if you want C++ 
exceptions, but always required).

For the people actually using freestanding I think they're mostly considered 
important enough that they're implemented in assembly anyway so this isn't 
really a burden, but...

> Ultimately I'm interested in implementing libc's mem function in C++. Let's 
> take memcpy for instance

Ah, that is an entirely different problem from what I thought you were trying 
to do. In that case I'm all in favour of some solution, but would start 
thinking along the lines of `-fno-builtin-memcpy` options (it's possible that 
already does what you want, but can't get LLVM to form a `memcpy` from quick 
tests to check).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60719



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


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-17 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 195609.
gtbercea marked an inline comment as done.
gtbercea added a comment.

- Update error message.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568

Files:
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CodeGenModule.cpp
  test/OpenMP/openmp_offload_registration.cpp

Index: test/OpenMP/openmp_offload_registration.cpp
===
--- test/OpenMP/openmp_offload_registration.cpp
+++ test/OpenMP/openmp_offload_registration.cpp
@@ -26,7 +26,7 @@
 // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 2, [[DEVTY]]* getelementptr inbounds ([2 x [[DEVTY]]], [2 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]])
 
 // Check target registration is registered as a Ctor.
-// CHECK: appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 0, void ()* @[[REGFN]], i8* bitcast (void ()* @[[REGFN]] to i8*) }]
+// CHECK: appending global [2 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 0, void ()* @.omp_offloading.requires_reg, i8* null }, { i32, void ()*, i8* } { i32 0, void ()* @[[REGFN]], i8* bitcast (void ()* @[[REGFN]] to i8*) }]
 
 // Check presence of foo() and the outlined target region
 // CHECK: define void [[FOO:@.+]]()
@@ -34,6 +34,11 @@
 
 // Check registration and unregistration code.
 
+// CHECK: define internal void @.omp_offloading.requires_reg()
+// CHECK: call void @__tgt_register_requires(i64 0)
+// CHECK: ret void
+// CHECK: declare void @__tgt_register_requires(i64)
+
 // CHECK: define internal void @[[UNREGFN:.+]](i8*)
 // CHECK-SAME: comdat($[[REGFN]]) {
 // CHECK: call i32 @__tgt_unregister_lib([[DSCTY]]* [[DESC]])
Index: lib/CodeGen/CodeGenModule.cpp
===
--- lib/CodeGen/CodeGenModule.cpp
+++ lib/CodeGen/CodeGenModule.cpp
@@ -410,6 +410,10 @@
   AddGlobalCtor(CudaCtorFunction);
   }
   if (OpenMPRuntime) {
+if (llvm::Function *OpenMPRequiresDirectiveRegFun =
+OpenMPRuntime->emitRequiresDirectiveRegFun()) {
+  AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
+}
 if (llvm::Function *OpenMPRegistrationFunction =
 OpenMPRuntime->emitRegistrationFunction()) {
   auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
Index: lib/CodeGen/CGOpenMPRuntimeNVPTX.h
===
--- lib/CodeGen/CGOpenMPRuntimeNVPTX.h
+++ lib/CodeGen/CGOpenMPRuntimeNVPTX.h
@@ -383,7 +383,7 @@
 
   /// Perform check on requires decl to ensure that target architecture
   /// supports unified addressing
-  void checkArchForUnifiedAddressing(const OMPRequiresDecl *D) const override;
+  void checkArchForUnifiedAddressing(const OMPRequiresDecl *D) override;
 
   /// Returns default address space for the constant firstprivates, __constant__
   /// address space by default.
Index: lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
===
--- lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
+++ lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
@@ -4942,7 +4942,7 @@
 /// Check to see if target architecture supports unified addressing which is
 /// a restriction for OpenMP requires clause "unified_shared_memory".
 void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
-const OMPRequiresDecl *D) const {
+const OMPRequiresDecl *D) {
   for (const OMPClause *Clause : D->clauselists()) {
 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
   switch (getCudaArch(CGM)) {
@@ -4987,6 +4987,7 @@
   }
 }
   }
+  CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
 }
 
 /// Get number of SMs and number of blocks per SM.
Index: lib/CodeGen/CGOpenMPRuntime.h
===
--- lib/CodeGen/CGOpenMPRuntime.h
+++ lib/CodeGen/CGOpenMPRuntime.h
@@ -636,6 +636,17 @@
   /// must be emitted.
   llvm::SmallDenseSet DeferredGlobalVariables;
 
+  /// Flag for keeping track of weather a requires unified_shared_memory
+  /// directive is present.
+  bool HasRequiresUnifiedSharedMemory = false;
+
+  /// Flag for keeping track of weather a target region has been emitted.
+  bool HasEmittedTargetRegion = false;
+
+  /// Flag for keeping track of weather a device routine has been emitted.
+  /// Device routines are specific to the
+  bool HasEmittedDeclareTargetRegion = false;
+
   /// Creates and registers offloading binary descriptor for the current
   /// compilation unit. The function that does the registration is returned.
   llvm::Function *createOffloadingBinaryDescriptorRegistration();
@@ -1429,6 +1440,10 @@
   /// \param GD Global to scan.
   virtual bool emitTargetGlobal(GlobalDecl GD);
 
+  

[PATCH] D60835: [Serialization] Stable serialization order for OpenCLTypeExtMap and OpenCLDeclExtMap

2019-04-17 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno created this revision.
riccibruno added reviewers: Anastasia, lebedev.ri.
riccibruno added a project: clang.
Herald added subscribers: cfe-commits, mgrang, yaxunl.

Sort the elements of `Sema::OpenCLTypeExtMap` and `Sema::OpenCLDeclExtMap` by 
`TypeID`s and `DeclID`s to guarantee a stable serialization order.


Repository:
  rC Clang

https://reviews.llvm.org/D60835

Files:
  lib/Serialization/ASTWriter.cpp


Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -4278,14 +4278,32 @@
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
+  // without copying them.
+  const llvm::DenseMap>  =
+  SemaRef.OpenCLTypeExtMap;
+  using ElementTy = std::pair *>;
+  llvm::SmallVector StableOpenCLTypeExtMap;
+  StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
+
+  for (const auto  : OpenCLTypeExtMap)
+StableOpenCLTypeExtMap.emplace_back(
+getTypeID(I.first->getCanonicalTypeInternal()), );
+
+  auto CompareByTypeID = [](const ElementTy , const ElementTy ) -> bool {
+return E1.first < E2.first;
+  };
+  llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
+
   RecordData Record;
-  for (const auto  : SemaRef.OpenCLTypeExtMap) {
-Record.push_back(
-static_cast(getTypeID(I.first->getCanonicalTypeInternal(;
-Record.push_back(I.second.size());
-for (auto Ext : I.second)
+  for (const ElementTy  : StableOpenCLTypeExtMap) {
+Record.push_back(E.first); // TypeID
+const std::set *ExtSet = E.second;
+Record.push_back(static_cast(ExtSet->size()));
+for (const std::string  : *ExtSet)
   AddString(Ext, Record);
   }
+
   Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
 }
 
@@ -4293,13 +4311,31 @@
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
+  // without copying them.
+  const llvm::DenseMap>  =
+  SemaRef.OpenCLDeclExtMap;
+  using ElementTy = std::pair *>;
+  llvm::SmallVector StableOpenCLDeclExtMap;
+  StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
+
+  for (const auto  : OpenCLDeclExtMap)
+StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), );
+
+  auto CompareByDeclID = [](const ElementTy , const ElementTy ) -> bool {
+return E1.first < E2.first;
+  };
+  llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
+
   RecordData Record;
-  for (const auto  : SemaRef.OpenCLDeclExtMap) {
-Record.push_back(getDeclID(I.first));
-Record.push_back(static_cast(I.second.size()));
-for (auto Ext : I.second)
+  for (const ElementTy  : StableOpenCLDeclExtMap) {
+Record.push_back(E.first); // DeclID
+const std::set *ExtSet = E.second;
+Record.push_back(static_cast(ExtSet->size()));
+for (const std::string  : *ExtSet)
   AddString(Ext, Record);
   }
+
   Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
 }
 


Index: lib/Serialization/ASTWriter.cpp
===
--- lib/Serialization/ASTWriter.cpp
+++ lib/Serialization/ASTWriter.cpp
@@ -4278,14 +4278,32 @@
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
+  // without copying them.
+  const llvm::DenseMap>  =
+  SemaRef.OpenCLTypeExtMap;
+  using ElementTy = std::pair *>;
+  llvm::SmallVector StableOpenCLTypeExtMap;
+  StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
+
+  for (const auto  : OpenCLTypeExtMap)
+StableOpenCLTypeExtMap.emplace_back(
+getTypeID(I.first->getCanonicalTypeInternal()), );
+
+  auto CompareByTypeID = [](const ElementTy , const ElementTy ) -> bool {
+return E1.first < E2.first;
+  };
+  llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
+
   RecordData Record;
-  for (const auto  : SemaRef.OpenCLTypeExtMap) {
-Record.push_back(
-static_cast(getTypeID(I.first->getCanonicalTypeInternal(;
-Record.push_back(I.second.size());
-for (auto Ext : I.second)
+  for (const ElementTy  : StableOpenCLTypeExtMap) {
+Record.push_back(E.first); // TypeID
+const std::set *ExtSet = E.second;
+Record.push_back(static_cast(ExtSet->size()));
+for (const std::string  : *ExtSet)
   AddString(Ext, Record);
   }
+
   Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
 }
 
@@ -4293,13 +4311,31 @@
   if (!SemaRef.Context.getLangOpts().OpenCL)
 return;
 
+  // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
+  // without copying them.
+  const llvm::DenseMap>  =
+  SemaRef.OpenCLDeclExtMap;
+  using ElementTy = std::pair *>;
+  llvm::SmallVector StableOpenCLDeclExtMap;
+  StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
+
+  for (const auto  : OpenCLDeclExtMap)
+StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), );
+
+  auto CompareByDeclID = 

[PATCH] D60778: Make precompiled headers reproducible by switching OpenCL extension to std::map

2019-04-17 Thread Bruno Ricci via Phabricator via cfe-commits
riccibruno added a comment.

What about something like D60835  ?


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

https://reviews.llvm.org/D60778



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


[PATCH] D60736: [Sema][ObjC] Don't warn about a block implicitly retaining self if the block is marked noescape

2019-04-17 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 195639.
ahatanak added a comment.

Diagnose implicitly retained self in `ActOnFinishFunctionBody`.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60736

Files:
  include/clang/AST/DeclBase.h
  include/clang/Sema/Sema.h
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaDeclObjC.cpp
  lib/Sema/SemaExpr.cpp
  test/SemaObjC/warn-implicit-self-in-block.m
  test/SemaObjCXX/warn-implicit-self-in-block.mm

Index: test/SemaObjCXX/warn-implicit-self-in-block.mm
===
--- /dev/null
+++ test/SemaObjCXX/warn-implicit-self-in-block.mm
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -x objective-c++ -std=c++11 -fobjc-arc -fblocks -Wimplicit-retain-self -verify %s
+// rdar://11194874
+
+typedef void (^BlockTy)();
+
+void noescapeFunc(__attribute__((noescape)) BlockTy);
+void escapeFunc(BlockTy);
+
+@interface Root @end
+
+@interface I : Root
+{
+  int _bar;
+}
+@end
+
+@implementation I
+  - (void)foo{
+  ^{
+   _bar = 3; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+   }();
+  }
+
+  - (void)testNested{
+noescapeFunc(^{
+  (void)_bar;
+  escapeFunc(^{
+(void)_bar; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+noescapeFunc(^{
+  (void)_bar; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+});
+(void)_bar; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+  });
+  (void)_bar;
+});
+  }
+
+  - (void)testLambdaInBlock{
+noescapeFunc(^{ [&](){ (void)_bar; }(); });
+escapeFunc(^{ [&](){ (void)_bar; }(); }); // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+  }
+@end
Index: test/SemaObjC/warn-implicit-self-in-block.m
===
--- test/SemaObjC/warn-implicit-self-in-block.m
+++ /dev/null
@@ -1,18 +0,0 @@
-// RUN: %clang_cc1 -x objective-c -fobjc-arc -fblocks -Wimplicit-retain-self -verify %s
-// rdar://11194874
-
-@interface Root @end
-
-@interface I : Root
-{
-  int _bar;
-}
-@end
-
-@implementation I
-  - (void)foo{
-  ^{
-   _bar = 3; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
-   }();
-  }
-@end
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -2575,11 +2575,9 @@
 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
   getCurFunction()->recordUseOfWeak(Result);
   }
-  if (getLangOpts().ObjCAutoRefCount) {
-if (CurContext->isClosure())
-  Diag(Loc, diag::warn_implicitly_retains_self)
-<< FixItHint::CreateInsertion(Loc, "self->");
-  }
+  if (getLangOpts().ObjCAutoRefCount)
+if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
+  ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
 
   return Result;
 }
Index: lib/Sema/SemaDeclObjC.cpp
===
--- lib/Sema/SemaDeclObjC.cpp
+++ lib/Sema/SemaDeclObjC.cpp
@@ -359,6 +359,7 @@
 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
 /// and user declared, in the method definition's AST.
 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
+  ImplicitlyRetainedSelfLocs.clear();
   assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
   ObjCMethodDecl *MDecl = dyn_cast_or_null(D);
 
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -13155,6 +13155,35 @@
   bool IsLambda = false;
 };
 
+static void diagnoseImplicitlyRetainedSelf(Sema ) {
+  llvm::DenseMap EscapeInfo;
+
+  auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
+if (EscapeInfo.count(BD))
+  return EscapeInfo[BD];
+
+bool R = false;
+const BlockDecl *CurBD = BD;
+
+do {
+  R = R || !CurBD->doesNotEscape();
+  if (R)
+break;
+  CurBD = CurBD->getParent()->getInnermostBlockDecl();
+} while (CurBD);
+
+return EscapeInfo[BD] = R;
+  };
+
+  // If the location where 'self' is implicitly retained is inside a escaping
+  // block, emit a diagnostic.
+  for (const std::pair  :
+   S.ImplicitlyRetainedSelfLocs)
+if (IsOrNestedInEscapingBlock(P.second))
+  S.Diag(P.first, diag::warn_implicitly_retains_self)
+  << FixItHint::CreateInsertion(P.first, "self->");
+}
+
 Decl 

[PATCH] D60543: [clang] Add matcher for subclasses of Objective-C interfaces 

2019-04-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:1479
+/// \endcode
+AST_MATCHER_P(ObjCInterfaceDecl, isSubclassOfInterface,
+  internal::Matcher,

jordan_rose wrote:
> aaron.ballman wrote:
> > jordan_rose wrote:
> > > aaron.ballman wrote:
> > > > stephanemoore wrote:
> > > > > aaron.ballman wrote:
> > > > > > stephanemoore wrote:
> > > > > > > I am still uncertain about the naming.
> > > > > > > 
> > > > > > > `isSubclassOf` seemed too generic as that could apply to C++ 
> > > > > > > classes.
> > > > > > > `objcIsSubclassOf` seemed unconventional as a matcher name.
> > > > > > > `isSubclassOfObjCInterface` and `isSubclassOfObjCClass` seemed 
> > > > > > > awkwardly lengthy.
> > > > > > > Creating a new namespace `clang::ast_matchers::objc` seemed 
> > > > > > > unprecedented.
> > > > > > > 
> > > > > > > I am happy to change the name if you think another name would be 
> > > > > > > more appropriate.
> > > > > > Does ObjC use the term "derived" by any chance? We already have 
> > > > > > `isDerivedFrom`, so I'm wondering if we can use that to also match 
> > > > > > on an `ObjCInterfaceDecl`?
> > > > > Objective-C doesn't generally use the term "derived" (for example, 
> > > > > see archive of [Programming With Objective-C > Defining 
> > > > > Classes](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW1)).
> > > > >  With that said, I don't think it's unreasonable or incorrect to use 
> > > > > the term "derived" to describe inheritance in Objective-C. The 
> > > > > behavior of this matcher is also consistent with the behavior of 
> > > > > `isDerivedFrom`. In order to change `isDerivedFrom`, I would also 
> > > > > need to update `isSameOrDerivedFrom`. That would probably be a good 
> > > > > thing so that derivation matching feature set is consistent for C++ 
> > > > > and Objective-C language variants.
> > > > > 
> > > > > Let me take a crack at merging this into `isDerivedFrom`.
> > > > I agree that if we go with `isDerivedFrom`, you should update 
> > > > `isSameOrDerivedFrom` at the same time.
> > > `isSubclassOf` sounds right to me, and since ObjC and C++ class 
> > > hierarchies can't mix, it _should_ be okay, right? They're analogous 
> > > concepts.
> > > isSubclassOf sounds right to me, and since ObjC and C++ class hierarchies 
> > > can't mix, it _should_ be okay, right? They're analogous concepts.
> > 
> > In the AST matchers, we try to overload the matchers that have similar 
> > behavior. My concern is that a user will reach for `isSubclassOf()` when 
> > they really mean `isDerivedFrom()` or vice versa, and only through annoying 
> > error messages learns about their mistake. Given that we already have 
> > `isDerivedFrom()` and renaming it would break code, I was trying to 
> > determine whether using that name for both C++ derivation and ObjC 
> > derivation would be acceptable.
> Ah, I see what you mean. Yes, I guess it's more important to be consistent 
> than to perfectly match the terminology. You will certainly confuse an 
> ObjC-only developer at first by using "non-standard" terminology, but any 
> developer has to learn a certain amount of compiler-isms anyway using AST 
> matchers.
Okay, so it sounds like it wouldn't be hugely problematic to go with 
`isDerivedFrom()`, just that it may sound a bit confusing at first to an ObjC 
developer. Are there some words you think we should add to the documentation to 
help an ObjC developer searching for this functionality?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60543



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


[clang-tools-extra] r358611 - [clangd] Use shorter, more recognizable codes for diagnostics.

2019-04-17 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Wed Apr 17 13:12:03 2019
New Revision: 358611

URL: http://llvm.org/viewvc/llvm-project?rev=358611=rev
Log:
[clangd] Use shorter, more recognizable codes for diagnostics.

Summary:
 - for warnings, use the flag the warning is controlled by (-Wfoo)
 - for errors, keep using the internal name (there's nothing better) but
   drop the err_ prefix

This comes at the cost of uniformity, it's no longer totally obvious
exactly what the code field contains. But the -Wname flags are so much
more useful to end-users than the internal warn_foo that this seems worth it.

Reviewers: kadircet

Subscribers: ilya-biryukov, ioeric, MaskRay, jkorous, arphaman, cfe-commits

Tags: #clang

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

Modified:
clang-tools-extra/trunk/clangd/Diagnostics.cpp
clang-tools-extra/trunk/test/clangd/compile-commands-path-in-initialize.test
clang-tools-extra/trunk/test/clangd/diagnostic-category.test
clang-tools-extra/trunk/test/clangd/diagnostics.test
clang-tools-extra/trunk/test/clangd/did-change-configuration-params.test
clang-tools-extra/trunk/test/clangd/execute-command.test
clang-tools-extra/trunk/test/clangd/fixits-codeaction.test
clang-tools-extra/trunk/test/clangd/fixits-command.test
clang-tools-extra/trunk/test/clangd/fixits-embed-in-diagnostic.test
clang-tools-extra/trunk/unittests/clangd/DiagnosticsTests.cpp

Modified: clang-tools-extra/trunk/clangd/Diagnostics.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Diagnostics.cpp?rev=358611=358610=358611=diff
==
--- clang-tools-extra/trunk/clangd/Diagnostics.cpp (original)
+++ clang-tools-extra/trunk/clangd/Diagnostics.cpp Wed Apr 17 13:12:03 2019
@@ -331,7 +331,17 @@ std::vector StoreDiags::take(const
   // Fill in name/source now that we have all the context needed to map them.
   for (auto  : Output) {
 if (const char *ClangDiag = getDiagnosticCode(Diag.ID)) {
-  Diag.Name = ClangDiag;
+  // Warnings controlled by -Wfoo are better recognized by that name.
+  StringRef Warning = DiagnosticIDs::getWarningOptionForDiag(Diag.ID);
+  if (!Warning.empty()) {
+Diag.Name = ("-W" + Warning).str();
+  } else {
+StringRef Name(ClangDiag);
+// Almost always an error, with a name like err_enum_class_reference.
+// Drop the err_ prefix for brevity.
+Name.consume_front("err_");
+Diag.Name = Name;
+  }
   Diag.Source = Diag::Clang;
   continue;
 }

Modified: 
clang-tools-extra/trunk/test/clangd/compile-commands-path-in-initialize.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/compile-commands-path-in-initialize.test?rev=358611=358610=358611=diff
==
--- 
clang-tools-extra/trunk/test/clangd/compile-commands-path-in-initialize.test 
(original)
+++ 
clang-tools-extra/trunk/test/clangd/compile-commands-path-in-initialize.test 
Wed Apr 17 13:12:03 2019
@@ -21,7 +21,7 @@
 # CHECK-NEXT:   "params": {
 # CHECK-NEXT: "diagnostics": [
 # CHECK-NEXT:   {
-# CHECK-NEXT: "code": "warn_pragma_message",
+# CHECK-NEXT: "code": "-W#pragma-messages",
 # CHECK-NEXT: "message": "MACRO is one",
 ---
 {"jsonrpc":"2.0","id":1,"method":"shutdown"}

Modified: clang-tools-extra/trunk/test/clangd/diagnostic-category.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/diagnostic-category.test?rev=358611=358610=358611=diff
==
--- clang-tools-extra/trunk/test/clangd/diagnostic-category.test (original)
+++ clang-tools-extra/trunk/test/clangd/diagnostic-category.test Wed Apr 17 
13:12:03 2019
@@ -7,7 +7,7 @@
 # CHECK-NEXT: "diagnostics": [
 # CHECK-NEXT:  {
 # CHECK-NEXT:"category": "Semantic Issue",
-# CHECK-NEXT:"code": "err_use_with_wrong_tag",
+# CHECK-NEXT:"code": "use_with_wrong_tag",
 # CHECK-NEXT:"message": "Use of 'Point' with tag type that does not 
match previous declaration (fix available)\n\nfoo.c:1:8: note: previous use is 
here",
 # CHECK-NEXT:"range": {
 # CHECK-NEXT:  "end": {

Modified: clang-tools-extra/trunk/test/clangd/diagnostics.test
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clangd/diagnostics.test?rev=358611=358610=358611=diff
==
--- clang-tools-extra/trunk/test/clangd/diagnostics.test (original)
+++ clang-tools-extra/trunk/test/clangd/diagnostics.test Wed Apr 17 13:12:03 
2019
@@ -6,7 +6,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"diagnostics": [
 # CHECK-NEXT:  {
-# CHECK-NEXT:"code": "ext_main_returns_nonint",
+# CHECK-NEXT:"code": "-Wmain-return-type",
 # 

[PATCH] D60417: [libunwind] Add support for ARMv7-M architecture which uses the Thumb 2 ISA (unified syntax)

2019-04-17 Thread Louis Dionne via Phabricator via cfe-commits
ldionne accepted this revision.
ldionne added a comment.
This revision is now accepted and ready to land.

I'm relaying approval to @mstorsjo, who seems okay with the change.


Repository:
  rUNW libunwind

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

https://reviews.llvm.org/D60417



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


[PATCH] D59371: [LibTooling] Add Stencil library for format-string style codegen.

2019-04-17 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 195602.
ymandel marked 9 inline comments as done.
ymandel added a comment.

Responded to comments, including changing call operator to return 
Expected instead of string.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59371

Files:
  clang/include/clang/Tooling/Refactoring/Stencil.h
  clang/lib/Tooling/Refactoring/CMakeLists.txt
  clang/lib/Tooling/Refactoring/Stencil.cpp
  clang/unittests/Tooling/CMakeLists.txt
  clang/unittests/Tooling/StencilTest.cpp

Index: clang/unittests/Tooling/StencilTest.cpp
===
--- /dev/null
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -0,0 +1,223 @@
+//===- unittest/Tooling/StencilTest.cpp ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Tooling/Refactoring/Stencil.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/FixIt.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+using namespace tooling;
+using namespace ast_matchers;
+
+namespace {
+using ::testing::AllOf;
+using ::testing::Eq;
+using ::testing::HasSubstr;
+using MatchResult = MatchFinder::MatchResult;
+using tooling::stencil::node;
+using tooling::stencil::sNode;
+using tooling::stencil::text;
+
+// In tests, we can't directly match on llvm::Expected since its accessors
+// mutate the object. So, we collapse it to an Optional.
+static llvm::Optional toOptional(llvm::Expected V) {
+  if (V)
+return *V;
+  ADD_FAILURE() << "Losing error in conversion to IsSomething: "
+<< llvm::toString(V.takeError());
+  return llvm::None;
+}
+
+// A very simple matcher for llvm::Optional values.
+MATCHER_P(IsSomething, ValueMatcher, "") {
+  if (!arg)
+return false;
+  return ::testing::ExplainMatchResult(ValueMatcher, *arg, result_listener);
+}
+
+// Create a valid translation-unit from a statement.
+static std::string wrapSnippet(llvm::Twine StatementCode) {
+  return ("auto stencil_test_snippet = []{" + StatementCode + "};").str();
+}
+
+static DeclarationMatcher wrapMatcher(const StatementMatcher ) {
+  return varDecl(hasName("stencil_test_snippet"),
+ hasDescendant(compoundStmt(hasAnySubstatement(Matcher;
+}
+
+struct TestMatch {
+  // The AST unit from which `result` is built. We bundle it because it backs
+  // the result. Users are not expected to access it.
+  std::unique_ptr AstUnit;
+  // The result to use in the test. References `ast_unit`.
+  MatchResult Result;
+};
+
+// Matches `Matcher` against the statement `StatementCode` and returns the
+// result. Handles putting the statement inside a function and modifying the
+// matcher correspondingly. `Matcher` should match `StatementCode` exactly --
+// that is, produce exactly one match.
+static llvm::Optional matchStmt(llvm::Twine StatementCode,
+   StatementMatcher Matcher) {
+  auto AstUnit = buildASTFromCode(wrapSnippet(StatementCode));
+  if (AstUnit == nullptr) {
+ADD_FAILURE() << "AST construction failed";
+return llvm::None;
+  }
+  ASTContext  = AstUnit->getASTContext();
+  auto Matches = ast_matchers::match(wrapMatcher(Matcher), Context);
+  // We expect a single, exact match for the statement.
+  if (Matches.size() != 1) {
+ADD_FAILURE() << "Wrong number of matches: " << Matches.size();
+return llvm::None;
+  }
+  return TestMatch{std::move(AstUnit), MatchResult(Matches[0], )};
+}
+
+class StencilTest : public ::testing::Test {
+protected:
+  // Verifies that the given stencil fails when evaluated on a valid match
+  // result. Binds a statement to "stmt", a (non-member) ctor-initializer to
+  // "init", an expression to "expr" and a (nameless) declaration to "decl".
+  void testError(const Stencil ,
+ ::testing::Matcher Matcher) {
+const std::string Snippet = R"cc(
+  struct A {};
+  class F : public A {
+   public:
+F(int) {}
+  };
+  F(1);
+)cc";
+auto StmtMatch = matchStmt(
+Snippet,
+stmt(hasDescendant(
+ cxxConstructExpr(
+ hasDeclaration(decl(hasDescendant(cxxCtorInitializer(
+   isBaseInitializer())
+   .bind("init")))
+.bind("decl")))
+ .bind("expr")))
+.bind("stmt"));
+ASSERT_TRUE(StmtMatch);
+if (auto ResultOrErr = Stencil.eval(StmtMatch->Result)) {
+  ADD_FAILURE() << "Expected 

[PATCH] D60543: [clang] Add matcher for subclasses of Objective-C interfaces 

2019-04-17 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:1479
+/// \endcode
+AST_MATCHER_P(ObjCInterfaceDecl, isSubclassOfInterface,
+  internal::Matcher,

jordan_rose wrote:
> aaron.ballman wrote:
> > stephanemoore wrote:
> > > aaron.ballman wrote:
> > > > stephanemoore wrote:
> > > > > I am still uncertain about the naming.
> > > > > 
> > > > > `isSubclassOf` seemed too generic as that could apply to C++ classes.
> > > > > `objcIsSubclassOf` seemed unconventional as a matcher name.
> > > > > `isSubclassOfObjCInterface` and `isSubclassOfObjCClass` seemed 
> > > > > awkwardly lengthy.
> > > > > Creating a new namespace `clang::ast_matchers::objc` seemed 
> > > > > unprecedented.
> > > > > 
> > > > > I am happy to change the name if you think another name would be more 
> > > > > appropriate.
> > > > Does ObjC use the term "derived" by any chance? We already have 
> > > > `isDerivedFrom`, so I'm wondering if we can use that to also match on 
> > > > an `ObjCInterfaceDecl`?
> > > Objective-C doesn't generally use the term "derived" (for example, see 
> > > archive of [Programming With Objective-C > Defining 
> > > Classes](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW1)).
> > >  With that said, I don't think it's unreasonable or incorrect to use the 
> > > term "derived" to describe inheritance in Objective-C. The behavior of 
> > > this matcher is also consistent with the behavior of `isDerivedFrom`. In 
> > > order to change `isDerivedFrom`, I would also need to update 
> > > `isSameOrDerivedFrom`. That would probably be a good thing so that 
> > > derivation matching feature set is consistent for C++ and Objective-C 
> > > language variants.
> > > 
> > > Let me take a crack at merging this into `isDerivedFrom`.
> > I agree that if we go with `isDerivedFrom`, you should update 
> > `isSameOrDerivedFrom` at the same time.
> `isSubclassOf` sounds right to me, and since ObjC and C++ class hierarchies 
> can't mix, it _should_ be okay, right? They're analogous concepts.
> isSubclassOf sounds right to me, and since ObjC and C++ class hierarchies 
> can't mix, it _should_ be okay, right? They're analogous concepts.

In the AST matchers, we try to overload the matchers that have similar 
behavior. My concern is that a user will reach for `isSubclassOf()` when they 
really mean `isDerivedFrom()` or vice versa, and only through annoying error 
messages learns about their mistake. Given that we already have 
`isDerivedFrom()` and renaming it would break code, I was trying to determine 
whether using that name for both C++ derivation and ObjC derivation would be 
acceptable.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60543



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


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-17 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 195608.
gtbercea marked an inline comment as done.
gtbercea added a comment.

- Add support for declare target routines.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568

Files:
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CodeGenModule.cpp
  test/OpenMP/openmp_offload_registration.cpp

Index: test/OpenMP/openmp_offload_registration.cpp
===
--- test/OpenMP/openmp_offload_registration.cpp
+++ test/OpenMP/openmp_offload_registration.cpp
@@ -26,7 +26,7 @@
 // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 2, [[DEVTY]]* getelementptr inbounds ([2 x [[DEVTY]]], [2 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]])
 
 // Check target registration is registered as a Ctor.
-// CHECK: appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 0, void ()* @[[REGFN]], i8* bitcast (void ()* @[[REGFN]] to i8*) }]
+// CHECK: appending global [2 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 0, void ()* @.omp_offloading.requires_reg, i8* null }, { i32, void ()*, i8* } { i32 0, void ()* @[[REGFN]], i8* bitcast (void ()* @[[REGFN]] to i8*) }]
 
 // Check presence of foo() and the outlined target region
 // CHECK: define void [[FOO:@.+]]()
@@ -34,6 +34,11 @@
 
 // Check registration and unregistration code.
 
+// CHECK: define internal void @.omp_offloading.requires_reg()
+// CHECK: call void @__tgt_register_requires(i64 0)
+// CHECK: ret void
+// CHECK: declare void @__tgt_register_requires(i64)
+
 // CHECK: define internal void @[[UNREGFN:.+]](i8*)
 // CHECK-SAME: comdat($[[REGFN]]) {
 // CHECK: call i32 @__tgt_unregister_lib([[DSCTY]]* [[DESC]])
Index: lib/CodeGen/CodeGenModule.cpp
===
--- lib/CodeGen/CodeGenModule.cpp
+++ lib/CodeGen/CodeGenModule.cpp
@@ -410,6 +410,10 @@
   AddGlobalCtor(CudaCtorFunction);
   }
   if (OpenMPRuntime) {
+if (llvm::Function *OpenMPRequiresDirectiveRegFun =
+OpenMPRuntime->emitRequiresDirectiveRegFun()) {
+  AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
+}
 if (llvm::Function *OpenMPRegistrationFunction =
 OpenMPRuntime->emitRegistrationFunction()) {
   auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
Index: lib/CodeGen/CGOpenMPRuntimeNVPTX.h
===
--- lib/CodeGen/CGOpenMPRuntimeNVPTX.h
+++ lib/CodeGen/CGOpenMPRuntimeNVPTX.h
@@ -383,7 +383,7 @@
 
   /// Perform check on requires decl to ensure that target architecture
   /// supports unified addressing
-  void checkArchForUnifiedAddressing(const OMPRequiresDecl *D) const override;
+  void checkArchForUnifiedAddressing(const OMPRequiresDecl *D) override;
 
   /// Returns default address space for the constant firstprivates, __constant__
   /// address space by default.
Index: lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
===
--- lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
+++ lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
@@ -4942,7 +4942,7 @@
 /// Check to see if target architecture supports unified addressing which is
 /// a restriction for OpenMP requires clause "unified_shared_memory".
 void CGOpenMPRuntimeNVPTX::checkArchForUnifiedAddressing(
-const OMPRequiresDecl *D) const {
+const OMPRequiresDecl *D) {
   for (const OMPClause *Clause : D->clauselists()) {
 if (Clause->getClauseKind() == OMPC_unified_shared_memory) {
   switch (getCudaArch(CGM)) {
@@ -4987,6 +4987,7 @@
   }
 }
   }
+  CGOpenMPRuntime::checkArchForUnifiedAddressing(D);
 }
 
 /// Get number of SMs and number of blocks per SM.
Index: lib/CodeGen/CGOpenMPRuntime.h
===
--- lib/CodeGen/CGOpenMPRuntime.h
+++ lib/CodeGen/CGOpenMPRuntime.h
@@ -636,6 +636,17 @@
   /// must be emitted.
   llvm::SmallDenseSet DeferredGlobalVariables;
 
+  /// Flag for keeping track of weather a requires unified_shared_memory
+  /// directive is present.
+  bool HasRequiresUnifiedSharedMemory = false;
+
+  /// Flag for keeping track of weather a target region has been emitted.
+  bool HasEmittedTargetRegion = false;
+
+  /// Flag for keeping track of weather a device routine has been emitted.
+  /// Device routines are specific to the
+  bool HasEmittedDeclareTargetRegion = false;
+
   /// Creates and registers offloading binary descriptor for the current
   /// compilation unit. The function that does the registration is returned.
   llvm::Function *createOffloadingBinaryDescriptorRegistration();
@@ -1429,6 +1440,10 @@
   /// \param GD Global to scan.
   virtual bool 

[PATCH] D59371: [LibTooling] Add Stencil library for format-string style codegen.

2019-04-17 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added inline comments.



Comment at: clang/lib/Tooling/Refactoring/Stencil.cpp:78
+
+template <> bool isEqualData(const RawTextData , const RawTextData ) {
+  return A.Text == B.Text;

ymandel wrote:
> sbenza wrote:
> > Any particular reason to use function template specialization instead of 
> > function overloading?
> > The former is rare and thus harder to reason about.
> > 
> > (same for `evalData` below)
> Stylistic -- it forces you to explicitly declare the "overload set" so to 
> speak.  However, i'm not particularly attached -- if you think this a bad 
> idea given its rarity, I'm happy to use overload sets. WDYT?
Converted to normal overload sets (as per off-thread chat).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59371



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


[PATCH] D60552: [X86] Enable intrinsics of AVX512_BF16, which are supported for BFLOAT16 in Cooper Lake

2019-04-17 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added inline comments.



Comment at: lib/Headers/avx512bf16intrin.h:23
+
+static __inline__ __m512bh __DEFAULT_FN_ATTRS512
+_mm512_cvtne2ps_pbh(__m512 __A, __m512 __B) {

All of these need proper doxygen based descriptions - see xmmintrin.h etc. for 
examples.



Comment at: test/CodeGen/avx512bf16-builtins.c:9
+  // CHECK-LABEL: @test_mm512_cvtne2ps2bf16
+  // CHECK: @llvm.x86.avx512bf16.cvtne2ps2bf16.512
+  return _mm512_cvtne2ps_pbh(A, B);

add ret/arg types?


Repository:
  rC Clang

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

https://reviews.llvm.org/D60552



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


Re: [PATCH] D60728: [clang] [test] Add a (xfailing) test for PR41027

2019-04-17 Thread Joerg Sonnenberger via cfe-commits
On Wed, Apr 17, 2019 at 05:34:04PM +, Kamil Rytarowski via Phabricator 
wrote:
> Right now this blocks upgrades on NetBSD as a number of CPUs is affected (but 
> not x86, so it was overlooked before 8.0 by others than @joerg).

Note that this is not about anything really specific to NetBSD, the kind
of conditional asm statements are pretty popular.

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


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-17 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea updated this revision to Diff 195644.
gtbercea added a comment.

- Update tests.
- Move error check in sema.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntime.h
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.h
  lib/CodeGen/CodeGenModule.cpp
  lib/Sema/SemaOpenMP.cpp
  test/OpenMP/openmp_offload_registration.cpp
  test/OpenMP/target_codegen.cpp
  test/OpenMP/target_codegen_registration.cpp

Index: test/OpenMP/target_codegen_registration.cpp
===
--- test/OpenMP/target_codegen_registration.cpp
+++ test/OpenMP/target_codegen_registration.cpp
@@ -180,10 +180,11 @@
 // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }, comdat($[[REGFN]])
 
 // We have 4 initializers, one for the 500 priority, another one for 501, or more for the default priority, and the last one for the offloading registration function.
-// CHECK: @llvm.global_ctors = appending global [4 x { i32, void ()*, i8* }] [
+// CHECK: @llvm.global_ctors = appending global [5 x { i32, void ()*, i8* }] [
 // CHECK-SAME: { i32, void ()*, i8* } { i32 500, void ()* [[P500:@[^,]+]], i8* null },
 // CHECK-SAME: { i32, void ()*, i8* } { i32 501, void ()* [[P501:@[^,]+]], i8* null },
 // CHECK-SAME: { i32, void ()*, i8* } { i32 65535, void ()* [[PMAX:@[^,]+]], i8* null },
+// CHECK-SAME: { i32, void ()*, i8* } { i32 0, void ()* @.omp_offloading.requires_reg, i8* null },
 // CHECK-SAME: { i32, void ()*, i8* } { i32 0, void ()* @[[REGFN]], i8* bitcast (void ()* @[[REGFN]] to i8*) }]
 
 // CHECK-NTARGET: @llvm.global_ctors = appending global [3   x { i32, void ()*, i8* }] [
@@ -387,6 +388,10 @@
 
 // Check registration and unregistration
 
+//CHECK: define internal void @.omp_offloading.requires_reg()
+//CHECK: call void @__tgt_register_requires(i64 1)
+//CHECK: ret void
+
 //CHECK: define internal void @[[UNREGFN:.+]](i8*)
 //CHECK-SAME: comdat($[[REGFN]]) {
 //CHECK: call i32 @__tgt_unregister_lib([[DSCTY]]* [[DESC]])
@@ -432,31 +437,31 @@
 
 // Check metadata is properly generated:
 // CHECK: !omp_offload.info = !{!{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 216, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 266, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 282, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 288, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 299, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 305, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 427, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 311, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 305, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 311, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 299, i32 {{[0-9]+}}}
-// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SCC1Ev", i32 241, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 217, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 267, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 283, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 289, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 300, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 306, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 432, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 312, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 306, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 312, i32 {{[0-9]+}}}
+// CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 300, i32 {{[0-9]+}}}
+// 

[PATCH] D60516: [LTO] Add plumbing to save stats during LTO on Darwin.

2019-04-17 Thread Steven Wu via Phabricator via cfe-commits
steven_wu accepted this revision.
steven_wu added a comment.
This revision is now accepted and ready to land.

LGTM with one additional small comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60516



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


[PATCH] D60543: [clang] Add matcher for subclasses of Objective-C interfaces 

2019-04-17 Thread Jordan Rose via Phabricator via cfe-commits
jordan_rose added inline comments.



Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:1479
+/// \endcode
+AST_MATCHER_P(ObjCInterfaceDecl, isSubclassOfInterface,
+  internal::Matcher,

aaron.ballman wrote:
> jordan_rose wrote:
> > aaron.ballman wrote:
> > > jordan_rose wrote:
> > > > aaron.ballman wrote:
> > > > > stephanemoore wrote:
> > > > > > aaron.ballman wrote:
> > > > > > > stephanemoore wrote:
> > > > > > > > I am still uncertain about the naming.
> > > > > > > > 
> > > > > > > > `isSubclassOf` seemed too generic as that could apply to C++ 
> > > > > > > > classes.
> > > > > > > > `objcIsSubclassOf` seemed unconventional as a matcher name.
> > > > > > > > `isSubclassOfObjCInterface` and `isSubclassOfObjCClass` seemed 
> > > > > > > > awkwardly lengthy.
> > > > > > > > Creating a new namespace `clang::ast_matchers::objc` seemed 
> > > > > > > > unprecedented.
> > > > > > > > 
> > > > > > > > I am happy to change the name if you think another name would 
> > > > > > > > be more appropriate.
> > > > > > > Does ObjC use the term "derived" by any chance? We already have 
> > > > > > > `isDerivedFrom`, so I'm wondering if we can use that to also 
> > > > > > > match on an `ObjCInterfaceDecl`?
> > > > > > Objective-C doesn't generally use the term "derived" (for example, 
> > > > > > see archive of [Programming With Objective-C > Defining 
> > > > > > Classes](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW1)).
> > > > > >  With that said, I don't think it's unreasonable or incorrect to 
> > > > > > use the term "derived" to describe inheritance in Objective-C. The 
> > > > > > behavior of this matcher is also consistent with the behavior of 
> > > > > > `isDerivedFrom`. In order to change `isDerivedFrom`, I would also 
> > > > > > need to update `isSameOrDerivedFrom`. That would probably be a good 
> > > > > > thing so that derivation matching feature set is consistent for C++ 
> > > > > > and Objective-C language variants.
> > > > > > 
> > > > > > Let me take a crack at merging this into `isDerivedFrom`.
> > > > > I agree that if we go with `isDerivedFrom`, you should update 
> > > > > `isSameOrDerivedFrom` at the same time.
> > > > `isSubclassOf` sounds right to me, and since ObjC and C++ class 
> > > > hierarchies can't mix, it _should_ be okay, right? They're analogous 
> > > > concepts.
> > > > isSubclassOf sounds right to me, and since ObjC and C++ class 
> > > > hierarchies can't mix, it _should_ be okay, right? They're analogous 
> > > > concepts.
> > > 
> > > In the AST matchers, we try to overload the matchers that have similar 
> > > behavior. My concern is that a user will reach for `isSubclassOf()` when 
> > > they really mean `isDerivedFrom()` or vice versa, and only through 
> > > annoying error messages learns about their mistake. Given that we already 
> > > have `isDerivedFrom()` and renaming it would break code, I was trying to 
> > > determine whether using that name for both C++ derivation and ObjC 
> > > derivation would be acceptable.
> > Ah, I see what you mean. Yes, I guess it's more important to be consistent 
> > than to perfectly match the terminology. You will certainly confuse an 
> > ObjC-only developer at first by using "non-standard" terminology, but any 
> > developer has to learn a certain amount of compiler-isms anyway using AST 
> > matchers.
> Okay, so it sounds like it wouldn't be hugely problematic to go with 
> `isDerivedFrom()`, just that it may sound a bit confusing at first to an ObjC 
> developer. Are there some words you think we should add to the documentation 
> to help an ObjC developer searching for this functionality?
I think just including "subclass" is sufficient. For example, the current doc 
comment is

```
/// Matches C++ classes that are directly or indirectly derived from
/// a class matching \c Base.
```

and it could be changed to something like

```
/// Matches C++ classes that are directly or indirectly derived from
/// a class matching \c Base, or Objective-C classes that directly or
/// indirectly subclass a class matching \c Base.
```

A little clunky, but you get what I mean.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60543



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


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-17 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea marked 2 inline comments as done.
gtbercea added inline comments.



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8975
+CGM.Error(Clause->getBeginLoc(),
+  "Target region emitted before requires directive.");
+  HasRequiresUnifiedSharedMemory = true;

ABataev wrote:
> The message speaks about target region but points to the clause. You need to 
> correct the message.
"A target region was emitted before this requires directive." ?


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568



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


[PATCH] D60568: [OpenMP] Add support for registering requires directives with the runtime

2019-04-17 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

Other tests in presence of the requires directive with the clause?




Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:8975
+CGM.Error(Clause->getBeginLoc(),
+  "Target region emitted before requires directive.");
+  HasRequiresUnifiedSharedMemory = true;

gtbercea wrote:
> ABataev wrote:
> > The message speaks about target region but points to the clause. You need 
> > to correct the message.
> "A target region was emitted before this requires directive." ?
Still does not look good, better to add previously emitted target regions in 
the diagnostic somehow. Also, it would be good to mention the clause in the 
message.



Comment at: lib/CodeGen/CGOpenMPRuntime.cpp:7956
 // Map other list items in the map clause which are not captured variables
-// but "declare target link" global variables.,
+// but "declare target link" global variables.
 for (const auto *C : this->CurDir.getClausesOfKind()) {

Restore the original, this must be changed in a separate patch.



Comment at: test/OpenMP/openmp_offload_registration.cpp:40
+// CHECK: ret void
+// CHECK: declare void @__tgt_register_requires(i64)
+

Why do you need this check?


Repository:
  rC Clang

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

https://reviews.llvm.org/D60568



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


[PATCH] D60736: [Sema][ObjC] Don't warn about a block implicitly retaining self if the block is marked noescape

2019-04-17 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

Alright, LGTM.


Repository:
  rC Clang

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

https://reviews.llvm.org/D60736



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


r358609 - [analyzer] PR41185: Fix regression where __builtin_* functions weren't recognized

2019-04-17 Thread Kristof Umann via cfe-commits
Author: szelethus
Date: Wed Apr 17 12:56:40 2019
New Revision: 358609

URL: http://llvm.org/viewvc/llvm-project?rev=358609=rev
Log:
[analyzer] PR41185: Fix regression where __builtin_* functions weren't 
recognized

For the following code snippet:

void builtin_function_call_crash_fixes(char *c) {
  __builtin_strncpy(c, "", 6);
  __builtin_memset(c, '\0', (0));
  __builtin_memcpy(c, c, 0);
}
security.insecureAPI.DeprecatedOrUnsafeBufferHandling caused a regression, as it
didn't recognize functions starting with __builtin_. Fixed exactly that.

I wanted to modify an existing test file, but the two I found didn't seem like
perfect candidates. While I was there, I prettified their RUN: lines.

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


Added:
cfe/trunk/test/Analysis/security-syntax-checks.c
Modified:
cfe/trunk/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
cfe/trunk/test/Analysis/security-syntax-checks-no-emit.c
cfe/trunk/test/Analysis/security-syntax-checks.m

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp?rev=358609=358608=358609=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp Wed Apr 
17 12:56:40 2019
@@ -740,7 +740,11 @@ void WalkAST::checkDeprecatedOrUnsafeBuf
   // Issue a warning. ArgIndex == -1: Deprecated but not unsafe (has size
   // restrictions).
   enum { DEPR_ONLY = -1, UNKNOWN_CALL = -2 };
+
   StringRef Name = FD->getIdentifier()->getName();
+  if (Name.startswith("__builtin_"))
+Name = Name.substr(10);
+
   int ArgIndex =
   llvm::StringSwitch(Name)
   .Cases("scanf", "wscanf", "vscanf", "vwscanf", 0)

Modified: cfe/trunk/test/Analysis/security-syntax-checks-no-emit.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/security-syntax-checks-no-emit.c?rev=358609=358608=358609=diff
==
--- cfe/trunk/test/Analysis/security-syntax-checks-no-emit.c (original)
+++ cfe/trunk/test/Analysis/security-syntax-checks-no-emit.c Wed Apr 17 
12:56:40 2019
@@ -1,4 +1,7 @@
-// RUN: %clang_analyze_cc1 -triple i686-pc-linux-gnu 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
+// RUN: %clang_analyze_cc1 -triple i686-pc-linux-gnu %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI \
+// RUN:   -analyzer-checker=security.FloatLoopCounter
+
 // expected-no-diagnostics
 
 // This file complements 'security-syntax-checks.m', but tests that we omit

Added: cfe/trunk/test/Analysis/security-syntax-checks.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/security-syntax-checks.c?rev=358609=auto
==
--- cfe/trunk/test/Analysis/security-syntax-checks.c (added)
+++ cfe/trunk/test/Analysis/security-syntax-checks.c Wed Apr 17 12:56:40 2019
@@ -0,0 +1,8 @@
+// RUN: %clang_analyze_cc1 %s -verify \
+// RUN:   -analyzer-checker=security.insecureAPI
+
+void builtin_function_call_crash_fixes(char *c) {
+  __builtin_strncpy(c, "", 6); // expected-warning{{Call to function 'strncpy' 
is insecure as it does not provide security checks introduced in the C11 
standard.}}
+  __builtin_memset(c, '\0', (0)); // expected-warning{{Call to function 
'memset' is insecure as it does not provide security checks introduced in the 
C11 standard.}}
+  __builtin_memcpy(c, c, 0); // expected-warning{{Call to function 'memcpy' is 
insecure as it does not provide security checks introduced in the C11 
standard.}}
+}

Modified: cfe/trunk/test/Analysis/security-syntax-checks.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/security-syntax-checks.m?rev=358609=358608=358609=diff
==
--- cfe/trunk/test/Analysis/security-syntax-checks.m (original)
+++ cfe/trunk/test/Analysis/security-syntax-checks.m Wed Apr 17 12:56:40 2019
@@ -1,11 +1,40 @@
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DUSE_BUILTINS 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DVARIANT 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 -triple i386-apple-darwin10 -DUSE_BUILTINS 
-DVARIANT -analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s 
-verify
-// RUN: %clang_analyze_cc1 -triple x86_64-unknown-cloudabi 
-analyzer-checker=security.insecureAPI,security.FloatLoopCounter %s -verify
-// RUN: %clang_analyze_cc1 

[PATCH] D60417: [libunwind] Add support for ARMv7-M architecture which uses the Thumb 2 ISA (unified syntax)

2019-04-17 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists added a comment.

I have no problem with this.


Repository:
  rUNW libunwind

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

https://reviews.llvm.org/D60417



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


r358624 - [Sema][ObjC] Don't warn about an implicitly retained self if the

2019-04-17 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Wed Apr 17 16:14:44 2019
New Revision: 358624

URL: http://llvm.org/viewvc/llvm-project?rev=358624=rev
Log:
[Sema][ObjC] Don't warn about an implicitly retained self if the
retaining block and all of the enclosing blocks are non-escaping.

If the block implicitly retaining self doesn't escape, there is no risk
of creating retain cycles, so clang shouldn't diagnose it and force
users to add self-> to silence the diagnostic.

Also, fix a bug where clang was failing to diagnose an implicitly
retained self inside a c++ lambda nested inside a block.

rdar://problem/25059955

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

Added:
cfe/trunk/test/SemaObjCXX/warn-implicit-self-in-block.mm
Removed:
cfe/trunk/test/SemaObjC/warn-implicit-self-in-block.m
Modified:
cfe/trunk/include/clang/AST/DeclBase.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/lib/Sema/SemaDeclObjC.cpp
cfe/trunk/lib/Sema/SemaExpr.cpp

Modified: cfe/trunk/include/clang/AST/DeclBase.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclBase.h?rev=358624=358623=358624=diff
==
--- cfe/trunk/include/clang/AST/DeclBase.h (original)
+++ cfe/trunk/include/clang/AST/DeclBase.h Wed Apr 17 16:14:44 2019
@@ -41,6 +41,7 @@ namespace clang {
 class ASTContext;
 class ASTMutationListener;
 class Attr;
+class BlockDecl;
 class DeclContext;
 class ExternalSourceSymbolAttr;
 class FunctionDecl;
@@ -1792,6 +1793,20 @@ public:
 
   bool isClosure() const { return getDeclKind() == Decl::Block; }
 
+  /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
+  /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
+  const BlockDecl *getInnermostBlockDecl() const {
+const DeclContext *Ctx = this;
+
+do {
+  if (Ctx->isClosure())
+return cast(Ctx);
+  Ctx = Ctx->getParent();
+} while (Ctx);
+
+return nullptr;
+  }
+
   bool isObjCContainer() const {
 switch (getDeclKind()) {
 case Decl::ObjCCategory:

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=358624=358623=358624=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Wed Apr 17 16:14:44 2019
@@ -1213,6 +1213,11 @@ public:
   /// of -Wselector.
   llvm::MapVector ReferencedSelectors;
 
+  /// List of SourceLocations where 'self' is implicitly retained inside a
+  /// block.
+  llvm::SmallVector, 1>
+  ImplicitlyRetainedSelfLocs;
+
   /// Kinds of C++ special members.
   enum CXXSpecialMember {
 CXXDefaultConstructor,

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=358624=358623=358624=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Wed Apr 17 16:14:44 2019
@@ -13150,6 +13150,35 @@ private:
   bool IsLambda = false;
 };
 
+static void diagnoseImplicitlyRetainedSelf(Sema ) {
+  llvm::DenseMap EscapeInfo;
+
+  auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
+if (EscapeInfo.count(BD))
+  return EscapeInfo[BD];
+
+bool R = false;
+const BlockDecl *CurBD = BD;
+
+do {
+  R = !CurBD->doesNotEscape();
+  if (R)
+break;
+  CurBD = CurBD->getParent()->getInnermostBlockDecl();
+} while (CurBD);
+
+return EscapeInfo[BD] = R;
+  };
+
+  // If the location where 'self' is implicitly retained is inside a escaping
+  // block, emit a diagnostic.
+  for (const std::pair  :
+   S.ImplicitlyRetainedSelfLocs)
+if (IsOrNestedInEscapingBlock(P.second))
+  S.Diag(P.first, diag::warn_implicitly_retains_self)
+  << FixItHint::CreateInsertion(P.first, "self->");
+}
+
 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
 bool IsInstantiation) {
   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
@@ -13361,6 +13390,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl
  diag::warn_objc_secondary_init_missing_init_call);
   getCurFunction()->ObjCWarnForNoInitDelegation = false;
 }
+
+diagnoseImplicitlyRetainedSelf(*this);
   } else {
 // Parsing the function declaration failed in some way. Pop the fake scope
 // we pushed on.

Modified: cfe/trunk/lib/Sema/SemaDeclObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclObjC.cpp?rev=358624=358623=358624=diff
==
--- cfe/trunk/lib/Sema/SemaDeclObjC.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclObjC.cpp Wed Apr 17 16:14:44 2019
@@ -359,6 +359,7 @@ HasExplicitOwnershipAttr(Sema , ParmVa
 /// 

[PATCH] D60826: Clarify -Winfinite-recursion message

2019-04-17 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith requested changes to this revision.
rsmith added inline comments.
This revision now requires changes to proceed.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:64
 def warn_infinite_recursive_function : Warning<
-  "all paths through this function will call itself">,
+  "in order to understand recursion, you must first understand recursion">,
   InGroup, DefaultIgnore;

Please also add a note explaining how to understand recursion, and emit it 
whenever you produce a warning or note that mentions recursion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60826



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


[PATCH] D60845: [VerifyDiagnosticConsumer] Document -verify= in doxygen

2019-04-17 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso accepted this revision.
Charusso added a comment.
This revision is now accepted and ready to land.

Thanks you!

I really like live working examples, I hope not just me. Could you link 
https://github.com/llvm/llvm-project/blob/master/clang/test/Analysis/use-after-move.cpp
 as well as a live example?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60845



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


[PATCH] D59744: Fix i386 ABI "__m64" type bug

2019-04-17 Thread Wei Xiao via Phabricator via cfe-commits
wxiao3 updated this revision to Diff 195659.

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

https://reviews.llvm.org/D59744

Files:
  lib/CodeGen/TargetInfo.cpp
  test/CodeGen/x86_32-arguments-linux.c
  test/CodeGen/x86_32-mmx-linux.c

Index: test/CodeGen/x86_32-mmx-linux.c
===
--- /dev/null
+++ test/CodeGen/x86_32-mmx-linux.c
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -w -O2 -fblocks -triple i386-pc-linux-gnu -target-cpu pentium4 -emit-llvm -o %t %s
+// RUN: FileCheck < %t %s
+
+// CHECK-LABEL: define x86_mmx @caller(x86_mmx %__m1.coerce, x86_mmx %__m2.coerce)
+// CHECK: tail call void @callee(x86_mmx %__m2.coerce, x86_mmx %__m1.coerce)
+// CHECK: ret x86_mmx
+
+#include 
+__m64 m64;
+void callee(__m64 __m1, __m64 __m2);
+__m64 caller(__m64 __m1, __m64 __m2)
+{
+  callee(__m2, __m1);
+  return m64;
+}
Index: test/CodeGen/x86_32-arguments-linux.c
===
--- test/CodeGen/x86_32-arguments-linux.c
+++ test/CodeGen/x86_32-arguments-linux.c
@@ -3,7 +3,7 @@
 
 // CHECK-LABEL: define void @f56(
 // CHECK: i8 signext %a0, %struct.s56_0* byval align 4 %a1,
-// CHECK: i64 %a2.coerce, %struct.s56_1* byval align 4,
+// CHECK: x86_mmx %a2.coerce, %struct.s56_1* byval align 4,
 // CHECK: <1 x double> %a4, %struct.s56_2* byval align 4,
 // CHECK: <4 x i32> %a6, %struct.s56_3* byval align 4,
 // CHECK: <2 x double> %a8, %struct.s56_4* byval align 4,
@@ -12,7 +12,7 @@
 
 // CHECK: call void (i32, ...) @f56_0(i32 1,
 // CHECK: i32 %{{.*}}, %struct.s56_0* byval align 4 %{{[^ ]*}},
-// CHECK: i64 %{{[^ ]*}}, %struct.s56_1* byval align 4 %{{[^ ]*}},
+// CHECK: x86_mmx %{{[^ ]*}}, %struct.s56_1* byval align 4 %{{[^ ]*}},
 // CHECK: <1 x double> %{{[^ ]*}}, %struct.s56_2* byval align 4 %{{[^ ]*}},
 // CHECK: <4 x i32> %{{[^ ]*}}, %struct.s56_3* byval align 4 %{{[^ ]*}},
 // CHECK: <2 x double> %{{[^ ]*}}, %struct.s56_4* byval align 4 %{{[^ ]*}},
Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp
+++ lib/CodeGen/TargetInfo.cpp
@@ -917,10 +917,10 @@
 
 /// IsX86_MMXType - Return true if this is an MMX type.
 bool IsX86_MMXType(llvm::Type *IRType) {
-  // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
+  // Return true if the type is an MMX type <1 x i64>, <2 x i32>, <4 x i16>,
+  // or <8 x i8>.
   return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
-cast(IRType)->getElementType()->isIntegerTy() &&
-IRType->getScalarSizeInBits() != 64;
+cast(IRType)->getElementType()->isIntegerTy();
 }
 
 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction ,
@@ -1011,6 +1011,7 @@
   bool IsSoftFloatABI;
   bool IsMCUABI;
   unsigned DefaultNumRegisterParameters;
+  bool IsMMXEnabled;
 
   static bool isRegisterSize(unsigned Size) {
 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
@@ -1070,13 +1071,15 @@
 
   X86_32ABIInfo(CodeGen::CodeGenTypes , bool DarwinVectorABI,
 bool RetSmallStructInRegABI, bool Win32StructABI,
-unsigned NumRegisterParameters, bool SoftFloatABI)
+unsigned NumRegisterParameters, bool SoftFloatABI,
+bool MMXEnabled)
 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
   IsRetSmallStructInRegABI(RetSmallStructInRegABI),
   IsWin32StructABI(Win32StructABI),
   IsSoftFloatABI(SoftFloatABI),
   IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
-  DefaultNumRegisterParameters(NumRegisterParameters) {}
+  DefaultNumRegisterParameters(NumRegisterParameters),
+  IsMMXEnabled(MMXEnabled) {}
 
   bool shouldPassIndirectlyForSwift(ArrayRef scalars,
 bool asReturnValue) const override {
@@ -1097,10 +1100,11 @@
 public:
   X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes , bool DarwinVectorABI,
   bool RetSmallStructInRegABI, bool Win32StructABI,
-  unsigned NumRegisterParameters, bool SoftFloatABI)
+  unsigned NumRegisterParameters, bool SoftFloatABI,
+  bool MMXEnabled = false)
   : TargetCodeGenInfo(new X86_32ABIInfo(
 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
-NumRegisterParameters, SoftFloatABI)) {}
+NumRegisterParameters, SoftFloatABI, MMXEnabled)) {}
 
   static bool isStructReturnInRegABI(
   const llvm::Triple , const CodeGenOptions );
@@ -1407,6 +1411,9 @@
   return getIndirectReturnResult(RetTy, State);
 }
 
+if (IsMMXEnabled && IsX86_MMXType(CGT.ConvertType(RetTy)))
+  return ABIArgInfo::getDirect(llvm::Type::getX86_MMXTy(getVMContext()));
+
 return ABIArgInfo::getDirect();
   }
 
@@ -1711,8 +1718,11 @@
 Size));
 }
 
-if 

[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-04-17 Thread Don Hinton via Phabricator via cfe-commits
hintonda added inline comments.



Comment at: clang-tidy/modernize/MakeSmartPtrCheck.cpp:69
+  IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)),
+  IgnoreListInit(Options.get("IgnoreListInit", false)) {}
 

hintonda wrote:
> axzhang wrote:
> > hintonda wrote:
> > > You’re setting it false here.
> > I thought that false was the default value if the options do not contain 
> > "IgnoreListInit"?
> Do you have a test that passes this option?  I didn’t see one.
I could be wrong, but when you do an Options.get(), that looks at what was 
passed on the commandline, and if it wasn't found, it sets the default provided.


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

https://reviews.llvm.org/D55044



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


r358627 - Move the implementation of getInnermostBlockDecl to the .cpp file to fix

2019-04-17 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Wed Apr 17 17:00:16 2019
New Revision: 358627

URL: http://llvm.org/viewvc/llvm-project?rev=358627=rev
Log:
Move the implementation of getInnermostBlockDecl to the .cpp file to fix
failing bots.

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

Modified: cfe/trunk/include/clang/AST/DeclBase.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclBase.h?rev=358627=358626=358627=diff
==
--- cfe/trunk/include/clang/AST/DeclBase.h (original)
+++ cfe/trunk/include/clang/AST/DeclBase.h Wed Apr 17 17:00:16 2019
@@ -1795,17 +1795,7 @@ public:
 
   /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
   /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
-  const BlockDecl *getInnermostBlockDecl() const {
-const DeclContext *Ctx = this;
-
-do {
-  if (Ctx->isClosure())
-return cast(Ctx);
-  Ctx = Ctx->getParent();
-} while (Ctx);
-
-return nullptr;
-  }
+  const BlockDecl *getInnermostBlockDecl() const;
 
   bool isObjCContainer() const {
 switch (getDeclKind()) {

Modified: cfe/trunk/lib/AST/DeclBase.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/DeclBase.cpp?rev=358627=358626=358627=diff
==
--- cfe/trunk/lib/AST/DeclBase.cpp (original)
+++ cfe/trunk/lib/AST/DeclBase.cpp Wed Apr 17 17:00:16 2019
@@ -1057,6 +1057,18 @@ DeclContext *DeclContext::getLookupParen
   return getParent();
 }
 
+const BlockDecl *DeclContext::getInnermostBlockDecl() const {
+  const DeclContext *Ctx = this;
+
+  do {
+if (Ctx->isClosure())
+  return cast(Ctx);
+Ctx = Ctx->getParent();
+  } while (Ctx);
+
+  return nullptr;
+}
+
 bool DeclContext::isInlineNamespace() const {
   return isNamespace() &&
  cast(this)->isInline();


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


r358626 - Fix test on PS4 which defaults to gnu99 which does not emit the expected warnings.

2019-04-17 Thread Douglas Yung via cfe-commits
Author: dyung
Date: Wed Apr 17 17:00:06 2019
New Revision: 358626

URL: http://llvm.org/viewvc/llvm-project?rev=358626=rev
Log:
Fix test on PS4 which defaults to gnu99 which does not emit the expected 
warnings.

Modified:
cfe/trunk/test/Analysis/security-syntax-checks.c

Modified: cfe/trunk/test/Analysis/security-syntax-checks.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/security-syntax-checks.c?rev=358626=358625=358626=diff
==
--- cfe/trunk/test/Analysis/security-syntax-checks.c (original)
+++ cfe/trunk/test/Analysis/security-syntax-checks.c Wed Apr 17 17:00:06 2019
@@ -1,8 +1,20 @@
 // RUN: %clang_analyze_cc1 %s -verify \
 // RUN:   -analyzer-checker=security.insecureAPI
+// RUN: %clang_analyze_cc1 %s -verify -std=gnu11 \
+// RUN:   -analyzer-checker=security.insecureAPI
+// RUN: %clang_analyze_cc1 %s -verify -std=gnu99 \
+// RUN:   -analyzer-checker=security.insecureAPI
 
 void builtin_function_call_crash_fixes(char *c) {
-  __builtin_strncpy(c, "", 6); // expected-warning{{Call to function 'strncpy' 
is insecure as it does not provide security checks introduced in the C11 
standard.}}
-  __builtin_memset(c, '\0', (0)); // expected-warning{{Call to function 
'memset' is insecure as it does not provide security checks introduced in the 
C11 standard.}}
-  __builtin_memcpy(c, c, 0); // expected-warning{{Call to function 'memcpy' is 
insecure as it does not provide security checks introduced in the C11 
standard.}}
+  __builtin_strncpy(c, "", 6);
+  __builtin_memset(c, '\0', (0));
+  __builtin_memcpy(c, c, 0);
+
+#if __STDC_VERSION__ > 199901
+  // expected-warning@-5{{Call to function 'strncpy' is insecure as it does 
not provide security checks introduced in the C11 standard.}}
+  // expected-warning@-5{{Call to function 'memset' is insecure as it does not 
provide security checks introduced in the C11 standard.}}
+  // expected-warning@-5{{Call to function 'memcpy' is insecure as it does not 
provide security checks introduced in the C11 standard.}}
+#else
+  // expected-no-diagnostics
+#endif
 }


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


[PATCH] D60362: [clang-format] [PR39719] clang-format converting object-like macro to function-like macro

2019-04-17 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

A more straightforward way, IMO, is to add to the `spaceRequiredBetween` 
function a separate `if` statement that returns false for the sequence of 
tokens: `#`, `define`, tok::identifier, and `(`


Repository:
  rC Clang

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

https://reviews.llvm.org/D60362



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


[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-04-17 Thread Don Hinton via Phabricator via cfe-commits
hintonda added inline comments.



Comment at: clang-tidy/modernize/MakeSmartPtrCheck.cpp:69
+  IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)),
+  IgnoreListInit(Options.get("IgnoreListInit", false)) {}
 

axzhang wrote:
> hintonda wrote:
> > You’re setting it false here.
> I thought that false was the default value if the options do not contain 
> "IgnoreListInit"?
Do you have a test that passes this option?  I didn’t see one.


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

https://reviews.llvm.org/D55044



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


[PATCH] D59754: [Sema] Add c++2a designated initializer warnings

2019-04-17 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

I think you're missing the enforcement of the rule that the same field name 
cannot be designated multiple times in a single 
//designated-initializer-list//. I'm fine with that being done separately (not 
as part of this patch), though.




Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:158
+def ext_c20_designated_init : Extension<
+  "C99 %0 designated initializers are a C++20 extension">, InGroup;
 def ext_designated_init : Extension<

See http://clang.llvm.org/docs/InternalsManual.html#the-format-string -- do not 
pass English text as arguments to diagnostics as this interferes with 
localization. Use `%select` instead, or use different diagnostics for the 
different kinds of problem.

I think use of multiple diagnostics would be preferable anyway, as it'd give 
you room to explain the nature of the problem better (for instance, rather than 
"mixed designated initializers", you could say "mixing designated and 
non-designated initializers in the same initializer list is a C99 feature not 
permitted in C++" or something like that).

Also, we use "X is a C++20 extension" to mean "this is a C++20 feature but you 
don't have C++20 enabled", which is very different from what you're using it to 
mean here. "ISO C++20 does not support X" is how we'd usually phrase "X is not 
a feature of C++20 but we know what you mean".



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:159-160
+  "C99 %0 designated initializers are a C++20 extension">, InGroup;
 def ext_designated_init : Extension<
   "designated initializers are a C99 feature">, InGroup;
 def err_array_designator_negative : Error<

In C++ <=17 mode, if we see a designated initializer that would be valid in 
C++20, we should diagnose that designated initializers are a C++20 feature, not 
that they're a C99 feature.



Comment at: clang/lib/Sema/SemaInit.cpp:2069-2072
+if (!VerifyOnly && HasDesignatedInit && SemaRef.getLangOpts().CPlusPlus2a) 
{
+  SemaRef.Diag(Init->getBeginLoc(), diag::ext_c20_designated_init)
+  << "mixed" << Init->getSourceRange();
+}

I think it would be preferable to diagnose the "mixed" case in the parser 
rather than here (it's a grammatical restriction in C++, after all). I'm 
worried that handling it here will get some cases wrong, such as perhaps:

```
struct A {
  union { int x, y; };
  int z;
};
A a = { .x = 123, 456 }; // should be rejected, but I think this patch might 
accept
```

... and it might also get template instantiation cases wrong for a case like:

```
struct Q { Q(); };
struct A { Q x, y; };
template void f() {
  A a = {.y = Q()};
}
void g() { f(); }
```

... where we might possibly end up passing an `InitListExpr` representing 
`{Q(), .y = Q()}` into `InitListChecker`.

I think the only C++20 restriction that it makes sense to check in 
`InitListChecker` is that the field names are in the right order; everything 
else should be checked earlier. This would also match the semantics of overload 
resolution, for which the "fields are in the right order" check is deferred 
until after a function is selected, whereas all the other checks are performed 
eagerly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D59754



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


[PATCH] D60845: [VerifyDiagnosticConsumer] Document -verify= in doxygen

2019-04-17 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Yup, i confirm that this improves discoverability of this feature :) Maybe it 
deserves its own .rst doc, like FileCheck 
, but for now doxygen seems 
to be the best source of truth on how to use -verify and i consult it regularly.

In D60845#1470980 , @Charusso wrote:

> I really like live working examples, I hope not just me. Could you link 
> https://github.com/llvm/llvm-project/blob/master/clang/test/Analysis/use-after-move.cpp
>  as well as a live example?


I'd rather reserve an ability for myself to move the test around without 
breaking links all over the place. Live examples are easy to grep for as soon 
as you know what to grep for.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60845



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


[PATCH] D60349: [COFF, ARM64] Fix ABI implementation of struct returns

2019-04-17 Thread Sanjin Sijaric via Phabricator via cfe-commits
ssijaric added inline comments.



Comment at: lib/CodeGen/MicrosoftCXXABI.cpp:1058
+
+  // 1. For return types <= 16 bytes, use the C return semantics.
+

richard.townsend.arm wrote:
> Microsoft have updated the spec since this was written, it now says to check 
> for aggregate-ness, trivial copy, and trivial destruct, instead of POD.  
This is only true for aggregates.  We can have non-aggregate return types that 
are less or equal to 16 bytes.  In this case, they are returned on the stack.



Comment at: lib/CodeGen/MicrosoftCXXABI.cpp:1075
+uint64_t RetTySize = getContext().getTypeSize(FI.getReturnType());
+if (RetTySize <= 16)
+  return false;

The size returned is in bits, not bytes.

As mentioned above, this applies to aggregates with trivial copy assignment 
operators and destructors.  I will provide a function to check for this.  At 
that point, the check can be removed from here, and the  check below can be 
replaced with something like:

bool isIndirectReturn = !canReturnInRegisters();


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

https://reviews.llvm.org/D60349



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


[PATCH] D60808: [analyzer] pr41335: NoStoreFuncVisitor: Fix crash when no-store event is in a body-farmed function.

2019-04-17 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ planned changes to this revision.
NoQ added a comment.

In D60808#1469734 , @NoQ wrote:

> Hmm, i think i'd love to know why doesn't the uninitialized variable checker 
> fire on the if-statement as farmed by the body farm:


Passing arguments to this whole body farm thing doesn't work. It builds the 
body for the declaration on line 4 but then calls the declaration on line 5, 
and parameter variables in the synthesized body don't match parameter variables 
of the call, so it cannot read argument values :/


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

https://reviews.llvm.org/D60808



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


[PATCH] D60362: [clang-format] [PR39719] clang-format converting object-like macro to function-like macro

2019-04-17 Thread Owen Pan via Phabricator via cfe-commits
owenpan added a comment.

Actually, there is a neater way: https://reviews.llvm.org/D60853


Repository:
  rC Clang

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

https://reviews.llvm.org/D60362



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


[PATCH] D60845: [VerifyDiagnosticConsumer] Document -verify= in doxygen

2019-04-17 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny created this revision.
jdenny added reviewers: NoQ, Charusso, hfinkel, rsmith.
Herald added a project: clang.

Previously, it was only documented by `-cc1 -help`, so people weren't
aware of it, as discussed in D60732 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D60845

Files:
  clang/include/clang/Frontend/VerifyDiagnosticConsumer.h


Index: clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
===
--- clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
+++ clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
@@ -33,7 +33,31 @@
 /// markers in the input source to check that all the emitted diagnostics match
 /// those expected.
 ///
-/// USING THE DIAGNOSTIC CHECKER:
+/// INVOKING THE DIAGNOSTIC CHECKER:
+///
+/// VerifyDiagnosticConsumer is typically invoked via the "-verify" option to
+/// "clang -cc1".  "-verify" is equivalent to "-verify=expected", so all
+/// diagnostics are typically specified with the prefix "expected".
+///
+/// For example:
+///
+/// \code
+///   int A = B; // expected-error {{use of undeclared identifier 'B'}}
+/// \endcode
+///
+/// Custom prefixes can be specified as a comma-separated sequence.  Each
+/// prefix must start with a letter and contain only alphanumeric characters,
+/// hyphens, and underscores.
+///
+/// For example, given "-verify=foo,bar", the above diagnostic would be
+/// ignored, but the following diagnostics would be recognized:
+///
+/// \code
+///   int A = B; // foo-error {{use of undeclared identifier 'B'}}
+///   int C = D; // bar-error {{use of undeclared identifier 'D'}}
+/// \endcode
+///
+/// SPECIFYING DIAGNOSTICS:
 ///
 /// Indicating that a line expects an error or a warning is simple. Put a
 /// comment on the line that has the diagnostic, use:


Index: clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
===
--- clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
+++ clang/include/clang/Frontend/VerifyDiagnosticConsumer.h
@@ -33,7 +33,31 @@
 /// markers in the input source to check that all the emitted diagnostics match
 /// those expected.
 ///
-/// USING THE DIAGNOSTIC CHECKER:
+/// INVOKING THE DIAGNOSTIC CHECKER:
+///
+/// VerifyDiagnosticConsumer is typically invoked via the "-verify" option to
+/// "clang -cc1".  "-verify" is equivalent to "-verify=expected", so all
+/// diagnostics are typically specified with the prefix "expected".
+///
+/// For example:
+///
+/// \code
+///   int A = B; // expected-error {{use of undeclared identifier 'B'}}
+/// \endcode
+///
+/// Custom prefixes can be specified as a comma-separated sequence.  Each
+/// prefix must start with a letter and contain only alphanumeric characters,
+/// hyphens, and underscores.
+///
+/// For example, given "-verify=foo,bar", the above diagnostic would be
+/// ignored, but the following diagnostics would be recognized:
+///
+/// \code
+///   int A = B; // foo-error {{use of undeclared identifier 'B'}}
+///   int C = D; // bar-error {{use of undeclared identifier 'D'}}
+/// \endcode
+///
+/// SPECIFYING DIAGNOSTICS:
 ///
 /// Indicating that a line expects an error or a warning is simple. Put a
 /// comment on the line that has the diagnostic, use:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D57435: [clang-tidy] Add abseil-wrap-unique check

2019-04-17 Thread Ryan Piantedosi via Phabricator via cfe-commits
Dosi-Dough added a comment.

Hi I was wondering if there were any other changes anyone recomends should be 
made to this revision?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D57435



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


LLVM buildmaster will be updated and restarted tonight

2019-04-17 Thread Galina Kistanova via cfe-commits
 Hello everyone,

LLVM buildmaster will be updated and restarted after 7PM Pacific time today.

Thanks

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


r358631 - [c++2a] Improve diagnostic for use of declaration from another TU's

2019-04-17 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Wed Apr 17 17:56:58 2019
New Revision: 358631

URL: http://llvm.org/viewvc/llvm-project?rev=358631=rev
Log:
[c++2a] Improve diagnostic for use of declaration from another TU's
global module fragment.

We know that the declaration in question should have been introduced by
a '#include', so try to figure out which one and suggest it. Don't
suggest importing the global module fragment itself!

Added:
cfe/trunk/test/CXX/basic/basic.scope/basic.scope.namespace/p2.cpp
Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/Lex/PPDirectives.cpp
cfe/trunk/lib/Sema/SemaLookup.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=358631=358630=358631=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Wed Apr 17 17:56:58 
2019
@@ -9238,6 +9238,12 @@ def err_module_unimported_use_header : E
   "%select{declaration|definition|default argument|"
   "explicit specialization|partial specialization}0 of %1 must be imported "
   "from module '%2' before it is required">;
+def err_module_unimported_use_global_module_fragment : Error<
+  "%select{missing '#include'|missing '#include %3'}2; "
+  "%select{||default argument of |explicit specialization of |"
+  "partial specialization of }0%1 must be "
+  "%select{declared|defined|defined|declared|declared}0 "
+  "before it is used">;
 def err_module_unimported_use_multiple : Error<
   "%select{declaration|definition|default argument|"
   "explicit specialization|partial specialization}0 of %1 must be imported "

Modified: cfe/trunk/lib/Lex/PPDirectives.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/PPDirectives.cpp?rev=358631=358630=358631=diff
==
--- cfe/trunk/lib/Lex/PPDirectives.cpp (original)
+++ cfe/trunk/lib/Lex/PPDirectives.cpp Wed Apr 17 17:56:58 2019
@@ -614,9 +614,16 @@ Preprocessor::getModuleHeaderToIncludeFo
  SourceLocation Loc) {
   assert(M && "no module to include");
 
+  // If the context is the global module fragment of some module, we never
+  // want to return that file; instead, we want the innermost include-guarded
+  // header that it included.
+  bool InGlobalModuleFragment = M->Kind == Module::GlobalModuleFragment;
+
   // If we have a module import syntax, we shouldn't include a header to
   // make a particular module visible.
-  if (getLangOpts().ObjC)
+  if ((getLangOpts().ObjC || getLangOpts().CPlusPlusModules ||
+   getLangOpts().ModulesTS) &&
+  !InGlobalModuleFragment)
 return nullptr;
 
   Module *TopM = M->getTopLevelModule();
@@ -633,6 +640,13 @@ Preprocessor::getModuleHeaderToIncludeFo
 if (!FE)
   break;
 
+if (InGlobalModuleFragment) {
+  if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
+return FE;
+  Loc = SM.getIncludeLoc(ID);
+  continue;
+}
+
 bool InTextualHeader = false;
 for (auto Header : HeaderInfo.getModuleMap().findAllModulesForHeader(FE)) {
   if (!Header.getModule()->isSubModuleOf(TopM))

Modified: cfe/trunk/lib/Sema/SemaLookup.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaLookup.cpp?rev=358631=358630=358631=diff
==
--- cfe/trunk/lib/Sema/SemaLookup.cpp (original)
+++ cfe/trunk/lib/Sema/SemaLookup.cpp Wed Apr 17 17:56:58 2019
@@ -5073,7 +5073,7 @@ void Sema::diagnoseMissingImport(SourceL
   auto Merged = Context.getModulesWithMergedDefinition(Def);
   OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
 
-  diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
+  diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
 Recover);
 }
 
@@ -5093,12 +5093,58 @@ void Sema::diagnoseMissingImport(SourceL
  MissingImportKind MIK, bool Recover) {
   assert(!Modules.empty());
 
+  auto NotePrevious = [&] {
+unsigned DiagID;
+switch (MIK) {
+case MissingImportKind::Declaration:
+  DiagID = diag::note_previous_declaration;
+  break;
+case MissingImportKind::Definition:
+  DiagID = diag::note_previous_definition;
+  break;
+case MissingImportKind::DefaultArgument:
+  DiagID = diag::note_default_argument_declared_here;
+  break;
+case MissingImportKind::ExplicitSpecialization:
+  DiagID = diag::note_explicit_specialization_declared_here;
+  break;
+case MissingImportKind::PartialSpecialization:
+  DiagID = diag::note_partial_specialization_declared_here;
+  break;
+}
+Diag(DeclLoc, DiagID);
+  };
+
   // Weed out 

r358632 - Add '#pragma clang __debug module_map module.name' to dump the module

2019-04-17 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Wed Apr 17 17:57:01 2019
New Revision: 358632

URL: http://llvm.org/viewvc/llvm-project?rev=358632=rev
Log:
Add '#pragma clang __debug module_map module.name' to dump the module
map being used for the module 'module.name'.

Modified:
cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td
cfe/trunk/lib/Lex/Pragma.cpp

Modified: cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td?rev=358632=358631=358632=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticLexKinds.td Wed Apr 17 17:57:01 2019
@@ -561,6 +561,8 @@ def warn_pragma_debug_unexpected_command
   "unexpected debug command '%0'">, InGroup;
 def warn_pragma_debug_missing_argument : Warning<
   "missing argument to debug command '%0'">, InGroup;
+def warn_pragma_debug_unknown_module : Warning<
+  "unknown module '%0'">, InGroup;
 // #pragma module
 def err_pp_expected_module_name : Error<
   "expected %select{identifier after '.' in |}0module name">;

Modified: cfe/trunk/lib/Lex/Pragma.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/Pragma.cpp?rev=358632=358631=358632=diff
==
--- cfe/trunk/lib/Lex/Pragma.cpp (original)
+++ cfe/trunk/lib/Lex/Pragma.cpp Wed Apr 17 17:57:01 2019
@@ -1010,7 +1010,7 @@ struct PragmaDebugHandler : public Pragm
   PragmaDebugHandler() : PragmaHandler("__debug") {}
 
   void HandlePragma(Preprocessor , PragmaIntroducerKind Introducer,
-Token ) override {
+Token ) override {
 Token Tok;
 PP.LexUnexpandedToken(Tok);
 if (Tok.isNot(tok::identifier)) {
@@ -1072,6 +1072,22 @@ struct PragmaDebugHandler : public Pragm
   else
 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
 << II->getName();
+} else if (II->isStr("module_map")) {
+  llvm::SmallVector, 8>
+  ModuleName;
+  if (LexModuleName(PP, Tok, ModuleName))
+return;
+  ModuleMap  = PP.getHeaderSearchInfo().getModuleMap();
+  Module *M = nullptr;
+  for (auto IIAndLoc : ModuleName) {
+M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
+if (!M) {
+  PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module)
+  << IIAndLoc.first;
+  return;
+}
+  }
+  M->dump();
 } else if (II->isStr("overflow_stack")) {
   DebugOverflowStack();
 } else if (II->isStr("handle_crash")) {


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


r358633 - Split out modules-specific declaration handling from SemaDecl.cpp into a

2019-04-17 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Wed Apr 17 17:57:02 2019
New Revision: 358633

URL: http://llvm.org/viewvc/llvm-project?rev=358633=rev
Log:
Split out modules-specific declaration handling from SemaDecl.cpp into a
new SemaModule.cpp.

Added:
cfe/trunk/lib/Sema/SemaModule.cpp
Modified:
cfe/trunk/lib/Sema/CMakeLists.txt
cfe/trunk/lib/Sema/SemaDecl.cpp

Modified: cfe/trunk/lib/Sema/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/CMakeLists.txt?rev=358633=358632=358633=diff
==
--- cfe/trunk/lib/Sema/CMakeLists.txt (original)
+++ cfe/trunk/lib/Sema/CMakeLists.txt Wed Apr 17 17:57:02 2019
@@ -43,6 +43,7 @@ add_clang_library(clangSema
   SemaInit.cpp
   SemaLambda.cpp
   SemaLookup.cpp
+  SemaModule.cpp
   SemaObjCProperty.cpp
   SemaOpenMP.cpp
   SemaOverload.cpp

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=358633=358632=358633=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Wed Apr 17 17:57:02 2019
@@ -17007,471 +17007,6 @@ Decl *Sema::ActOnFileScopeAsmDecl(Expr *
   return New;
 }
 
-static void checkModuleImportContext(Sema , Module *M,
- SourceLocation ImportLoc, DeclContext *DC,
- bool FromInclude = false) {
-  SourceLocation ExternCLoc;
-
-  if (auto *LSD = dyn_cast(DC)) {
-switch (LSD->getLanguage()) {
-case LinkageSpecDecl::lang_c:
-  if (ExternCLoc.isInvalid())
-ExternCLoc = LSD->getBeginLoc();
-  break;
-case LinkageSpecDecl::lang_cxx:
-  break;
-}
-DC = LSD->getParent();
-  }
-
-  while (isa(DC) || isa(DC))
-DC = DC->getParent();
-
-  if (!isa(DC)) {
-S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
-  ? diag::ext_module_import_not_at_top_level_noop
-  : diag::err_module_import_not_at_top_level_fatal)
-<< M->getFullModuleName() << DC;
-S.Diag(cast(DC)->getBeginLoc(),
-   diag::note_module_import_not_at_top_level)
-<< DC;
-  } else if (!M->IsExternC && ExternCLoc.isValid()) {
-S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
-  << M->getFullModuleName();
-S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
-  }
-}
-
-Sema::DeclGroupPtrTy
-Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
-  if (!ModuleScopes.empty() &&
-  ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
-// Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
-// already implicitly entering the global module fragment. That's OK.
-assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&
-   "unexpectedly encountered multiple global module fragment decls");
-ModuleScopes.back().BeginLoc = ModuleLoc;
-return nullptr;
-  }
-
-  // We start in the global module; all those declarations are implicitly
-  // module-private (though they do not have module linkage).
-  auto  = PP.getHeaderSearchInfo().getModuleMap();
-  auto *GlobalModule = Map.createGlobalModuleForInterfaceUnit(ModuleLoc);
-  assert(GlobalModule && "module creation should not fail");
-
-  // Enter the scope of the global module.
-  ModuleScopes.push_back({});
-  ModuleScopes.back().BeginLoc = ModuleLoc;
-  ModuleScopes.back().Module = GlobalModule;
-  VisibleModules.setVisible(GlobalModule, ModuleLoc);
-
-  // All declarations created from now on are owned by the global module.
-  auto *TU = Context.getTranslationUnitDecl();
-  TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
-  TU->setLocalOwningModule(GlobalModule);
-
-  // FIXME: Consider creating an explicit representation of this declaration.
-  return nullptr;
-}
-
-Sema::DeclGroupPtrTy
-Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
-  ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl) 
{
-  assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&
- "should only have module decl in Modules TS or C++20");
-
-  // A module implementation unit requires that we are not compiling a module
-  // of any kind. A module interface unit requires that we are not compiling a
-  // module map.
-  switch (getLangOpts().getCompilingModule()) {
-  case LangOptions::CMK_None:
-// It's OK to compile a module interface as a normal translation unit.
-break;
-
-  case LangOptions::CMK_ModuleInterface:
-if (MDK != ModuleDeclKind::Implementation)
-  break;
-
-// We were asked to compile a module interface unit but this is a module
-// implementation unit. That indicates the 'export' is missing.
-Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
-  << FixItHint::CreateInsertion(ModuleLoc, "export ");
-

[PATCH] D55409: [clang-tidy] check for using declarations not in an anonymous namespace when there exists one

2019-04-17 Thread Yucheng Wu via Phabricator via cfe-commits
Ywicheng updated this revision to Diff 195656.

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

https://reviews.llvm.org/D55409

Files:
  clang-tidy/abseil/AbseilTidyModule.cpp
  clang-tidy/abseil/AnonymousEnclosedAliasesCheck.cpp
  clang-tidy/abseil/AnonymousEnclosedAliasesCheck.h
  clang-tidy/abseil/CMakeLists.txt
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/abseil-anonymous-enclosed-aliases.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/abseil-anonymous-enclosed-aliases.cpp

Index: test/clang-tidy/abseil-anonymous-enclosed-aliases.cpp
===
--- /dev/null
+++ test/clang-tidy/abseil-anonymous-enclosed-aliases.cpp
@@ -0,0 +1,56 @@
+// RUN: %check_clang_tidy %s abseil-anonymous-enclosed-aliases %t
+namespace bar {
+
+class A {};
+class B {};
+
+} // namespace bar
+
+namespace foo1 {
+
+// CHECK-MESSAGES: :[[@LINE+4]]:12: warning: using declaration 'A' should
+// be in the anonymous namespace. Use discretion when moving using declarations
+// as it might necessitate moving lines containing relevant aliases.
+// [abseil-anonymous-enclosed-aliases]
+using bar::A;
+void f(A a);
+
+namespace {} // anonymous namespace
+
+} // namespace foo1
+
+namespace foo2 {
+
+namespace {
+
+// This is okay
+using ::bar::B;
+
+} // anonymous namespace
+
+void g(B b);
+
+} // namespace foo2
+
+// Check should not be triggered below when the using declaration is at
+// function or class (instead of namespace) scope.
+namespace outer {
+
+int fun_scope() {
+  using ::bar::A;
+  return 0;
+} // function scope
+
+class Base {
+public:
+  void f();
+}; // class scope
+
+class Derived : public Base {
+public:
+  using Base::f;
+}; // class scope
+
+namespace {} // anonymous namespace
+
+} // namespace outer
\ No newline at end of file
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -4,6 +4,7 @@
 =
 
 .. toctree::
+   abseil-anonymous-enclosed-aliases
abseil-duration-addition
abseil-duration-comparison
abseil-duration-conversion-cast
Index: docs/clang-tidy/checks/abseil-anonymous-enclosed-aliases.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/abseil-anonymous-enclosed-aliases.rst
@@ -0,0 +1,20 @@
+.. title:: clang-tidy - abseil-anonymous-enclosed-aliases
+
+abseil-anonymous-enclosed-aliases
+=
+
+Finds using declarations outside of anonymous namespaces, and
+suggests those declarations be moved to that namespace.
+
+Example:
+.. code-block:: c++
+
+  namespace foo {
+  
+  using something; // should be inside the anonymous namespace below
+
+  namespace {
+
+  } // anonymous namespace
+
+  } // foo
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -67,6 +67,12 @@
 Improvements to clang-tidy
 --
 
+- New :doc:`abseil-anonymous-enclosed-aliases
+  ` check.
+
+  Finds instances of using declarations not in an anonymous namespace
+  when there exists one.
+
 - New :doc:`abseil-duration-addition
   ` check.
 
Index: clang-tidy/abseil/CMakeLists.txt
===
--- clang-tidy/abseil/CMakeLists.txt
+++ clang-tidy/abseil/CMakeLists.txt
@@ -2,6 +2,7 @@
 
 add_clang_library(clangTidyAbseilModule
   AbseilTidyModule.cpp
+  AnonymousEnclosedAliasesCheck.cpp
   DurationAdditionCheck.cpp
   DurationComparisonCheck.cpp
   DurationConversionCastCheck.cpp
Index: clang-tidy/abseil/AnonymousEnclosedAliasesCheck.h
===
--- /dev/null
+++ clang-tidy/abseil/AnonymousEnclosedAliasesCheck.h
@@ -0,0 +1,40 @@
+//===--- AnonymousEnclosedAliasesCheck.h - clang-tidy ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ANONYMOUSENCLOSEDALIASESCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_ANONYMOUSENCLOSEDALIASESCHECK_H
+
+#include "../ClangTidy.h"
+#include 
+
+namespace clang {
+namespace tidy {
+namespace abseil {
+
+/// Detecting incorrect practice of putting using declarations outside an
+/// anonymous namespace when there exists one.
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/
+/// abseil-anonymous-enclosed-aliases.html
+class AnonymousEnclosedAliasesCheck : public ClangTidyCheck {
+public:
+  AnonymousEnclosedAliasesCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void 

[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-04-17 Thread Andy Zhang via Phabricator via cfe-commits
axzhang marked an inline comment as done.
axzhang added inline comments.



Comment at: clang-tidy/modernize/MakeSmartPtrCheck.cpp:69
+  IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)),
+  IgnoreListInit(Options.get("IgnoreListInit", false)) {}
 

hintonda wrote:
> You’re setting it false here.
I thought that false was the default value if the options do not contain 
"IgnoreListInit"?


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

https://reviews.llvm.org/D55044



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


[PATCH] D60349: [COFF, ARM64] Fix ABI implementation of struct returns

2019-04-17 Thread Richard Townsend (Arm) via Phabricator via cfe-commits
richard.townsend.arm added inline comments.



Comment at: lib/CodeGen/MicrosoftCXXABI.cpp:1058
+
+  // 1. For return types <= 16 bytes, use the C return semantics.
+

Microsoft have updated the spec since this was written, it now says to check 
for aggregate-ness, trivial copy, and trivial destruct, instead of POD.  


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

https://reviews.llvm.org/D60349



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


[PATCH] D60736: [Sema][ObjC] Don't warn about a block implicitly retaining self if the block is marked noescape

2019-04-17 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358624: [Sema][ObjC] Dont warn about an implicitly 
retained self if the (authored by ahatanak, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D60736?vs=195639=195650#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D60736

Files:
  cfe/trunk/include/clang/AST/DeclBase.h
  cfe/trunk/include/clang/Sema/Sema.h
  cfe/trunk/lib/Sema/SemaDecl.cpp
  cfe/trunk/lib/Sema/SemaDeclObjC.cpp
  cfe/trunk/lib/Sema/SemaExpr.cpp
  cfe/trunk/test/SemaObjC/warn-implicit-self-in-block.m
  cfe/trunk/test/SemaObjCXX/warn-implicit-self-in-block.mm

Index: cfe/trunk/include/clang/AST/DeclBase.h
===
--- cfe/trunk/include/clang/AST/DeclBase.h
+++ cfe/trunk/include/clang/AST/DeclBase.h
@@ -41,6 +41,7 @@
 class ASTContext;
 class ASTMutationListener;
 class Attr;
+class BlockDecl;
 class DeclContext;
 class ExternalSourceSymbolAttr;
 class FunctionDecl;
@@ -1792,6 +1793,20 @@
 
   bool isClosure() const { return getDeclKind() == Decl::Block; }
 
+  /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
+  /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
+  const BlockDecl *getInnermostBlockDecl() const {
+const DeclContext *Ctx = this;
+
+do {
+  if (Ctx->isClosure())
+return cast(Ctx);
+  Ctx = Ctx->getParent();
+} while (Ctx);
+
+return nullptr;
+  }
+
   bool isObjCContainer() const {
 switch (getDeclKind()) {
 case Decl::ObjCCategory:
Index: cfe/trunk/include/clang/Sema/Sema.h
===
--- cfe/trunk/include/clang/Sema/Sema.h
+++ cfe/trunk/include/clang/Sema/Sema.h
@@ -1213,6 +1213,11 @@
   /// of -Wselector.
   llvm::MapVector ReferencedSelectors;
 
+  /// List of SourceLocations where 'self' is implicitly retained inside a
+  /// block.
+  llvm::SmallVector, 1>
+  ImplicitlyRetainedSelfLocs;
+
   /// Kinds of C++ special members.
   enum CXXSpecialMember {
 CXXDefaultConstructor,
Index: cfe/trunk/test/SemaObjCXX/warn-implicit-self-in-block.mm
===
--- cfe/trunk/test/SemaObjCXX/warn-implicit-self-in-block.mm
+++ cfe/trunk/test/SemaObjCXX/warn-implicit-self-in-block.mm
@@ -0,0 +1,42 @@
+// RUN: %clang_cc1 -x objective-c++ -std=c++11 -fobjc-arc -fblocks -Wimplicit-retain-self -verify %s
+// rdar://11194874
+
+typedef void (^BlockTy)();
+
+void noescapeFunc(__attribute__((noescape)) BlockTy);
+void escapeFunc(BlockTy);
+
+@interface Root @end
+
+@interface I : Root
+{
+  int _bar;
+}
+@end
+
+@implementation I
+  - (void)foo{
+  ^{
+   _bar = 3; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+   }();
+  }
+
+  - (void)testNested{
+noescapeFunc(^{
+  (void)_bar;
+  escapeFunc(^{
+(void)_bar; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+noescapeFunc(^{
+  (void)_bar; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+});
+(void)_bar; // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+  });
+  (void)_bar;
+});
+  }
+
+  - (void)testLambdaInBlock{
+noescapeFunc(^{ [&](){ (void)_bar; }(); });
+escapeFunc(^{ [&](){ (void)_bar; }(); }); // expected-warning {{block implicitly retains 'self'; explicitly mention 'self' to indicate this is intended behavior}}
+  }
+@end
Index: cfe/trunk/lib/Sema/SemaExpr.cpp
===
--- cfe/trunk/lib/Sema/SemaExpr.cpp
+++ cfe/trunk/lib/Sema/SemaExpr.cpp
@@ -2575,11 +2575,9 @@
 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
   getCurFunction()->recordUseOfWeak(Result);
   }
-  if (getLangOpts().ObjCAutoRefCount) {
-if (CurContext->isClosure())
-  Diag(Loc, diag::warn_implicitly_retains_self)
-<< FixItHint::CreateInsertion(Loc, "self->");
-  }
+  if (getLangOpts().ObjCAutoRefCount)
+if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
+  ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
 
   return Result;
 }
Index: cfe/trunk/lib/Sema/SemaDecl.cpp
===
--- cfe/trunk/lib/Sema/SemaDecl.cpp
+++ cfe/trunk/lib/Sema/SemaDecl.cpp
@@ -13150,6 +13150,35 @@
   bool IsLambda = false;
 };
 
+static void diagnoseImplicitlyRetainedSelf(Sema ) {
+  llvm::DenseMap EscapeInfo;
+
+  auto 

[PATCH] D60845: [VerifyDiagnosticConsumer] Document -verify= in doxygen

2019-04-17 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D60845#1470986 , @NoQ wrote:

> Yup, i confirm that this improves discoverability of this feature :) Maybe it 
> deserves its own .rst doc, like FileCheck 
> , but for now doxygen 
> seems to be the best source of truth on how to use -verify and i consult it 
> regularly.


I've seen a few projects outside of clang use `-verify` mode for their own 
testing of various things. Maybe it's time we promote it from an internal 
self-testing tool to a full-fledged and supported part of Clang's interface 
(including adding a driver flag and a proper description in the user manual)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60845



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


r358630 - [clang-format] Remove unused Environment constructor.

2019-04-17 Thread Alexander Kornienko via cfe-commits
Author: alexfh
Date: Wed Apr 17 17:36:51 2019
New Revision: 358630

URL: http://llvm.org/viewvc/llvm-project?rev=358630=rev
Log:
[clang-format] Remove unused Environment constructor.

Modified:
cfe/trunk/lib/Format/TokenAnalyzer.h

Modified: cfe/trunk/lib/Format/TokenAnalyzer.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnalyzer.h?rev=358630=358629=358630=diff
==
--- cfe/trunk/lib/Format/TokenAnalyzer.h (original)
+++ cfe/trunk/lib/Format/TokenAnalyzer.h Wed Apr 17 17:36:51 2019
@@ -35,10 +35,6 @@ namespace format {
 
 class Environment {
 public:
-  Environment(SourceManager , FileID ID, ArrayRef Ranges)
-  : SM(SM), ID(ID), CharRanges(Ranges.begin(), Ranges.end()),
-FirstStartColumn(0), NextStartColumn(0), LastStartColumn(0) {}
-
   // This sets up an virtual file system with file \p FileName containing the
   // fragment \p Code. Assumes that \p Code starts at \p FirstStartColumn,
   // that the next lines of \p Code should start at \p NextStartColumn, and


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


[PATCH] D55411: [clang-tidy] check for flagging using declarations not in the inner most namespace

2019-04-17 Thread Yucheng Wu via Phabricator via cfe-commits
Ywicheng updated this revision to Diff 195661.
Ywicheng marked 3 inline comments as done.

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

https://reviews.llvm.org/D55411

Files:
  clang-tidy/abseil/AbseilTidyModule.cpp
  clang-tidy/abseil/CMakeLists.txt
  clang-tidy/abseil/SafelyScopedCheck.cpp
  clang-tidy/abseil/SafelyScopedCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/abseil-safely-scoped.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/abseil-safely-scoped.cpp

Index: test/clang-tidy/abseil-safely-scoped.cpp
===
--- /dev/null
+++ test/clang-tidy/abseil-safely-scoped.cpp
@@ -0,0 +1,55 @@
+// RUN: %check_clang_tidy %s abseil-safely-scoped %t
+namespace bar {
+
+class A {};
+class B {};
+
+} // namespace bar
+
+namespace foo1 {
+
+// CHECK-MESSAGES: :[[@LINE+4]]:12: warning: using declaration 'A' is not
+// declared in the innermost namespace. Use discretion when moving using
+// declarations as it might necessitate moving lines containing relevant
+// aliases. [abseil-safely-scoped]
+using bar::A;
+void f(A a);
+
+namespace {} // anonymous namespace
+
+} // namespace foo1
+
+namespace foo2 {
+
+namespace {
+
+using ::bar::B;
+
+} // anonymous namespace
+
+void g(B b);
+
+} // namespace foo2
+
+// Check should not be triggered below when we are at
+// function (instead of namespace) scope.
+namespace outer {
+
+int fun_scope() {
+  using ::bar::A;
+  return 0;
+} // function scope
+
+class Base {
+public:
+  void f();
+}; // class scope
+
+class Derived : public Base {
+public:
+  using Base::f;
+}; // class scope
+
+namespace inner {} // namespace inner
+
+} // namespace outer
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -16,6 +16,7 @@
abseil-no-internal-dependencies
abseil-no-namespace
abseil-redundant-strcat-calls
+   abseil-safely-scoped
abseil-str-cat-append
abseil-string-find-startswith
abseil-time-subtraction
Index: docs/clang-tidy/checks/abseil-safely-scoped.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/abseil-safely-scoped.rst
@@ -0,0 +1,28 @@
+.. title:: clang-tidy - abseil-safely-scoped
+
+abseil-safely-scoped
+
+
+Flags using declarations that are not contained in an innermost
+namespace, and suggests these declarations be moved elsewhere.
+
+Example:
+
+.. code-block:: c++
+
+  using something; // should be inside the innermost namespace bar below
+
+  namespace foo {
+  namespace bar {
+	
+  } // bar
+
+  using something_else; // shoulw be inside the innermost namespace bar above
+
+  } // foo
+
+Placing convenience aliases in upper level namespaces can lead to ambiguity in 
+which name the compiler should use. 
+
+See https://abseil.io/tips/119 for more explanation. 
+
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -67,6 +67,12 @@
 Improvements to clang-tidy
 --
 
+- New :doc:`abseil-safely-scoped
+  ` check.
+
+  Finds instances of using declarations not in the innermost layer
+  of a series of namespaces.
+
 - New :doc:`abseil-duration-addition
   ` check.
 
Index: clang-tidy/abseil/SafelyScopedCheck.h
===
--- /dev/null
+++ clang-tidy/abseil/SafelyScopedCheck.h
@@ -0,0 +1,36 @@
+//===--- SafelyScopedCheck.h - clang-tidy ---*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_SAFELYSCOPEDCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_SAFELYSCOPEDCHECK_H
+
+#include "../ClangTidy.h"
+
+namespace clang {
+namespace tidy {
+namespace abseil {
+
+/// Detecting using declarations not in a namespace declaration or not in
+/// the innermost layer of namespace declarations.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/abseil-safely-scoped.html
+class SafelyScopedCheck : public ClangTidyCheck {
+public:
+  SafelyScopedCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+};
+
+} // namespace abseil
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_ABSEIL_SAFELYSCOPEDCHECK_H
Index: clang-tidy/abseil/SafelyScopedCheck.cpp
===
--- 

[PATCH] D60848: [Parser] Avoid correcting delayed typos in array subscript multiple times.

2019-04-17 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added reviewers: rsmith, erik.pilkington, majnemer.
Herald added subscribers: dexonsmith, jkorous.

We correct some typos in `ActOnArraySubscriptExpr` and
`ActOnOMPArraySectionExpr`, so when their result is `ExprError`, we can
end up correcting delayed typos in the same expressions again. In
general it is OK but when `NumTypos` is incorrect, we can hit the
assertion

> Assertion failed: (Entry != DelayedTypos.end() && "Failed to get the state 
> for a TypoExpr!"), function getTypoExprState, file 
> clang/lib/Sema/SemaLookup.cpp, line 5219.

This assertion is reproducible with Objective-C method

- (void)test { [self undeclaredMethod:undeclaredArg]; NSMutableDictionary *opts 
= [NSMutableDictionary new]; opts[(__bridge id)undeclaredKey] = @0; }

There is no test for the fix because `NumTypos` is still incorrect and
we hit the assertion

> Assertion failed: (DelayedTypos.empty() && "Uncorrected typos!"), function 
> ~Sema, file clang/lib/Sema/Sema.cpp, line 382.

Another option is to fix tracking delayed typos but it is non-trivial as
in many cases we drop erroneous expressions without cleaning up
`TypoExpr` they contain. Also the assertion in `~Sema` isn't causing
problems with assertions disabled, while a missing `TypoExprState` can
cause a segmentation fault.

rdar://problem/47403222


https://reviews.llvm.org/D60848

Files:
  clang/lib/Parse/ParseExpr.cpp
  clang/test/SemaCXX/typo-correction.cpp


Index: clang/test/SemaCXX/typo-correction.cpp
===
--- clang/test/SemaCXX/typo-correction.cpp
+++ clang/test/SemaCXX/typo-correction.cpp
@@ -678,7 +678,7 @@
 struct a0is0 {};
 struct b0is0 {};
 int g() {
-  0 [ // expected-error {{subscripted value is not an array}}
+  0 [
   sizeof(c0is0)]; // expected-error {{use of undeclared identifier}}
 };
 }
Index: clang/lib/Parse/ParseExpr.cpp
===
--- clang/lib/Parse/ParseExpr.cpp
+++ clang/lib/Parse/ParseExpr.cpp
@@ -1582,7 +1582,9 @@
 
   SourceLocation RLoc = Tok.getLocation();
 
-  ExprResult OrigLHS = LHS;
+  LHS = Actions.CorrectDelayedTyposInExpr(LHS);
+  Idx = Actions.CorrectDelayedTyposInExpr(Idx);
+  Length = Actions.CorrectDelayedTyposInExpr(Length);
   if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
   Tok.is(tok::r_square)) {
 if (ColonLoc.isValid()) {
@@ -1594,12 +1596,6 @@
 }
   } else {
 LHS = ExprError();
-  }
-  if (LHS.isInvalid()) {
-(void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
-(void)Actions.CorrectDelayedTyposInExpr(Idx);
-(void)Actions.CorrectDelayedTyposInExpr(Length);
-LHS = ExprError();
 Idx = ExprError();
   }
 


Index: clang/test/SemaCXX/typo-correction.cpp
===
--- clang/test/SemaCXX/typo-correction.cpp
+++ clang/test/SemaCXX/typo-correction.cpp
@@ -678,7 +678,7 @@
 struct a0is0 {};
 struct b0is0 {};
 int g() {
-  0 [ // expected-error {{subscripted value is not an array}}
+  0 [
   sizeof(c0is0)]; // expected-error {{use of undeclared identifier}}
 };
 }
Index: clang/lib/Parse/ParseExpr.cpp
===
--- clang/lib/Parse/ParseExpr.cpp
+++ clang/lib/Parse/ParseExpr.cpp
@@ -1582,7 +1582,9 @@
 
   SourceLocation RLoc = Tok.getLocation();
 
-  ExprResult OrigLHS = LHS;
+  LHS = Actions.CorrectDelayedTyposInExpr(LHS);
+  Idx = Actions.CorrectDelayedTyposInExpr(Idx);
+  Length = Actions.CorrectDelayedTyposInExpr(Length);
   if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
   Tok.is(tok::r_square)) {
 if (ColonLoc.isValid()) {
@@ -1594,12 +1596,6 @@
 }
   } else {
 LHS = ExprError();
-  }
-  if (LHS.isInvalid()) {
-(void)Actions.CorrectDelayedTyposInExpr(OrigLHS);
-(void)Actions.CorrectDelayedTyposInExpr(Idx);
-(void)Actions.CorrectDelayedTyposInExpr(Length);
-LHS = ExprError();
 Idx = ExprError();
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60853: clang-format incorrectly inserts a space after a macro function name that is a keyword

2019-04-17 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: klimek, djasper, reuk, russellmcc, sammccall, 
MyDeveloperDay.
owenpan added a project: clang.
Herald added a subscriber: cfe-commits.

See https://bugs.llvm.org/show_bug.cgi?id=39719 and discussion: 
https://reviews.llvm.org/D60362


Repository:
  rC Clang

https://reviews.llvm.org/D60853

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -2468,6 +2468,12 @@
 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
   EXPECT_EQ("#define A (x)", format("#define A (x)"));
   EXPECT_EQ("#define A(x)", format("#define A(x)"));
+
+  FormatStyle Style = getLLVMStyle();
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
+  verifyFormat("#define true ((foo)1)", Style);
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
+  verifyFormat("#define false((foo)0)", Style);
 }
 
 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -805,7 +805,7 @@
 void UnwrappedLineParser::parsePPDefine() {
   nextToken();
 
-  if (FormatTok->Tok.getKind() != tok::identifier) {
+  if (!FormatTok->Tok.getIdentifierInfo()) {
 IncludeGuard = IG_Rejected;
 IncludeGuardToken = nullptr;
 parsePPUnknown();


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -2468,6 +2468,12 @@
 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
   EXPECT_EQ("#define A (x)", format("#define A (x)"));
   EXPECT_EQ("#define A(x)", format("#define A(x)"));
+
+  FormatStyle Style = getLLVMStyle();
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
+  verifyFormat("#define true ((foo)1)", Style);
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
+  verifyFormat("#define false((foo)0)", Style);
 }
 
 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -805,7 +805,7 @@
 void UnwrappedLineParser::parsePPDefine() {
   nextToken();
 
-  if (FormatTok->Tok.getKind() != tok::identifier) {
+  if (!FormatTok->Tok.getIdentifierInfo()) {
 IncludeGuard = IG_Rejected;
 IncludeGuardToken = nullptr;
 parsePPUnknown();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59744: Fix i386 ABI "__m64" type bug

2019-04-17 Thread Wei Xiao via Phabricator via cfe-commits
wxiao3 updated this revision to Diff 195660.

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

https://reviews.llvm.org/D59744

Files:
  lib/CodeGen/TargetInfo.cpp
  test/CodeGen/vector.c
  test/CodeGen/x86_32-arguments-darwin.c
  test/CodeGen/x86_32-arguments-linux.c
  test/CodeGen/x86_32-m64.c

Index: test/CodeGen/x86_32-m64.c
===
--- /dev/null
+++ test/CodeGen/x86_32-m64.c
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -w -O2 -fblocks -triple i386-pc-linux-gnu -target-cpu pentium4 -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,LINUX
+// RUN: %clang_cc1 -w -O2 -fblocks -triple i386-apple-darwin9 -target-cpu yonah -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,DARWIN
+// RUN: %clang_cc1 -w -O2 -fblocks -triple i386-pc-elfiamcu -mfloat-abi soft -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,IAMCU
+// RUN: %clang_cc1 -w -O2 -fblocks -triple i386-pc-win32 -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,WIN32
+
+#include 
+__m64 m64;
+void callee(__m64 __m1, __m64 __m2);
+__m64 caller(__m64 __m1, __m64 __m2)
+{
+// LINUX-LABEL: define x86_mmx @caller(x86_mmx %__m1.coerce, x86_mmx %__m2.coerce)
+// LINUX: tail call void @callee(x86_mmx %__m2.coerce, x86_mmx %__m1.coerce)
+// LINUX: ret x86_mmx
+// DARWIN-LABEL: define i64 @caller(i64 %__m1.coerce, i64 %__m2.coerce)
+// DARWIN: tail call void @callee(i64 %__m2.coerce, i64 %__m1.coerce)
+// DARWIN: ret i64
+// IAMCU-LABEL: define <1 x i64> @caller(i64 %__m1.coerce, i64 %__m2.coerce)
+// IAMCU: tail call void @callee(i64 %__m2.coerce, i64 %__m1.coerce)
+// IAMCU: ret <1 x i64>
+// WIN32-LABEL: define dso_local <1 x i64> @caller(i64 %__m1.coerce, i64 %__m2.coerce)
+// WIN32: call void @callee(i64 %__m2.coerce, i64 %__m1.coerce)
+// WIN32: ret <1 x i64>
+  callee(__m2, __m1);
+  return m64;
+}
Index: test/CodeGen/x86_32-arguments-linux.c
===
--- test/CodeGen/x86_32-arguments-linux.c
+++ test/CodeGen/x86_32-arguments-linux.c
@@ -3,7 +3,7 @@
 
 // CHECK-LABEL: define void @f56(
 // CHECK: i8 signext %a0, %struct.s56_0* byval align 4 %a1,
-// CHECK: i64 %a2.coerce, %struct.s56_1* byval align 4,
+// CHECK: x86_mmx %a2.coerce, %struct.s56_1* byval align 4,
 // CHECK: <1 x double> %a4, %struct.s56_2* byval align 4,
 // CHECK: <4 x i32> %a6, %struct.s56_3* byval align 4,
 // CHECK: <2 x double> %a8, %struct.s56_4* byval align 4,
@@ -12,7 +12,7 @@
 
 // CHECK: call void (i32, ...) @f56_0(i32 1,
 // CHECK: i32 %{{.*}}, %struct.s56_0* byval align 4 %{{[^ ]*}},
-// CHECK: i64 %{{[^ ]*}}, %struct.s56_1* byval align 4 %{{[^ ]*}},
+// CHECK: x86_mmx %{{[^ ]*}}, %struct.s56_1* byval align 4 %{{[^ ]*}},
 // CHECK: <1 x double> %{{[^ ]*}}, %struct.s56_2* byval align 4 %{{[^ ]*}},
 // CHECK: <4 x i32> %{{[^ ]*}}, %struct.s56_3* byval align 4 %{{[^ ]*}},
 // CHECK: <2 x double> %{{[^ ]*}}, %struct.s56_4* byval align 4 %{{[^ ]*}},
Index: test/CodeGen/x86_32-arguments-darwin.c
===
--- test/CodeGen/x86_32-arguments-darwin.c
+++ test/CodeGen/x86_32-arguments-darwin.c
@@ -229,7 +229,7 @@
 
 // CHECK-LABEL: define void @f56(
 // CHECK: i8 signext %a0, %struct.s56_0* byval align 4 %a1,
-// CHECK: i64 %a2.coerce, %struct.s56_1* byval align 4,
+// CHECK: x86_mmx %a2.coerce, %struct.s56_1* byval align 4,
 // CHECK: i64 %a4.coerce, %struct.s56_2* byval align 4,
 // CHECK: <4 x i32> %a6, %struct.s56_3* byval align 16 %a7,
 // CHECK: <2 x double> %a8, %struct.s56_4* byval align 16 %a9,
@@ -238,7 +238,7 @@
 
 // CHECK:   call void (i32, ...) @f56_0(i32 1,
 // CHECK: i32 %{{[^ ]*}}, %struct.s56_0* byval align 4 %{{[^ ]*}},
-// CHECK: i64 %{{[^ ]*}}, %struct.s56_1* byval align 4 %{{[^ ]*}},
+// CHECK: x86_mmx %{{[^ ]*}}, %struct.s56_1* byval align 4 %{{[^ ]*}},
 // CHECK: i64 %{{[^ ]*}}, %struct.s56_2* byval align 4 %{{[^ ]*}},
 // CHECK: <4 x i32> %{{[^ ]*}}, %struct.s56_3* byval align 16 %{{[^ ]*}},
 // CHECK: <2 x double> %{{[^ ]*}}, %struct.s56_4* byval align 16 %{{[^ ]*}},
Index: test/CodeGen/vector.c
===
--- test/CodeGen/vector.c
+++ test/CodeGen/vector.c
@@ -78,5 +78,5 @@
   return y;
 }
 
-// CHECK: define void @lax_vector_compare2(<2 x i32>* {{.*sret.*}}, i64 {{.*}}, i64 {{.*}})
+// CHECK: define void @lax_vector_compare2(<2 x i32>* {{.*sret.*}}, i64 {{.*}}, x86_mmx {{.*}})
 // CHECK: icmp eq <2 x i32>
Index: lib/CodeGen/TargetInfo.cpp
===
--- lib/CodeGen/TargetInfo.cpp
+++ lib/CodeGen/TargetInfo.cpp
@@ -917,10 +917,10 @@
 
 /// IsX86_MMXType - Return true if this is an MMX type.
 bool IsX86_MMXType(llvm::Type *IRType) {
-  // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
+  // Return true if the type is an MMX type <1 x i64>, <2 x i32>, <4 x i16>,
+  // or <8 x i8>.
   return IRType->isVectorTy() && 

[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-04-17 Thread Don Hinton via Phabricator via cfe-commits
hintonda added inline comments.



Comment at: clang-tidy/modernize/MakeSmartPtrCheck.cpp:69
+  IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)),
+  IgnoreListInit(Options.get("IgnoreListInit", false)) {}
 

You’re setting it false here.


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

https://reviews.llvm.org/D55044



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


[PATCH] D55044: [clang-tidy] check for Abseil make_unique

2019-04-17 Thread Andy Zhang via Phabricator via cfe-commits
axzhang marked an inline comment as done.
axzhang added a comment.

I'm having some issues with the AbseilTidyModule options. I am storing 
IgnoreListInit as true for the abseil-make-unique check, but when I run the 
check it shows IgnoreListInit as being false. Any ideas why this is happening?


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

https://reviews.llvm.org/D55044



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


[PATCH] D59712: [APSInt][OpenMP] Fix isNegative, etc. for unsigned types

2019-04-17 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D59712#1469693 , @jdenny wrote:

> In D59712#1469392 , @lebedev.ri 
> wrote:
>
> > In D59712#1469358 , @jdenny wrote:
> >
> > > In D59712#1469301 , @lebedev.ri 
> > > wrote:
> > >
> > > > In D59712#1469295 , 
> > > > @craig.topper wrote:
> > > >
> > > > > Wondering if it would be better to assert for asking for the sign of 
> > > > > an unsigned APSInt. I could see a caller just wanting to get the msb 
> > > > > for some reason and not knowing that isNegative won’t work.
> > > >
> > > >
> > > > Yes, i, too, would think an assert is much better solution (since i 
> > > > literally just tripped over this in this review.)
> > >
> >
> >
> > Does this pass `check-all`? `check-all` of stage-2? test-suite?
>
>
> No.  The assert breaks cases in at least ExprConstant.cpp and SemaExpr.cpp.


Err, i was talking about the current code in the patch :)


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

https://reviews.llvm.org/D59712



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


[clang-tools-extra] r358561 - [clangd] lower_bound -> bsearch, NFC

2019-04-17 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Wed Apr 17 00:00:36 2019
New Revision: 358561

URL: http://llvm.org/viewvc/llvm-project?rev=358561=rev
Log:
[clangd] lower_bound -> bsearch, NFC

Modified:
clang-tools-extra/trunk/clangd/index/Symbol.cpp
clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp

Modified: clang-tools-extra/trunk/clangd/index/Symbol.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Symbol.cpp?rev=358561=358560=358561=diff
==
--- clang-tools-extra/trunk/clangd/index/Symbol.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Symbol.cpp Wed Apr 17 00:00:36 2019
@@ -35,9 +35,8 @@ float quality(const Symbol ) {
 }
 
 SymbolSlab::const_iterator SymbolSlab::find(const SymbolID ) const {
-  auto It = std::lower_bound(
-  Symbols.begin(), Symbols.end(), ID,
-  [](const Symbol , const SymbolID ) { return S.ID < I; });
+  auto It =
+  llvm::bsearch(Symbols, [&](const Symbol ) { return !(S.ID < ID); });
   if (It != Symbols.end() && It->ID == ID)
 return It;
   return Symbols.end();

Modified: clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp?rev=358561=358560=358561=diff
==
--- clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/PostingList.cpp Wed Apr 17 
00:00:36 2019
@@ -9,6 +9,7 @@
 #include "PostingList.h"
 #include "Iterator.h"
 #include "Token.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/MathExtras.h"
 
@@ -49,7 +50,8 @@ public:
   return;
 advanceToChunk(ID);
 // Try to find ID within current chunk.
-CurrentID = std::lower_bound(CurrentID, std::end(DecompressedChunk), ID);
+CurrentID = llvm::bsearch(CurrentID, DecompressedChunk.end(),
+  [&](const DocID D) { return D >= ID; });
 normalizeCursor();
   }
 
@@ -100,10 +102,9 @@ private:
   void advanceToChunk(DocID ID) {
 if ((CurrentChunk != Chunks.end() - 1) &&
 ((CurrentChunk + 1)->Head <= ID)) {
-  // Find the next chunk with Head >= ID.
-  CurrentChunk = std::lower_bound(
-  CurrentChunk + 1, Chunks.end(), ID,
-  [](const Chunk , const DocID ID) { return C.Head <= ID; });
+  CurrentChunk =
+  llvm::bsearch(CurrentChunk + 1, Chunks.end(),
+[&](const Chunk ) { return C.Head >= ID; });
   --CurrentChunk;
   DecompressedChunk = CurrentChunk->decompress();
   CurrentID = DecompressedChunk.begin();


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


[PATCH] D58291: [clangd] Include textual diagnostic ID as Diagnostic.code.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added a comment.

In D58291#1400569 , @kadircet wrote:

> LG but is this information really useful to users? According to LSP `The 
> diagnostic's code, which might appear in the user interface.`, I think seeing 
> this will be mostly noise for users.


It's a good question, it depends how this is surfaced, and we may want to tweak 
the behavior or suppress entirely in some cases.
I think at least some are useful:

- clang-tidy check names are things users need to know about (used for 
configuration)
- for warnings, we quite likely should replace with the most specific warning 
category (e.g. "unreachable-code-loop-increment"), again these are used for 
configuration (-W)
- for others, maybe we should at least trim the err_ prefix, or maybe drop them 
entirely.




Comment at: clangd/Diagnostics.cpp:39
+#include "clang/Basic/DiagnosticCommentKinds.inc"
+#include "clang/Basic/DiagnosticSemaKinds.inc"
+#include "clang/Basic/DiagnosticAnalysisKinds.inc"

kadircet wrote:
> I suppose `CrossTUKinds` is left out intentionally ?
Yeah, this isn't really part of clang, and seems to be part of static analyzer.
Some places include it and others don't...



Comment at: clangd/Diagnostics.cpp:281
+if (auto* Name = getDiagnosticCode(D.ID))
+  Main.code = Name;
 if (Opts.EmbedFixesInDiagnostics) {

jkorous wrote:
> It seems to me that in case `ID` is undefined (hits the default case in 
> `getDiagnosticCode`) we are calling `std::string` non-explicit constructor 
> with `nullptr` which is UB.
> How about changing `char* getDiagnosticCode` to `Optional 
> getDiagnosticCode` or similar to make it less error-prone?
This is an if statement - if the pointer is null we never assign to std::string.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D58291



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


[PATCH] D60316: [clangd] Include insertion: require header guards, drop other heuristics, treat .def like .inc.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 195519.
sammccall marked 3 inline comments as done.
sammccall added a comment.

address review comments


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60316

Files:
  clangd/index/CanonicalIncludes.cpp
  clangd/index/CanonicalIncludes.h
  clangd/index/SymbolCollector.cpp
  unittests/clangd/CodeCompleteTests.cpp
  unittests/clangd/FileIndexTests.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
@@ -52,6 +52,9 @@
   // Index to use when building AST.
   const SymbolIndex *ExternalIndex = nullptr;
 
+  // Simulate a header guard of the header (using an #import directive).
+  bool ImplicitHeaderGuard = true;
+
   ParsedAST build() const;
   SymbolSlab headerSymbols() const;
   std::unique_ptr index() const;
Index: unittests/clangd/TestTU.cpp
===
--- unittests/clangd/TestTU.cpp
+++ unittests/clangd/TestTU.cpp
@@ -19,13 +19,19 @@
 
 ParsedAST TestTU::build() const {
   std::string FullFilename = testPath(Filename),
-  FullHeaderName = testPath(HeaderFilename);
+  FullHeaderName = testPath(HeaderFilename),
+  ImportThunk = testPath("import_thunk.h");
   std::vector Cmd = {"clang", FullFilename.c_str()};
+  // We want to implicitly include HeaderFilename without messing up offsets.
+  // -include achieves this, but sometimes we want #import (to simulate a header
+  // guard without messing up offsets). In this case, use an intermediate file.
+  std::string ThunkContents = "#import \"" + FullHeaderName + "\"\n";
   // FIXME: this shouldn't need to be conditional, but it breaks a
   // GoToDefinition test for some reason (getMacroArgExpandedLocation fails).
   if (!HeaderCode.empty()) {
 Cmd.push_back("-include");
-Cmd.push_back(FullHeaderName.c_str());
+Cmd.push_back(ImplicitHeaderGuard ? ImportThunk.c_str()
+  : FullHeaderName.c_str());
   }
   Cmd.insert(Cmd.end(), ExtraArgs.begin(), ExtraArgs.end());
   ParseInputs Inputs;
@@ -33,7 +39,9 @@
   Inputs.CompileCommand.CommandLine = {Cmd.begin(), Cmd.end()};
   Inputs.CompileCommand.Directory = testRoot();
   Inputs.Contents = Code;
-  Inputs.FS = buildTestFS({{FullFilename, Code}, {FullHeaderName, HeaderCode}});
+  Inputs.FS = buildTestFS({{FullFilename, Code},
+   {FullHeaderName, HeaderCode},
+   {ImportThunk, ThunkContents}});
   Inputs.Opts = ParseOptions();
   Inputs.Opts.ClangTidyOpts.Checks = ClangTidyChecks;
   Inputs.Index = ExternalIndex;
Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -20,6 +20,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/VirtualFileSystem.h"
+#include "gmock/gmock-more-matchers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -33,7 +34,7 @@
 using testing::_;
 using testing::AllOf;
 using testing::Contains;
-using testing::Eq;
+using testing::ElementsAre;
 using testing::Field;
 using testing::IsEmpty;
 using testing::Not;
@@ -58,6 +59,7 @@
   return StringRef(arg.CanonicalDeclaration.FileURI) == P;
 }
 MATCHER_P(DefURI, P, "") { return StringRef(arg.Definition.FileURI) == P; }
+MATCHER(IncludeHeader, "") { return !arg.IncludeHeaders.empty(); }
 MATCHER_P(IncludeHeader, P, "") {
   return (arg.IncludeHeaders.size() == 1) &&
  (arg.IncludeHeaders.begin()->IncludeHeader == P);
@@ -249,6 +251,8 @@
 TestFileURI = URI::create(TestFileName).toString();
   }
 
+  // Note that unlike TestTU, no automatic header guard is added.
+  // HeaderCode should start with #pragma once to be treated as modular.
   bool runSymbolCollector(llvm::StringRef HeaderCode, llvm::StringRef MainCode,
   const std::vector  = {}) {
 llvm::IntrusiveRefCntPtr Files(
@@ -268,8 +272,8 @@
 Args, Factory->create(), Files.get(),
 std::make_shared());
 
-InMemoryFileSystem->addFile(TestHeaderName, 0,
-llvm::MemoryBuffer::getMemBuffer(HeaderCode));
+InMemoryFileSystem->addFile(
+TestHeaderName, 0, llvm::MemoryBuffer::getMemBuffer(HeaderCode));
 InMemoryFileSystem->addFile(TestFileName, 0,
 llvm::MemoryBuffer::getMemBuffer(MainCode));
 Invocation.run();
@@ -920,7 +924,7 @@
 
 TEST_F(SymbolCollectorTest, IncludeHeaderSameAsFileURI) {
   CollectorOpts.CollectIncludePath = true;
-  runSymbolCollector("class Foo {};", /*Main=*/"");
+  runSymbolCollector("#pragma once\nclass Foo {};", 

[PATCH] D60719: Demonstrate how to fix freestanding for memcpy

2019-04-17 Thread Clement Courbet via Phabricator via cfe-commits
courbet added a comment.

As discussed offline, I think this should go through an RFC process.

I guess the main reservation that people will have is that this might generate 
a very large number of load stores (because we don't have a good way to 
generate loops here). This is not an issue for X86 because of REPMOVS, but it 
would be cool to have the opinion of people familiar with other architectures. 
One way to tackle this issue could be to expand existing `mem*` functions 
before the DAG. This is already happening for `memcmp` in `ExpandMemcmp`, which 
could be made aware of this flag. Similar approaches could be used for other 
`mem*` functions. But eventually this has to be handled here as the dag itself 
can call `getMemcpy()`.

Also, the current approach does not protect against current users and future 
unsavvy users calling `SelectionDAG::getMemcpy` with `AlwaysAlign == false`, so 
what about actually retrieving the flag //within// the function instead of 
outside ? This happens e.g. in `SelectionDAG::visitMemPCpyCall()`m 
`AArch64TargetLowering::LowerCall` and others.




Comment at: clang/test/CodeGen/freestanding-disables-libc.c:6
+
+// NOTE: Test that assembly doesn't call memcpy function in freestanding mode.
+// RUN: %clang_cc1 -triple i386-unknown-unknown -O2 -S %s -o - | grep 'memcpy'

That's the responsibility of LLVM, so this test should be in 
`llvm/test/Codegen`.



Comment at: llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp:6093
 
+  assert(MF->getFunction().getParent()->getModuleFlag("force-inline-libc") ==
+ nullptr);

Please add an error message (maybe "modules with 'force-inline-libc' should 
never emit library calls")



Comment at: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:5483
 
+static bool IsForceInlineLibc(const SelectionDAG ) {
+  const Module *M = DAG.getMachineFunction().getFunction().getParent();

isForceInlineLibc


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60719



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


[PATCH] D58291: [clangd] Include textual diagnostic ID as Diagnostic.code.

2019-04-17 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.

In D58291#1469880 , @sammccall wrote:

> It's a good question, it depends how this is surfaced, and we may want to 
> tweak the behavior or suppress entirely in some cases.
>  I think at least some are useful:
>
> - clang-tidy check names are things users need to know about (used for 
> configuration)
> - for warnings, we quite likely should replace with the most specific warning 
> category (e.g. "unreachable-code-loop-increment"), again these are used for 
> configuration (-W)
> - for others, maybe we should at least trim the err_ prefix, or maybe drop 
> them entirely.


I see, I believe we can decide on what tweaks to perform after landing this 
patch and seeing behaviors in different editors, but up to you.

As for the lit-tests, it would be great to have a diag with source clang-tidy 
if it is not too much of a hustle.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D58291



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


[PATCH] D60728: [clang] [test] Add a (xfailing) test for PR41027

2019-04-17 Thread Michał Górny via Phabricator via cfe-commits
mgorny updated this revision to Diff 195518.
mgorny added a comment.

Updated per request.


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

https://reviews.llvm.org/D60728

Files:
  clang/test/Sema/pr41027.c


Index: clang/test/Sema/pr41027.c
===
--- /dev/null
+++ clang/test/Sema/pr41027.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple x86_64 -fsyntax-only %s
+// XFAIL: *
+
+inline void pr41027(unsigned a, unsigned b) {
+  if (__builtin_constant_p(a)) {
+__asm__ volatile("outl %0,%w1" : : "a"(b), "n"(a));
+  } else {
+__asm__ volatile("outl %0,%w1" : : "a"(b), "d"(a));
+  }
+}


Index: clang/test/Sema/pr41027.c
===
--- /dev/null
+++ clang/test/Sema/pr41027.c
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple x86_64 -fsyntax-only %s
+// XFAIL: *
+
+inline void pr41027(unsigned a, unsigned b) {
+  if (__builtin_constant_p(a)) {
+__asm__ volatile("outl %0,%w1" : : "a"(b), "n"(a));
+  } else {
+__asm__ volatile("outl %0,%w1" : : "a"(b), "d"(a));
+  }
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D58291: [clangd] Include textual diagnostic ID as Diagnostic.code.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 195522.
sammccall marked an inline comment as done.
sammccall added a comment.
Herald added a subscriber: dexonsmith.

Rebase to head and expand scope a bit:

- now also setting code for clang-tidy checks
- to enable this to be used from the C++ API, the string code is now on Diag
- and also expose Source over LSP (just an oversight?)


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D58291

Files:
  clangd/ClangdUnit.cpp
  clangd/Diagnostics.cpp
  clangd/Diagnostics.h
  clangd/Protocol.cpp
  clangd/Protocol.h
  test/clangd/compile-commands-path-in-initialize.test
  test/clangd/diagnostic-category.test
  test/clangd/diagnostics.test
  test/clangd/did-change-configuration-params.test
  test/clangd/execute-command.test
  test/clangd/fixits-codeaction.test
  test/clangd/fixits-command.test
  test/clangd/fixits-embed-in-diagnostic.test
  unittests/clangd/DiagnosticsTests.cpp

Index: unittests/clangd/DiagnosticsTests.cpp
===
--- unittests/clangd/DiagnosticsTests.cpp
+++ unittests/clangd/DiagnosticsTests.cpp
@@ -12,6 +12,7 @@
 #include "TestIndex.h"
 #include "TestTU.h"
 #include "index/MemIndex.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -58,7 +59,8 @@
  std::tie(LSPDiag.range, LSPDiag.severity, LSPDiag.message);
 }
 
-MATCHER_P(DiagSource, Source, "") { return arg.S == Source; }
+MATCHER_P(DiagSource, S, "") { return arg.Source == S; }
+MATCHER_P(DiagName, N, "") { return arg.Name == N; }
 
 MATCHER_P(EqualToFix, Fix, "LSP fix " + llvm::to_string(Fix)) {
   if (arg.Message != Fix.Message)
@@ -105,6 +107,7 @@
   AllOf(Diag(Test.range("typo"),
  "use of undeclared identifier 'goo'; did you mean 'foo'?"),
 DiagSource(Diag::Clang),
+DiagName("err_undeclared_var_use_suggest"),
 WithFix(
 Fix(Test.range("typo"), "foo", "change 'go\\ o' to 'foo'")),
 // This is a pretty normal range.
@@ -149,7 +152,8 @@
   EXPECT_THAT(TU.build().getDiagnostics(),
   ElementsAre(testing::AllOf(
   Diag(Test.range(), "'not-found.h' file not found"),
-  DiagSource(Diag::Clang;
+  DiagSource(Diag::Clang),
+  DiagName("err_pp_file_not_found";
 }
 
 TEST(DiagnosticsTest, ClangTidy) {
@@ -175,6 +179,7 @@
  "inclusion of deprecated C++ header 'assert.h'; consider "
  "using 'cassert' instead [modernize-deprecated-headers]"),
 DiagSource(Diag::ClangTidy),
+DiagName("modernize-deprecated-headers"),
 WithFix(Fix(Test.range("deprecated"), "",
 "change '\"assert.h\"' to ''"))),
   Diag(Test.range("doubled"),
@@ -185,6 +190,7 @@
"side effects in the 1st macro argument 'X' are repeated in "
"macro expansion [bugprone-macro-repeated-side-effects]"),
   DiagSource(Diag::ClangTidy),
+  DiagName("bugprone-macro-repeated-side-effects"),
   WithNote(Diag(Test.range("macrodef"),
 "macro 'SQUARE' defined here "
 "[bugprone-macro-repeated-side-effects]"))),
@@ -246,6 +252,9 @@
 
 TEST(DiagnosticsTest, ToLSP) {
   clangd::Diag D;
+  D.ID = clang::diag::err_enum_class_reference;
+  D.Name = "err_enum_class_reference";
+  D.Source = clangd::Diag::Clang;
   D.Message = "something terrible happened";
   D.Range = {pos(1, 2), pos(3, 4)};
   D.InsideMainFile = true;
@@ -314,6 +323,10 @@
   LSPDiags,
   ElementsAre(Pair(EqualToLSPDiag(MainLSP), ElementsAre(EqualToFix(F))),
   Pair(EqualToLSPDiag(NoteInMainLSP), IsEmpty(;
+  EXPECT_EQ(LSPDiags[0].first.code, "err_enum_class_reference");
+  EXPECT_EQ(LSPDiags[0].first.source, "clang");
+  EXPECT_EQ(LSPDiags[1].first.code, "");
+  EXPECT_EQ(LSPDiags[1].first.source, "");
 }
 
 struct SymbolWithHeader {
Index: test/clangd/fixits-embed-in-diagnostic.test
===
--- test/clangd/fixits-embed-in-diagnostic.test
+++ test/clangd/fixits-embed-in-diagnostic.test
@@ -6,6 +6,7 @@
 # CHECK-NEXT:  "params": {
 # CHECK-NEXT:"diagnostics": [
 # CHECK-NEXT:  {
+# CHECK-NEXT:"code": "err_use_with_wrong_tag",
 # CHECK-NEXT:"codeActions": [
 # CHECK-NEXT:  {
 # CHECK-NEXT:"edit": {
@@ -42,7 +43,8 @@
 # CHECK-NEXT:"line": 0
 # CHECK-NEXT:  }
 # CHECK-NEXT:},
-# CHECK-NEXT:"severity": 1
+# CHECK-NEXT:"severity": 1,
+# CHECK-NEXT:"source": "clang"
 # CHECK-NEXT:  },
 # CHECK-NEXT:  {
 # CHECK-NEXT:"message": 

[PATCH] D60728: [clang] [test] Add a (xfailing) test for PR41027

2019-04-17 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

In D60728#1468713 , @krytarowski wrote:

> In D60728#1468486 , @hans wrote:
>
> > What's the value in checking in this xfail'ed test without an actual fix 
> > for the problem?
>
>
> Raise awareness about the problem.


I don't think that works. No one is reading through the test files of the 
repository.

In D60728#1468868 , @mgorny wrote:

> 1. It may help whoever tries to address it in the future, to have a 
> known-good reproducer.


The usual way to do this is to post it on the bug tracker, which was already 
done.

> 2. If someone addresses this independently and doesn't notice the bug, it 
> will help us get informed that the issue was fixed.

Fair enough, that seems somewhat useful :-)




Comment at: clang/test/Sema/pr41027.c:1
+// XFAIL: *
+// RUN: %clang_cc1 -triple x86_64 -fsyntax-only %s

nit: the XFAIL usually comes after the RUN line, and there's usually an empty 
line between these lines and the other contents of the file


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

https://reviews.llvm.org/D60728



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


[PATCH] D58236: Make address space conversions a bit stricter.

2019-04-17 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan updated this revision to Diff 195520.
ebevhan edited the summary of this revision.

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

https://reviews.llvm.org/D58236

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/Sema.h
  lib/Sema/SemaCast.cpp
  lib/Sema/SemaExpr.cpp
  test/CodeGenOpenCL/numbered-address-space.cl
  test/SemaOpenCL/address-spaces.cl
  test/SemaOpenCL/event_t_overload.cl
  test/SemaOpenCL/numbered-address-space.cl
  test/SemaOpenCL/queue_t_overload.cl

Index: test/SemaOpenCL/queue_t_overload.cl
===
--- test/SemaOpenCL/queue_t_overload.cl
+++ test/SemaOpenCL/queue_t_overload.cl
@@ -7,6 +7,6 @@
   queue_t q;
   foo(q, src1);
   foo(0, src2);
-  foo(q, src3); // expected-error {{call to 'foo' is ambiguous}}
+  foo(q, src3); // expected-error {{no matching function for call to 'foo'}}
   foo(1, src3); // expected-error {{no matching function for call to 'foo'}}
 }
Index: test/SemaOpenCL/numbered-address-space.cl
===
--- test/SemaOpenCL/numbered-address-space.cl
+++ test/SemaOpenCL/numbered-address-space.cl
@@ -26,6 +26,6 @@
 
 void test_generic_as_to_builtin_parameterimplicit_cast_numeric(__attribute__((address_space(3))) int *as3_ptr, float src) {
   generic int* generic_ptr = as3_ptr;
-  volatile float result = __builtin_amdgcn_ds_fmaxf(generic_ptr, src, 0, 0, false); // expected-warning {{incompatible pointer types passing '__generic int *' to parameter of type '__local float *'}}
+  volatile float result = __builtin_amdgcn_ds_fmaxf(generic_ptr, src, 0, 0, false); // expected-error {{passing '__generic int *' to parameter of type '__local float *' changes address space of pointer}}
 }
 
Index: test/SemaOpenCL/event_t_overload.cl
===
--- test/SemaOpenCL/event_t_overload.cl
+++ test/SemaOpenCL/event_t_overload.cl
@@ -7,5 +7,5 @@
   event_t evt;
   foo(evt, src1);
   foo(0, src2);
-  foo(evt, src3); // expected-error {{call to 'foo' is ambiguous}}
+  foo(evt, src3); // expected-error {{no matching function for call to 'foo'}}
 }
Index: test/SemaOpenCL/address-spaces.cl
===
--- test/SemaOpenCL/address-spaces.cl
+++ test/SemaOpenCL/address-spaces.cl
@@ -124,6 +124,106 @@
   p = (__private int *)p2;
 }
 
+#if !__OPENCL_CPP_VERSION__
+void nested(__global int *g, __global int * __private *gg, __local int *l, __local int * __private *ll, __global float * __private *gg_f) {
+  g = gg;// expected-error {{assigning '__global int **' to '__global int *' changes address space of pointer}}
+  g = l; // expected-error {{assigning '__local int *' to '__global int *' changes address space of pointer}}
+  g = ll;// expected-error {{assigning '__local int **' to '__global int *' changes address space of pointer}}
+  g = gg_f;  // expected-error {{assigning '__global float **' to '__global int *' changes address space of pointer}}
+  g = (__global int *)gg_f; // expected-error {{casting '__global float **' to type '__global int *' changes address space of pointer}}
+
+  gg = g;// expected-error {{assigning '__global int *' to '__global int **' changes address space of pointer}}
+  gg = l;// expected-error {{assigning '__local int *' to '__global int **' changes address space of pointer}}
+  gg = ll;   // expected-error {{assigning '__local int **' to '__global int **' changes address space of nested pointer}}
+  gg = gg_f; // expected-warning {{incompatible pointer types assigning to '__global int **' from '__global float **'}}
+  gg = (__global int * __private *)gg_f;
+
+  l = g; // expected-error {{assigning '__global int *' to '__local int *' changes address space of pointer}}
+  l = gg;// expected-error {{assigning '__global int **' to '__local int *' changes address space of pointer}}
+  l = ll;// expected-error {{assigning '__local int **' to '__local int *' changes address space of pointer}}
+  l = gg_f;  // expected-error {{assigning '__global float **' to '__local int *' changes address space of pointer}}
+  l = (__local int *)gg_f; // expected-error {{casting '__global float **' to type '__local int *' changes address space of pointer}}
+
+  ll = g;// expected-error {{assigning '__global int *' to '__local int **' changes address space of pointer}}
+  ll = gg;   // expected-error {{assigning '__global int **' to '__local int **' changes address space of nested pointer}}
+  ll = l;// expected-error {{assigning '__local int *' to '__local int **' changes address space of pointer}}
+  ll = gg_f; // expected-error {{assigning '__global float **' to '__local int **' changes address space of nested pointer}}
+  ll = (__local int * __private *)gg_f; // expected-warning {{casting '__global float **' to type '__local int **' discards qualifiers in nested pointer types}}

[PATCH] D60775: [libclang] Expose ext_vector_type

2019-04-17 Thread Sven van Haastregt via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358566: [libclang] Expose ext_vector_type (authored by 
svenvh, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D60775?vs=195373=195521#toc

Repository:
  rL LLVM

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

https://reviews.llvm.org/D60775

Files:
  cfe/trunk/bindings/python/clang/cindex.py
  cfe/trunk/include/clang-c/Index.h
  cfe/trunk/test/Index/opencl-types.cl
  cfe/trunk/tools/libclang/CXType.cpp


Index: cfe/trunk/include/clang-c/Index.h
===
--- cfe/trunk/include/clang-c/Index.h
+++ cfe/trunk/include/clang-c/Index.h
@@ -32,7 +32,7 @@
  * compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
  */
 #define CINDEX_VERSION_MAJOR 0
-#define CINDEX_VERSION_MINOR 54
+#define CINDEX_VERSION_MINOR 55
 
 #define CINDEX_VERSION_ENCODE(major, minor) ( \
   ((major) * 1)   \
@@ -3315,7 +3315,9 @@
   CXType_OCLIntelSubgroupAVCImeResultDualRefStreamout = 173,
   CXType_OCLIntelSubgroupAVCImeSingleRefStreamin = 174,
 
-  CXType_OCLIntelSubgroupAVCImeDualRefStreamin = 175
+  CXType_OCLIntelSubgroupAVCImeDualRefStreamin = 175,
+
+  CXType_ExtVector = 176
 };
 
 /**
Index: cfe/trunk/test/Index/opencl-types.cl
===
--- cfe/trunk/test/Index/opencl-types.cl
+++ cfe/trunk/test/Index/opencl-types.cl
@@ -17,11 +17,11 @@
 }
 
 // CHECK: VarDecl=scalarHalf:11:8 (Definition){{( \(invalid\))?}} [type=half] 
[typekind=Half] [isPOD=1]
-// CHECK: VarDecl=vectorHalf:12:9 (Definition) [type=half4] [typekind=Typedef] 
[canonicaltype=half __attribute__((ext_vector_type(4)))] 
[canonicaltypekind=Unexposed] [isPOD=1]
+// CHECK: VarDecl=vectorHalf:12:9 (Definition) [type=half4] [typekind=Typedef] 
[canonicaltype=half __attribute__((ext_vector_type(4)))] 
[canonicaltypekind=ExtVector] [isPOD=1]
 // CHECK: VarDecl=scalarFloat:13:9 (Definition) [type=float] [typekind=Float] 
[isPOD=1]
-// CHECK: VarDecl=vectorFloat:14:10 (Definition) [type=float4] 
[typekind=Typedef] [canonicaltype=float __attribute__((ext_vector_type(4)))] 
[canonicaltypekind=Unexposed] [isPOD=1]
+// CHECK: VarDecl=vectorFloat:14:10 (Definition) [type=float4] 
[typekind=Typedef] [canonicaltype=float __attribute__((ext_vector_type(4)))] 
[canonicaltypekind=ExtVector] [isPOD=1]
 // CHECK: VarDecl=scalarDouble:15:10 (Definition){{( \(invalid\))?}} 
[type=double] [typekind=Double] [isPOD=1]
-// CHECK: VarDecl=vectorDouble:16:11 (Definition){{( \(invalid\))?}} 
[type=double4] [typekind=Typedef] [canonicaltype=double 
__attribute__((ext_vector_type(4)))] [canonicaltypekind=Unexposed] [isPOD=1]
+// CHECK: VarDecl=vectorDouble:16:11 (Definition){{( \(invalid\))?}} 
[type=double4] [typekind=Typedef] [canonicaltype=double 
__attribute__((ext_vector_type(4)))] [canonicaltypekind=ExtVector] [isPOD=1]
 
 #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
 
Index: cfe/trunk/tools/libclang/CXType.cpp
===
--- cfe/trunk/tools/libclang/CXType.cpp
+++ cfe/trunk/tools/libclang/CXType.cpp
@@ -109,6 +109,7 @@
 TKCASE(VariableArray);
 TKCASE(DependentSizedArray);
 TKCASE(Vector);
+TKCASE(ExtVector);
 TKCASE(MemberPointer);
 TKCASE(Auto);
 TKCASE(Elaborated);
@@ -600,6 +601,7 @@
 TKIND(VariableArray);
 TKIND(DependentSizedArray);
 TKIND(Vector);
+TKIND(ExtVector);
 TKIND(MemberPointer);
 TKIND(Auto);
 TKIND(Elaborated);
@@ -804,6 +806,9 @@
 case Type::Vector:
   ET = cast (TP)->getElementType();
   break;
+case Type::ExtVector:
+  ET = cast(TP)->getElementType();
+  break;
 case Type::Complex:
   ET = cast (TP)->getElementType();
   break;
@@ -827,6 +832,9 @@
 case Type::Vector:
   result = cast (TP)->getNumElements();
   break;
+case Type::ExtVector:
+  result = cast(TP)->getNumElements();
+  break;
 default:
   break;
 }
Index: cfe/trunk/bindings/python/clang/cindex.py
===
--- cfe/trunk/bindings/python/clang/cindex.py
+++ cfe/trunk/bindings/python/clang/cindex.py
@@ -2121,6 +2121,8 @@
 TypeKind.OCLQUEUE = TypeKind(159)
 TypeKind.OCLRESERVEID = TypeKind(160)
 
+TypeKind.EXTVECTOR = TypeKind(176)
+
 class RefQualifierKind(BaseEnumeration):
 """Describes a specific ref-qualifier of a type."""
 


Index: cfe/trunk/include/clang-c/Index.h
===
--- cfe/trunk/include/clang-c/Index.h
+++ cfe/trunk/include/clang-c/Index.h
@@ -32,7 +32,7 @@
  * compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
  */
 #define CINDEX_VERSION_MAJOR 0
-#define CINDEX_VERSION_MINOR 54
+#define CINDEX_VERSION_MINOR 55
 

r358566 - [libclang] Expose ext_vector_type

2019-04-17 Thread Sven van Haastregt via cfe-commits
Author: svenvh
Date: Wed Apr 17 02:08:50 2019
New Revision: 358566

URL: http://llvm.org/viewvc/llvm-project?rev=358566=rev
Log:
[libclang] Expose ext_vector_type

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

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/include/clang-c/Index.h
cfe/trunk/test/Index/opencl-types.cl
cfe/trunk/tools/libclang/CXType.cpp

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=358566=358565=358566=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Wed Apr 17 02:08:50 2019
@@ -2121,6 +2121,8 @@ TypeKind.OCLEVENT = TypeKind(158)
 TypeKind.OCLQUEUE = TypeKind(159)
 TypeKind.OCLRESERVEID = TypeKind(160)
 
+TypeKind.EXTVECTOR = TypeKind(176)
+
 class RefQualifierKind(BaseEnumeration):
 """Describes a specific ref-qualifier of a type."""
 

Modified: cfe/trunk/include/clang-c/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang-c/Index.h?rev=358566=358565=358566=diff
==
--- cfe/trunk/include/clang-c/Index.h (original)
+++ cfe/trunk/include/clang-c/Index.h Wed Apr 17 02:08:50 2019
@@ -32,7 +32,7 @@
  * compatible, thus CINDEX_VERSION_MAJOR is expected to remain stable.
  */
 #define CINDEX_VERSION_MAJOR 0
-#define CINDEX_VERSION_MINOR 54
+#define CINDEX_VERSION_MINOR 55
 
 #define CINDEX_VERSION_ENCODE(major, minor) ( \
   ((major) * 1)   \
@@ -3315,7 +3315,9 @@ enum CXTypeKind {
   CXType_OCLIntelSubgroupAVCImeResultDualRefStreamout = 173,
   CXType_OCLIntelSubgroupAVCImeSingleRefStreamin = 174,
 
-  CXType_OCLIntelSubgroupAVCImeDualRefStreamin = 175
+  CXType_OCLIntelSubgroupAVCImeDualRefStreamin = 175,
+
+  CXType_ExtVector = 176
 };
 
 /**

Modified: cfe/trunk/test/Index/opencl-types.cl
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/opencl-types.cl?rev=358566=358565=358566=diff
==
--- cfe/trunk/test/Index/opencl-types.cl (original)
+++ cfe/trunk/test/Index/opencl-types.cl Wed Apr 17 02:08:50 2019
@@ -17,11 +17,11 @@ void kernel testFloatTypes() {
 }
 
 // CHECK: VarDecl=scalarHalf:11:8 (Definition){{( \(invalid\))?}} [type=half] 
[typekind=Half] [isPOD=1]
-// CHECK: VarDecl=vectorHalf:12:9 (Definition) [type=half4] [typekind=Typedef] 
[canonicaltype=half __attribute__((ext_vector_type(4)))] 
[canonicaltypekind=Unexposed] [isPOD=1]
+// CHECK: VarDecl=vectorHalf:12:9 (Definition) [type=half4] [typekind=Typedef] 
[canonicaltype=half __attribute__((ext_vector_type(4)))] 
[canonicaltypekind=ExtVector] [isPOD=1]
 // CHECK: VarDecl=scalarFloat:13:9 (Definition) [type=float] [typekind=Float] 
[isPOD=1]
-// CHECK: VarDecl=vectorFloat:14:10 (Definition) [type=float4] 
[typekind=Typedef] [canonicaltype=float __attribute__((ext_vector_type(4)))] 
[canonicaltypekind=Unexposed] [isPOD=1]
+// CHECK: VarDecl=vectorFloat:14:10 (Definition) [type=float4] 
[typekind=Typedef] [canonicaltype=float __attribute__((ext_vector_type(4)))] 
[canonicaltypekind=ExtVector] [isPOD=1]
 // CHECK: VarDecl=scalarDouble:15:10 (Definition){{( \(invalid\))?}} 
[type=double] [typekind=Double] [isPOD=1]
-// CHECK: VarDecl=vectorDouble:16:11 (Definition){{( \(invalid\))?}} 
[type=double4] [typekind=Typedef] [canonicaltype=double 
__attribute__((ext_vector_type(4)))] [canonicaltypekind=Unexposed] [isPOD=1]
+// CHECK: VarDecl=vectorDouble:16:11 (Definition){{( \(invalid\))?}} 
[type=double4] [typekind=Typedef] [canonicaltype=double 
__attribute__((ext_vector_type(4)))] [canonicaltypekind=ExtVector] [isPOD=1]
 
 #pragma OPENCL EXTENSION cl_khr_gl_msaa_sharing : enable
 

Modified: cfe/trunk/tools/libclang/CXType.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/libclang/CXType.cpp?rev=358566=358565=358566=diff
==
--- cfe/trunk/tools/libclang/CXType.cpp (original)
+++ cfe/trunk/tools/libclang/CXType.cpp Wed Apr 17 02:08:50 2019
@@ -109,6 +109,7 @@ static CXTypeKind GetTypeKind(QualType T
 TKCASE(VariableArray);
 TKCASE(DependentSizedArray);
 TKCASE(Vector);
+TKCASE(ExtVector);
 TKCASE(MemberPointer);
 TKCASE(Auto);
 TKCASE(Elaborated);
@@ -600,6 +601,7 @@ CXString clang_getTypeKindSpelling(enum
 TKIND(VariableArray);
 TKIND(DependentSizedArray);
 TKIND(Vector);
+TKIND(ExtVector);
 TKIND(MemberPointer);
 TKIND(Auto);
 TKIND(Elaborated);
@@ -804,6 +806,9 @@ CXType clang_getElementType(CXType CT) {
 case Type::Vector:
   ET = cast (TP)->getElementType();
   break;
+case Type::ExtVector:
+  ET = cast(TP)->getElementType();
+  break;
 case Type::Complex:
   ET = cast 

r358570 - clang-cl: Parse /openmp:experimental

2019-04-17 Thread Hans Wennborg via cfe-commits
Author: hans
Date: Wed Apr 17 03:05:58 2019
New Revision: 358570

URL: http://llvm.org/viewvc/llvm-project?rev=358570=rev
Log:
clang-cl: Parse /openmp:experimental

It was added to the MS docs recently here:
https://github.com/MicrosoftDocs/cpp-docs/commit/3951085ab722fbb488ca40864f4a0553f7b71855

Modified:
cfe/trunk/include/clang/Driver/CLCompatOptions.td
cfe/trunk/test/Driver/cl-options.c

Modified: cfe/trunk/include/clang/Driver/CLCompatOptions.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/CLCompatOptions.td?rev=358570=358569=358570=diff
==
--- cfe/trunk/include/clang/Driver/CLCompatOptions.td (original)
+++ cfe/trunk/include/clang/Driver/CLCompatOptions.td Wed Apr 17 03:05:58 2019
@@ -428,6 +428,7 @@ def _SLASH_kernel : CLFlag<"kernel">;
 def _SLASH_LN : CLFlag<"LN">;
 def _SLASH_MP : CLJoined<"MP">;
 def _SLASH_openmp : CLFlag<"openmp">;
+def _SLASH_openmp_experimental : CLFlag<"openmp:experimental">;
 def _SLASH_Qfast_transcendentals : CLFlag<"Qfast_transcendentals">;
 def _SLASH_QIfist : CLFlag<"QIfist">;
 def _SLASH_Qimprecise_fwaits : CLFlag<"Qimprecise_fwaits">;

Modified: cfe/trunk/test/Driver/cl-options.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/cl-options.c?rev=358570=358569=358570=diff
==
--- cfe/trunk/test/Driver/cl-options.c (original)
+++ cfe/trunk/test/Driver/cl-options.c Wed Apr 17 03:05:58 2019
@@ -442,6 +442,7 @@
 // RUN: /o foo.obj \
 // RUN: /ofoo.obj \
 // RUN: /openmp \
+// RUN: /openmp:experimental \
 // RUN: /Qfast_transcendentals \
 // RUN: /QIfist \
 // RUN: /Qimprecise_fwaits \


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


[PATCH] D60815: [clangd] Recognize "don't include me directly" pattern, and suppress include insertion.

2019-04-17 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked an inline comment as done.
sammccall added inline comments.



Comment at: clangd/index/SymbolCollector.cpp:602
+/// Returns None if includes should not be inserted for this file.
+llvm::Optional
+SymbolCollector::getIncludeHeader(llvm::StringRef QName, FileID FID) {

this function has been moved to a member so it can call isSelfContainedHeader 
which is now a member.

Apart from no longer having to change so many params, it is unmodified.



Comment at: clangd/index/SymbolCollector.cpp:631
+
+bool SymbolCollector::isSelfContainedHeader(FileID FID) {
+  // The real computation (which will be memoized).

this has been moved to a member so it can use the cache and the 
(non-threadsafe) regex, and its logic has obviously been changed.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D60815



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


[PATCH] D60455: [SYCL] Add support for SYCL device attributes

2019-04-17 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D60455#1469150 , @aaron.ballman 
wrote:

> In D60455#1468714 , @bader wrote:
>
> > In D60455#1468386 , @Fznamznon 
> > wrote:
> >
> > > > Ok, my question is whether you are planning to duplicate the same logic 
> > > > as for OpenCL kernel which doesn't really seem like an ideal design 
> > > > choice. Is this the only difference then we can simply add an extra 
> > > > check for SYCL compilation mode in this template handling case. The 
> > > > overall interaction between OpenCL and SYCL implementation is still a 
> > > > very big unknown to me so it's not very easy to judge about the 
> > > > implementations details...
> > >
> > > Of course, if nothing prevents us to re-use OpenCL kernel attribute for 
> > > SYCL I assume it would be good idea. 
> > >  But I'm thinking about the situation with 
> > > https://reviews.llvm.org/D60454 . If we re-use OpenCL kernel attributes - 
> > > we affected by OpenCL-related changes and OpenCL-related changes 
> > > shouldn't violate SYCL semantics. Will it be usable for SYCL/OpenCL clang 
> > > developers? @bader , what do you think about it?
> >
> >
> > I also think it's worth trying. We should be able to cover "SYCL semantics" 
> > with LIT test to avoid regressions by OpenCL related changes. E.g. add a 
> > test case checking that -fsycl-is-device option disables restriction on 
> > applying `__kernel` to template functions.
> >  I want to confirm that everyone is okay to enable `__kernel` keyword for 
> > SYCL extension and cover SYCL use cases with additional regression tests. 
> > IIRC, on yesterday call, @keryell, said that having SYCL specific 
> > attributes useful for separation of concerns.
>
>
> I'm not comfortable with that decision unless the attribute semantics are 
> sufficiently related to justify it. If we're just going to have a lot of 
> `KernelAttr->isSYCL()` vs `KernelAttr->isOpenCL()` accessor calls, it may 
> make more sense to use separate semantic attributes (even if they share 
> spellings), though then I'd be curious how a user combines OpenCL and SYCL 
> attributes.


I am not sure we need to add a keyword actually, the attribute can just be 
added in AST since it's not supposed to be used in the source code? My 
understanding of SYCL kernel is that it mainly matches OpenCL kernel 
functionality because the original intent of SYCL was to provide single source 
functionality on top of OpenCL. But I am not an expert in SYCL to confirm that. 
I think what we are missing currently is a thorough analysis/comparison between 
SYCL device mode and OpenCL kernel language mode to understand what's the best 
implementation strategy. That would apply to many other features: kernel 
function restrictions, address spaces, vectors, special types, etc. I still see 
no point in polluting our code base with extra code that just does the same 
thing. It will save us a lot of time to just work cooperatively on the same 
problem and even improve readability of the code. But of course this can only 
be done if there is no need to diverge the implementation significantly.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D60455



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


  1   2   >