[PATCH] D69876: Allow output constraints on "asm goto"

2019-11-11 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 228595.
void added a comment.

Adjust the ASM so that it references labels.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69876

Files:
  clang/include/clang/AST/Stmt.h
  clang/lib/AST/Stmt.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Parse/ParseStmtAsm.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  clang/test/CodeGen/asm-goto.c
  clang/test/Parser/asm-goto.c
  clang/test/Parser/asm-goto.cpp
  clang/test/Sema/asm-goto.cpp

Index: clang/test/Sema/asm-goto.cpp
===
--- clang/test/Sema/asm-goto.cpp
+++ clang/test/Sema/asm-goto.cpp
@@ -1,53 +1,51 @@
 // RUN: %clang_cc1 %s -triple i386-pc-linux-gnu -verify -fsyntax-only
 // RUN: %clang_cc1 %s -triple x86_64-pc-linux-gnu -verify -fsyntax-only
 
-struct NonTrivial {
-  ~NonTrivial();
+struct S {
+  ~S();
   int f(int);
 private:
   int k;
 };
-void JumpDiagnostics(int n) {
-// expected-error@+1 {{cannot jump from this goto statement to its label}}
+void test1(int n) {
+  // expected-error@+1 {{cannot jump from this goto statement to its label}}
   goto DirectJump;
-// expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
-  NonTrivial tnp1;
+  // expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
+  S s1;
 
 DirectJump:
-// expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
+  // expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
   asm goto("jmp %l0;" Later);
-// expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
-  NonTrivial tnp2;
-// expected-note@+1 {{possible target of asm goto statement}}
+  // expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
+  S s2;
+  // expected-note@+1 {{possible target of asm goto statement}}
 Later:
   return;
 }
 
-struct S { ~S(); };
-void foo(int a) {
+struct T { ~T(); };
+void test2(int a) {
   if (a) {
 FOO:
-// expected-note@+2 {{jump exits scope of variable with non-trivial destructor}}
-// expected-note@+1 {{jump exits scope of variable with non-trivial destructor}}
-S s;
-void *p = &&BAR;
-// expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
-  asm goto("jmp %l0;" BAR);
-// expected-error@+1 {{cannot jump from this indirect goto statement to one of its possible targets}}
+// expected-note@+2 {{jump exits scope of variable with non-trivial destructor}}
+// expected-note@+1 {{jump exits scope of variable with non-trivial destructor}}
+T t;
+void *p = &&bar;
+  // expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
+  asm goto("jmp %l0;" bar);
+// expected-error@+1 {{cannot jump from this indirect goto statement to one of its possible targets}}
 goto *p;
 p = &&FOO;
 goto *p;
 return;
   }
-// expected-note@+2 {{possible target of asm goto statement}}
-// expected-note@+1 {{possible target of indirect goto statement}}
-BAR:
+  // expected-note@+2 {{possible target of asm goto statement}}
+  // expected-note@+1 {{possible target of indirect goto statement}}
+bar:
   return;
 }
 
-
-//Asm goto:
-int test16(int n)
+int test3(int n)
 {
   // expected-error@+2 {{cannot jump from this asm goto statement to one of its possible targets}}
   // expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
@@ -57,7 +55,7 @@
   return ({int a[n];label_true: 2;});
   // expected-note@+1 {{jump bypasses initialization of variable length array}}
   int b[n];
-// expected-note@+1 {{possible target of asm goto statement}}
+  // expected-note@+1 {{possible target of asm goto statement}}
 loop:
   return 0;
 }
Index: clang/test/Parser/asm-goto.cpp
===
--- clang/test/Parser/asm-goto.cpp
+++ clang/test/Parser/asm-goto.cpp
@@ -1,14 +1,54 @@
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -fsyntax-only -verify -std=c++11 %s
 // RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fsyntax-only -verify -std=c++11 %s
 
-int zoo ()
-{
+int a, b, c, d, e, f, g, h, i, j, k, l;
+
+void test1(void) {
+  __asm__ volatile goto (""
+:: [a] "r" (a), [b] "r" (b), [c] "r" (c), [d] "r" (d),
+   [e] "r" (e), [f] "r" (f), [g] "r" (g), [h] "r" (h),
+   [i] "r" (i), [j] "r" (j), [k] "r" (k), [l] "r" (l)
+::lab1,lab2);
+lab1: return;
+lab2: return;
+}
+
+void test2(void) {
+  __asm__ volatile goto (""
+:: [a] "r,m" (a), [b] "r,m" (b), [c] "r,m" (c), [d] "r,m" (d),
+   [e] "r,m" (e), [f] "r,m" (f), [g] "r,m" (g), [h] "r,m" (h),
+   [i] "r,m" (i), [j] "r,m" (j), [k] "r,m" (k), [l] "r,m" (l)
+:: lab);
+  lab: return;
+}
+
+int test3(int x) {
+  __asm__ volatile goto ("decl %0; jnz %l[a]"
+   

[PATCH] D69922: [OpenMP] Use the OpenMP-IR-Builder

2019-11-11 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: clang/test/OpenMP/barrier_codegen.cpp:22
+// CLANGCG-NOT: readonly
+// IRBUILDER:  ; Function Attrs: nofree nosync nounwind readonly
+// IRBUILDER-NEXT: declare i32 @__kmpc_global_thread_num(%struct.ident_t*)

ABataev wrote:
> jdoerfert wrote:
> > ABataev wrote:
> > > jdoerfert wrote:
> > > > ABataev wrote:
> > > > > jdoerfert wrote:
> > > > > > ABataev wrote:
> > > > > > > jdoerfert wrote:
> > > > > > > > ABataev wrote:
> > > > > > > > > Not sure about correct use of `nosync` and `readonly` 
> > > > > > > > > attributes. OpenMP runtime uses lazy initialization of the 
> > > > > > > > > runtime library and when any runtime function is called, the 
> > > > > > > > > inner parts of the OpenMP runtime are initialized 
> > > > > > > > > automatically. It may use some sync primitives and may modify 
> > > > > > > > > memory, I assume. Same about `nofree`.
> > > > > > > > There are two versions of these functions, host and device. I 
> > > > > > > > assume host functions are not inlined but device functions 
> > > > > > > > might be. This is basically all the modes we support right now.
> > > > > > > > 
> > > > > > > > If we do not inline the function (host) we don't necessarily 
> > > > > > > > care what they do but what effect the user can expect.
> > > > > > > > The user can not expect to synchronize through 
> > > > > > > > `__kmpc_global_thread_num` calls in a defined way, thus 
> > > > > > > > `nosync`.
> > > > > > > > Similarly, from the users perspective there is no way to 
> > > > > > > > determine if something was written or freed, no matter how many 
> > > > > > > > of these calls I issue and under which control conditions, all 
> > > > > > > > I see is the number as a result. Thus, `readonly` and `nofree`. 
> > > > > > > > I believe `readnone` is even fine here but it might not work 
> > > > > > > > for the device version (see below) so I removed it.
> > > > > > > > 
> > > > > > > > If we do inline the function (device) we need to make sure the 
> > > > > > > > attributes are compatible with the inlined code to not cause 
> > > > > > > > UB. The code of `__kmpc_global_thread_num` at least does not 
> > > > > > > > write anything and only reads stuff (as far as I can tell).
> > > > > > > > 
> > > > > > > > Please correct me if I overlooked something. 
> > > > > > > But someone may try to inline the host-based runtime or try to 
> > > > > > > use LTO with it.
> > > > > > > The question is not about the user expectations but about the 
> > > > > > > optimizations which can be triggered with these attributes.
> > > > > > This is our runtime and we have supported and unsupported usage 
> > > > > > models.
> > > > > Hmm, I don't think this the right approach. Plus, you still did not 
> > > > > answer about optimizations. Maybe, currently, these attributes won't 
> > > > > trigger dangerous optimizations but they can do this in the future 
> > > > > and it may lead to unpredictable results. I would use the pessimistic 
> > > > > model here rather than over-optimistic.
> > > > I did (try to) describe why there cannot be any problems wrt. 
> > > > optimizations:
> > > > The specified behavior of the runtime call is _as if_ it is `readonly`, 
> > > > `nofree`, and `nosync`.
> > > > That is, from the perspective of the compiler this is true and 
> > > > optimizations are allowed to use that fact.
> > > >  
> > > > The fact that the first ever runtime call initializes the runtime is 
> > > > neither part of the specification nor of the observable behavior. If we 
> > > > change the order between two call to `__kmpc_global_thread_num`, or 
> > > > similar calls, we cannot observe if/which one initialized the runtime 
> > > > and which read only stuff.
> > > Here is the code of this function from the libomp:
> > > ```
> > >   int gtid;
> > > 
> > >   if (!__kmp_init_serial) {
> > > gtid = KMP_GTID_DNE;
> > >   } else
> > > #ifdef KMP_TDATA_GTID
> > >   if (TCR_4(__kmp_gtid_mode) >= 3) {
> > > KA_TRACE(1000, ("*** __kmp_get_global_thread_id_reg: using TDATA\n"));
> > > gtid = __kmp_gtid;
> > >   } else
> > > #endif
> > >   if (TCR_4(__kmp_gtid_mode) >= 2) {
> > > KA_TRACE(1000, ("*** __kmp_get_global_thread_id_reg: using keyed 
> > > TLS\n"));
> > > gtid = __kmp_gtid_get_specific();
> > >   } else {
> > > KA_TRACE(1000,
> > >  ("*** __kmp_get_global_thread_id_reg: using internal 
> > > alg.\n"));
> > > gtid = __kmp_get_global_thread_id();
> > >   }
> > > 
> > >   /* we must be a new uber master sibling thread */
> > >   if (gtid == KMP_GTID_DNE) {
> > > KA_TRACE(10,
> > >  ("__kmp_get_global_thread_id_reg: Encountered new root 
> > > thread. "
> > >   "Registering a new gtid.\n"));
> > > __kmp_acquire_bootstrap_lock(&__kmp_initz_lock);
> > > if (!__kmp_init_serial) {
> > >   __kmp_do_serial_initialize();
> > >   gtid = __kmp_gtid_get_sp

[clang] 6c94068 - [Driver] Remove unused variable. NFC.

2019-11-11 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2019-11-10T12:53:19+01:00
New Revision: 6c94068da99ae694a14f2484a2c9ac74a22bf61a

URL: 
https://github.com/llvm/llvm-project/commit/6c94068da99ae694a14f2484a2c9ac74a22bf61a
DIFF: 
https://github.com/llvm/llvm-project/commit/6c94068da99ae694a14f2484a2c9ac74a22bf61a.diff

LOG: [Driver] Remove unused variable. NFC.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Darwin.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index d550eea94670..b47150d1cee4 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1062,7 +1062,6 @@ StringRef Darwin::getPlatformFamily() const {
 
 StringRef Darwin::getSDKName(StringRef isysroot) {
   // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
-  llvm::sys::path::const_iterator SDKDir;
   auto BeginSDK = llvm::sys::path::begin(isysroot);
   auto EndSDK = llvm::sys::path::end(isysroot);
   for (auto IT = BeginSDK; IT != EndSDK; ++IT) {



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


[PATCH] D70052: [clang-tidy] Add misc-mutating-copy check

2019-11-11 Thread Gabor Bencze via Phabricator via cfe-commits
gbencze created this revision.
gbencze added reviewers: aaron.ballman, alexfh, JonasToth, Charusso.
gbencze added a project: clang-tools-extra.
Herald added subscribers: cfe-commits, mgehre, xazax.hun, mgorny.
Herald added a project: clang.

The check warns when (a member of) the copied object is assigned to in a 
copy constructor or copy assignment operator. Based on 
https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP58-CPP.+Copy+operations+must+not+mutate+the+source+object


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D70052

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/clang-tidy/misc/MutatingCopyCheck.cpp
  clang-tools-extra/clang-tidy/misc/MutatingCopyCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc-mutating-copy.rst
  clang-tools-extra/test/clang-tidy/misc-mutating-copy.cpp

Index: clang-tools-extra/test/clang-tidy/misc-mutating-copy.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/misc-mutating-copy.cpp
@@ -0,0 +1,107 @@
+// RUN: %check_clang_tidy %s misc-mutating-copy %t -std=c++11-or-later
+
+// Example test cases from CERT rule
+// https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP58-CPP.+Copy+operations+must+not+mutate+the+source+object
+namespace test_mutating_noncompliant_example {
+class A {
+  mutable int m;
+
+public:
+  A() : m(0) {}
+  explicit A(int m) : m(m) {}
+
+  A(const A &other) : m(other.m) {
+other.m = 0;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+  }
+
+  A &operator=(const A &other) {
+if (&other != this) {
+  m = other.m;
+  other.m = 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: mutating copied object
+}
+return *this;
+  }
+
+  int get_m() const { return m; }
+};
+} // namespace test_mutating_noncompliant_example
+
+namespace test_mutating_compliant_example {
+class B {
+  int m;
+
+public:
+  B() : m(0) {}
+  explicit B(int m) : m(m) {}
+
+  B(const B &other) : m(other.m) {}
+  B(B &&other) : m(other.m) {
+other.m = 0; //no-warning: mutation allowed in move constructor
+  }
+
+  B &operator=(const B &other) {
+if (&other != this) {
+  m = other.m;
+}
+return *this;
+  }
+
+  B &operator=(B &&other) {
+m = other.m;
+other.m = 0; //no-warning: mutation allowed in move assignment operator
+return *this;
+  }
+
+  int get_m() const { return m; }
+};
+} // namespace test_mutating_compliant_example
+
+namespace test_mutating_pointer {
+class C {
+  C *ptr;
+  int value;
+
+  C();
+  C(C &other) {
+other = {};
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+other.ptr = nullptr;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+other.value = 0;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+
+// no-warning: mutating a pointee is allowed
+other.ptr->value = 0;
+*other.ptr = {};
+  }
+};
+} // namespace test_mutating_pointer
+
+namespace test_mutating_indirect_member {
+struct S {
+  int x;
+};
+
+class D {
+  S s;
+  D(D &other) {
+other.s = {};
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+other.s.x = 0;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+  }
+};
+} // namespace test_mutating_indirect_member
+
+namespace test_mutating_other_object {
+class E {
+  E();
+  E(E &other) {
+E tmp;
+// no-warning: mutating an object that is not the source is allowed
+tmp = {};
+  }
+};
+} // namespace test_mutating_other_object
Index: clang-tools-extra/docs/clang-tidy/checks/misc-mutating-copy.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/misc-mutating-copy.rst
@@ -0,0 +1,11 @@
+.. title:: clang-tidy - misc-mutating-copy
+
+misc-mutating-copy
+==
+
+Finds assignments to and to direct or indirect members of the copied object 
+in copy constructors and copy assignment operators.
+
+This check corresponds to the CERT C Coding Standard rule
+`OOP58-CPP. Copy operations must not mutate the source object
+`_.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -283,6 +283,7 @@
llvm-twine-local
misc-definitions-in-headers
misc-misplaced-const
+   misc-mutating-copy
misc-new-delete-overloads
misc-non-copyable-objects
misc-non-private-member-variables-in-classes
Index: clang-tools-extra/docs/ReleaseNotes.rst
=

[PATCH] D70052: [clang-tidy] Add misc-mutating-copy check

2019-11-11 Thread Matthias Gehre via Phabricator via cfe-commits
mgehre added a comment.

Have you run your check over the LLVM/clang source base and seen true 
positives/false positives?




Comment at: clang-tools-extra/docs/clang-tidy/checks/misc-mutating-copy.rst:6
+
+Finds assignments to and to direct or indirect members of the copied object 
+in copy constructors and copy assignment operators.

`to and to`


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D70052



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


[PATCH] D69935: [DeclCXX] Remove unknown external linkage specifications

2019-11-11 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: clang/include/clang/AST/DeclCXX.h:2762
   /// ensure a stable ABI for this, we choose the DW_LANG_ encodings
   /// from the dwarf standard.
   enum LanguageIDs {

Using DWARF encodings here does nothing for AST format stability (compared to 
using our own numbering system), and is clearly creating confusion. Please just 
number these sequentially and remove the mention of DWARF here. We don't have a 
stable AST format across major releases, so it's fine to change the numbers 
(and hence the AST format) on master. (We don't even have working stability 
across patch releases yet, but should change/fix that at some point.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69935



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


[PATCH] D70052: [clang-tidy] Add misc-mutating-copy check

2019-11-11 Thread Gabor Bencze via Phabricator via cfe-commits
gbencze added a comment.

In D70052#1740075 , @mgehre wrote:

> Have you run your check over the LLVM/clang source base and seen true 
> positives/false positives?


I tested it on the Xerces and Bitcoin codebases and did not get any warnings.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D70052



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


[PATCH] D67545: [clang-tidy] Added DefaultOperatorNewCheck.

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

Land this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67545



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


[PATCH] D70048: [LLD] Add NetBSD support as a new flavor of LLD (nb.lld)

2019-11-11 Thread Kamil Rytarowski via Phabricator via cfe-commits
krytarowski added a comment.

Short summary:

- FreeBSD/OpenBSD ship with mutations of the behavior of ELF/GNU/Linux in 
certain nits, we do the same with our driver.
- MinGW ships with a frontend driver to COFF, we do the same with a driver to 
ELF/GNU/Linux.
- Darwin ships with default search paths, we do the same in our driver.
- NetBSD is not a GNU system, it is a BSD system that differs with 
ELF/GNU/Linux, GNU/Linux is at most an inspiration, none of our project goals 
is about reimplementing Linux. The same applies to MinGW, Darwin etc that do 
not reimplement Linux.

The proposed change does not make anything without prior art.

LLD is practically the last piece of the LLVM toolchain stack without NetBSD 
support. We run the NetBSD buildbot for LLD since 2018 and there are no plans 
to detach it.

We intend to integrate LLD into our distribution, but we first must make it 
work in the upstream version out of the box.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70048



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


[PATCH] D70052: [clang-tidy] Add misc-mutating-copy check

2019-11-11 Thread Matthias Gehre via Phabricator via cfe-commits
mgehre added a comment.

Did you consider to warn on copy constructors/assignment operators take a their 
arguments by non-`const` reference, and suggest the user to turn them into 
const references? This seems like a more useful (and easier) check to me.
The link above contains `Ideally, the copy operator should have an idiomatic 
signature. For copy constructors, that is T(const T&); and for copy assignment 
operators, that is T& operator=(const T&);.`.

The only remaining case are then `mutable` members which are quite rare.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D70052



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


[clang] 8e9e433 - clang/Modules: Remove unused parameter from ModuleManager::removeModules

2019-11-11 Thread Duncan P. N. Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2019-11-10T11:18:33-08:00
New Revision: 8e9e433a2af7c435923ba71ea7d75374408b0b32

URL: 
https://github.com/llvm/llvm-project/commit/8e9e433a2af7c435923ba71ea7d75374408b0b32
DIFF: 
https://github.com/llvm/llvm-project/commit/8e9e433a2af7c435923ba71ea7d75374408b0b32.diff

LOG: clang/Modules: Remove unused parameter from ModuleManager::removeModules

The other paremeters appear to be sufficient to determine which modules
have just been loaded and need to be removed, so stop collecting and
sending in that set explicitly.

Added: 


Modified: 
clang/include/clang/Serialization/ModuleManager.h
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ModuleManager.cpp

Removed: 




diff  --git a/clang/include/clang/Serialization/ModuleManager.h 
b/clang/include/clang/Serialization/ModuleManager.h
index 5b3b22be759c..5f20fd7d2eca 100644
--- a/clang/include/clang/Serialization/ModuleManager.h
+++ b/clang/include/clang/Serialization/ModuleManager.h
@@ -255,9 +255,7 @@ class ModuleManager {
 std::string &ErrorStr);
 
   /// Remove the modules starting from First (to the end).
-  void removeModules(ModuleIterator First,
- llvm::SmallPtrSetImpl &LoadedSuccessfully,
- ModuleMap *modMap);
+  void removeModules(ModuleIterator First, ModuleMap *modMap);
 
   /// Add an in-memory buffer the list of known buffers
   void addInMemoryBuffer(StringRef FileName,

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 2d3884ebe021..b8bdfef791b9 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -4185,11 +4185,7 @@ ASTReader::ASTReadResult ASTReader::ReadAST(StringRef 
FileName,
   case VersionMismatch:
   case ConfigurationMismatch:
   case HadErrors: {
-llvm::SmallPtrSet LoadedSet;
-for (const ImportedModule &IM : Loaded)
-  LoadedSet.insert(IM.Mod);
-
-ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
+ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
 PP.getLangOpts().Modules
 ? &PP.getHeaderSearchInfo().getModuleMap()
 : nullptr);

diff  --git a/clang/lib/Serialization/ModuleManager.cpp 
b/clang/lib/Serialization/ModuleManager.cpp
index 4b9f20fca4f8..669ab901731f 100644
--- a/clang/lib/Serialization/ModuleManager.cpp
+++ b/clang/lib/Serialization/ModuleManager.cpp
@@ -219,10 +219,7 @@ ModuleManager::addModule(StringRef FileName, ModuleKind 
Type,
   return NewlyLoaded;
 }
 
-void ModuleManager::removeModules(
-ModuleIterator First,
-llvm::SmallPtrSetImpl &LoadedSuccessfully,
-ModuleMap *modMap) {
+void ModuleManager::removeModules(ModuleIterator First, ModuleMap *modMap) {
   auto Last = end();
   if (First == Last)
 return;



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


[PATCH] D70056: clang/Modules: Split loop in ReadAST between failable and not

2019-11-11 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: aprantl, bruno, Bigcheese.
Herald added a subscriber: ributzka.

Split a loop in ReadAST that visits the just-loaded module chain,
between an initial loop that reads further from the ASTs (and can fail)
and a second loop that does some preloading (and cannot fail).  This
makes it less likely for a reading failure to affect the AST.

This is not fixing a known bug and the behaviour change may not be
observable, it's just part of an audit to look at all of the error
handling in the ASTReader.


https://reviews.llvm.org/D70056

Files:
  clang/lib/Serialization/ASTReader.cpp


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -4206,7 +4206,8 @@
 
   // Here comes stuff that we only do once the entire chain is loaded.
 
-  // Load the AST blocks of all of the modules that we loaded.
+  // Load the AST blocks of all of the modules that we loaded.  We can still
+  // hit errors parsing the ASTs at this point.
   for (SmallVectorImpl::iterator M = Loaded.begin(),
   MEnd = Loaded.end();
M != MEnd; ++M) {
@@ -4227,7 +4228,13 @@
 F.GlobalBitOffset = TotalModulesSizeInBits;
 TotalModulesSizeInBits += F.SizeInBits;
 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
+  }
 
+  // Preload source locations and interesting indentifiers.
+  for (SmallVectorImpl::iterator M = Loaded.begin(),
+  MEnd = Loaded.end();
+   M != MEnd; ++M) {
+ModuleFile &F = *M->Mod;
 // Preload SLocEntries.
 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
   int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -4206,7 +4206,8 @@
 
   // Here comes stuff that we only do once the entire chain is loaded.
 
-  // Load the AST blocks of all of the modules that we loaded.
+  // Load the AST blocks of all of the modules that we loaded.  We can still
+  // hit errors parsing the ASTs at this point.
   for (SmallVectorImpl::iterator M = Loaded.begin(),
   MEnd = Loaded.end();
M != MEnd; ++M) {
@@ -4227,7 +4228,13 @@
 F.GlobalBitOffset = TotalModulesSizeInBits;
 TotalModulesSizeInBits += F.SizeInBits;
 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
+  }
 
+  // Preload source locations and interesting indentifiers.
+  for (SmallVectorImpl::iterator M = Loaded.begin(),
+  MEnd = Loaded.end();
+   M != MEnd; ++M) {
+ModuleFile &F = *M->Mod;
 // Preload SLocEntries.
 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
   int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70058: clang/Modules: Delay err_module_file_conflict if a diagnostic is in flight

2019-11-11 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: aprantl, bruno, Bigcheese.
Herald added a subscriber: ributzka.

As part of an audit of whether all errors are being reported from the
ASTReader, delay err_module_file_conflict if a diagnostic is already in
flight when it is hit.  This required plumbing an extra argument through
the delayed diagnostic mechanics in DiagnosticsEngine.


https://reviews.llvm.org/D70058

Files:
  clang/include/clang/Basic/Diagnostic.h
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Basic/Diagnostic.cpp
  clang/lib/Serialization/ASTReader.cpp


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -1239,12 +1239,12 @@
   }
 }
 
-void ASTReader::Error(unsigned DiagID,
-  StringRef Arg1, StringRef Arg2) const {
+void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
+  StringRef Arg3) const {
   if (Diags.isDiagnosticInFlight())
-Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
+Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
   else
-Diag(DiagID) << Arg1 << Arg2;
+Diag(DiagID) << Arg1 << Arg2 << Arg3;
 }
 
 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
@@ -5487,12 +5487,9 @@
   // Don't emit module relocation error if we have -fno-validate-pch
   if (!PP.getPreprocessorOpts().DisablePCHValidation &&
   CurFile != F.File) {
-if (!Diags.isDiagnosticInFlight()) {
-  Diag(diag::err_module_file_conflict)
-<< CurrentModule->getTopLevelModuleName()
-<< CurFile->getName()
-<< F.File->getName();
-}
+Error(diag::err_module_file_conflict,
+  CurrentModule->getTopLevelModuleName(), CurFile->getName(),
+  F.File->getName());
 return Failure;
   }
 }
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -145,19 +145,20 @@
 }
 
 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
- StringRef Arg2) {
+ StringRef Arg2, StringRef Arg3) {
   if (DelayedDiagID)
 return;
 
   DelayedDiagID = DiagID;
   DelayedDiagArg1 = Arg1.str();
   DelayedDiagArg2 = Arg2.str();
+  DelayedDiagArg3 = Arg3.str();
 }
 
 void DiagnosticsEngine::ReportDelayed() {
   unsigned ID = DelayedDiagID;
   DelayedDiagID = 0;
-  Report(ID) << DelayedDiagArg1 << DelayedDiagArg2;
+  Report(ID) << DelayedDiagArg1 << DelayedDiagArg2 << DelayedDiagArg3;
 }
 
 void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {
Index: clang/include/clang/Serialization/ASTReader.h
===
--- clang/include/clang/Serialization/ASTReader.h
+++ clang/include/clang/Serialization/ASTReader.h
@@ -1440,7 +1440,7 @@
   /// do with non-routine failures (e.g., corrupted AST file).
   void Error(StringRef Msg) const;
   void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
- StringRef Arg2 = StringRef()) const;
+ StringRef Arg2 = StringRef(), StringRef Arg3 = StringRef()) const;
   void Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
  unsigned Select) const;
   void Error(llvm::Error &&Err) const;
Index: clang/include/clang/Basic/Diagnostic.h
===
--- clang/include/clang/Basic/Diagnostic.h
+++ clang/include/clang/Basic/Diagnostic.h
@@ -473,6 +473,9 @@
   /// Second string argument for the delayed diagnostic.
   std::string DelayedDiagArg2;
 
+  /// Second string argument for the delayed diagnostic.
+  std::string DelayedDiagArg3;
+
   /// Optional flag value.
   ///
   /// Some flags accept values, for instance: -Wframe-larger-than= and
@@ -875,7 +878,7 @@
   /// diagnostic. A copy of this string will be stored in the
   /// DiagnosticsEngine object itself.
   void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
-StringRef Arg2 = "");
+StringRef Arg2 = "", StringRef Arg3 = "");
 
   /// Clear out the current diagnostic.
   void Clear() { CurDiagID = std::numeric_limits::max(); }


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -1239,12 +1239,12 @@
   }
 }
 
-void ASTReader::Error(unsigned DiagID,
-  StringRef Arg1, StringRef Arg2) const {
+void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
+  StringRef Arg3) const {
  

[PATCH] D70055: clang/Modules: Clean up modules on error in ReadAST

2019-11-11 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: bruno, aprantl, Bigcheese.
Herald added a subscriber: ributzka.

ReadASTBlock and ReadASTExtensions can both return failures.  Be
consistent and remove all the just-loaded modules, just like when
ReadASTCore returns failures.


https://reviews.llvm.org/D70055

Files:
  clang/lib/Serialization/ASTReader.cpp


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -4174,17 +4174,8 @@
 PreviousGeneration = incrementGeneration(*ContextObj);
 
   unsigned NumModules = ModuleMgr.size();
-  SmallVector Loaded;
-  switch (ASTReadResult ReadResult =
-  ReadASTCore(FileName, Type, ImportLoc,
-  /*ImportedBy=*/nullptr, Loaded, 0, 0,
-  ASTFileSignature(), ClientLoadCapabilities)) {
-  case Failure:
-  case Missing:
-  case OutOfDate:
-  case VersionMismatch:
-  case ConfigurationMismatch:
-  case HadErrors: {
+  auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
+assert(ReadResult && "expected to return error");
 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
 PP.getLangOpts().Modules
 ? &PP.getHeaderSearchInfo().getModuleMap()
@@ -4195,7 +4186,20 @@
 GlobalIndex.reset();
 ModuleMgr.setGlobalIndex(nullptr);
 return ReadResult;
-  }
+  };
+
+  SmallVector Loaded;
+  switch (ASTReadResult ReadResult =
+  ReadASTCore(FileName, Type, ImportLoc,
+  /*ImportedBy=*/nullptr, Loaded, 0, 0,
+  ASTFileSignature(), ClientLoadCapabilities)) {
+  case Failure:
+  case Missing:
+  case OutOfDate:
+  case VersionMismatch:
+  case ConfigurationMismatch:
+  case HadErrors:
+return removeModulesAndReturn(ReadResult);
   case Success:
 break;
   }
@@ -4210,12 +4214,12 @@
 
 // Read the AST block.
 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
-  return Result;
+  return removeModulesAndReturn(Result);
 
 // Read the extension blocks.
 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
   if (ASTReadResult Result = ReadExtensionBlock(F))
-return Result;
+return removeModulesAndReturn(Result);
 }
 
 // Once read, set the ModuleFile bit base offset and update the size in


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -4174,17 +4174,8 @@
 PreviousGeneration = incrementGeneration(*ContextObj);
 
   unsigned NumModules = ModuleMgr.size();
-  SmallVector Loaded;
-  switch (ASTReadResult ReadResult =
-  ReadASTCore(FileName, Type, ImportLoc,
-  /*ImportedBy=*/nullptr, Loaded, 0, 0,
-  ASTFileSignature(), ClientLoadCapabilities)) {
-  case Failure:
-  case Missing:
-  case OutOfDate:
-  case VersionMismatch:
-  case ConfigurationMismatch:
-  case HadErrors: {
+  auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
+assert(ReadResult && "expected to return error");
 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
 PP.getLangOpts().Modules
 ? &PP.getHeaderSearchInfo().getModuleMap()
@@ -4195,7 +4186,20 @@
 GlobalIndex.reset();
 ModuleMgr.setGlobalIndex(nullptr);
 return ReadResult;
-  }
+  };
+
+  SmallVector Loaded;
+  switch (ASTReadResult ReadResult =
+  ReadASTCore(FileName, Type, ImportLoc,
+  /*ImportedBy=*/nullptr, Loaded, 0, 0,
+  ASTFileSignature(), ClientLoadCapabilities)) {
+  case Failure:
+  case Missing:
+  case OutOfDate:
+  case VersionMismatch:
+  case ConfigurationMismatch:
+  case HadErrors:
+return removeModulesAndReturn(ReadResult);
   case Success:
 break;
   }
@@ -4210,12 +4214,12 @@
 
 // Read the AST block.
 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
-  return Result;
+  return removeModulesAndReturn(Result);
 
 // Read the extension blocks.
 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
   if (ASTReadResult Result = ReadExtensionBlock(F))
-return Result;
+return removeModulesAndReturn(Result);
 }
 
 // Once read, set the ModuleFile bit base offset and update the size in
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70058: clang/Modules: Delay err_module_file_conflict if a diagnostic is in flight

2019-11-11 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith updated this revision to Diff 228618.
dexonsmith added a comment.

Updated header docs for the new delayed diagnostic parameter.


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

https://reviews.llvm.org/D70058

Files:
  clang/include/clang/Basic/Diagnostic.h
  clang/include/clang/Serialization/ASTReader.h
  clang/lib/Basic/Diagnostic.cpp
  clang/lib/Serialization/ASTReader.cpp

Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -1239,12 +1239,12 @@
   }
 }
 
-void ASTReader::Error(unsigned DiagID,
-  StringRef Arg1, StringRef Arg2) const {
+void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
+  StringRef Arg3) const {
   if (Diags.isDiagnosticInFlight())
-Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
+Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
   else
-Diag(DiagID) << Arg1 << Arg2;
+Diag(DiagID) << Arg1 << Arg2 << Arg3;
 }
 
 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
@@ -5487,12 +5487,9 @@
   // Don't emit module relocation error if we have -fno-validate-pch
   if (!PP.getPreprocessorOpts().DisablePCHValidation &&
   CurFile != F.File) {
-if (!Diags.isDiagnosticInFlight()) {
-  Diag(diag::err_module_file_conflict)
-<< CurrentModule->getTopLevelModuleName()
-<< CurFile->getName()
-<< F.File->getName();
-}
+Error(diag::err_module_file_conflict,
+  CurrentModule->getTopLevelModuleName(), CurFile->getName(),
+  F.File->getName());
 return Failure;
   }
 }
Index: clang/lib/Basic/Diagnostic.cpp
===
--- clang/lib/Basic/Diagnostic.cpp
+++ clang/lib/Basic/Diagnostic.cpp
@@ -145,19 +145,20 @@
 }
 
 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
- StringRef Arg2) {
+ StringRef Arg2, StringRef Arg3) {
   if (DelayedDiagID)
 return;
 
   DelayedDiagID = DiagID;
   DelayedDiagArg1 = Arg1.str();
   DelayedDiagArg2 = Arg2.str();
+  DelayedDiagArg3 = Arg3.str();
 }
 
 void DiagnosticsEngine::ReportDelayed() {
   unsigned ID = DelayedDiagID;
   DelayedDiagID = 0;
-  Report(ID) << DelayedDiagArg1 << DelayedDiagArg2;
+  Report(ID) << DelayedDiagArg1 << DelayedDiagArg2 << DelayedDiagArg3;
 }
 
 void DiagnosticsEngine::DiagStateMap::appendFirst(DiagState *State) {
Index: clang/include/clang/Serialization/ASTReader.h
===
--- clang/include/clang/Serialization/ASTReader.h
+++ clang/include/clang/Serialization/ASTReader.h
@@ -1440,7 +1440,7 @@
   /// do with non-routine failures (e.g., corrupted AST file).
   void Error(StringRef Msg) const;
   void Error(unsigned DiagID, StringRef Arg1 = StringRef(),
- StringRef Arg2 = StringRef()) const;
+ StringRef Arg2 = StringRef(), StringRef Arg3 = StringRef()) const;
   void Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
  unsigned Select) const;
   void Error(llvm::Error &&Err) const;
Index: clang/include/clang/Basic/Diagnostic.h
===
--- clang/include/clang/Basic/Diagnostic.h
+++ clang/include/clang/Basic/Diagnostic.h
@@ -473,6 +473,9 @@
   /// Second string argument for the delayed diagnostic.
   std::string DelayedDiagArg2;
 
+  /// Third string argument for the delayed diagnostic.
+  std::string DelayedDiagArg3;
+
   /// Optional flag value.
   ///
   /// Some flags accept values, for instance: -Wframe-larger-than= and
@@ -874,8 +877,12 @@
   /// \param Arg2 A string argument that will be provided to the
   /// diagnostic. A copy of this string will be stored in the
   /// DiagnosticsEngine object itself.
+  ///
+  /// \param Arg3 A string argument that will be provided to the
+  /// diagnostic. A copy of this string will be stored in the
+  /// DiagnosticsEngine object itself.
   void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
-StringRef Arg2 = "");
+StringRef Arg2 = "", StringRef Arg3 = "");
 
   /// Clear out the current diagnostic.
   void Clear() { CurDiagID = std::numeric_limits::max(); }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70057: clang/Modules: Add missing diagnostics for malformed AST files

2019-11-11 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: aprantl, bruno, Bigcheese.
Herald added a subscriber: ributzka.

These were found via an audit.  In the case of `ParseLineTable` this is
actually dead code, since parsing the line table always succeeds, but
it's prudent to be defensive since it's possible an assertion there
could be converted to a `true` return in the future.


https://reviews.llvm.org/D70057

Files:
  clang/lib/Serialization/ASTReader.cpp


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -3408,8 +3408,10 @@
   break;
 
 case SOURCE_MANAGER_LINE_TABLE:
-  if (ParseLineTable(F, Record))
+  if (ParseLineTable(F, Record)) {
+Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
 return Failure;
+  }
   break;
 
 case SOURCE_LOCATION_PRELOADS: {
@@ -4780,8 +4782,10 @@
 switch (MaybeRecCode.get()) {
 case EXTENSION_METADATA: {
   ModuleFileExtensionMetadata Metadata;
-  if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
+  if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
+Error("malformed EXTENSION_METADATA in AST file");
 return Failure;
+  }
 
   // Find a module file extension with this block name.
   auto Known = ModuleFileExtensions.find(Metadata.BlockName);


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -3408,8 +3408,10 @@
   break;
 
 case SOURCE_MANAGER_LINE_TABLE:
-  if (ParseLineTable(F, Record))
+  if (ParseLineTable(F, Record)) {
+Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
 return Failure;
+  }
   break;
 
 case SOURCE_LOCATION_PRELOADS: {
@@ -4780,8 +4782,10 @@
 switch (MaybeRecCode.get()) {
 case EXTENSION_METADATA: {
   ModuleFileExtensionMetadata Metadata;
-  if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
+  if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
+Error("malformed EXTENSION_METADATA in AST file");
 return Failure;
+  }
 
   // Find a module file extension with this block name.
   auto Known = ModuleFileExtensions.find(Metadata.BlockName);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70052: [clang-tidy] Add misc-mutating-copy check

2019-11-11 Thread Gabor Bencze via Phabricator via cfe-commits
gbencze added a comment.

In D70052#1740142 , @mgehre wrote:

> Did you consider to warn on copy constructors/assignment operators take a 
> their arguments by non-`const` reference, and suggest the user to turn them 
> into const references? This seems like a more useful (and easier) check to me.
>  The link above contains `Ideally, the copy operator should have an idiomatic 
> signature. For copy constructors, that is T(const T&); and for copy 
> assignment operators, that is T& operator=(const T&);.`.
>
> The only remaining case are then `mutable` members which are quite rare.


I haven't really considered it as the non-compliant example has the idiomatic 
signature, but it probably would be a good addition to the check. 
misc-unconventional-assign-operator already seems to do this for the assignment 
operator.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D70052



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


[PATCH] D70063: clang/Modules: Error if ReadASTBlock does not find the main module

2019-11-11 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: aprantl, bruno, Bigcheese.
Herald added a subscriber: ributzka.
dexonsmith added parent revisions: D70055: clang/Modules: Clean up modules on 
error in ReadAST, D70056: clang/Modules: Split loop in ReadAST between failable 
and not, D70057: clang/Modules: Add missing diagnostics for malformed AST 
files, D70058: clang/Modules: Delay err_module_file_conflict if a diagnostic is 
in flight.

If ReadASTBlock does not find the main module, there's something wrong
the with the PCM.  Error in that case, to avoid hitting problems further
from the source.

Note that the Swift compiler sometimes finds in
CompilerInstance::loadModule that the main module mysteriously does not
have Module::IsFromModuleFile set.  That will emit a confusing
warn_missing_submodule, which was never intended for a top-level module.
The recent audit of error-handling in ReadAST may have rooted out the
real problem.  If not, this commit will help to clarify the real
problem, and replace a confusing warning with an error pointing at the
malformed PCM file.


https://reviews.llvm.org/D70063

Files:
  clang/include/clang/Serialization/Module.h
  clang/lib/Serialization/ASTReader.cpp


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -4219,6 +4219,13 @@
 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
   return removeModulesAndReturn(Result);
 
+if (F.isModule() && !F.DidReadMainModule) {
+  // The AST block is malformed if it does not contain a definition for the
+  // main module.
+  Error("missing main SUBMODULE_DEFINITION in AST file");
+  return removeModulesAndReturn(Failure);
+}
+
 // Read the extension blocks.
 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
   if (ASTReadResult Result = ReadExtensionBlock(F))
@@ -5494,6 +5501,7 @@
   }
 }
 
+F.DidReadMainModule = true;
 CurrentModule->setASTFile(F.File);
 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
   }
Index: clang/include/clang/Serialization/Module.h
===
--- clang/include/clang/Serialization/Module.h
+++ clang/include/clang/Serialization/Module.h
@@ -159,6 +159,9 @@
   /// Whether the PCH has a corresponding object file.
   bool PCHHasObjectFile = false;
 
+  /// Whether the main module has been read from the AST file.
+  bool DidReadMainModule = false;
+
   /// The file entry for the module file.
   const FileEntry *File = nullptr;
 


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -4219,6 +4219,13 @@
 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
   return removeModulesAndReturn(Result);
 
+if (F.isModule() && !F.DidReadMainModule) {
+  // The AST block is malformed if it does not contain a definition for the
+  // main module.
+  Error("missing main SUBMODULE_DEFINITION in AST file");
+  return removeModulesAndReturn(Failure);
+}
+
 // Read the extension blocks.
 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
   if (ASTReadResult Result = ReadExtensionBlock(F))
@@ -5494,6 +5501,7 @@
   }
 }
 
+F.DidReadMainModule = true;
 CurrentModule->setASTFile(F.File);
 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
   }
Index: clang/include/clang/Serialization/Module.h
===
--- clang/include/clang/Serialization/Module.h
+++ clang/include/clang/Serialization/Module.h
@@ -159,6 +159,9 @@
   /// Whether the PCH has a corresponding object file.
   bool PCHHasObjectFile = false;
 
+  /// Whether the main module has been read from the AST file.
+  bool DidReadMainModule = false;
+
   /// The file entry for the module file.
   const FileEntry *File = nullptr;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70063: clang/Modules: Error if ReadASTBlock does not find the main module

2019-11-11 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith updated this revision to Diff 228626.
dexonsmith added a comment.

Updated to use a new diagnostic (`err_module_file_missing_definition`) that 
includes the filename of the PCM.


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

https://reviews.llvm.org/D70063

Files:
  clang/include/clang/Basic/DiagnosticSerializationKinds.td
  clang/include/clang/Serialization/Module.h
  clang/lib/Serialization/ASTReader.cpp


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -4219,6 +4219,12 @@
 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
   return removeModulesAndReturn(Result);
 
+// The AST block should always have a definition for the main module.
+if (F.isModule() && !F.DidReadMainModule) {
+  Error(diag::err_module_file_missing_definition, F.FileName);
+  return removeModulesAndReturn(Failure);
+}
+
 // Read the extension blocks.
 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
   if (ASTReadResult Result = ReadExtensionBlock(F))
@@ -5494,6 +5500,7 @@
   }
 }
 
+F.DidReadMainModule = true;
 CurrentModule->setASTFile(F.File);
 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
   }
Index: clang/include/clang/Serialization/Module.h
===
--- clang/include/clang/Serialization/Module.h
+++ clang/include/clang/Serialization/Module.h
@@ -159,6 +159,9 @@
   /// Whether the PCH has a corresponding object file.
   bool PCHHasObjectFile = false;
 
+  /// Whether the main module has been read from the AST file.
+  bool DidReadMainModule = false;
+
   /// The file entry for the module file.
   const FileEntry *File = nullptr;
 
Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -74,6 +74,8 @@
   "imported by %select{|module '%2' in }1'%0'">;
 def err_module_file_not_module : Error<
   "AST file '%0' was not built as a module">, DefaultFatal;
+def err_module_file_missing_definition : Error<
+  "module file '%0' is missing the main module's definition">, DefaultFatal;
 
 def remark_module_import : Remark<
   "importing module '%0'%select{| into '%3'}2 from '%1'">,


Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -4219,6 +4219,12 @@
 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
   return removeModulesAndReturn(Result);
 
+// The AST block should always have a definition for the main module.
+if (F.isModule() && !F.DidReadMainModule) {
+  Error(diag::err_module_file_missing_definition, F.FileName);
+  return removeModulesAndReturn(Failure);
+}
+
 // Read the extension blocks.
 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
   if (ASTReadResult Result = ReadExtensionBlock(F))
@@ -5494,6 +5500,7 @@
   }
 }
 
+F.DidReadMainModule = true;
 CurrentModule->setASTFile(F.File);
 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
   }
Index: clang/include/clang/Serialization/Module.h
===
--- clang/include/clang/Serialization/Module.h
+++ clang/include/clang/Serialization/Module.h
@@ -159,6 +159,9 @@
   /// Whether the PCH has a corresponding object file.
   bool PCHHasObjectFile = false;
 
+  /// Whether the main module has been read from the AST file.
+  bool DidReadMainModule = false;
+
   /// The file entry for the module file.
   const FileEntry *File = nullptr;
 
Index: clang/include/clang/Basic/DiagnosticSerializationKinds.td
===
--- clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -74,6 +74,8 @@
   "imported by %select{|module '%2' in }1'%0'">;
 def err_module_file_not_module : Error<
   "AST file '%0' was not built as a module">, DefaultFatal;
+def err_module_file_missing_definition : Error<
+  "module file '%0' is missing the main module's definition">, DefaultFatal;
 
 def remark_module_import : Remark<
   "importing module '%0'%select{| into '%3'}2 from '%1'">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D70052: [clang-tidy] Add misc-mutating-copy check

2019-11-11 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

If this is CERT rule, why check is not placed in relevant module?




Comment at: clang-tools-extra/docs/ReleaseNotes.rst:126
+
+  Finds copy operations that mutate the source object.
+

Please synchronize with first statement in documentation.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D70052



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


[PATCH] D69876: Allow output constraints on "asm goto"

2019-11-11 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

I think -Wuninitialized (UninitializedValues.cpp) should be taught how to 
detect the use of output variables in error blocks, at least for trivial cases.

Actually, for some reason -- it looks like the warning is failing the wrong way 
right now, and emits an uninitialized use warning even where there shouldn't be 
one.

E.g. this example should be okay:

  int foo(int x) {
int y;
asm goto("# %0 %1 %2" : "=r"(y) : "r"(x) : : err);
return y;
  err:
return -1;
  }

But now warns:

  $ clang -Wall -fsyntax-only foo.c
  foo.c:4:10: warning: variable 'y' is uninitialized when used here 
[-Wuninitialized]
return y;
   ^
  foo.c:2:8: note: initialize the variable 'y' to silence this warning
int y;
 ^
  = 0
  1 warning generated.

I'd expect a warning only if the code was modified to say "return y" in the err 
block.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69876



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


[PATCH] D69876: Allow output constraints on "asm goto"

2019-11-11 Thread Bill Wendling via Phabricator via cfe-commits
void marked an inline comment as done.
void added a comment.

This change is ready for review. PTAL.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69876



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


[PATCH] D69876: Allow output constraints on "asm goto"

2019-11-11 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

Also, since this means we are no longer simply implementing according to GCC's 
documentation, I think this means we'll need a brand new section in the Clang 
docs for its inline-asm support.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69876



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


[PATCH] D69979: clang: Guess at some platform FTZ/DAZ default settings

2019-11-11 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

In D69979#1738723 , @spatel wrote:

> Also, I may have missed some discussions. Does this patch series replace the 
> proposal to add instruction-level FMF for denorms?
>  http://lists.llvm.org/pipermail/llvm-dev/2019-September/135183.html
>
> Ie, did we decide that a function-level attribute is good enough?


I think this is an orthogonal question. I would still find a ftz flag useful 
even in the presence of this attribute indicating flushing. For AMDGPU it would 
be useful with a specific instruction context to allow flushing even when the 
default mode is set to not flush. For example llvm.fmuladd could be emitted 
with an ftz flag which would select to an instruction that would ordinarily be 
illegal if denormals are enabled


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

https://reviews.llvm.org/D69979



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


[PATCH] D69979: clang: Guess at some platform FTZ/DAZ default settings

2019-11-11 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

In D69979#1738099 , @craig.topper 
wrote:

> I checked Redhat 7.4 that's on the server I'm using for work. And I had a 
> coworker check his Ubuntu 18.04 system with this program. And both systems 
> printed 1f80 as the value of MXCSR which shows FTZ and DAZ are both 0. Are 
> you seeing something different?
>
>   #include 
>   #include 
>  
>   int main() {
> int csr = _mm_getcsr();
> printf("%x\n", csr);
> return 0;
>   }
>


I see the value as 1f80. However the test program I wrote suggests the default 
is to flush (and what the comments in bug 34994 suggest?):

  In default FP mode
  neg_subnormal + neg_subnormal: -0x0p+0
  neg_subnormal + neg_zero: -0x0p+0
  sqrtf subnormal: 0x0p+0
  sqrtf neg_subnormal: -0x0p+0
  sqrtf neg_zero: -0x0p+0
  
  With denormals disabled
  neg_subnormal + neg_subnormal: -0x0p+0
  neg_subnormal + neg_zero: -0x0p+0
  sqrtf subnormal: 0x0p+0
  sqrtf neg_subnormal: -0x0p+0
  sqrtf neg_zero: -0x0p+0
  
  With denormals enabled
  neg_subnormal + neg_subnormal: -0x1p-126
  neg_subnormal + neg_zero: -0x1p-127
  sqrtf subnormal: 0x1.6a09e6p-64
  sqrtf neg_subnormal: -nan
  sqrtf neg_zero: -0x0p+0
  
  With daz only
  neg_subnormal + neg_subnormal: -0x0p+0
  neg_subnormal + neg_zero: -0x0p+0
  sqrtf subnormal: 0x0p+0
  sqrtf neg_subnormal: -0x0p+0
  sqrtf neg_zero: -0x0p+0
  
  With ftz only
  neg_subnormal + neg_subnormal: -0x1p-126
  neg_subnormal + neg_zero: -0x0p+0
  sqrtf subnormal: 0x1.6a09e6p-64
  sqrtf neg_subnormal: -nan
  sqrtf neg_zero: -0x0p+0


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

https://reviews.llvm.org/D69979



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


[clang-tools-extra] b4f46a9 - [clangd] Fixes colon escaping on Windows

2019-11-11 Thread Ilya Biryukov via cfe-commits

Author: Ilya Biryukov
Date: 2019-11-11T09:21:25+01:00
New Revision: b4f46a9bb42972e663f8b7b4d15e4c8ed3fecef4

URL: 
https://github.com/llvm/llvm-project/commit/b4f46a9bb42972e663f8b7b4d15e4c8ed3fecef4
DIFF: 
https://github.com/llvm/llvm-project/commit/b4f46a9bb42972e663f8b7b4d15e4c8ed3fecef4.diff

LOG: [clangd] Fixes colon escaping on Windows

vscode always escapes the colon on the file uri, which causes the semantic 
highlighting fails on windows.

fixes: https://github.com/clangd/clangd/issues/176

Added: 


Modified: 
clang-tools-extra/clangd/clients/clangd-vscode/package-lock.json
clang-tools-extra/clangd/clients/clangd-vscode/package.json
clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts

Removed: 




diff  --git a/clang-tools-extra/clangd/clients/clangd-vscode/package-lock.json 
b/clang-tools-extra/clangd/clients/clangd-vscode/package-lock.json
index 0b59b2ffcc05..bbff586bbdca 100644
--- a/clang-tools-extra/clangd/clients/clangd-vscode/package-lock.json
+++ b/clang-tools-extra/clangd/clients/clangd-vscode/package-lock.json
@@ -1,6 +1,6 @@
 {
 "name": "vscode-clangd",
-"version": "0.0.18",
+"version": "0.0.19",
 "lockfileVersion": 1,
 "requires": true,
 "dependencies": {

diff  --git a/clang-tools-extra/clangd/clients/clangd-vscode/package.json 
b/clang-tools-extra/clangd/clients/clangd-vscode/package.json
index 03de7b3e58b0..05aafeb5f850 100644
--- a/clang-tools-extra/clangd/clients/clangd-vscode/package.json
+++ b/clang-tools-extra/clangd/clients/clangd-vscode/package.json
@@ -2,7 +2,7 @@
 "name": "vscode-clangd",
 "displayName": "vscode-clangd",
 "description": "Clang Language Server",
-"version": "0.0.18",
+"version": "0.0.19",
 "publisher": "llvm-vs-code-extensions",
 "homepage": "https://clang.llvm.org/extra/clangd.html";,
 "engines": {

diff  --git 
a/clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts 
b/clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
index 930079b1b2da..17517441bab9 100644
--- 
a/clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
+++ 
b/clang-tools-extra/clangd/clients/clangd-vscode/src/semantic-highlighting.ts
@@ -114,17 +114,17 @@ export class SemanticHighlightingFeature implements 
vscodelc.StaticFeature {
 this.loadCurrentTheme();
 // Event handling for handling with TextDocuments/Editors lifetimes.
 this.subscriptions.push(vscode.window.onDidChangeVisibleTextEditors(
-(editors: vscode.TextEditor[]) =>
-editors.forEach((e) => this.highlighter.applyHighlights(
-e.document.uri.toString();
+(editors: vscode.TextEditor[]) => editors.forEach(
+(e) => this.highlighter.applyHighlights(e.document.uri;
 this.subscriptions.push(vscode.workspace.onDidCloseTextDocument(
-(doc) => 
this.highlighter.removeFileHighlightings(doc.uri.toString(;
+(doc) => this.highlighter.removeFileHighlightings(doc.uri)));
   }
 
   handleNotification(params: SemanticHighlightingParams) {
 const lines: SemanticHighlightingLine[] = params.lines.map(
 (line) => ({line : line.line, tokens : decodeTokens(line.tokens)}));
-this.highlighter.highlight(params.textDocument.uri, lines);
+this.highlighter.highlight(vscode.Uri.parse(params.textDocument.uri),
+   lines);
   }
   // Disposes of all disposable resources used by this object.
   public dispose() {
@@ -199,19 +199,21 @@ export class Highlighter {
   // Adds incremental highlightings to the current highlightings for the file
   // with fileUri. Also applies the highlightings to any associated
   // TextEditor(s).
-  public highlight(fileUri: string,
+  public highlight(fileUri: vscode.Uri,
highlightingLines: SemanticHighlightingLine[]) {
-if (!this.files.has(fileUri)) {
-  this.files.set(fileUri, new Map());
+const fileUriStr = fileUri.toString();
+if (!this.files.has(fileUriStr)) {
+  this.files.set(fileUriStr, new Map());
 }
-const fileHighlightings = this.files.get(fileUri);
+const fileHighlightings = this.files.get(fileUriStr);
 highlightingLines.forEach((line) => fileHighlightings.set(line.line, 
line));
 this.applyHighlights(fileUri);
   }
 
   // Applies all the highlightings currently stored for a file with fileUri.
-  public applyHighlights(fileUri: string) {
-if (!this.files.has(fileUri))
+  public applyHighlights(fileUri: vscode.Uri) {
+const fileUriStr = fileUri.toString();
+if (!this.files.has(fileUriStr))
   // There are no highlightings for this file, must return early or will 
get
   // out of bounds when applying the decorations below.
   return;
@@ -224,7 +226,7 @@ export class Highlighter {
 // TextEditorDecorationType is used per scop

[PATCH] D69996: [clangd] Fixes colon escaping on Windows

2019-11-11 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov closed this revision.
ilya-biryukov added a comment.

Sorry for the delay, forgot to submit on Friday.
Also updated `package-lock.json` before submitting.


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

https://reviews.llvm.org/D69996



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


[PATCH] D69996: [clangd] Fixes colon escaping on Windows

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

I believe this patch fixes the issue,  but we need to update the file 
`test/semantic-highlighting.test.ts`), the test "Colorizer groups decorations 
correctly" is diverged from the actual code, although it is still passed (both 
`string` and `vscode.Uri` have the `toString` method unfortunately).

@lh123  do you mind doing that?


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

https://reviews.llvm.org/D69996



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


[PATCH] D69961: [clangd] Fix a regression of not showing documentation from forward declarations.

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

test union and struct kinds.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69961

Files:
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp


Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -408,13 +408,20 @@
 }
 
 TEST(MergeIndexTest, NonDocumentation) {
+  using index::SymbolKind;
   Symbol L, R;
   L.ID = R.ID = SymbolID("x");
   L.Definition.FileURI = "file:/x.h";
   R.Documentation = "Forward declarations because x.h is too big to include";
-
-  Symbol M = mergeSymbol(L, R);
-  EXPECT_EQ(M.Documentation, "");
+  for (auto ClassLikeKind :
+   {SymbolKind::Class, SymbolKind::Struct, SymbolKind::Union}) {
+L.SymInfo.Kind = ClassLikeKind;
+EXPECT_EQ(mergeSymbol(L, R).Documentation, "");
+  }
+
+  L.SymInfo.Kind = SymbolKind::Function;
+  R.Documentation = "Documentation from non-class symbols should be included";
+  EXPECT_EQ(mergeSymbol(L, R).Documentation, R.Documentation);
 }
 
 MATCHER_P2(IncludeHeaderWithRef, IncludeHeader, References, "") {
Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -186,11 +186,17 @@
 S.Signature = O.Signature;
   if (S.CompletionSnippetSuffix == "")
 S.CompletionSnippetSuffix = O.CompletionSnippetSuffix;
-  // Don't accept documentation from bare forward declarations, if there is a
-  // definition and it didn't provide one. S is often an undocumented class,
-  // and O is a non-canonical forward decl preceded by an irrelevant comment.
-  if (S.Documentation == "" && !S.Definition)
-S.Documentation = O.Documentation;
+  if (S.Documentation == "") {
+// Don't accept documentation from bare forward class declarations, if 
there
+// is a definition and it didn't provide one. S is often an undocumented
+// class, and O is a non-canonical forward decl preceded by an irrelevant
+// comment.
+bool IsClass = S.SymInfo.Kind == index::SymbolKind::Class ||
+   S.SymInfo.Kind == index::SymbolKind::Struct ||
+   S.SymInfo.Kind == index::SymbolKind::Union;
+if (!IsClass || !S.Definition)
+  S.Documentation = O.Documentation;
+  }
   if (S.ReturnType == "")
 S.ReturnType = O.ReturnType;
   if (S.Type == "")


Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -408,13 +408,20 @@
 }
 
 TEST(MergeIndexTest, NonDocumentation) {
+  using index::SymbolKind;
   Symbol L, R;
   L.ID = R.ID = SymbolID("x");
   L.Definition.FileURI = "file:/x.h";
   R.Documentation = "Forward declarations because x.h is too big to include";
-
-  Symbol M = mergeSymbol(L, R);
-  EXPECT_EQ(M.Documentation, "");
+  for (auto ClassLikeKind :
+   {SymbolKind::Class, SymbolKind::Struct, SymbolKind::Union}) {
+L.SymInfo.Kind = ClassLikeKind;
+EXPECT_EQ(mergeSymbol(L, R).Documentation, "");
+  }
+
+  L.SymInfo.Kind = SymbolKind::Function;
+  R.Documentation = "Documentation from non-class symbols should be included";
+  EXPECT_EQ(mergeSymbol(L, R).Documentation, R.Documentation);
 }
 
 MATCHER_P2(IncludeHeaderWithRef, IncludeHeader, References, "") {
Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -186,11 +186,17 @@
 S.Signature = O.Signature;
   if (S.CompletionSnippetSuffix == "")
 S.CompletionSnippetSuffix = O.CompletionSnippetSuffix;
-  // Don't accept documentation from bare forward declarations, if there is a
-  // definition and it didn't provide one. S is often an undocumented class,
-  // and O is a non-canonical forward decl preceded by an irrelevant comment.
-  if (S.Documentation == "" && !S.Definition)
-S.Documentation = O.Documentation;
+  if (S.Documentation == "") {
+// Don't accept documentation from bare forward class declarations, if there
+// is a definition and it didn't provide one. S is often an undocumented
+// class, and O is a non-canonical forward decl preceded by an irrelevant
+// comment.
+bool IsClass = S.SymInfo.Kind == index::SymbolKind::Class ||
+   S.SymInfo.Kind == index::SymbolKind::Struct ||
+   S.SymInfo.Kind == index::SymbolKind::Union;
+if (!IsClass || !S.Definition)
+  S.Documentation = O.Document

[PATCH] D69961: [clangd] Fix a regression of not showing documentation from forward declarations.

2019-11-11 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG41104a9406dd: [clangd] Fix a regression of not showing 
documentation from forward… (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69961

Files:
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp


Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -408,13 +408,20 @@
 }
 
 TEST(MergeIndexTest, NonDocumentation) {
+  using index::SymbolKind;
   Symbol L, R;
   L.ID = R.ID = SymbolID("x");
   L.Definition.FileURI = "file:/x.h";
   R.Documentation = "Forward declarations because x.h is too big to include";
-
-  Symbol M = mergeSymbol(L, R);
-  EXPECT_EQ(M.Documentation, "");
+  for (auto ClassLikeKind :
+   {SymbolKind::Class, SymbolKind::Struct, SymbolKind::Union}) {
+L.SymInfo.Kind = ClassLikeKind;
+EXPECT_EQ(mergeSymbol(L, R).Documentation, "");
+  }
+
+  L.SymInfo.Kind = SymbolKind::Function;
+  R.Documentation = "Documentation from non-class symbols should be included";
+  EXPECT_EQ(mergeSymbol(L, R).Documentation, R.Documentation);
 }
 
 MATCHER_P2(IncludeHeaderWithRef, IncludeHeader, References, "") {
Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -186,11 +186,17 @@
 S.Signature = O.Signature;
   if (S.CompletionSnippetSuffix == "")
 S.CompletionSnippetSuffix = O.CompletionSnippetSuffix;
-  // Don't accept documentation from bare forward declarations, if there is a
-  // definition and it didn't provide one. S is often an undocumented class,
-  // and O is a non-canonical forward decl preceded by an irrelevant comment.
-  if (S.Documentation == "" && !S.Definition)
-S.Documentation = O.Documentation;
+  if (S.Documentation == "") {
+// Don't accept documentation from bare forward class declarations, if 
there
+// is a definition and it didn't provide one. S is often an undocumented
+// class, and O is a non-canonical forward decl preceded by an irrelevant
+// comment.
+bool IsClass = S.SymInfo.Kind == index::SymbolKind::Class ||
+   S.SymInfo.Kind == index::SymbolKind::Struct ||
+   S.SymInfo.Kind == index::SymbolKind::Union;
+if (!IsClass || !S.Definition)
+  S.Documentation = O.Documentation;
+  }
   if (S.ReturnType == "")
 S.ReturnType = O.ReturnType;
   if (S.Type == "")


Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -408,13 +408,20 @@
 }
 
 TEST(MergeIndexTest, NonDocumentation) {
+  using index::SymbolKind;
   Symbol L, R;
   L.ID = R.ID = SymbolID("x");
   L.Definition.FileURI = "file:/x.h";
   R.Documentation = "Forward declarations because x.h is too big to include";
-
-  Symbol M = mergeSymbol(L, R);
-  EXPECT_EQ(M.Documentation, "");
+  for (auto ClassLikeKind :
+   {SymbolKind::Class, SymbolKind::Struct, SymbolKind::Union}) {
+L.SymInfo.Kind = ClassLikeKind;
+EXPECT_EQ(mergeSymbol(L, R).Documentation, "");
+  }
+
+  L.SymInfo.Kind = SymbolKind::Function;
+  R.Documentation = "Documentation from non-class symbols should be included";
+  EXPECT_EQ(mergeSymbol(L, R).Documentation, R.Documentation);
 }
 
 MATCHER_P2(IncludeHeaderWithRef, IncludeHeader, References, "") {
Index: clang-tools-extra/clangd/index/Merge.cpp
===
--- clang-tools-extra/clangd/index/Merge.cpp
+++ clang-tools-extra/clangd/index/Merge.cpp
@@ -186,11 +186,17 @@
 S.Signature = O.Signature;
   if (S.CompletionSnippetSuffix == "")
 S.CompletionSnippetSuffix = O.CompletionSnippetSuffix;
-  // Don't accept documentation from bare forward declarations, if there is a
-  // definition and it didn't provide one. S is often an undocumented class,
-  // and O is a non-canonical forward decl preceded by an irrelevant comment.
-  if (S.Documentation == "" && !S.Definition)
-S.Documentation = O.Documentation;
+  if (S.Documentation == "") {
+// Don't accept documentation from bare forward class declarations, if there
+// is a definition and it didn't provide one. S is often an undocumented
+// class, and O is a non-canonical forward decl preceded by an irrelevant
+// comment.
+bool IsClass = S.SymInfo.Kind == index::SymbolKind::Class ||
+   S.SymInfo.Kind == index::SymbolKind::Struct ||
+   S.SymInfo.Kind == index::SymbolKind::Union;
+if (!IsC

[clang] b1ac1f0 - Revert cdcf58e5af0 "[RISCV] enable LTO support, pass some options to linker."

2019-11-11 Thread Hans Wennborg via cfe-commits

Author: Hans Wennborg
Date: 2019-11-11T10:58:39+01:00
New Revision: b1ac1f0071626e5cf7f2847484b5b7595253a295

URL: 
https://github.com/llvm/llvm-project/commit/b1ac1f0071626e5cf7f2847484b5b7595253a295
DIFF: 
https://github.com/llvm/llvm-project/commit/b1ac1f0071626e5cf7f2847484b5b7595253a295.diff

LOG: Revert cdcf58e5af0 "[RISCV] enable LTO support, pass some options to 
linker."

This started passing target-features on the linker line, not just for RISCV but
for all targets, leading to error messages in Chromium Android build:

  '+soft-float-abi' is not a recognized feature for this target (ignoring 
feature)
  '+soft-float-abi' is not a recognized feature for this target (ignoring 
feature)

See Phabricator review for details.

Reverting until this can be fixed properly.

> Summary:
> 1. enable LTO need to pass target feature and abi to LTO code generation
>RISCV backend need the target feature to decide which extension used in
>code generation.
> 2. move getTargetFeatures to CommonArgs.h and add ForLTOPlugin flag
> 3. add general tools::getTargetABI in CommonArgs.h because different target 
> uses different
>way to get the target ABI.
>
> Patch by Kuan Hsu Chen (khchen)
>
> Reviewers: lenary, lewis-revill, asb, MaskRay
>
> Reviewed By: lenary
>
> Subscribers: hiraditya, dschuff, aheejin, fedor.sergeev, mehdi_amini, 
> inglorion, asb, rbar, johnrusso, simoncook, apazos, sabuasal, niosHD, 
> kito-cheng, shiva0217, jrtc27, MaskRay, zzheng, edward-jones, steven_wu, 
> rogfer01, MartinMosbeck, brucehoult, the_o, dexonsmith, rkruppe, PkmX, 
> jocewei, psnobl, benna, Jim, lenary, s.egerton, pzheng, cfe-commits
>
> Tags: #clang
>
> Differential Revision: https://reviews.llvm.org/D67409

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Driver/ToolChains/CommonArgs.h
clang/lib/Driver/ToolChains/RISCVToolchain.cpp
clang/lib/Driver/ToolChains/RISCVToolchain.h
clang/test/Driver/gold-lto.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 008742aca57f..04589d65e6d7 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -302,6 +302,95 @@ static void ParseMPreferVectorWidth(const Driver &D, const 
ArgList &Args,
   }
 }
 
+static void getWebAssemblyTargetFeatures(const ArgList &Args,
+ std::vector &Features) {
+  handleTargetFeaturesGroup(Args, Features, 
options::OPT_m_wasm_Features_Group);
+}
+
+static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
+  const ArgList &Args, ArgStringList &CmdArgs,
+  bool ForAS) {
+  const Driver &D = TC.getDriver();
+  std::vector Features;
+  switch (Triple.getArch()) {
+  default:
+break;
+  case llvm::Triple::mips:
+  case llvm::Triple::mipsel:
+  case llvm::Triple::mips64:
+  case llvm::Triple::mips64el:
+mips::getMIPSTargetFeatures(D, Triple, Args, Features);
+break;
+
+  case llvm::Triple::arm:
+  case llvm::Triple::armeb:
+  case llvm::Triple::thumb:
+  case llvm::Triple::thumbeb:
+arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
+break;
+
+  case llvm::Triple::ppc:
+  case llvm::Triple::ppc64:
+  case llvm::Triple::ppc64le:
+ppc::getPPCTargetFeatures(D, Triple, Args, Features);
+break;
+  case llvm::Triple::riscv32:
+  case llvm::Triple::riscv64:
+riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
+break;
+  case llvm::Triple::systemz:
+systemz::getSystemZTargetFeatures(Args, Features);
+break;
+  case llvm::Triple::aarch64:
+  case llvm::Triple::aarch64_be:
+aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
+break;
+  case llvm::Triple::x86:
+  case llvm::Triple::x86_64:
+x86::getX86TargetFeatures(D, Triple, Args, Features);
+break;
+  case llvm::Triple::hexagon:
+hexagon::getHexagonTargetFeatures(D, Args, Features);
+break;
+  case llvm::Triple::wasm32:
+  case llvm::Triple::wasm64:
+getWebAssemblyTargetFeatures(Args, Features);
+break;
+  case llvm::Triple::sparc:
+  case llvm::Triple::sparcel:
+  case llvm::Triple::sparcv9:
+sparc::getSparcTargetFeatures(D, Args, Features);
+break;
+  case llvm::Triple::r600:
+  case llvm::Triple::amdgcn:
+amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
+break;
+  case llvm::Triple::msp430:
+msp430::getMSP430TargetFeatures(D, Args, Features);
+  }
+
+  // Find the last of each feature.
+  llvm::StringMap LastOpt;
+  for (unsigned I = 0, N = Features.size(); I < N; ++I) {
+StringRef Name = Features[I];
+assert(Name[0] == '-' || Name[0] == '+');
+LastOpt[Name.drop_front(1)] = I;
+  }
+
+  for (unsigned I = 0, N = Features.size(); I < N; ++I) {
+// If this feature was overridden,

[clang-tools-extra] 41104a9 - [clangd] Fix a regression of not showing documentation from forward declarations.

2019-11-11 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2019-11-11T10:46:52+01:00
New Revision: 41104a9406dd284d984f7bee30c7756fcfe2b59e

URL: 
https://github.com/llvm/llvm-project/commit/41104a9406dd284d984f7bee30c7756fcfe2b59e
DIFF: 
https://github.com/llvm/llvm-project/commit/41104a9406dd284d984f7bee30c7756fcfe2b59e.diff

LOG: [clangd] Fix a regression of not showing documentation from forward 
declarations.

Summary:
There is a regression from https://reviews.llvm.org/D68467. Unlike class
forward declarations, function ducomentation is written in the declaration in
headers, the function definition doesn't contain any documentation, cases like:

```
foo.h
// this is foo.
void foo();
foo.cc

void foo() {}
```
we should still show documentation from the foo declaration.

Reviewers: ilya-biryukov

Reviewed By: ilya-biryukov

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/index/Merge.cpp
clang-tools-extra/clangd/unittests/IndexTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/Merge.cpp 
b/clang-tools-extra/clangd/index/Merge.cpp
index 76c5955893e4..0c9d0c8d3b12 100644
--- a/clang-tools-extra/clangd/index/Merge.cpp
+++ b/clang-tools-extra/clangd/index/Merge.cpp
@@ -186,11 +186,17 @@ Symbol mergeSymbol(const Symbol &L, const Symbol &R) {
 S.Signature = O.Signature;
   if (S.CompletionSnippetSuffix == "")
 S.CompletionSnippetSuffix = O.CompletionSnippetSuffix;
-  // Don't accept documentation from bare forward declarations, if there is a
-  // definition and it didn't provide one. S is often an undocumented class,
-  // and O is a non-canonical forward decl preceded by an irrelevant comment.
-  if (S.Documentation == "" && !S.Definition)
-S.Documentation = O.Documentation;
+  if (S.Documentation == "") {
+// Don't accept documentation from bare forward class declarations, if 
there
+// is a definition and it didn't provide one. S is often an undocumented
+// class, and O is a non-canonical forward decl preceded by an irrelevant
+// comment.
+bool IsClass = S.SymInfo.Kind == index::SymbolKind::Class ||
+   S.SymInfo.Kind == index::SymbolKind::Struct ||
+   S.SymInfo.Kind == index::SymbolKind::Union;
+if (!IsClass || !S.Definition)
+  S.Documentation = O.Documentation;
+  }
   if (S.ReturnType == "")
 S.ReturnType = O.ReturnType;
   if (S.Type == "")

diff  --git a/clang-tools-extra/clangd/unittests/IndexTests.cpp 
b/clang-tools-extra/clangd/unittests/IndexTests.cpp
index 9f0265d4190a..e868828d7868 100644
--- a/clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ b/clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -408,13 +408,20 @@ TEST(MergeIndexTest, Refs) {
 }
 
 TEST(MergeIndexTest, NonDocumentation) {
+  using index::SymbolKind;
   Symbol L, R;
   L.ID = R.ID = SymbolID("x");
   L.Definition.FileURI = "file:/x.h";
   R.Documentation = "Forward declarations because x.h is too big to include";
-
-  Symbol M = mergeSymbol(L, R);
-  EXPECT_EQ(M.Documentation, "");
+  for (auto ClassLikeKind :
+   {SymbolKind::Class, SymbolKind::Struct, SymbolKind::Union}) {
+L.SymInfo.Kind = ClassLikeKind;
+EXPECT_EQ(mergeSymbol(L, R).Documentation, "");
+  }
+
+  L.SymInfo.Kind = SymbolKind::Function;
+  R.Documentation = "Documentation from non-class symbols should be included";
+  EXPECT_EQ(mergeSymbol(L, R).Documentation, R.Documentation);
 }
 
 MATCHER_P2(IncludeHeaderWithRef, IncludeHeader, References, "") {



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


[PATCH] D67409: [RISCV] enable LTO support, pass some options to linker.

2019-11-11 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

I've reverted in  b1ac1f00716 
 until it 
can be fixed properly.

We noticed this in Chromium where we started seeing build spam like:

'+soft-float-abi' is not a recognized feature for this target (ignoring feature)
'+soft-float-abi' is not a recognized feature for this target (ignoring feature)

See https://bugs.chromium.org/p/chromium/issues/detail?id=1023280 for details.

Sorry for not reporting it earlier, but because it didn't break the build per 
se, we didn't notice until now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67409



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


[PATCH] D69961: [clangd] Fix a regression of not showing documentation from forward declarations.

2019-11-11 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: pass - 59966 tests passed, 0 failed and 763 were skipped.
Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69961



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


[PATCH] D70008: [clangd] Store xref for Macros in ParsedAST.

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



Comment at: clang-tools-extra/clangd/CollectMacros.h:29
   std::vector Ranges;
+  llvm::DenseMap> MacroRefs;
 };

I think the `Ranges` and `MacrosRefs` have a lot of duplications, it is 
wasteful to store a same range twice. We don't need the MainFilePath, the 
callers should know the corresponding file path for the AST. Something like 
`llvm::DenseMap> Refs;` should be enough.

symbol id for macro generation is required the definition location, but only 
defined macros have it, we may need an extra `vector` to store ranges for 
undefined macros.

```
#ifndef abc // there is no macro info* for abc, so getSymbolID will fail, but 
we still want it, e.g. in semantic highlighting.
#endif
``` 

There may be more tricky cases, it would be nice to have in the test.

```
#define abc 1
#undef abc

#define abc 2
#undef abc
```



Comment at: clang-tools-extra/clangd/XRefs.cpp:898
+  // Handle macros.
+  if (auto Macro = locateMacroAt(Loc, AST.getPreprocessor())) {
+if (auto MacroSID = getSymbolID(Macro->Name, Macro->Info, SM)) {

this is not completed, it only shows the macro refs in main file, we still need 
to query the index to get the rest (but our index doesn't collect macro at the 
moment). I'd prefer not doing this in this patch until our index is ready.

For testing, I think we can create a new test file for `CollectMainFileMacros`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70008



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


[PATCH] D70071: [ConstExprPreter] Removed the flag forcing the use of the interpreter

2019-11-11 Thread Nandor Licker via Phabricator via cfe-commits
nand created this revision.
nand added reviewers: jfb, Bigcheese, rsmith, dexonsmith.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
nand edited the summary of this revision.

Removed the `-fforce-experimental-new-constant-interpreter flag`, leaving
only the `-fexperimental-new-constant-interpreter` one. The interpreter
now always emits an error on an unsupported feature.

Allowing the interpreter to bail out would require a mapping from APValue to
interpreter memory, which will not be necessary in the final version. It is 
more sensible to always emit an error if the interpreter fails.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70071

Files:
  clang/docs/ConstantInterpreter.rst
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Context.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/AST/Interp/cond.cpp

Index: clang/test/AST/Interp/cond.cpp
===
--- clang/test/AST/Interp/cond.cpp
+++ clang/test/AST/Interp/cond.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++17 -fsyntax-only -fforce-experimental-new-constant-interpreter %s -verify
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -fexperimental-new-constant-interpreter %s -verify
 // RUN: %clang_cc1 -std=c++17 -fsyntax-only %s -verify
 // expected-no-diagnostics
 
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2836,8 +2836,6 @@
   getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
   Opts.EnableNewConstInterp =
   Args.hasArg(OPT_fexperimental_new_constant_interpreter);
-  Opts.ForceNewConstInterp =
-  Args.hasArg(OPT_fforce_experimental_new_constant_interpreter);
   Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
   Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
   Opts.NumLargeByValueCopy =
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4428,9 +4428,6 @@
   if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
 
-  if (Args.hasArg(options::OPT_fforce_experimental_new_constant_interpreter))
-CmdArgs.push_back("-fforce-experimental-new-constant-interpreter");
-
   if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
 CmdArgs.push_back("-fbracket-depth");
 CmdArgs.push_back(A->getValue());
Index: clang/lib/AST/Interp/Context.h
===
--- clang/lib/AST/Interp/Context.h
+++ clang/lib/AST/Interp/Context.h
@@ -34,16 +34,6 @@
 class State;
 enum PrimType : unsigned;
 
-/// Wrapper around interpreter termination results.
-enum class InterpResult {
-  /// Interpreter successfully computed a value.
-  Success,
-  /// Interpreter encountered an error and quit.
-  Fail,
-  /// Interpreter encountered an unimplemented feature, AST fallback.
-  Bail,
-};
-
 /// Holds all information required to evaluate constexpr code in a module.
 class Context {
 public:
@@ -54,15 +44,13 @@
   ~Context();
 
   /// Checks if a function is a potential constant expression.
-  InterpResult isPotentialConstantExpr(State &Parent,
-   const FunctionDecl *FnDecl);
+  bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FnDecl);
 
   /// Evaluates a toplevel expression as an rvalue.
-  InterpResult evaluateAsRValue(State &Parent, const Expr *E, APValue &Result);
+  bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result);
 
   /// Evaluates a toplevel initializer.
-  InterpResult evaluateAsInitializer(State &Parent, const VarDecl *VD,
- APValue &Result);
+  bool evaluateAsInitializer(State &Parent, const VarDecl *VD, APValue &Result);
 
   /// Returns the AST context.
   ASTContext &getASTContext() const { return Ctx; }
@@ -78,16 +66,14 @@
 
 private:
   /// Runs a function.
-  InterpResult Run(State &Parent, Function *Func, APValue &Result);
+  bool Run(State &Parent, Function *Func, APValue &Result);
 
   /// Checks a result fromt the interpreter.
-  InterpResult Check(State &Parent, llvm::Expected &&R);
+  bool Check(State &Parent, llvm::Expected &&R);
 
 private:
   /// Current compilation context.
   ASTContext &Ctx;
-  /// Flag to indicate if the use of the interpreter is mandatory.
-  bool ForceInterp;
   /// Interpreter stack, shared across invocations.
   InterpStack Stk;
   /// Constexpr program.
Index: clang/lib/AST/Interp/Context.cpp

[clang-tools-extra] 02ec6ff - [clangd] Use name of Macro to compute its SymbolID, NFC.

2019-11-11 Thread Haojian Wu via cfe-commits

Author: Utkarsh Saxena
Date: 2019-11-11T12:38:49+01:00
New Revision: 02ec6ff77eb718528138737c885e67c248ecae49

URL: 
https://github.com/llvm/llvm-project/commit/02ec6ff77eb718528138737c885e67c248ecae49
DIFF: 
https://github.com/llvm/llvm-project/commit/02ec6ff77eb718528138737c885e67c248ecae49.diff

LOG: [clangd] Use name of Macro to compute its SymbolID, NFC.

Summary:
We use the name from the IdentifierInfo of the Macro to compute its
SymbolID. It is better to just take the Name as a parameter to avoid
storing the IdentifierInfo whenever we need the SymbolID for the Macro.

Patch by UTKARSH SAXENA!

Reviewers: hokein

Reviewed By: hokein

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/AST.cpp
clang-tools-extra/clangd/AST.h
clang-tools-extra/clangd/CodeComplete.cpp
clang-tools-extra/clangd/index/SymbolCollector.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/AST.cpp 
b/clang-tools-extra/clangd/AST.cpp
index 002f2ef08cc7..1958ebf80c4c 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -203,13 +203,13 @@ llvm::Optional getSymbolID(const Decl *D) {
   return SymbolID(USR);
 }
 
-llvm::Optional getSymbolID(const IdentifierInfo &II,
+llvm::Optional getSymbolID(const llvm::StringRef MacroName,
  const MacroInfo *MI,
  const SourceManager &SM) {
   if (MI == nullptr)
 return None;
   llvm::SmallString<128> USR;
-  if (index::generateUSRForMacro(II.getName(), MI->getDefinitionLoc(), SM, 
USR))
+  if (index::generateUSRForMacro(MacroName, MI->getDefinitionLoc(), SM, USR))
 return None;
   return SymbolID(USR);
 }

diff  --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index b05e0a224774..8f1abdd3297d 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -17,6 +17,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/MacroInfo.h"
+#include "llvm/ADT/StringRef.h"
 
 namespace clang {
 class SourceManager;
@@ -69,7 +70,7 @@ llvm::Optional getSymbolID(const Decl *D);
 /// macro (e.g. a change in definition offset can result in a 
diff erent USR). We
 /// could change these semantics in the future by reimplementing this funcure
 /// (e.g. avoid USR for macros).
-llvm::Optional getSymbolID(const IdentifierInfo &II,
+llvm::Optional getSymbolID(const llvm::StringRef MacroName,
  const MacroInfo *MI,
  const SourceManager &SM);
 

diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index db9f9cc0519b..4ef9842a381c 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -492,7 +492,7 @@ llvm::Optional getSymbolID(const 
CodeCompletionResult &R,
 return clang::clangd::getSymbolID(R.Declaration);
   }
   case CodeCompletionResult::RK_Macro:
-return clang::clangd::getSymbolID(*R.Macro, R.MacroDefInfo, SM);
+return clang::clangd::getSymbolID(R.Macro->getName(), R.MacroDefInfo, SM);
   case CodeCompletionResult::RK_Keyword:
 return None;
   }

diff  --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index b0932dcf97ad..06fe854b2e0b 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -377,7 +377,7 @@ bool SymbolCollector::handleMacroOccurence(const 
IdentifierInfo *Name,
 Roles & static_cast(index::SymbolRole::Definition)))
 return true;
 
-  auto ID = getSymbolID(*Name, MI, SM);
+  auto ID = getSymbolID(Name->getName(), MI, SM);
   if (!ID)
 return true;
 
@@ -473,14 +473,14 @@ void SymbolCollector::finish() {
 // First, drop header guards. We can't identify these until EOF.
 for (const IdentifierInfo *II : IndexedMacros) {
   if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
-if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
+if (auto ID = getSymbolID(II->getName(), MI, PP->getSourceManager()))
   if (MI->isUsedForHeaderGuard())
 Symbols.erase(*ID);
 }
 // Now increment refcounts.
 for (const IdentifierInfo *II : ReferencedMacros) {
   if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
-if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
+if (auto ID = getSymbolID(II->getName(), MI, PP->getSourceManager()))
   IncRef(*ID);
 }
   }



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

[PATCH] D69707: [AArch64][SVE] Implement additional floating-point arithmetic intrinsics

2019-11-11 Thread Kerry McLaughlin via Phabricator via cfe-commits
kmclaughlin updated this revision to Diff 228660.
kmclaughlin added a comment.

- Changed target constant to MVT::i32 in complexrotateop & complexrotateopodd 
definitions


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

https://reviews.llvm.org/D69707

Files:
  llvm/include/llvm/IR/IntrinsicsAArch64.td
  llvm/lib/Target/AArch64/AArch64InstrFormats.td
  llvm/lib/Target/AArch64/AArch64SVEInstrInfo.td
  llvm/lib/Target/AArch64/SVEInstrFormats.td
  llvm/test/CodeGen/AArch64/sve-intrinsics-fp-arith.ll

Index: llvm/test/CodeGen/AArch64/sve-intrinsics-fp-arith.ll
===
--- llvm/test/CodeGen/AArch64/sve-intrinsics-fp-arith.ll
+++ llvm/test/CodeGen/AArch64/sve-intrinsics-fp-arith.ll
@@ -69,6 +69,112 @@
 }
 
 ;
+; FCADD
+;
+
+define  @fcadd_h( %pg,  %a,  %b) {
+; CHECK-LABEL: fcadd_h:
+; CHECK: fcadd z0.h, p0/m, z0.h, z1.h, #90
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.fcadd.nxv8f16( %pg,
+   %a,
+   %b,
+  i32 90)
+  ret  %out
+}
+
+define  @fcadd_s( %pg,  %a,  %b) {
+; CHECK-LABEL: fcadd_s:
+; CHECK: fcadd z0.s, p0/m, z0.s, z1.s, #270
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.fcadd.nxv4f32( %pg,
+%a,
+%b,
+   i32 270)
+  ret  %out
+}
+
+define  @fcadd_d( %pg,  %a,  %b) {
+; CHECK-LABEL: fcadd_d:
+; CHECK: fcadd z0.d, p0/m, z0.d, z1.d, #90
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.fcadd.nxv2f64( %pg,
+ %a,
+ %b,
+i32 90)
+  ret  %out
+}
+
+;
+; FCMLA
+;
+
+define  @fcmla_h( %pg,  %a,  %b,  %c) {
+; CHECK-LABEL: fcmla_h:
+; CHECK: fcmla z0.h, p0/m, z1.h, z2.h, #90
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.fcmla.nxv8f16( %pg,
+   %a,
+   %b,
+   %c,
+  i32 90)
+  ret  %out
+}
+
+define  @fcmla_s( %pg,  %a,  %b,  %c) {
+; CHECK-LABEL: fcmla_s:
+; CHECK: fcmla z0.s, p0/m, z1.s, z2.s, #180
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.fcmla.nxv4f32( %pg,
+%a,
+%b,
+%c,
+   i32 180)
+  ret  %out
+}
+
+define  @fcmla_d( %pg,  %a,  %b,  %c) {
+; CHECK-LABEL: fcmla_d:
+; CHECK: fcmla z0.d, p0/m, z1.d, z2.d, #270
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.fcmla.nxv2f64( %pg,
+ %a,
+ %b,
+ %c,
+i32 270)
+  ret  %out
+}
+
+;
+; FCMLA (Indexed)
+;
+
+define  @fcmla_lane_h( %a,  %b,  %c) {
+; CHECK-LABEL: fcmla_lane_h:
+; CHECK: fcmla z0.h, z1.h, z2.h[3], #0
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.fcmla.lane.nxv8f16( %a,
+%b,
+%c,
+   i32 3,
+   i32 0)
+  ret  %out
+}
+
+define  @fcmla_lane_s( %a,  %b,  %c) {
+; CHECK-LABEL: fcmla_lane_s:
+; CHECK: fcmla z0.s, z1.s, z2.s[1], #90
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.fcmla.lane.nxv4f32( %a,
+ %b,
+ %c,
+i32 1,
+i32 90)
+  ret  %out
+}
+
+
+;
 ; FDIV
 ;
 
@@ -137,6 +243,43 @@
 }
 
 ;
+; FMAD
+;
+
+define  @fmad_h( %pg,  %a,  %b,  %c) {
+; CHECK-LABEL: fmad_h:
+; CHECK: fmad z0.h, p0/m, z1.h, z2.h
+; CHECK-NEXT: ret
+  %out = call  @llvm.aarch64.sve.fmad.nxv8f16( %pg,
+  %a,
+   

[PATCH] D69573: [clang-format] [PR36294] AlwaysBreakAfterReturnType works incorrectly for some operator functions

2019-11-11 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Thanks, looks great!
Sorry for the delay, I was out last week.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69573



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


[PATCH] D68407: [WIP][RISCV] Use compiler-rt if no GCC installation detected

2019-11-11 Thread Sam Elliott via Phabricator via cfe-commits
lenary added a comment.

LGTM.

I looked at what `g++` and `gcc` do (my riscv64-unknown-elf toolchain):

- `gcc`: Passes `-lgcc --start-group -lc -lgloss --end-group -lgcc` to the 
linker
- `g++`: Passes `"-lstdc++" -lm -lgcc --start-group -lc -lgloss --end-group 
-lgcc` to the linker

This patch:

- `clang` passes `"--start-group" "-lc" "-lgloss" "--end-group" "-lgcc"` to the 
linker
- `clang++` passes `"-lstdc++" "--start-group" "-lc" "-lgloss" "--end-group" 
"-lgcc"` to the linker

I think these are all compatible. I'm not sure where the `-lm` is coming from 
in the g++ invocation vs the `clang++` invocation, but given we have TODOs in 
this driver code around C++, I don't think that needs to be fixed in this patch.


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

https://reviews.llvm.org/D68407



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


[PATCH] D69937: [clangd] Use name of Macro to compute its SymbolID.

2019-11-11 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG02ec6ff77eb7: [clangd] Use name of Macro to compute its 
SymbolID, NFC. (authored by usaxena95, committed by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69937

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


Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -377,7 +377,7 @@
 Roles & static_cast(index::SymbolRole::Definition)))
 return true;
 
-  auto ID = getSymbolID(*Name, MI, SM);
+  auto ID = getSymbolID(Name->getName(), MI, SM);
   if (!ID)
 return true;
 
@@ -473,14 +473,14 @@
 // First, drop header guards. We can't identify these until EOF.
 for (const IdentifierInfo *II : IndexedMacros) {
   if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
-if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
+if (auto ID = getSymbolID(II->getName(), MI, PP->getSourceManager()))
   if (MI->isUsedForHeaderGuard())
 Symbols.erase(*ID);
 }
 // Now increment refcounts.
 for (const IdentifierInfo *II : ReferencedMacros) {
   if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
-if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
+if (auto ID = getSymbolID(II->getName(), MI, PP->getSourceManager()))
   IncRef(*ID);
 }
   }
Index: clang-tools-extra/clangd/CodeComplete.cpp
===
--- clang-tools-extra/clangd/CodeComplete.cpp
+++ clang-tools-extra/clangd/CodeComplete.cpp
@@ -492,7 +492,7 @@
 return clang::clangd::getSymbolID(R.Declaration);
   }
   case CodeCompletionResult::RK_Macro:
-return clang::clangd::getSymbolID(*R.Macro, R.MacroDefInfo, SM);
+return clang::clangd::getSymbolID(R.Macro->getName(), R.MacroDefInfo, SM);
   case CodeCompletionResult::RK_Keyword:
 return None;
   }
Index: clang-tools-extra/clangd/AST.h
===
--- clang-tools-extra/clangd/AST.h
+++ clang-tools-extra/clangd/AST.h
@@ -17,6 +17,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Lex/MacroInfo.h"
+#include "llvm/ADT/StringRef.h"
 
 namespace clang {
 class SourceManager;
@@ -69,7 +70,7 @@
 /// macro (e.g. a change in definition offset can result in a different USR). 
We
 /// could change these semantics in the future by reimplementing this funcure
 /// (e.g. avoid USR for macros).
-llvm::Optional getSymbolID(const IdentifierInfo &II,
+llvm::Optional getSymbolID(const llvm::StringRef MacroName,
  const MacroInfo *MI,
  const SourceManager &SM);
 
Index: clang-tools-extra/clangd/AST.cpp
===
--- clang-tools-extra/clangd/AST.cpp
+++ clang-tools-extra/clangd/AST.cpp
@@ -203,13 +203,13 @@
   return SymbolID(USR);
 }
 
-llvm::Optional getSymbolID(const IdentifierInfo &II,
+llvm::Optional getSymbolID(const llvm::StringRef MacroName,
  const MacroInfo *MI,
  const SourceManager &SM) {
   if (MI == nullptr)
 return None;
   llvm::SmallString<128> USR;
-  if (index::generateUSRForMacro(II.getName(), MI->getDefinitionLoc(), SM, 
USR))
+  if (index::generateUSRForMacro(MacroName, MI->getDefinitionLoc(), SM, USR))
 return None;
   return SymbolID(USR);
 }


Index: clang-tools-extra/clangd/index/SymbolCollector.cpp
===
--- clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -377,7 +377,7 @@
 Roles & static_cast(index::SymbolRole::Definition)))
 return true;
 
-  auto ID = getSymbolID(*Name, MI, SM);
+  auto ID = getSymbolID(Name->getName(), MI, SM);
   if (!ID)
 return true;
 
@@ -473,14 +473,14 @@
 // First, drop header guards. We can't identify these until EOF.
 for (const IdentifierInfo *II : IndexedMacros) {
   if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
-if (auto ID = getSymbolID(*II, MI, PP->getSourceManager()))
+if (auto ID = getSymbolID(II->getName(), MI, PP->getSourceManager()))
   if (MI->isUsedForHeaderGuard())
 Symbols.erase(*ID);
 }
 // Now increment refcounts.
 for (const IdentifierInfo *II : ReferencedMacros) {
   if (const auto *MI = PP->getMacroDefinition(II).getMacroInfo())
-if (auto ID = 

[PATCH] D69813: [analyzer] CERTStrChecker: Model gets()

2019-11-11 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 228675.
Charusso added a comment.

- The packaging have not been addressed yet.
- Inject the "zombie" size expression to the new function call (`fgets`) if 
none of the size expression's regions have been modified.

The idea is that: When we set up a variable `size = 13;` it modifies the 
region, but the size expression is not stored yet, so we do not invalidate 
anything. We store the `malloc(size + 1)`'s `size`, after that the 
dead-symbol-purging kick in and it either invalidate the region or makes it 
keep alive.

- If the region of `size` is alive after the purge point we cannot inject the 
"zombie" `size + 1` as an expression, we need to obtain its concrete value: 
`14`. (When the redefinition happen I wanted to create a `NoteTag`, but I have 
not seen a simple way to do so.)

- If the region of `size` has been purged out, it is safe to copy-and-paste the 
"zombie" `size + 1` as an expression.


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

https://reviews.llvm.org/D69813

Files:
  clang/include/clang/Lex/Preprocessor.h
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/include/clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicSizeInfo.h
  clang/lib/StaticAnalyzer/Checkers/AllocationState.h
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/cert/StrChecker.cpp
  clang/lib/StaticAnalyzer/Core/CommonBugCategories.cpp
  clang/lib/StaticAnalyzer/Core/DynamicSize.cpp
  clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer.cpp
  clang/test/Analysis/Inputs/system-header-simulator.h
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/cert/str31-alloc.cpp
  clang/test/Analysis/cert/str31-notes.cpp
  clang/test/Analysis/cert/str31-safe.cpp
  clang/test/Analysis/cert/str31-unsafe.cpp

Index: clang/test/Analysis/cert/str31-unsafe.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/str31-unsafe.cpp
@@ -0,0 +1,34 @@
+// RUN: %check_analyzer_fixit %s %t \
+// RUN:  -analyzer-checker=core,unix,security.cert.Str \
+// RUN:  -analyzer-config security.cert.Str:WantToUseSafeFunctions=true \
+// RUN:  -I %S
+
+// See the examples on the page of STR31:
+// https://wiki.sei.cmu.edu/confluence/display/c/STR31-C.+Guarantee+that+storage+for+strings+has+sufficient+space+for+character+data+and+the+null+terminator
+
+#include "../Inputs/system-header-simulator.h"
+
+// The following is not defined therefore the safe functions are unavailable.
+// #define __STDC_LIB_EXT1__ 1
+#define __STDC_WANT_LIB_EXT1__ 1
+
+namespace test_gets_bad {
+#define BUFFER_SIZE 1024
+
+void func(void) {
+  char buf[BUFFER_SIZE];
+  if (gets(buf)) {}
+  // expected-warning@-1 {{'gets' could write outside of 'buf'}}
+  // CHECK-FIXES: if (fgets(buf, sizeof(buf), stdin)) {}
+}
+} // namespace test_gets_bad
+
+namespace test_gets_good {
+enum { BUFFERSIZE = 32 };
+
+void func(void) {
+  char buff[BUFFERSIZE];
+
+  if (fgets(buff, sizeof(buff), stdin)) {}
+}
+} // namespace test_gets_good
Index: clang/test/Analysis/cert/str31-safe.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/str31-safe.cpp
@@ -0,0 +1,33 @@
+// RUN: %check_analyzer_fixit %s %t \
+// RUN:  -analyzer-checker=core,unix,security.cert.Str \
+// RUN:  -analyzer-config security.cert.Str:WantToUseSafeFunctions=true \
+// RUN:  -I %S
+
+// See the examples on the page of STR31:
+// https://wiki.sei.cmu.edu/confluence/display/c/STR31-C.+Guarantee+that+storage+for+strings+has+sufficient+space+for+character+data+and+the+null+terminator
+
+#include "../Inputs/system-header-simulator.h"
+
+#define __STDC_LIB_EXT1__ 1
+#define __STDC_WANT_LIB_EXT1__ 1
+
+namespace test_gets_bad {
+#define BUFFER_SIZE 1024
+
+void func(void) {
+  char buf[BUFFER_SIZE];
+  if (gets(buf)) {}
+  // expected-warning@-1 {{'gets' could write outside of 'buf'}}
+  // CHECK-FIXES: if (gets_s(buf, sizeof(buf))) {}
+}
+} // namespace test_gets_bad
+
+namespace test_gets_good {
+enum { BUFFERSIZE = 32 };
+
+void func(void) {
+  char buff[BUFFERSIZE];
+
+  if (gets_s(buff, sizeof(buff))) {}
+}
+} // namespace test_gets_good
Index: clang/test/Analysis/cert/str31-notes.cpp
===
--- /dev/null
+++ clang/test/Analysis/cert/str31-notes.cpp
@@ -0,0 +1,48 @@
+// RUN: %check_analyzer_fixit %s %t \
+// RUN:  -analyzer-checker=core,unix,security.cert.Str \
+// RUN:  -analyzer-config security.cert.Str:WantToUseSafeFunctions=true \
+// RUN:  -analyzer-output=text -I %S
+
+// See the examples on the page of STR31:
+// https://wiki.sei.cmu.edu/confluence/display/c/STR31-C.+Guarantee+that+storage+for+strings+has+sufficient+space+for+character+data+a

[PATCH] D69764: [clang-format] Add Left/Right Const (East/West , Before/After) fixer capability

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

(Sorry for arriving at this late)

At a strategic level, I have some concerns here: the fact that clang-format 
generally doesn't touch the token sequence isn't an accident.
e.g. formatting `int x;;` will insert a newline rather than deleting the 
redundant semicolon. Like the one in this patch, that would be a useful 
feature, but it's a path the clang-format authors deliberately decided to close 
off.

The conservative approach means that pseudo-parser gets things wrong, we get 
broken formatting, and ~never broken code.
This means:

- a simpler mental model. People are happier to blindly apply it, not to 
require review of formatting changes, etc
- the ability to require clang-formatting as a pre-commit hook, knowing that at 
worst people will have to badly format their code
- a lesser risk when rolling out new versions of clang-format from (our org 
does this from head weekly)

(There are exceptions, e.g. comment splitting, but they're pretty rare)

@klimek in case he has thoughts.




Comment at: clang/lib/Format/Format.cpp:768
   LLVMStyle.CommentPragmas = "^ IWYU pragma:";
+  LLVMStyle.ConstStyle = FormatStyle::CS_Leave;
   LLVMStyle.CompactNamespaces = false;

MyDeveloperDay wrote:
> lebedev.ri wrote:
> > MyDeveloperDay wrote:
> > > lebedev.ri wrote:
> > > > Based on code reviews, this should be `CS_West`.
> > > I would tend to agree for the LLVM project itself, but I really don't 
> > > feel I can change this due to the huge number of projects which have 
> > > BasedOnStyle: LLVM  (not to mention most other style inherit from LLVM 
> > > like Google, Chromium etc...)
> > > 
> > > I think this needs to be an opt-in change in the .clang-format (at least 
> > > for now)
> > There is already a number of stylistic LLVM-specific decisions in LLVM style
> > * 80-col wrap
> > * pointer alignment to the right
> > * spaces instead of tabs
> > * ???
> > I think it first and foremost is an LLVM style, and i don't
> > really recall any guarantees that it must not/will not change.
> Again I do agree, but I think those rules were established before 
> clang-format really gained such popular usage, those coming to clang-format 
> changed those probably straight away if they didn't agree with their 
> established their style.
> 
> Changing something under everyone now feels like I'd have a different agenda 
> (for west const to win), and that that is not my goal. I'm simply trying to 
> facilitate compliance.
> 
> I think we can agree the east/west const rebellion is a contentious issue, 
> (as where the previous formatting wars!), my aim here is to help try and 
> remove the discussion from the debate and let people move on! but I think 
> what it doesn't need is someone like clang-format being considered the bad 
> guy by dictating a default style globally.
> 
> I did a quick search on github, the hits to "const int" and "int const" alone 
> are too eye-watering. I really don't want to break the internet with this.
> 
For non-style reasons, I do think this should be CS_Leave in every built-in 
style, so that adjusting const would have to at least be explicitly in 
.clang-format.


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

https://reviews.llvm.org/D69764



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


[PATCH] D69764: [clang-format] Add Left/Right Const (East/West , Before/After) fixer capability

2019-11-11 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D69764#1740582 , @sammccall wrote:

> (Sorry for arriving at this late)
>
> At a strategic level, I have some concerns here: the fact that clang-format 
> generally doesn't touch the token sequence isn't an accident.
>  e.g. formatting `int x;;` will insert a newline rather than deleting the 
> redundant semicolon. Like the one in this patch, that would be a useful 
> feature, but it's a path the clang-format authors deliberately decided to 
> close off.


I would agree that in the beginning that was true, but now with sorting of 
includes/using we are making replacements to move things around, The fact we 
are using the same Replacement ideas that clang-tidy uses for fix-its I feel 
this isn't a huge change of direction.

Since I also added the dry-run approach, I also think we can use this kind of 
approach to validate code for conformance (and not necessarily replace the 
actual code). But at least in the initial tests I've done on relatively large 
codebases this actually works better than I anticipated.

This is a requested feature both in our bug database but also on stack 
overflow, this felt like a natural fit (and an interesting challenge)


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

https://reviews.llvm.org/D69764



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


[PATCH] D69921: [clang-format] refactor the use of the SMDiagnostics in replacement warnings

2019-11-11 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay marked an inline comment as done.
MyDeveloperDay added inline comments.



Comment at: clang/tools/clang-format/ClangFormat.cpp:304
 
-  StringRef Line(StartBuf, (EndBuf - StartBuf) - 1);
+  Mgr.AddNewSourceBuffer(
+  MemoryBuffer::getMemBuffer(StartBuf, AssumedFileName), SMLoc());

Note to self: this can probably go outside the loop.


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

https://reviews.llvm.org/D69921



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


[PATCH] D70008: [clangd] Store xref for Macros in ParsedAST.

2019-11-11 Thread UTKARSH SAXENA via Phabricator via cfe-commits
usaxena95 added inline comments.



Comment at: clang-tools-extra/clangd/XRefs.cpp:898
+  // Handle macros.
+  if (auto Macro = locateMacroAt(Loc, AST.getPreprocessor())) {
+if (auto MacroSID = getSymbolID(Macro->Name, Macro->Info, SM)) {

hokein wrote:
> this is not completed, it only shows the macro refs in main file, we still 
> need to query the index to get the rest (but our index doesn't collect macro 
> at the moment). I'd prefer not doing this in this patch until our index is 
> ready.
> 
> For testing, I think we can create a new test file for 
> `CollectMainFileMacros`.
Yup. This patch is just for the main file. The index and the lookup will be 
modified in the next patch. Wanted to keep this small.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70008



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


[PATCH] D70008: [clangd] Store xref for Macros in ParsedAST.

2019-11-11 Thread UTKARSH SAXENA via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 228679.
usaxena95 marked an inline comment as done.
usaxena95 added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70008

Files:
  clang-tools-extra/clangd/CollectMacros.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2050,6 +2050,23 @@
 } // namespace ns
 int main() { [[^ns]]::Foo foo; }
   )cpp",
+
+  R"cpp(// Macros
+#define [[FOO]](x,y) (x + y)
+// FIXME: No references for nested macros.
+#define BAR(x,y,z) (FOO(x, y) * FOO(y, z))
+int main() {
+  int x = [[FOO]](1, 2);
+  int y = [[FOO]]([[FO^O]](x, 1), [[FOO]](1, 1));
+  int z = BAR(1, 2, 3);
+}
+#define FOO(x) (x + 1)
+  )cpp",
+
+  R"cpp(// Macros: Cursor on definition.
+#define [[F^OO]](x,y) (x + y)
+int main() { int x = [[FOO]](1, 2); }
+  )cpp",
   };
   for (const char *Test : Tests) {
 Annotations T(Test);
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -21,6 +21,7 @@
 #include "index/Merge.h"
 #include "index/Relation.h"
 #include "index/SymbolCollector.h"
+#include "index/SymbolID.h"
 #include "index/SymbolLocation.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
@@ -47,6 +48,7 @@
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 
 namespace clang {
 namespace clangd {
@@ -891,7 +893,20 @@
   }
   auto Loc = SM.getMacroArgExpandedLocation(
   getBeginningOfIdentifier(Pos, SM, AST.getASTContext().getLangOpts()));
-  // TODO: should we handle macros, too?
+
+  // Handle macros.
+  if (auto Macro = locateMacroAt(Loc, AST.getPreprocessor())) {
+if (auto MacroSID = getSymbolID(Macro->Name, Macro->Info, SM)) {
+  const auto &IDToRefs = AST.getMacros().MacroRefs;
+  auto Refs = IDToRefs.find(*MacroSID);
+  if (Refs != IDToRefs.end())
+Results.insert(Results.end(), Refs->second.begin(), Refs->second.end());
+}
+if (Results.size() > Limit)
+  Results.resize(Limit);
+return Results;
+  }
+
   // We also show references to the targets of using-decls, so we include
   // DeclRelation::Underlying.
   DeclRelationSet Relations = DeclRelation::TemplatePattern |
@@ -911,8 +926,7 @@
  MainFileRefs.end());
   for (const auto &Ref : MainFileRefs) {
 if (auto Range =
-getTokenRange(AST.getASTContext().getSourceManager(),
-  AST.getASTContext().getLangOpts(), Ref.Loc)) {
+getTokenRange(SM, AST.getASTContext().getLangOpts(), Ref.Loc)) {
   Location Result;
   Result.range = *Range;
   Result.uri = URIForFile::canonicalize(*MainFilePath, *MainFilePath);
Index: clang-tools-extra/clangd/CollectMacros.h
===
--- clang-tools-extra/clangd/CollectMacros.h
+++ clang-tools-extra/clangd/CollectMacros.h
@@ -9,10 +9,13 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_COLLECTEDMACROS_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_COLLECTEDMACROS_H
 
+#include "AST.h"
 #include "Protocol.h"
 #include "SourceCode.h"
+#include "index/SymbolID.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Lex/PPCallbacks.h"
+#include "llvm/ADT/DenseMap.h"
 #include 
 
 namespace clang {
@@ -23,6 +26,7 @@
   // Instead of storing SourceLocation, we have to store the token range because
   // SourceManager from preamble is not available when we build the AST.
   std::vector Ranges;
+  llvm::DenseMap> MacroRefs;
 };
 
 /// Collects macro references (e.g. definitions, expansions) in the main file.
@@ -39,6 +43,12 @@
   void FileChanged(SourceLocation Loc, FileChangeReason,
SrcMgr::CharacteristicKind, FileID) override {
 InMainFile = isInsideMainFile(Loc, SM);
+if (InMainFile) {
+  auto MainFilePath =
+  getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM);
+  if (MainFilePath)
+MainFileURI = URIForFile::canonicalize(*MainFilePath, *MainFilePath);
+}
   }
 
   void MacroDefined(const Token &MacroName, const MacroDirective *MD) override {
@@ -82,9 +92,17 @@
 if (auto Range = getTokenRange(SM, LangOpts, Loc)) {
   Out.Names.insert(MacroNameTok.getIdentifierInfo()->getName());
   Out.Ranges.push_back(*Range);
+  if (auto SID = getSymbolID(MacroNameTok.getIdentifierInfo()->getName(),
+ MI, SM)) {
+Location Loc;
+

[PATCH] D69764: [clang-format] Add Left/Right Const (East/West , Before/After) fixer capability

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

In D69764#1740594 , @MyDeveloperDay 
wrote:

> In D69764#1740582 , @sammccall wrote:
>
> > (Sorry for arriving at this late)
> >
> > At a strategic level, I have some concerns here: the fact that clang-format 
> > generally doesn't touch the token sequence isn't an accident.
> >  e.g. formatting `int x;;` will insert a newline rather than deleting the 
> > redundant semicolon. Like the one in this patch, that would be a useful 
> > feature, but it's a path the clang-format authors deliberately decided to 
> > close off.
>
>
> I would agree that in the beginning that was true, but now with sorting of 
> includes/using we are making replacements to move things around,


Yes. Making include-sorting a style option (and then turning that option on for 
google style) has been controversial and in hindsight a mistake IMO. I believe 
making it (only) a command-line flag is an option we should consider now (and 
should have considered then).

There are important differences here: include insertion (and I think using too) 
is less likely to hit pseudoparser problems, but more likely that bad fixes 
change program behavior.

> The fact we are using the same Replacement ideas that clang-tidy uses for 
> fix-its I feel this isn't a huge change of direction.

clang-tidy and clang-format are very different tools with very different 
philosophies. clang-tidy is fairly successful and widely used, but clang-format 
much more so.


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

https://reviews.llvm.org/D69764



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


[PATCH] D70008: [clangd] Store xref for Macros in ParsedAST.

2019-11-11 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

Build result: pass - 59967 tests passed, 0 failed and 763 were skipped.
Log files: console-log.txt 
,
 CMakeCache.txt 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70008



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


[PATCH] D70078: [clangd] fixes semantic highlighting test

2019-11-11 Thread liu hui via Phabricator via cfe-commits
lh123 created this revision.
lh123 added reviewers: ilya-biryukov, hokein, sammccall.
lh123 added a project: clang-tools-extra.
Herald added subscribers: cfe-commits, usaxena95, kadircet, arphaman, jkorous, 
MaskRay.
Herald added a project: clang.

fixes https://github.com/clangd/clangd/issues/176


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70078

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

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -84,19 +84,24 @@
   return scopeRanges;
 };
 
+const fileUri1 = vscode.Uri.parse('file:///file1');
+const fileUri2 = vscode.Uri.parse('file:///file2');
+const fileUri1Str = fileUri1.toString();
+const fileUri2Str = fileUri2.toString();
+
 class MockHighlighter extends semanticHighlighting.Highlighter {
   applicationUriHistory: string[] = [];
   // Override to make the highlighting calls accessible to the test. Also
   // makes the test not depend on visible text editors.
-  applyHighlights(fileUri: string) {
-this.applicationUriHistory.push(fileUri);
+  applyHighlights(fileUri: vscode.Uri) {
+this.applicationUriHistory.push(fileUri.toString());
   }
   // Override to make it accessible from the test.
-  getDecorationRanges(fileUri: string) {
+  getDecorationRanges(fileUri: vscode.Uri) {
 return super.getDecorationRanges(fileUri);
   }
   // Override to make tests not depend on visible text editors.
-  getVisibleTextEditorUris() { return [ 'file1', 'file2' ]; }
+  getVisibleTextEditorUris() { return [ fileUri1, fileUri2 ]; }
 }
 const highlighter = new MockHighlighter(scopeTable);
 const tm = new semanticHighlighting.ThemeRuleMatcher([
@@ -104,11 +109,11 @@
   {scope : 'entity.type', foreground : '2'},
 ]);
 // Recolorizes when initialized.
-highlighter.highlight('file1', []);
-assert.deepEqual(highlighter.applicationUriHistory, [ 'file1' ]);
+highlighter.highlight(fileUri1, []);
+assert.deepEqual(highlighter.applicationUriHistory, [ fileUri1Str ]);
 highlighter.initialize(tm);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2' ]);
+ [ fileUri1Str, fileUri1Str, fileUri2Str ]);
 // Groups decorations into the scopes used.
 let highlightingsInLine: semanticHighlighting.SemanticHighlightingLine[] = [
   {
@@ -128,10 +133,10 @@
   },
 ];
 
-highlighter.highlight('file1', highlightingsInLine);
+highlighter.highlight(fileUri1, highlightingsInLine);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2', 'file1' ]);
-assert.deepEqual(highlighter.getDecorationRanges('file1'),
+ [ fileUri1Str, fileUri1Str, fileUri2Str, fileUri1Str ]);
+assert.deepEqual(highlighter.getDecorationRanges(fileUri1),
  createHighlightingScopeRanges(highlightingsInLine));
 // Keeps state separate between files.
 const highlightingsInLine1:
@@ -141,26 +146,29 @@
 {character : 2, length : 1, scopeIndex : 0},
   ]
 };
-highlighter.highlight('file2', [ highlightingsInLine1 ]);
-assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2', 'file1', 'file2' ]);
-assert.deepEqual(highlighter.getDecorationRanges('file2'),
+highlighter.highlight(fileUri2, [ highlightingsInLine1 ]);
+assert.deepEqual(
+highlighter.applicationUriHistory,
+[ fileUri1Str, fileUri1Str, fileUri2Str, fileUri1Str, fileUri2Str ]);
+assert.deepEqual(highlighter.getDecorationRanges(fileUri2),
  createHighlightingScopeRanges([ highlightingsInLine1 ]));
 // Does full colorizations.
-highlighter.highlight('file1', [ highlightingsInLine1 ]);
-assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2', 'file1', 'file2', 'file1' ]);
+highlighter.highlight(fileUri1, [ highlightingsInLine1 ]);
+assert.deepEqual(highlighter.applicationUriHistory, [
+  fileUri1Str, fileUri1Str, fileUri2Str, fileUri1Str, fileUri2Str,
+  fileUri1Str
+]);
 // After the incremental update to line 1, the old highlightings at line 1
 // will no longer exist in the array.
 assert.deepEqual(
-highlighter.getDecorationRanges('file1'),
+highlighter.getDecorationRanges(fileUri1),
 createHighlightingScopeRanges(
 [ highlightingsInLine1, ...highlightingsInLine.slice(1) ]

[PATCH] D69996: [clangd] Fixes colon escaping on Windows

2019-11-11 Thread liu hui via Phabricator via cfe-commits
lh123 added a comment.

In D69996#1740412 , @hokein wrote:

> I believe this patch fixes the issue,  but we need to update the file 
> `test/semantic-highlighting.test.ts`), the test "Colorizer groups decorations 
> correctly" is diverged from the actual code, although it is still passed 
> (both `string` and `vscode.Uri` have the `toString` method unfortunately).
>
> @lh123  do you mind doing that?


Sorry, I forgot to update the test case, I have submitted a new patch. D70078 



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

https://reviews.llvm.org/D69996



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


[PATCH] D69785: [OpenMP] Introduce the OpenMP-IR-Builder

2019-11-11 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: llvm/include/llvm/IR/OpenMPKinds.def:186
+///{
+
+#ifndef OMP_IDENT_FLAG

jdoerfert wrote:
> Meinersbur wrote:
> > jdoerfert wrote:
> > > JonChesterfield wrote:
> > > > Sharing constants between the compiler and the runtime is an 
> > > > interesting subproblem. I think the cleanest solution is the one used 
> > > > by libc, where the compiler generates header files containing the 
> > > > constants which the runtime library includes.
> > > I'd prefer not to tackle this right now but get this done first and 
> > > revisit the issue later. OK?
> > I don't think this is a good solution. It means that libomp cannot built 
> > built anymore without also building clang. Moreover, the values cannot be 
> > changed anyway since it would break the ABI.
> > 
> > I'd go the other route: The libomp defines what it's ABI is, the compiler 
> > generates code for it. 
> This patch doesn't change what we do, just where. The numbers are hard coded 
> in clang now. Let's start a discussion on the list and if we come up with a 
> different scheme we do it after this landed.
Revisit later sounds good.

@Meinersbur Do you know of an example of a non-llvm compiler using this libomp?

The usual order is build a compiler, then use it to build the runtime 
libraries, then the whole package can build other stuff. Provided the compiler 
doesn't need any of the runtime libraries (compiler-rt, maths libraries, libomp 
etc) itself the system bootstraps cleanly. Especially important when cross 
compiling and I suspect the gpu targets in openmp have similarly strict 
requirements on the first compiler.

Closely related to that, I tend to assume that the runtime libraries can be 
rewritten to best serve their only client - the associated compiler - so if 
libomp is used by out of tree compilers I'd like to know who we are at risk of 
breaking.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69785



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


[PATCH] D70078: [clangd] fixes semantic highlighting test

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

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70078



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


[PATCH] D69952: [OPENMP50]Generalize handling of context matching/scoring.

2019-11-11 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev updated this revision to Diff 228690.
ABataev added a comment.

Address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69952

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/OpenMPKinds.def
  clang/include/clang/Basic/OpenMPKinds.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -388,22 +388,36 @@
   if (Expr *E = Attr.getVariantFuncRef())
 VariantFuncRef = Subst(E);
 
-  ExprResult Score;
-  if (Expr *E = Attr.getScore())
-Score = Subst(E);
-
   // Check function/variant ref.
   Optional> DeclVarData =
   S.checkOpenMPDeclareVariantFunction(
   S.ConvertDeclToDeclGroup(New), VariantFuncRef.get(), Attr.getRange());
   if (!DeclVarData)
 return;
-  // Instantiate the attribute.
-  Sema::OpenMPDeclareVariantCtsSelectorData Data(
-  Attr.getCtxSelectorSet(), Attr.getCtxSelector(),
-  llvm::makeMutableArrayRef(Attr.implVendors_begin(),
-Attr.implVendors_size()),
-  Score);
+  SmallVector Data;
+  for (unsigned I = 0, E = Attr.scores_size(); I < E; ++I) {
+ExprResult Score;
+if (Expr *E = *std::next(Attr.scores_begin(), I))
+  Score = Subst(E);
+// Instantiate the attribute.
+auto CtxSet = static_cast(
+*std::next(Attr.ctxSelectorSets_begin(), I));
+auto Ctx = static_cast(
+*std::next(Attr.ctxSelectors_begin(), I));
+switch (CtxSet) {
+case OMP_CTX_SET_implementation:
+  switch (Ctx) {
+  case OMP_CTX_vendor:
+Data.emplace_back(CtxSet, Ctx, Score, Attr.implVendors());
+break;
+  case OMP_CTX_unknown:
+llvm_unreachable("Unexpected context selector kind.");
+  }
+  break;
+case OMP_CTX_SET_unknown:
+  llvm_unreachable("Unexpected context selector set kind.");
+}
+  }
   S.ActOnOpenMPDeclareVariantDirective(DeclVarData.getValue().first,
DeclVarData.getValue().second,
Attr.getRange(), Data);
Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -5192,28 +5192,59 @@
 
 void Sema::ActOnOpenMPDeclareVariantDirective(
 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
-const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
-  if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
-  Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
+ArrayRef Data) {
+  if (Data.empty())
 return;
-  Expr *Score = nullptr;
-  if (Data.CtxScore.isUsable()) {
-Score = Data.CtxScore.get();
-if (!Score->isTypeDependent() && !Score->isValueDependent() &&
-!Score->isInstantiationDependent() &&
-!Score->containsUnexpandedParameterPack()) {
-  llvm::APSInt Result;
-  ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
-  if (ICE.isInvalid())
-return;
+  SmallVector CtxScores;
+  SmallVector CtxSets;
+  SmallVector Ctxs;
+  SmallVector ImplVendors;
+  bool IsError = false;
+  for (const OMPCtxSelectorData &D : Data) {
+OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
+OpenMPContextSelectorKind Ctx = D.Ctx;
+if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
+  return;
+Expr *Score = nullptr;
+if (D.Score.isUsable()) {
+  Score = D.Score.get();
+  if (!Score->isTypeDependent() && !Score->isValueDependent() &&
+  !Score->isInstantiationDependent() &&
+  !Score->containsUnexpandedParameterPack()) {
+Score =
+PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
+.get();
+if (Score)
+  Score = VerifyIntegerConstantExpression(Score).get();
+  }
+} else {
+  Score = ActOnIntegerConstant(SourceLocation(), 0).get();
 }
-  } else {
-Score = ActOnIntegerConstant(SourceLocation(), 0).get();
+switch (CtxSet) {
+case OMP_CTX_SET_implementation:
+  switch (Ctx) {
+  case OMP_CTX_vendor:
+ImplVendors.append(D.Names.begin(), D.Names.end());
+break;
+  case OMP_CTX_unknown:
+llvm_unreachable("Unexpected context selector kind.");
+  }
+  break;
+case OMP_CTX_SET_unknown:
+  llvm_unreachable("Unexpected context selector set kind.");
+}
+IsError = IsError || !Score;
+CtxSets.push_back(CtxSet);
+Ctxs.push_back(Ctx);
+CtxScores.push_back(Score);
+

[PATCH] D70046: [OpenMP] Use an explicit copy in a range-based for

2019-11-11 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70046



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


[clang] a7638d3 - clang-format: [JS] support null operators.

2019-11-11 Thread Martin Probst via cfe-commits

Author: Martin Probst
Date: 2019-11-11T16:35:35+01:00
New Revision: a7638d384983e8e3eb44a2d8c757238efc7096dc

URL: 
https://github.com/llvm/llvm-project/commit/a7638d384983e8e3eb44a2d8c757238efc7096dc
DIFF: 
https://github.com/llvm/llvm-project/commit/a7638d384983e8e3eb44a2d8c757238efc7096dc.diff

LOG: clang-format: [JS] support null operators.

Summary:
JavaScript / TypeScript is adding two new operators: the null
propagating operator `?.` and the nullish coalescing operator `??`.

const x = foo ?? 'default';
const z = foo?.bar?.baz;

This change adds support to lex and format both.

Reviewers: krasimir

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index b11f36559a8b..39498280fb6d 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -60,6 +60,8 @@ namespace format {
   TYPE(JsExponentiationEqual)  
\
   TYPE(JsFatArrow) 
\
   TYPE(JsNonNullAssertion) 
\
+  TYPE(JsNullishCoalescingOperator)
\
+  TYPE(JsNullPropagatingOperator)  
\
   TYPE(JsPrivateIdentifier)
\
   TYPE(JsTypeColon)
\
   TYPE(JsTypeOperator) 
\

diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 5d8a77577c0b..ef20ba884fb3 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -100,6 +100,10 @@ void FormatTokenLexer::tryMergePreviousTokens() {
 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
 static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
tok::starequal};
+static const tok::TokenKind JSNullPropagatingOperator[] = {tok::question,
+   tok::period};
+static const tok::TokenKind JSNullishOperator[] = {tok::question,
+   tok::question};
 
 // FIXME: Investigate what token type gives the correct operator priority.
 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
@@ -116,6 +120,14 @@ void FormatTokenLexer::tryMergePreviousTokens() {
   Tokens.back()->Tok.setKind(tok::starequal);
   return;
 }
+if (tryMergeTokens(JSNullishOperator, TT_JsNullishCoalescingOperator))
+  return;
+if (tryMergeTokens(JSNullPropagatingOperator,
+   TT_JsNullPropagatingOperator)) {
+  // Treat like a regular "." access.
+  Tokens.back()->Tok.setKind(tok::period);
+  return;
+}
 if (tryMergeJSPrivateIdentifier())
   return;
   }

diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index ca2093a05cce..30a0b37ef69b 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -,6 +,16 @@ TEST_F(FormatTestJS, NonNullAssertionOperator) {
   verifyFormat("return !!x;\n");
 }
 
+TEST_F(FormatTestJS, NullPropagatingOperator) {
+  verifyFormat("let x = foo?.bar?.baz();\n");
+  verifyFormat("let x = foo?.(foo);\n");
+  verifyFormat("let x = foo?.['arr'];\n");
+}
+
+TEST_F(FormatTestJS, NullishCoalescingOperator) {
+  verifyFormat("const val = something ?? 'some other default';\n");
+}
+
 TEST_F(FormatTestJS, Conditional) {
   verifyFormat("y = x ? 1 : 2;");
   verifyFormat("x ? 1 : 2;");



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


[PATCH] D69764: [clang-format] Add Left/Right Const (East/West , Before/After) fixer capability

2019-11-11 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

I definitely agree with the default being "do nothing", its not just google 
style, nearly everyone is using a style which is derived from one of these base 
styles,  that said turning on a const style by default would IMHO be a mistake, 
the level of churn could be immense.

I do get the concerns over the matching of "lexed" tokens rather than perhaps a 
semantic analysis could lead to false positives, that's harder to tell without 
running this over a larger amount of code and then running the unit tests of 
those projects, I feel the saving grace is the scenarios are limited to where 
the word `const` can appear in the language and so this should allow us to 
limit the possible failure scenarios a little.

I just didn't want to do this in clang-tidy, because I find the whole -fix part 
of clang-tidy unsatisfactory unless i'm dealing with just one checker at a time.


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

https://reviews.llvm.org/D69764



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


[clang] 6bcd8d4 - clang-format: [JS] test declared fields.

2019-11-11 Thread Martin Probst via cfe-commits

Author: Martin Probst
Date: 2019-11-11T16:36:00+01:00
New Revision: 6bcd8d4a18fc0604a2297a626c1fc808cbfb7b9b

URL: 
https://github.com/llvm/llvm-project/commit/6bcd8d4a18fc0604a2297a626c1fc808cbfb7b9b
DIFF: 
https://github.com/llvm/llvm-project/commit/6bcd8d4a18fc0604a2297a626c1fc808cbfb7b9b.diff

LOG: clang-format: [JS] test declared fields.

Summary:
TypeScript now supports declaring fields:

class Foo {
  declare field: string;
}

clang-format happens to already format this fine, so this change just
adds a regression test.

Reviewers: krasimir

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 30a0b37ef69b..619a19f1a22d 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -2369,5 +2369,12 @@ TEST_F(FormatTestJS, SupportPrivateFieldsAndMethods) {
"  static #staticPrivateMethod() {}\n");
 }
 
+TEST_F(FormatTestJS, DeclaredFields) {
+  verifyFormat("class Example {\n"
+   "  declare pub: string;\n"
+   "  declare private priv: string;\n"
+   "}\n");
+}
+
 } // namespace format
 } // end namespace clang



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


[PATCH] D69972: clang-format: [JS] test declared fields.

2019-11-11 Thread Martin Probst via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6bcd8d4a18fc: clang-format: [JS] test declared fields. 
(authored by mprobst).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69972

Files:
  clang/unittests/Format/FormatTestJS.cpp


Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -2369,5 +2369,12 @@
"  static #staticPrivateMethod() {}\n");
 }
 
+TEST_F(FormatTestJS, DeclaredFields) {
+  verifyFormat("class Example {\n"
+   "  declare pub: string;\n"
+   "  declare private priv: string;\n"
+   "}\n");
+}
+
 } // namespace format
 } // end namespace clang


Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -2369,5 +2369,12 @@
"  static #staticPrivateMethod() {}\n");
 }
 
+TEST_F(FormatTestJS, DeclaredFields) {
+  verifyFormat("class Example {\n"
+   "  declare pub: string;\n"
+   "  declare private priv: string;\n"
+   "}\n");
+}
+
 } // namespace format
 } // end namespace clang
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D69971: clang-format: [JS] support null operators.

2019-11-11 Thread Martin Probst via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa7638d384983: clang-format: [JS] support null operators. 
(authored by mprobst).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69971

Files:
  clang/lib/Format/FormatToken.h
  clang/lib/Format/FormatTokenLexer.cpp
  clang/unittests/Format/FormatTestJS.cpp


Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -,6 +,16 @@
   verifyFormat("return !!x;\n");
 }
 
+TEST_F(FormatTestJS, NullPropagatingOperator) {
+  verifyFormat("let x = foo?.bar?.baz();\n");
+  verifyFormat("let x = foo?.(foo);\n");
+  verifyFormat("let x = foo?.['arr'];\n");
+}
+
+TEST_F(FormatTestJS, NullishCoalescingOperator) {
+  verifyFormat("const val = something ?? 'some other default';\n");
+}
+
 TEST_F(FormatTestJS, Conditional) {
   verifyFormat("y = x ? 1 : 2;");
   verifyFormat("x ? 1 : 2;");
Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -100,6 +100,10 @@
 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
 static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
tok::starequal};
+static const tok::TokenKind JSNullPropagatingOperator[] = {tok::question,
+   tok::period};
+static const tok::TokenKind JSNullishOperator[] = {tok::question,
+   tok::question};
 
 // FIXME: Investigate what token type gives the correct operator priority.
 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
@@ -116,6 +120,14 @@
   Tokens.back()->Tok.setKind(tok::starequal);
   return;
 }
+if (tryMergeTokens(JSNullishOperator, TT_JsNullishCoalescingOperator))
+  return;
+if (tryMergeTokens(JSNullPropagatingOperator,
+   TT_JsNullPropagatingOperator)) {
+  // Treat like a regular "." access.
+  Tokens.back()->Tok.setKind(tok::period);
+  return;
+}
 if (tryMergeJSPrivateIdentifier())
   return;
   }
Index: clang/lib/Format/FormatToken.h
===
--- clang/lib/Format/FormatToken.h
+++ clang/lib/Format/FormatToken.h
@@ -60,6 +60,8 @@
   TYPE(JsExponentiationEqual)  
\
   TYPE(JsFatArrow) 
\
   TYPE(JsNonNullAssertion) 
\
+  TYPE(JsNullishCoalescingOperator)
\
+  TYPE(JsNullPropagatingOperator)  
\
   TYPE(JsPrivateIdentifier)
\
   TYPE(JsTypeColon)
\
   TYPE(JsTypeOperator) 
\


Index: clang/unittests/Format/FormatTestJS.cpp
===
--- clang/unittests/Format/FormatTestJS.cpp
+++ clang/unittests/Format/FormatTestJS.cpp
@@ -,6 +,16 @@
   verifyFormat("return !!x;\n");
 }
 
+TEST_F(FormatTestJS, NullPropagatingOperator) {
+  verifyFormat("let x = foo?.bar?.baz();\n");
+  verifyFormat("let x = foo?.(foo);\n");
+  verifyFormat("let x = foo?.['arr'];\n");
+}
+
+TEST_F(FormatTestJS, NullishCoalescingOperator) {
+  verifyFormat("const val = something ?? 'some other default';\n");
+}
+
 TEST_F(FormatTestJS, Conditional) {
   verifyFormat("y = x ? 1 : 2;");
   verifyFormat("x ? 1 : 2;");
Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -100,6 +100,10 @@
 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
 static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
tok::starequal};
+static const tok::TokenKind JSNullPropagatingOperator[] = {tok::question,
+   tok::period};
+static const tok::TokenKind JSNullishOperator[] = {tok::question,
+   tok::question};
 
 // FIXME: Investigate what token type gives the correct operator priority.
 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
@@ -116,6 +120,14 @@
   Tokens.back()->Tok.setKind(tok::starequal);
   return;
 }
+if (tryMergeT

[clang-tools-extra] f8c17fe - [clangd] fixes semantic highlighting test

2019-11-11 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2019-11-11T16:47:44+01:00
New Revision: f8c17fe1112009e793d6f9a261622423c2c62049

URL: 
https://github.com/llvm/llvm-project/commit/f8c17fe1112009e793d6f9a261622423c2c62049
DIFF: 
https://github.com/llvm/llvm-project/commit/f8c17fe1112009e793d6f9a261622423c2c62049.diff

LOG: [clangd] fixes semantic highlighting test

Summary: fixes https://github.com/clangd/clangd/issues/176

Patch by liu hui!

Reviewers: ilya-biryukov, hokein, sammccall

Reviewed By: hokein

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

Tags: #clang-tools-extra, #clang

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

Added: 


Modified: 

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

Removed: 




diff  --git 
a/clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
 
b/clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
index 6bc3c45a8b60..9f3e8bd9371f 100644
--- 
a/clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ 
b/clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -84,19 +84,24 @@ suite('SemanticHighlighting Tests', () => {
   return scopeRanges;
 };
 
+const fileUri1 = vscode.Uri.parse('file:///file1');
+const fileUri2 = vscode.Uri.parse('file:///file2');
+const fileUri1Str = fileUri1.toString();
+const fileUri2Str = fileUri2.toString();
+
 class MockHighlighter extends semanticHighlighting.Highlighter {
   applicationUriHistory: string[] = [];
   // Override to make the highlighting calls accessible to the test. Also
   // makes the test not depend on visible text editors.
-  applyHighlights(fileUri: string) {
-this.applicationUriHistory.push(fileUri);
+  applyHighlights(fileUri: vscode.Uri) {
+this.applicationUriHistory.push(fileUri.toString());
   }
   // Override to make it accessible from the test.
-  getDecorationRanges(fileUri: string) {
+  getDecorationRanges(fileUri: vscode.Uri) {
 return super.getDecorationRanges(fileUri);
   }
   // Override to make tests not depend on visible text editors.
-  getVisibleTextEditorUris() { return [ 'file1', 'file2' ]; }
+  getVisibleTextEditorUris() { return [ fileUri1, fileUri2 ]; }
 }
 const highlighter = new MockHighlighter(scopeTable);
 const tm = new semanticHighlighting.ThemeRuleMatcher([
@@ -104,11 +109,11 @@ suite('SemanticHighlighting Tests', () => {
   {scope : 'entity.type', foreground : '2'},
 ]);
 // Recolorizes when initialized.
-highlighter.highlight('file1', []);
-assert.deepEqual(highlighter.applicationUriHistory, [ 'file1' ]);
+highlighter.highlight(fileUri1, []);
+assert.deepEqual(highlighter.applicationUriHistory, [ fileUri1Str ]);
 highlighter.initialize(tm);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2' ]);
+ [ fileUri1Str, fileUri1Str, fileUri2Str ]);
 // Groups decorations into the scopes used.
 let highlightingsInLine: semanticHighlighting.SemanticHighlightingLine[] = 
[
   {
@@ -128,10 +133,10 @@ suite('SemanticHighlighting Tests', () => {
   },
 ];
 
-highlighter.highlight('file1', highlightingsInLine);
+highlighter.highlight(fileUri1, highlightingsInLine);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2', 'file1' ]);
-assert.deepEqual(highlighter.getDecorationRanges('file1'),
+ [ fileUri1Str, fileUri1Str, fileUri2Str, fileUri1Str ]);
+assert.deepEqual(highlighter.getDecorationRanges(fileUri1),
  createHighlightingScopeRanges(highlightingsInLine));
 // Keeps state separate between files.
 const highlightingsInLine1:
@@ -141,26 +146,29 @@ suite('SemanticHighlighting Tests', () => {
 {character : 2, length : 1, scopeIndex : 0},
   ]
 };
-highlighter.highlight('file2', [ highlightingsInLine1 ]);
-assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2', 'file1', 'file2' ]);
-assert.deepEqual(highlighter.getDecorationRanges('file2'),
+highlighter.highlight(fileUri2, [ highlightingsInLine1 ]);
+assert.deepEqual(
+highlighter.applicationUriHistory,
+[ fileUri1Str, fileUri1Str, fileUri2Str, fileUri1Str, fileUri2Str ]);
+assert.deepEqual(highlighter.getDecorationRanges(fileUri2),
  createHighlightingScopeRanges([ highlightingsInLine1 ]));
 // Does full colorizations.
-highlighter.highlight('file1', [ highlightingsInLine1 ]);
-assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2', 'file1', 'file2', 'file1' ]);

[PATCH] D70078: [clangd] fixes semantic highlighting test

2019-11-11 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf8c17fe11120: [clangd] fixes semantic highlighting test 
(authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D70078?vs=228681&id=228697#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D70078

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

Index: clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
===
--- clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
+++ clang-tools-extra/clangd/clients/clangd-vscode/test/semantic-highlighting.test.ts
@@ -84,19 +84,24 @@
   return scopeRanges;
 };
 
+const fileUri1 = vscode.Uri.parse('file:///file1');
+const fileUri2 = vscode.Uri.parse('file:///file2');
+const fileUri1Str = fileUri1.toString();
+const fileUri2Str = fileUri2.toString();
+
 class MockHighlighter extends semanticHighlighting.Highlighter {
   applicationUriHistory: string[] = [];
   // Override to make the highlighting calls accessible to the test. Also
   // makes the test not depend on visible text editors.
-  applyHighlights(fileUri: string) {
-this.applicationUriHistory.push(fileUri);
+  applyHighlights(fileUri: vscode.Uri) {
+this.applicationUriHistory.push(fileUri.toString());
   }
   // Override to make it accessible from the test.
-  getDecorationRanges(fileUri: string) {
+  getDecorationRanges(fileUri: vscode.Uri) {
 return super.getDecorationRanges(fileUri);
   }
   // Override to make tests not depend on visible text editors.
-  getVisibleTextEditorUris() { return [ 'file1', 'file2' ]; }
+  getVisibleTextEditorUris() { return [ fileUri1, fileUri2 ]; }
 }
 const highlighter = new MockHighlighter(scopeTable);
 const tm = new semanticHighlighting.ThemeRuleMatcher([
@@ -104,11 +109,11 @@
   {scope : 'entity.type', foreground : '2'},
 ]);
 // Recolorizes when initialized.
-highlighter.highlight('file1', []);
-assert.deepEqual(highlighter.applicationUriHistory, [ 'file1' ]);
+highlighter.highlight(fileUri1, []);
+assert.deepEqual(highlighter.applicationUriHistory, [ fileUri1Str ]);
 highlighter.initialize(tm);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2' ]);
+ [ fileUri1Str, fileUri1Str, fileUri2Str ]);
 // Groups decorations into the scopes used.
 let highlightingsInLine: semanticHighlighting.SemanticHighlightingLine[] = [
   {
@@ -128,10 +133,10 @@
   },
 ];
 
-highlighter.highlight('file1', highlightingsInLine);
+highlighter.highlight(fileUri1, highlightingsInLine);
 assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2', 'file1' ]);
-assert.deepEqual(highlighter.getDecorationRanges('file1'),
+ [ fileUri1Str, fileUri1Str, fileUri2Str, fileUri1Str ]);
+assert.deepEqual(highlighter.getDecorationRanges(fileUri1),
  createHighlightingScopeRanges(highlightingsInLine));
 // Keeps state separate between files.
 const highlightingsInLine1:
@@ -141,26 +146,29 @@
 {character : 2, length : 1, scopeIndex : 0},
   ]
 };
-highlighter.highlight('file2', [ highlightingsInLine1 ]);
-assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2', 'file1', 'file2' ]);
-assert.deepEqual(highlighter.getDecorationRanges('file2'),
+highlighter.highlight(fileUri2, [ highlightingsInLine1 ]);
+assert.deepEqual(
+highlighter.applicationUriHistory,
+[ fileUri1Str, fileUri1Str, fileUri2Str, fileUri1Str, fileUri2Str ]);
+assert.deepEqual(highlighter.getDecorationRanges(fileUri2),
  createHighlightingScopeRanges([ highlightingsInLine1 ]));
 // Does full colorizations.
-highlighter.highlight('file1', [ highlightingsInLine1 ]);
-assert.deepEqual(highlighter.applicationUriHistory,
- [ 'file1', 'file1', 'file2', 'file1', 'file2', 'file1' ]);
+highlighter.highlight(fileUri1, [ highlightingsInLine1 ]);
+assert.deepEqual(highlighter.applicationUriHistory, [
+  fileUri1Str, fileUri1Str, fileUri2Str, fileUri1Str, fileUri2Str,
+  fileUri1Str
+]);
 // After the incremental update to line 1, the old highlightings at line 1
 // will no longer exist in the array.
 assert.deepEqual(
-highlighter.getDecorationRanges('file1'),
+highlighter.getDecorationRanges(fileUri1),
 createHighlightingScopeRanges(
 [ highlightingsInLine1, ...highlightingsInLine.slice(1) ]));
 // Closing a text document removes 

[PATCH] D69204: [OpenMP 5.0] - Extend defaultmap

2019-11-11 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/Parse/ParseOpenMP.cpp:2343-2344
+// pointer
+if (Arg.back() < OMPC_DEFAULTMAP_MODIFIER_unknown)
+  Arg.back() = OMPC_DEFAULTMAP_MODIFIER_unknown;
 KLoc.push_back(Tok.getLocation());

cchen wrote:
> ABataev wrote:
> > Is this possible at all? I think it must an assertion rather this kind of 
> > trick.
> This is definitely possible since the `getOpenMPSimpleClauseType` function in 
> OpenMPKinds.cpp, parse defaultmap modifier and defaultmap kind in a same 
> stringswitch statement, so for `defaultmap(scalar`, it will set the 
> defaultmap modifier to be 0, however, the unknown is 3 
> (OMPC_DEFAULTMAP_MODIFIER_unknown == OMPC_DEFAULTMAP_unknown).
Ok, I see. Then store the result in the temp var and change it there rather use 
`Arg.back() = ...`.I still don't like this solution but the redesign is the 
different problem.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:659
+DefaultMapImplicitBehavior DMIB = getDefaultDMIB(DMVC);
+return (DMIB == DMIB_unspecified) || (DMIB == DMIB_firstprivate) ||
+   (DMIB == DMIB_default);

Why `DMIB_firstprivate` is the default behavior? This is true only for scalars 
and pointers. Plus, this function is used in the context that does not match 
its name. Better to rename it to something like `mustBeFirstprivate` or 
something similar.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:663
+  bool
+  isDefaultmapDefaultBehaviorAtLevel(unsigned Level,
+ DefaultMapVariableCategory DMVC) const {

Same here



Comment at: clang/lib/Sema/SemaOpenMP.cpp:2824
 
+static DefaultMapVariableCategory getVariableCategoryFromDecl(ValueDecl *VD) {
+  if (VD->getType().getNonReferenceType()->isAnyPointerType())

`const ValueDecl *`



Comment at: clang/lib/Sema/SemaOpenMP.cpp:2841-2860
+switch (DMIB) {
+case DMIB_alloc:
+  Kind = OMPC_MAP_alloc;
+  break;
+case DMIB_to:
+  Kind = OMPC_MAP_to;
+  break;

Why inner switch for the same variable `DMIB`?



Comment at: clang/lib/Sema/SemaOpenMP.cpp:4451
+SmallVector ImplicitMaps[OMPC_MAP_delete];
+for (unsigned I = 0; I < OMPC_MAP_delete; I++) {
+  ArrayRef ImplicitMap =

Use preincrement instead of postincrement.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:4476
 }
-if (!ImplicitMaps.empty()) {
-  CXXScopeSpec MapperIdScopeSpec;
-  DeclarationNameInfo MapperId;
-  if (OMPClause *Implicit = ActOnOpenMPMapClause(
-  llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
-  OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
-  SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
-ClausesWithImplicit.emplace_back(Implicit);
-ErrorFound |=
-cast(Implicit)->varlist_size() != 
ImplicitMaps.size();
-  } else {
-ErrorFound = true;
+for (unsigned I = 0; I < OMPC_MAP_delete; I++) {
+  if (!ImplicitMaps[I].empty()) {

Use range-based loop here.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:4477
+for (unsigned I = 0; I < OMPC_MAP_delete; I++) {
+  if (!ImplicitMaps[I].empty()) {
+CXXScopeSpec MapperIdScopeSpec;

Simplify inner complexity here by using `continue;` if the condition is true.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:16393-16416
+static DefaultMapImplicitBehavior
+getImplicitBehaviorFromModifier(OpenMPDefaultmapClauseModifier M) {
+  switch (M) {
+  case OMPC_DEFAULTMAP_MODIFIER_alloc:
+return DMIB_alloc;
+  case OMPC_DEFAULTMAP_MODIFIER_to:
+return DMIB_to;

Do we need types `DefaultMapImplicitBehavior` and `DefaultMapVariableCategory` 
if the map 1 to 1 to `OpenMPDefaultmapClauseModifier` and 
`OpenMPDefaultmapClauseKind`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69204



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


[PATCH] D67573: Fix __atomic_is_lock_free's return type.

2019-11-11 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

Ping!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67573



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


[clang-tools-extra] 4edf0cb - [clang-tidy] Add bugprone-bad-signal-to-kill-thread checker and alias cert-pos44-c

2019-11-11 Thread Abel Kocsis via cfe-commits

Author: Abel Kocsis
Date: 2019-11-11T17:26:44+01:00
New Revision: 4edf0cb0e03e31d468979d0d7dec08bd9f4f8204

URL: 
https://github.com/llvm/llvm-project/commit/4edf0cb0e03e31d468979d0d7dec08bd9f4f8204
DIFF: 
https://github.com/llvm/llvm-project/commit/4edf0cb0e03e31d468979d0d7dec08bd9f4f8204.diff

LOG: [clang-tidy] Add bugprone-bad-signal-to-kill-thread checker and alias 
cert-pos44-c

Added: 
bad-signal-to-kill-thread.patch
clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h

clang-tools-extra/docs/clang-tidy/checks/bugprone-bad-signal-to-kill-thread.rst
clang-tools-extra/docs/clang-tidy/checks/cert-pos44-c.rst
clang-tools-extra/test/clang-tidy/bugprone-bad-signal-to-kill-thread.cpp

Modified: 
clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/bad-signal-to-kill-thread.patch b/bad-signal-to-kill-thread.patch
new file mode 100644
index ..39b17574646d
--- /dev/null
+++ b/bad-signal-to-kill-thread.patch
@@ -0,0 +1,1133 @@
+
diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
+new file mode 100644
+index 000..1f3dec497c0
+--- /dev/null
 b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
+@@ -0,0 +1,70 @@
++//===--- BadSignalToKillThreadCheck.cpp - clang-tidy 
-===//
++//
++// 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 "BadSignalToKillThreadCheck.h"
++#include "clang/AST/ASTContext.h"
++#include "clang/ASTMatchers/ASTMatchFinder.h"
++
++using namespace clang::ast_matchers;
++
++namespace clang {
++namespace tidy {
++namespace bugprone {
++
++void BadSignalToKillThreadCheck::registerMatchers(MatchFinder *Finder) {
++  Finder->addMatcher(
++  callExpr(allOf(callee(functionDecl(hasName("::pthread_kill"))),
++ argumentCountIs(2)),
++   hasArgument(1, integerLiteral().bind("integer-literal")))
++  .bind("thread-kill"),
++  this);
++}
++
++static Preprocessor *PP;
++
++void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult 
&Result) {
++  const auto IsSigterm = [](const auto &KeyValue) -> bool {
++return KeyValue.first->getName() == "SIGTERM";
++  };
++  const auto TryExpandAsInteger =
++  [](Preprocessor::macro_iterator It) -> Optional {
++if (It == PP->macro_end())
++  return llvm::None;
++const MacroInfo *MI = PP->getMacroInfo(It->first);
++const Token &T = MI->tokens().back();
++StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
++
++llvm::APInt IntValue;
++constexpr unsigned AutoSenseRadix = 0;
++if (ValueStr.getAsInteger(AutoSenseRadix, IntValue))
++  return llvm::None;
++return IntValue.getZExtValue();
++  };
++
++  const auto SigtermMacro = llvm::find_if(PP->macros(), IsSigterm);
++
++  if (!SigtermValue && !(SigtermValue = TryExpandAsInteger(SigtermMacro)))
++return;
++
++  const auto *MatchedExpr = Result.Nodes.getNodeAs("thread-kill");
++  const auto *MatchedIntLiteral =
++  Result.Nodes.getNodeAs("integer-literal");
++  if (MatchedIntLiteral->getValue() == *SigtermValue) {
++diag(MatchedExpr->getBeginLoc(),
++ "thread should not be terminated by raising the 'SIGTERM' signal");
++  }
++}
++
++void BadSignalToKillThreadCheck::registerPPCallbacks(
++const SourceManager &SM, Preprocessor *pp, Preprocessor 
*ModuleExpanderPP) {
++  PP = pp;
++}
++
++} // namespace bugprone
++} // namespace tidy
++} // namespace clang
+
diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
+new file mode 100644
+index 000..d39fdec2e7d
+--- /dev/null
 b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
+@@ -0,0 +1,37 @@
++//===--- BadSignalToKillThreadCheck.h - clang-tidy --*- C++ 
-*-===//
++//
++// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
++// See https://llvm.org/LICENSE.txt for license information.
++// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
++//
++//===--===//
++
++#ifndef 
LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BADSIGNALTOKILLTHREADCHECK_H
++#define 
LL

[PATCH] D70086: [ConstExprPreter] Implemented control flow statements

2019-11-11 Thread Nandor Licker via Phabricator via cfe-commits
nand created this revision.
nand added reviewers: Bigcheese, jfb, rsmith, dexonsmith.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Added support for:

- for
- switch
- do-while
- while

Also implemented assignment to enable useful tests.

The patch also includes range-based for loops which are
not yet tested, but having them in ByteCodeStmtGen should
simplify the process of slicing off further patches.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70086

Files:
  clang/lib/AST/Interp/ByteCodeEmitter.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/lib/AST/Interp/ByteCodeStmtGen.h
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Context.h
  clang/lib/AST/Interp/EvalEmitter.cpp
  clang/lib/AST/Interp/InterpLoop.cpp
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/Opcodes/Comparison.h
  clang/test/AST/Interp/flow.cpp

Index: clang/test/AST/Interp/flow.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/flow.cpp
@@ -0,0 +1,116 @@
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -fexperimental-new-constant-interpreter %s -verify
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only %s -verify
+// expected-no-diagnostics
+
+constexpr int fn_for_break(int n) {
+  int x = 0;
+  for (int i = 0; i < 20; i = i + 1) {
+if (i == n)
+  break;
+x = x + 1;
+  }
+  return x;
+}
+using A = int[5];
+using A = int[fn_for_break(5)];
+
+constexpr int fn_for_cont(int n) {
+  int x = 0;
+  for (int i = 0; i < 20; i = i + 1) {
+if (i < n)
+  continue;
+x = x + 1;
+  }
+  return x;
+}
+using B = int[15];
+using B = int[fn_for_cont(5)];
+
+constexpr int fn_while_break(unsigned n) {
+  int x = 0;
+  int i = 0;
+  while (int next = i = i + 1) {
+if (next == n) {
+  break;
+}
+x = x + 1;
+  }
+  return x;
+}
+using C = int[4];
+using C = int[fn_while_break(5)];
+
+constexpr int fn_while_cont(unsigned n) {
+  int x = 0;
+  int i = 0;
+  while (i < 10) {
+i = i + 1;
+if (i < n) {
+  continue;
+}
+x = x + 1;
+  }
+  return x;
+}
+using D = int[6];
+using D = int[fn_while_cont(5)];
+
+constexpr int fn_do_break(unsigned n) {
+  int x = 0;
+  int i = 0;
+  do {
+if (i == n) {
+  break;
+}
+x = x + 1;
+i = i + 1;
+  } while (i < 20);
+  return x;
+}
+using E = int[5];
+using E = int[fn_do_break(5)];
+
+constexpr int fn_do_continue(unsigned n) {
+  int x = 0;
+  int i = 0;
+  do {
+i = i + 1;
+if (i < n) {
+  continue;
+}
+x = x + 1;
+  } while (i < 20);
+  return x;
+}
+using F = int[16];
+using F = int[fn_do_continue(5)];
+
+constexpr int fn_for_cond_var(int n) {
+  int a = 0;
+  for (int i = n; int b = a + 1; i = i + 1) {
+if (i == 50) {
+  a = 0 - b;
+}
+  }
+  return a - 1;
+}
+
+using G = int[-fn_for_cond_var(10)];
+using G = int[2];
+
+constexpr int fn_switch(int a) {
+  switch (a) {
+case 0: return 2;
+case 1: return 5;
+default: return 6;
+  }
+}
+
+using H0 = int[2];
+using H0 = int[fn_switch(0)];
+
+using H1 = int[5];
+using H1 = int[fn_switch(1)];
+
+using H2 = int[6];
+using H2 = int[fn_switch(2)];
Index: clang/lib/AST/Interp/Opcodes/Comparison.h
===
--- clang/lib/AST/Interp/Opcodes/Comparison.h
+++ clang/lib/AST/Interp/Opcodes/Comparison.h
@@ -118,4 +118,15 @@
   return false;
 }
 
+template 
+bool InRange(InterpState &S, CodePtr OpPC) {
+  using T = typename PrimConv::T;
+  const T &RHS = S.Stk.pop();
+  const T &LHS = S.Stk.pop();
+  const T &Value = S.Stk.pop();
+
+  S.Stk.push(LHS <= Value && Value <= RHS);
+  return true;
+}
+
 #endif
Index: clang/lib/AST/Interp/Opcodes.td
===
--- clang/lib/AST/Interp/Opcodes.td
+++ clang/lib/AST/Interp/Opcodes.td
@@ -339,6 +339,16 @@
 def GT : ComparisonOpcode;
 def GE : ComparisonOpcode;
 
+//===--===//
+// Range test.
+//===--===//
+
+// [Real, Real, Real] -> [Bool]
+def InRange : Opcode {
+  let Types = [AluFPTypeClass];
+  let HasGroup = 1;
+}
+
 //===--===//
 // Stack management.
 //===--===//
Index: clang/lib/AST/Interp/InterpLoop.cpp
===
--- clang/lib/AST/Interp/InterpLoop.cpp
+++ clang/lib/AST/Interp/InterpLoop.cpp
@@ -108,6 +108,8 @@
 return false;
   if (S.checkingPotentialConstantExpression())
 return false;
+  if (!F->isConstexpr())
+return false;
 
   // Adjust the state.
   S.CallStackDepth++;
Index: clang/lib/AST/Interp/EvalEmitter.cpp
==

[PATCH] D64305: [clangd] Add path mappings functionality

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

(also welcome back and thanks for picking this up!)


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

https://reviews.llvm.org/D64305



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


[PATCH] D64305: [clangd] Add path mappings functionality

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

Thanks, this looks a lot better.
Main thing that was unclear to me is the fact that the paths in the mappings 
are now URI-paths, so "/C:/foo" on windows.

This looks like the right idea as it ensures much of the path-mapping code gets 
to ignore slashes and such.
Docs/naming could reflect it a bit better.




Comment at: clang-tools-extra/clangd/PathMapping.cpp:30
+  const auto &K = V.kind();
+  if (K == Kind::Object) {
+for (auto &KV : *V.getAsObject()) {

wwagner19 wrote:
> sammccall wrote:
> > object keys may be file uris too. (see `WorkspaceEdit.changes`)
> > 
> > This case is going to be a bit annoying to handle, I think :-(
> Indeed, it seems so. It doesn't look like `json::Object` has any key removal 
> functionality (although I could very well be reading this wrong). If so, then 
> I guess I can just create a new `json::Object`, moving over the old values, 
> and replacing the keys if necessary. 
Sorry, you're right - I'll fix `json::Object`.
Nevertheless I think the copy-into-new-object approach is the clearest way to 
deal with renames of keys that may otherwise collide in the intermediate state.



Comment at: clang-tools-extra/clangd/PathMapping.cpp:36
   using Kind = llvm::json::Value::Kind;
-  const auto &K = V.kind();
+  const Kind &K = V.kind();
   if (K == Kind::Object) {

by value, not by ref



Comment at: clang-tools-extra/clangd/PathMapping.cpp:137
 
+// Returns whether a path mapping should take place for \pOrigPath
+// i.e. \pMappingPath is a proper sub-path of \p OrigPath

this isn't a doxygen comment, please omit \p



Comment at: clang-tools-extra/clangd/PathMapping.cpp:153
+// Converts \pPath to a posix-style absolute, i.e. if it's a windows path
+// then the backward-slash notation will be converted to forward slash
+llvm::Expected parsePath(llvm::StringRef Path) {

"posix-style" doesn't really describe representing `c:\foo` as `/c:/foo`. 
That's really *just* a URI thing AFAIK.

Something like "Converts a unix/windows path to the path part of a file URI".
But in that case, I think the implementation is just 
`URI::createFile(Path).body()`. Does that pass tests?



Comment at: clang-tools-extra/clangd/PathMapping.cpp:201
+  const PathMappings &Mappings) {
+  if (!S.startswith("file://"))
+return llvm::None;

nit: add a comment like "bail out quickly in the common case"? to make it clear 
this is (only) a performance optimization



Comment at: clang-tools-extra/clangd/PathMapping.cpp:205
+  if (!Uri) {
+return llvm::None;
+  }

you need to consume the error, or it'll assert

consumeError(Uri.takeError());



Comment at: clang-tools-extra/clangd/PathMapping.cpp:214
+  llvm::SmallString<256> MappedPath(Uri->body());
+  llvm::sys::path::replace_path_prefix(MappedPath, From, To);
+  auto MappedUri = URI(Uri->scheme(), Uri->authority(), 
MappedPath.c_str());

Sorry, I know I suggested replace_path_prefix, but now that the mappings 
consist of paths in their URL form, I think the old string::replace version is 
what you want :-/



Comment at: clang-tools-extra/clangd/PathMapping.h:26
+/// dependencies at different locations than the server.
 ///
 /// For example, if the mappings were {{"/home/user", "/workarea"}}, then

add a comment: `Therefore, both paths are represented as in file URI bodies, 
e.g. /etc/passwd or /C:/config.sys`



Comment at: clang-tools-extra/clangd/PathMapping.h:33
+  PathMapping() {}
+  PathMapping(llvm::StringRef ClientPath, llvm::StringRef ServerPath)
+  : ClientPath(ClientPath), ServerPath(ServerPath) {}

nit: you can probably drop these constructors and use `{}` aggregate 
initialization, up to you.



Comment at: clang-tools-extra/clangd/PathMapping.h:42
+
+/// Parse the command line \pRawPathMappings (e.g. "/client=/server") into
 /// pairs. Returns an error if the mappings are malformed, i.e. not absolute or

nit: please `\p RawPathMappings` with a space, or drop the doxygen tag 
entirely. These are read more often in the code than in rendered documentation, 
and `\pFoo` is hard to read.



Comment at: clang-tools-extra/clangd/PathMapping.h:56
 /// untouched.
-llvm::json::Value doPathMapping(const llvm::json::Value &Params,
-bool IsIncoming, const PathMappings &Mappings);
+void applyPathMappings(llvm::json::Value &Params, bool IsIncoming,
+   const PathMappings &Mappings);

nit: the sense of the bool is pretty arbitrary here, prefer a two value enum?

e.g. `enum class PathMapping::Direction { ServerToClient, ClientToServer }`

(Reusing the "server" and "client" 

[clang-tools-extra] 8cec7e0 - Revert "[clang-tidy] Add bugprone-bad-signal-to-kill-thread checker and alias cert-pos44-c"

2019-11-11 Thread Abel Kocsis via cfe-commits

Author: Abel Kocsis
Date: 2019-11-11T17:34:04+01:00
New Revision: 8cec7e0208f5b65790fd5c73b90d6d35944b07b1

URL: 
https://github.com/llvm/llvm-project/commit/8cec7e0208f5b65790fd5c73b90d6d35944b07b1
DIFF: 
https://github.com/llvm/llvm-project/commit/8cec7e0208f5b65790fd5c73b90d6d35944b07b1.diff

LOG: Revert "[clang-tidy] Add bugprone-bad-signal-to-kill-thread checker and 
alias cert-pos44-c"

This reverts commit 4edf0cb0e03e31d468979d0d7dec08bd9f4f8204.

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 
bad-signal-to-kill-thread.patch
clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h

clang-tools-extra/docs/clang-tidy/checks/bugprone-bad-signal-to-kill-thread.rst
clang-tools-extra/docs/clang-tidy/checks/cert-pos44-c.rst
clang-tools-extra/test/clang-tidy/bugprone-bad-signal-to-kill-thread.cpp



diff  --git a/bad-signal-to-kill-thread.patch b/bad-signal-to-kill-thread.patch
deleted file mode 100644
index 39b17574646d..
--- a/bad-signal-to-kill-thread.patch
+++ /dev/null
@@ -1,1133 +0,0 @@
-
diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
-new file mode 100644
-index 000..1f3dec497c0
 /dev/null
-+++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
-@@ -0,0 +1,70 @@
-+//===--- BadSignalToKillThreadCheck.cpp - clang-tidy 
-===//
-+//
-+// 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 "BadSignalToKillThreadCheck.h"
-+#include "clang/AST/ASTContext.h"
-+#include "clang/ASTMatchers/ASTMatchFinder.h"
-+
-+using namespace clang::ast_matchers;
-+
-+namespace clang {
-+namespace tidy {
-+namespace bugprone {
-+
-+void BadSignalToKillThreadCheck::registerMatchers(MatchFinder *Finder) {
-+  Finder->addMatcher(
-+  callExpr(allOf(callee(functionDecl(hasName("::pthread_kill"))),
-+ argumentCountIs(2)),
-+   hasArgument(1, integerLiteral().bind("integer-literal")))
-+  .bind("thread-kill"),
-+  this);
-+}
-+
-+static Preprocessor *PP;
-+
-+void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult 
&Result) {
-+  const auto IsSigterm = [](const auto &KeyValue) -> bool {
-+return KeyValue.first->getName() == "SIGTERM";
-+  };
-+  const auto TryExpandAsInteger =
-+  [](Preprocessor::macro_iterator It) -> Optional {
-+if (It == PP->macro_end())
-+  return llvm::None;
-+const MacroInfo *MI = PP->getMacroInfo(It->first);
-+const Token &T = MI->tokens().back();
-+StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
-+
-+llvm::APInt IntValue;
-+constexpr unsigned AutoSenseRadix = 0;
-+if (ValueStr.getAsInteger(AutoSenseRadix, IntValue))
-+  return llvm::None;
-+return IntValue.getZExtValue();
-+  };
-+
-+  const auto SigtermMacro = llvm::find_if(PP->macros(), IsSigterm);
-+
-+  if (!SigtermValue && !(SigtermValue = TryExpandAsInteger(SigtermMacro)))
-+return;
-+
-+  const auto *MatchedExpr = Result.Nodes.getNodeAs("thread-kill");
-+  const auto *MatchedIntLiteral =
-+  Result.Nodes.getNodeAs("integer-literal");
-+  if (MatchedIntLiteral->getValue() == *SigtermValue) {
-+diag(MatchedExpr->getBeginLoc(),
-+ "thread should not be terminated by raising the 'SIGTERM' signal");
-+  }
-+}
-+
-+void BadSignalToKillThreadCheck::registerPPCallbacks(
-+const SourceManager &SM, Preprocessor *pp, Preprocessor 
*ModuleExpanderPP) {
-+  PP = pp;
-+}
-+
-+} // namespace bugprone
-+} // namespace tidy
-+} // namespace clang
-
diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
-new file mode 100644
-index 000..d39fdec2e7d
 /dev/null
-+++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
-@@ -0,0 +1,37 @@
-+//===--- BadSignalToKillThreadCheck.h - clang-tidy --*- C++ 
-*-===//
-+//
-+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-+// See https://llvm.org/LICENSE.txt for license information.
-+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-+//
-+//===--===//
-+
-+#ifndef 
LLVM_CLAN

[PATCH] D70087: [ConstExprPreter] String and basic pointer arithmetic.

2019-11-11 Thread Nandor Licker via Phabricator via cfe-commits
nand created this revision.
nand added reviewers: rsmith, jfb, Bigcheese, dexonsmith.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Implemented string constants and the following pointer operations:

- AddOffset
- SubOffset
- Narrow
- Expand
- LogicalNot

To allow for sensible tests, short-circuiting logical ops were also implemented.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70087

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/Opcodes/Logical.h
  clang/lib/AST/Interp/Opcodes/Offset.h
  clang/lib/AST/Interp/Program.cpp
  clang/lib/AST/Interp/Program.h
  clang/test/AST/Interp/string.cpp

Index: clang/test/AST/Interp/string.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/string.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -fexperimental-new-constant-interpreter %s -verify
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only %s -verify
+// expected-no-diagnostics
+
+constexpr bool streq(const char *a, const char *b) {
+  while (*a && *a == *b) {
+a = a + 1;
+b = b + 1;
+  }
+  return *a == *b;
+}
+
+constexpr bool is_equal() {
+  const char *a = "Hello";
+  const char *b = "Hello";
+  return streq(a, b);
+}
+
+static_assert(is_equal());
+
+constexpr bool not_equal() {
+  const char *a = "HA";
+  const char *b = "HB";
+  return streq(a, b);
+}
+
+static_assert(!streq("HA", "HB"));
Index: clang/lib/AST/Interp/Program.h
===
--- clang/lib/AST/Interp/Program.h
+++ clang/lib/AST/Interp/Program.h
@@ -63,6 +63,14 @@
 public:
   Program(Context &Ctx) : Ctx(Ctx) {}
 
+  /// Emits a string literal among global data.
+  unsigned createGlobalString(const StringLiteral *S);
+
+  /// Returns a pointer to a global.
+  Pointer getPtrGlobal(GlobalLocation Idx);
+  /// Returns  a pointer to a global by index.
+  Pointer getPtrGlobal(const ValueDecl *VD);
+
   /// Creates a new function from a code range.
   template 
   Function *createFunction(const FunctionDecl *Def, Ts &&... Args) {
@@ -95,7 +103,11 @@
 
 private:
   friend class DeclScope;
- /// Reference to the VM context.
+
+  llvm::Optional createGlobal(const DeclTy &D, QualType Ty,
+  bool IsStatic, bool IsExtern);
+
+  /// Reference to the VM context.
   Context &Ctx;
   /// Mapping from decls to cached bytecode functions.
   llvm::DenseMap> Funcs;
@@ -108,9 +120,38 @@
   /// Custom allocator for global storage.
   using PoolAllocTy = llvm::BumpPtrAllocatorImpl;
 
+  /// Descriptor + storage for a global object.
+  ///
+  /// Global objects never go out of scope, thus they do not track pointers.
+  class Global {
+  public:
+/// Create a global descriptor for string literals.
+template 
+Global(Tys... Args) : B(std::forward(Args)...) {}
+
+/// Allocates the global in the pool, reserving storate for data.
+void *operator new(size_t Meta, PoolAllocTy &Alloc, size_t Data) {
+  return Alloc.Allocate(Meta + Data, alignof(void *));
+}
+
+/// Return a pointer to the data.
+char *data() { return B.data(); }
+/// Return a pointer to the block.
+Block *block() { return &B; }
+
+  private:
+/// Required metadata - does not actually track pointers.
+Block B;
+  };
+
   /// Allocator for globals.
   PoolAllocTy Allocator;
 
+  /// Global objects.
+  std::vector Globals;
+  /// Cached global indices.
+  llvm::DenseMap GlobalIndices;
+
   /// Creates a new descriptor.
   template  Descriptor *allocateDescriptor(Ts &&... Args) {
 return new (Allocator) Descriptor(std::forward(Args)...);
Index: clang/lib/AST/Interp/Program.cpp
===
--- clang/lib/AST/Interp/Program.cpp
+++ clang/lib/AST/Interp/Program.cpp
@@ -18,6 +18,78 @@
 using namespace clang;
 using namespace clang::interp;
 
+unsigned Program::createGlobalString(const StringLiteral *S) {
+  const size_t CharWidth = S->getCharByteWidth();
+  const size_t BitWidth = CharWidth * Ctx.getCharBit();
+
+  PrimType CharType;
+  switch (CharWidth) {
+  case 1:
+CharType = PT_Sint8;
+break;
+  case 2:
+CharType = PT_Uint16;
+break;
+  case 4:
+CharType = PT_Uint32;
+break;
+  default:
+llvm_unreachable("unsupported character width");
+  }
+
+  // Create a descriptor for the string.
+  Descriptor *Desc = allocateDescriptor(S, CharType, S->getLength() + 1,
+/*isConst=*/true,
+/*isTemporary=*/false,
+/*isMutable=*/false);
+
+  // Allocate storage for the string.
+  // The byte length does not include the null terminator.
+  unsigned I = Globals.size();
+  unsigned Sz = Desc->getAllocSize();
+  auto *G = new (Al

[PATCH] D69204: [OpenMP 5.0] - Extend defaultmap

2019-11-11 Thread Chi Chun Chen via Phabricator via cfe-commits
cchen marked an inline comment as done.
cchen added inline comments.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:4476
 }
-if (!ImplicitMaps.empty()) {
-  CXXScopeSpec MapperIdScopeSpec;
-  DeclarationNameInfo MapperId;
-  if (OMPClause *Implicit = ActOnOpenMPMapClause(
-  llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
-  OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
-  SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
-ClausesWithImplicit.emplace_back(Implicit);
-ErrorFound |=
-cast(Implicit)->varlist_size() != 
ImplicitMaps.size();
-  } else {
-ErrorFound = true;
+for (unsigned I = 0; I < OMPC_MAP_delete; I++) {
+  if (!ImplicitMaps[I].empty()) {

ABataev wrote:
> Use range-based loop here.
But in line 4480, I require the index of the iteration. If I use range based 
for loop, then I'll need to get the index like `addressof(ImplicitMap) - 
addressof(ImplicitMaps[0])`, which I'm not sure I should write code like this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69204



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


[clang-tools-extra] 8d288a0 - [clang-tidy] Add bugprone-bad-signal-to-kill-thread check and its alias cert-pos44-c

2019-11-11 Thread Abel Kocsis via cfe-commits

Author: Abel Kocsis
Date: 2019-11-11T17:47:14+01:00
New Revision: 8d288a0668a574863d52784084ff565c89f7366e

URL: 
https://github.com/llvm/llvm-project/commit/8d288a0668a574863d52784084ff565c89f7366e
DIFF: 
https://github.com/llvm/llvm-project/commit/8d288a0668a574863d52784084ff565c89f7366e.diff

LOG: [clang-tidy] Add bugprone-bad-signal-to-kill-thread check and its alias 
cert-pos44-c

Added: 
clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h

clang-tools-extra/docs/clang-tidy/checks/bugprone-bad-signal-to-kill-thread.rst
clang-tools-extra/docs/clang-tidy/checks/cert-pos44-c.rst
clang-tools-extra/test/clang-tidy/bugprone-bad-signal-to-kill-thread.cpp

Modified: 
clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
new file mode 100644
index ..1f3dec497c07
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp
@@ -0,0 +1,70 @@
+//===--- BadSignalToKillThreadCheck.cpp - clang-tidy -===//
+//
+// 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 "BadSignalToKillThreadCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace bugprone {
+
+void BadSignalToKillThreadCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  callExpr(allOf(callee(functionDecl(hasName("::pthread_kill"))),
+ argumentCountIs(2)),
+   hasArgument(1, integerLiteral().bind("integer-literal")))
+  .bind("thread-kill"),
+  this);
+}
+
+static Preprocessor *PP;
+
+void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult &Result) 
{
+  const auto IsSigterm = [](const auto &KeyValue) -> bool {
+return KeyValue.first->getName() == "SIGTERM";
+  };
+  const auto TryExpandAsInteger =
+  [](Preprocessor::macro_iterator It) -> Optional {
+if (It == PP->macro_end())
+  return llvm::None;
+const MacroInfo *MI = PP->getMacroInfo(It->first);
+const Token &T = MI->tokens().back();
+StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
+
+llvm::APInt IntValue;
+constexpr unsigned AutoSenseRadix = 0;
+if (ValueStr.getAsInteger(AutoSenseRadix, IntValue))
+  return llvm::None;
+return IntValue.getZExtValue();
+  };
+
+  const auto SigtermMacro = llvm::find_if(PP->macros(), IsSigterm);
+
+  if (!SigtermValue && !(SigtermValue = TryExpandAsInteger(SigtermMacro)))
+return;
+
+  const auto *MatchedExpr = Result.Nodes.getNodeAs("thread-kill");
+  const auto *MatchedIntLiteral =
+  Result.Nodes.getNodeAs("integer-literal");
+  if (MatchedIntLiteral->getValue() == *SigtermValue) {
+diag(MatchedExpr->getBeginLoc(),
+ "thread should not be terminated by raising the 'SIGTERM' signal");
+  }
+}
+
+void BadSignalToKillThreadCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *pp, Preprocessor *ModuleExpanderPP) 
{
+  PP = pp;
+}
+
+} // namespace bugprone
+} // namespace tidy
+} // namespace clang

diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
new file mode 100644
index ..d39fdec2e7de
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h
@@ -0,0 +1,37 @@
+//===--- BadSignalToKillThreadCheck.h - clang-tidy --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BADSIGNALTOKILLTHREADCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BADSIGNALTOKILLTHREADCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang {
+namespace tidy {
+namespace bugprone {
+
+/// Finds ``pthread_kill`` function calls when thread is terminated by
+/// ``SIGTERM`` signal.
+/// For the user-facing documentation see:
+/// 
http://clang.llvm

[PATCH] D68682: Clang-tidy fix removals removing all non-blank text from a line should remove the line

2019-11-11 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/include/clang/AST/CommentLexer.h:25
+
+/// Requires that BufferPtr point to a newline character (/n or /r).
+/// Returns a pointer past the end of any platform newline, i.e. past

"\n" and "\r" (everywhere)



Comment at: clang/lib/AST/CommentLexer.cpp:20
+
+// Consider moving this useful function to a more general utility location.
+const char *skipNewline(const char *BufferPtr, const char *BufferEnd) {

Please do so in this change. clang/include/clang/Basic/CharInfo.h?



Comment at: clang/lib/AST/CommentParser.cpp:19
 
-static inline bool isWhitespace(llvm::StringRef S) {
+// Consider moving this useful function to a more general utility location.
+bool isWhitespace(llvm::StringRef S) {

clang/include/clang/Basic/CharInfo.h ?



Comment at: clang/lib/Format/Format.cpp:2367
+  // and confirmed that the replacement result so far will be entirely blank.
+  std::list> PotentialWholeLineCuts;
+  int LineStartPos = -1;

Why std::list? std::vector seems more appropriate to me.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D68682



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


[PATCH] D69238: Fix clang-tidy readability-redundant-string-init for c++17/c++2a

2019-11-11 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added a comment.
This revision is now accepted and ready to land.

Thanks! Do you have commit access or do you need me to commit for you?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D69238



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


[PATCH] D69548: Give clang-tidy readability-redundant-string-init a customizable list of string types to fix

2019-11-11 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability-redundant-string-init.rst:30
+Semicolon-delimited list of base class names to apply this check to.
+By default `::std::basic_string` applies to std::string and std::wstring.
+Set to e.g. `::std::basic_string;llvm::StringRef;QString` to perform this

gribozavr2 wrote:
> Please wrap std::string and std::wstring in backtics.
Double back-ticks, because names are language constructs here.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D69548



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


[PATCH] D69548: Give clang-tidy readability-redundant-string-init a customizable list of string types to fix

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



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability-redundant-string-init.rst:29
+
+Semicolon-delimited list of base class names to apply this check to.
+By default `::std::basic_string` applies to std::string and std::wstring.

"of class names"

I don't think there's anything about base classes here.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/readability-redundant-string-init.rst:30
+Semicolon-delimited list of base class names to apply this check to.
+By default `::std::basic_string` applies to std::string and std::wstring.
+Set to e.g. `::std::basic_string;llvm::StringRef;QString` to perform this

Please wrap std::string and std::wstring in backtics.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D69548



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


[clang-tools-extra] b6cd799 - Fix filename typo in rG8d288a0668a5

2019-11-11 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2019-11-11T17:23:21Z
New Revision: b6cd799e29a9a5cef4d1d722f267e3b59ef6aaca

URL: 
https://github.com/llvm/llvm-project/commit/b6cd799e29a9a5cef4d1d722f267e3b59ef6aaca
DIFF: 
https://github.com/llvm/llvm-project/commit/b6cd799e29a9a5cef4d1d722f267e3b59ef6aaca.diff

LOG: Fix filename typo in rG8d288a0668a5

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a94ee3defd1e..5737dc3d288d 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -94,8 +94,8 @@ Improvements to clang-tidy
   Without the null terminator it can result in undefined behaviour when the
   string is read.
 
-- New alias :doc:`cert-pos44-cpp
-  ` to
+- New alias :doc:`cert-pos44-c
+  ` to
   :doc:`bugprone-bad-signal-to-kill-thread
   ` was added.
 



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


[PATCH] D69204: [OpenMP 5.0] - Extend defaultmap

2019-11-11 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/lib/Sema/SemaOpenMP.cpp:4476
 }
-if (!ImplicitMaps.empty()) {
-  CXXScopeSpec MapperIdScopeSpec;
-  DeclarationNameInfo MapperId;
-  if (OMPClause *Implicit = ActOnOpenMPMapClause(
-  llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
-  OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
-  SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
-ClausesWithImplicit.emplace_back(Implicit);
-ErrorFound |=
-cast(Implicit)->varlist_size() != 
ImplicitMaps.size();
-  } else {
-ErrorFound = true;
+for (unsigned I = 0; I < OMPC_MAP_delete; I++) {
+  if (!ImplicitMaps[I].empty()) {

cchen wrote:
> ABataev wrote:
> > Use range-based loop here.
> But in line 4480, I require the index of the iteration. If I use range based 
> for loop, then I'll need to get the index like `addressof(ImplicitMap) - 
> addressof(ImplicitMaps[0])`, which I'm not sure I should write code like this.
Better to use a new counter var here for ClauseKind


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69204



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


[clang-tools-extra] 489449c - [libTooling] Further simplify `Stencil` type and introduce `MatchComputation`.

2019-11-11 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2019-11-11T12:44:15-05:00
New Revision: 489449c28aaa45086d507fbad96826420adf409d

URL: 
https://github.com/llvm/llvm-project/commit/489449c28aaa45086d507fbad96826420adf409d
DIFF: 
https://github.com/llvm/llvm-project/commit/489449c28aaa45086d507fbad96826420adf409d.diff

LOG: [libTooling] Further simplify `Stencil` type and introduce 
`MatchComputation`.

Summary:
This revision introduces a new interface `MatchComputation` which generalizes
the `Stencil` interface and replaces the `std::function` interface of
`MatchConsumer`. With this revision, `Stencil` (as an abstraction) becomes just
one collection of implementations of
`MatchComputation`. Correspondingly, we remove the `Stencil` class
entirely in favor of a simple type alias, deprecate `MatchConsumer` and change
all functions that accepted `MatchConsumer` to use
`MatchComputation` instead.

Reviewers: gribozavr

Subscribers: cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
clang/include/clang/Tooling/Transformer/MatchConsumer.h
clang/include/clang/Tooling/Transformer/RewriteRule.h
clang/include/clang/Tooling/Transformer/Stencil.h
clang/lib/Tooling/Transformer/RewriteRule.cpp
clang/lib/Tooling/Transformer/Stencil.cpp
clang/unittests/Tooling/StencilTest.cpp
clang/unittests/Tooling/TransformerTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp 
b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
index 1c31cf56c68a..515997b14231 100644
--- a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
@@ -85,7 +85,7 @@ void TransformerClangTidyCheck::check(
   if (Transformations->empty())
 return;
 
-  Expected Explanation = Case.Explanation(Result);
+  Expected Explanation = Case.Explanation->eval(Result);
   if (!Explanation) {
 llvm::errs() << "Error in explanation: "
  << llvm::toString(Explanation.takeError()) << "\n";

diff  --git a/clang/include/clang/Tooling/Transformer/MatchConsumer.h 
b/clang/include/clang/Tooling/Transformer/MatchConsumer.h
index 0a1dbe13ea1e..f407ffce3d25 100644
--- a/clang/include/clang/Tooling/Transformer/MatchConsumer.h
+++ b/clang/include/clang/Tooling/Transformer/MatchConsumer.h
@@ -51,6 +51,53 @@ MatchConsumer ifBound(std::string ID, MatchConsumer 
TrueC,
 return (Map.find(ID) != Map.end() ? TrueC : FalseC)(Result);
   };
 }
+
+/// A failable computation over nodes bound by AST matchers, with (limited)
+/// reflection via the `toString` method.
+///
+/// The computation should report any errors though its return value (rather
+/// than terminating the program) to enable usage in interactive scenarios like
+/// clang-query.
+///
+/// This is a central abstraction of the Transformer framework. It is a
+/// generalization of `MatchConsumer` and intended to replace it.
+template  class MatchComputation {
+public:
+  virtual ~MatchComputation() = default;
+
+  /// Evaluates the computation and (potentially) updates the accumulator \c
+  /// Result.  \c Result is undefined in the case of an error. `Result` is an
+  /// out parameter to optimize case where the computation involves composing
+  /// the result of sub-computation evaluations.
+  virtual llvm::Error eval(const ast_matchers::MatchFinder::MatchResult &Match,
+   T *Result) const = 0;
+
+  /// Convenience version of `eval`, for the case where the computation is 
being
+  /// evaluated on its own.
+  llvm::Expected eval(const ast_matchers::MatchFinder::MatchResult &R) 
const;
+
+  /// Constructs a string representation of the computation, for informational
+  /// purposes. The representation must be deterministic, but is not required 
to
+  /// be unique.
+  virtual std::string toString() const = 0;
+
+protected:
+  MatchComputation() = default;
+
+  // Since this is an abstract class, copying/assigning only make sense for
+  // derived classes implementing `clone()`.
+  MatchComputation(const MatchComputation &) = default;
+  MatchComputation &operator=(const MatchComputation &) = default;
+};
+
+template 
+llvm::Expected MatchComputation::eval(
+const ast_matchers::MatchFinder::MatchResult &R) const {
+  T Output;
+  if (auto Err = eval(R, &Output))
+return std::move(Err);
+  return Output;
+}
 } // namespace transformer
 
 namespace tooling {

diff  --git a/clang/include/clang/Tooling/Transformer/RewriteRule.h 
b/clang/include/clang/Tooling/Transformer/RewriteRule.h
index 11ff2bc9867f..7daf6ea154be 100644
--- a/clang/include/clang/Tooling/Transformer/RewriteRule.h
+++ b/clang/include/clang/Tooling/Transformer/RewriteRule.h
@@ -30,7 +30,7 @@
 
 namespace clang {
 namespace transformer {
-using TextGen

[PATCH] D69802: [libTooling] Further simplify `Stencil` type and introduce `MatchComputation`.

2019-11-11 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 228720.
ymandel added a comment.

syntax fixes (to compile)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69802

Files:
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang/include/clang/Tooling/Transformer/MatchConsumer.h
  clang/include/clang/Tooling/Transformer/RewriteRule.h
  clang/include/clang/Tooling/Transformer/Stencil.h
  clang/lib/Tooling/Transformer/RewriteRule.cpp
  clang/lib/Tooling/Transformer/Stencil.cpp
  clang/unittests/Tooling/StencilTest.cpp
  clang/unittests/Tooling/TransformerTest.cpp

Index: clang/unittests/Tooling/TransformerTest.cpp
===
--- clang/unittests/Tooling/TransformerTest.cpp
+++ clang/unittests/Tooling/TransformerTest.cpp
@@ -575,13 +575,16 @@
   std::string Input = "int conflictOneRule() { return 3 + 7; }";
   // Try to change the whole binary-operator expression AND one its operands:
   StringRef O = "O";
-  auto AlwaysFail = [](const ast_matchers::MatchFinder::MatchResult &)
-  -> llvm::Expected {
-return llvm::createStringError(llvm::errc::invalid_argument, "ERROR");
+  class AlwaysFail : public transformer::MatchComputation {
+llvm::Error eval(const ast_matchers::MatchFinder::MatchResult &,
+ std::string *) const override {
+  return llvm::createStringError(llvm::errc::invalid_argument, "ERROR");
+}
+std::string toString() const override { return "AlwaysFail"; }
   };
-  Transformer T(
-  makeRule(binaryOperator().bind(O), changeTo(node(O), AlwaysFail)),
-  consumer());
+  Transformer T(makeRule(binaryOperator().bind(O),
+ changeTo(node(O), std::make_shared())),
+consumer());
   T.registerMatchers(&MatchFinder);
   EXPECT_FALSE(rewrite(Input));
   EXPECT_THAT(Changes, IsEmpty());
Index: clang/unittests/Tooling/StencilTest.cpp
===
--- clang/unittests/Tooling/StencilTest.cpp
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -24,7 +24,6 @@
 using ::llvm::HasValue;
 using ::llvm::StringError;
 using ::testing::AllOf;
-using ::testing::Eq;
 using ::testing::HasSubstr;
 using MatchResult = MatchFinder::MatchResult;
 
@@ -135,26 +134,6 @@
HasValue("if (!true) return 0; else return 1;"));
 }
 
-// Tests `stencil`.
-TEST_F(StencilTest, StencilFactoryFunction) {
-  StringRef Condition("C"), Then("T"), Else("E");
-  const std::string Snippet = R"cc(
-if (true)
-  return 1;
-else
-  return 0;
-  )cc";
-  auto StmtMatch = matchStmt(
-  Snippet, ifStmt(hasCondition(expr().bind(Condition)),
-  hasThen(stmt().bind(Then)), hasElse(stmt().bind(Else;
-  ASSERT_TRUE(StmtMatch);
-  // Invert the if-then-else.
-  auto Consumer = cat("if (!", node(Condition), ") ", statement(Else), " else ",
-  statement(Then));
-  EXPECT_THAT_EXPECTED(Consumer(StmtMatch->Result),
-   HasValue("if (!true) return 0; else return 1;"));
-}
-
 TEST_F(StencilTest, UnboundNode) {
   const std::string Snippet = R"cc(
 if (true)
Index: clang/lib/Tooling/Transformer/Stencil.cpp
===
--- clang/lib/Tooling/Transformer/Stencil.cpp
+++ clang/lib/Tooling/Transformer/Stencil.cpp
@@ -272,14 +272,6 @@
 };
 } // namespace
 
-llvm::Expected
-StencilInterface::eval(const MatchFinder::MatchResult &R) const {
-  std::string Output;
-  if (auto Err = eval(R, &Output))
-return std::move(Err);
-  return Output;
-}
-
 Stencil transformer::detail::makeStencil(StringRef Text) { return text(Text); }
 
 Stencil transformer::detail::makeStencil(RangeSelector Selector) {
@@ -287,52 +279,50 @@
 }
 
 Stencil transformer::text(StringRef Text) {
-  return Stencil(std::make_shared>(Text));
+  return std::make_shared>(Text);
 }
 
 Stencil transformer::selection(RangeSelector Selector) {
-  return Stencil(
-  std::make_shared>(std::move(Selector)));
+  return std::make_shared>(std::move(Selector));
 }
 
 Stencil transformer::dPrint(StringRef Id) {
-  return Stencil(std::make_shared>(Id));
+  return std::make_shared>(Id);
 }
 
 Stencil transformer::expression(llvm::StringRef Id) {
-  return Stencil(std::make_shared>(
-  UnaryNodeOperator::Parens, Id));
+  return std::make_shared>(
+  UnaryNodeOperator::Parens, Id);
 }
 
 Stencil transformer::deref(llvm::StringRef ExprId) {
-  return Stencil(std::make_shared>(
-  UnaryNodeOperator::Deref, ExprId));
+  return std::make_shared>(
+  UnaryNodeOperator::Deref, ExprId);
 }
 
 Stencil transformer::addressOf(llvm::StringRef ExprId) {
-  return Stencil(std::make_shared>(
-  UnaryNodeOperator::Address, ExprId));
+  return std::make_shared>(
+  UnaryNodeOperator::Address, ExprId);
 }
 
 Stencil transformer::access(StringRef BaseId, Stencil Member) {

[PATCH] D69802: [libTooling] Further simplify `Stencil` type and introduce `MatchComputation`.

2019-11-11 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG489449c28aaa: [libTooling] Further simplify `Stencil` type 
and introduce `MatchComputation`. (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69802

Files:
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang/include/clang/Tooling/Transformer/MatchConsumer.h
  clang/include/clang/Tooling/Transformer/RewriteRule.h
  clang/include/clang/Tooling/Transformer/Stencil.h
  clang/lib/Tooling/Transformer/RewriteRule.cpp
  clang/lib/Tooling/Transformer/Stencil.cpp
  clang/unittests/Tooling/StencilTest.cpp
  clang/unittests/Tooling/TransformerTest.cpp

Index: clang/unittests/Tooling/TransformerTest.cpp
===
--- clang/unittests/Tooling/TransformerTest.cpp
+++ clang/unittests/Tooling/TransformerTest.cpp
@@ -575,13 +575,16 @@
   std::string Input = "int conflictOneRule() { return 3 + 7; }";
   // Try to change the whole binary-operator expression AND one its operands:
   StringRef O = "O";
-  auto AlwaysFail = [](const ast_matchers::MatchFinder::MatchResult &)
-  -> llvm::Expected {
-return llvm::createStringError(llvm::errc::invalid_argument, "ERROR");
+  class AlwaysFail : public transformer::MatchComputation {
+llvm::Error eval(const ast_matchers::MatchFinder::MatchResult &,
+ std::string *) const override {
+  return llvm::createStringError(llvm::errc::invalid_argument, "ERROR");
+}
+std::string toString() const override { return "AlwaysFail"; }
   };
-  Transformer T(
-  makeRule(binaryOperator().bind(O), changeTo(node(O), AlwaysFail)),
-  consumer());
+  Transformer T(makeRule(binaryOperator().bind(O),
+ changeTo(node(O), std::make_shared())),
+consumer());
   T.registerMatchers(&MatchFinder);
   EXPECT_FALSE(rewrite(Input));
   EXPECT_THAT(Changes, IsEmpty());
Index: clang/unittests/Tooling/StencilTest.cpp
===
--- clang/unittests/Tooling/StencilTest.cpp
+++ clang/unittests/Tooling/StencilTest.cpp
@@ -24,7 +24,6 @@
 using ::llvm::HasValue;
 using ::llvm::StringError;
 using ::testing::AllOf;
-using ::testing::Eq;
 using ::testing::HasSubstr;
 using MatchResult = MatchFinder::MatchResult;
 
@@ -135,26 +134,6 @@
HasValue("if (!true) return 0; else return 1;"));
 }
 
-// Tests `stencil`.
-TEST_F(StencilTest, StencilFactoryFunction) {
-  StringRef Condition("C"), Then("T"), Else("E");
-  const std::string Snippet = R"cc(
-if (true)
-  return 1;
-else
-  return 0;
-  )cc";
-  auto StmtMatch = matchStmt(
-  Snippet, ifStmt(hasCondition(expr().bind(Condition)),
-  hasThen(stmt().bind(Then)), hasElse(stmt().bind(Else;
-  ASSERT_TRUE(StmtMatch);
-  // Invert the if-then-else.
-  auto Consumer = cat("if (!", node(Condition), ") ", statement(Else), " else ",
-  statement(Then));
-  EXPECT_THAT_EXPECTED(Consumer(StmtMatch->Result),
-   HasValue("if (!true) return 0; else return 1;"));
-}
-
 TEST_F(StencilTest, UnboundNode) {
   const std::string Snippet = R"cc(
 if (true)
Index: clang/lib/Tooling/Transformer/Stencil.cpp
===
--- clang/lib/Tooling/Transformer/Stencil.cpp
+++ clang/lib/Tooling/Transformer/Stencil.cpp
@@ -272,14 +272,6 @@
 };
 } // namespace
 
-llvm::Expected
-StencilInterface::eval(const MatchFinder::MatchResult &R) const {
-  std::string Output;
-  if (auto Err = eval(R, &Output))
-return std::move(Err);
-  return Output;
-}
-
 Stencil transformer::detail::makeStencil(StringRef Text) { return text(Text); }
 
 Stencil transformer::detail::makeStencil(RangeSelector Selector) {
@@ -287,52 +279,50 @@
 }
 
 Stencil transformer::text(StringRef Text) {
-  return Stencil(std::make_shared>(Text));
+  return std::make_shared>(Text);
 }
 
 Stencil transformer::selection(RangeSelector Selector) {
-  return Stencil(
-  std::make_shared>(std::move(Selector)));
+  return std::make_shared>(std::move(Selector));
 }
 
 Stencil transformer::dPrint(StringRef Id) {
-  return Stencil(std::make_shared>(Id));
+  return std::make_shared>(Id);
 }
 
 Stencil transformer::expression(llvm::StringRef Id) {
-  return Stencil(std::make_shared>(
-  UnaryNodeOperator::Parens, Id));
+  return std::make_shared>(
+  UnaryNodeOperator::Parens, Id);
 }
 
 Stencil transformer::deref(llvm::StringRef ExprId) {
-  return Stencil(std::make_shared>(
-  UnaryNodeOperator::Deref, ExprId));
+  return std::make_shared>(
+  UnaryNodeOperator::Deref, ExprId);
 }
 
 Stencil transformer::addressOf(llvm::StringRef ExprId) {
-  return Stencil(std::make_shared>(
-  UnaryNodeOperator::Address, ExprId));
+  return std::make_shared>(
+ 

[clang-tools-extra] b9213df - [clangd] Fix crash in DefineInline::prepare()

2019-11-11 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2019-11-11T19:01:06+01:00
New Revision: b9213dfec4d8ce42d90507c25545564f4a0bbfb8

URL: 
https://github.com/llvm/llvm-project/commit/b9213dfec4d8ce42d90507c25545564f4a0bbfb8
DIFF: 
https://github.com/llvm/llvm-project/commit/b9213dfec4d8ce42d90507c25545564f4a0bbfb8.diff

LOG: [clangd] Fix crash in DefineInline::prepare()

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
clang-tools-extra/clangd/unittests/TweakTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
index f6966f619ade..6d0599e8821c 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp
@@ -388,7 +388,7 @@ class DefineInline : public Tweak {
 if (!SelNode)
   return false;
 Source = getSelectedFunction(SelNode);
-if (!Source || !Source->isThisDeclarationADefinition())
+if (!Source || !Source->hasBody())
   return false;
 // Only the last level of template parameter locations are not kept in AST,
 // so if we are inlining a method that is in a templated class, there is no

diff  --git a/clang-tools-extra/clangd/unittests/TweakTests.cpp 
b/clang-tools-extra/clangd/unittests/TweakTests.cpp
index 5a6df2e03e67..ab2808835832 100644
--- a/clang-tools-extra/clangd/unittests/TweakTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TweakTests.cpp
@@ -920,6 +920,9 @@ TEST_F(DefineInlineTest, TriggersOnFunctionDecl) {
 [[(void)(5+3);
 return;]]
   }]]
+
+  // Definition with no body.
+  class Bar { Bar() = def^ault; }
   )cpp");
 }
 



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


[PATCH] D69383: [RISCV] Match GCC `-march`/`-mabi` driver defaults

2019-11-11 Thread Sam Elliott via Phabricator via cfe-commits
lenary added a comment.

I think this is just about ready to land, given our discussion on the RISC-V 
call on 7 November 2019.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69383



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


[PATCH] D69383: [RISCV] Match GCC `-march`/`-mabi` driver defaults

2019-11-11 Thread Sam Elliott via Phabricator via cfe-commits
lenary updated this revision to Diff 228728.
lenary added a comment.

- Rebase
- Update comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69383

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/lib/Driver/ToolChains/Arch/RISCV.h
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/test/Driver/riscv-abi.c
  clang/test/Driver/riscv-gnutools.c

Index: clang/test/Driver/riscv-gnutools.c
===
--- clang/test/Driver/riscv-gnutools.c
+++ clang/test/Driver/riscv-gnutools.c
@@ -1,19 +1,40 @@
 // Check gnutools are invoked with propagated values for -mabi and -march.
+//
+// This test also checks the default -march/-mabi for certain targets.
 
-// RUN: %clang -target riscv32 -fno-integrated-as %s -###  -c \
-// RUN: 2>&1 | FileCheck -check-prefix=MABI-ILP32 %s
+// 32-bit checks
 
-// RUN: %clang -target riscv32 -fno-integrated-as -march=rv32g %s -### -c \
-// RUN: 2>&1 | FileCheck -check-prefix=MABI-ILP32-MARCH-G %s
+// Check default on riscv32-unknown-elf
+// RUN: %clang -target riscv32-unknown-elf -fno-integrated-as %s -### -c \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV32IMAC-ILP32 %s
 
-// RUN: %clang -target riscv64 -fno-integrated-as %s -###  -c \
-// RUN: 2>&1 | FileCheck -check-prefix=MABI-ILP64 %s
+// Check default on riscv32-unknown-linux-gnu
+// RUN: %clang -target riscv32-unknown-linux-gnu -fno-integrated-as %s -### -c \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV32IMAFDC-ILP32D %s
 
-// RUN: %clang -target riscv64 -fno-integrated-as -march=rv64g %s -### -c \
-// RUN: 2>&1 | FileCheck -check-prefix=MABI-ILP64-MARCH-G %s
+// Check default when -march=rv32g specified
+// RUN: %clang -target riscv32 -fno-integrated-as %s -### -c -march=rv32g \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV32G-ILP32D %s
 
-// MABI-ILP32: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32"
-// MABI-ILP32-MARCH-G: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32" "-march" "rv32g"
+// CHECK-RV32IMAC-ILP32: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32" "-march" "rv32imac"
+// CHECK-RV32IMAFDC-ILP32D: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32d" "-march" "rv32imafdc"
+// CHECK-RV32G-ILP32D: "{{.*}}as{{(.exe)?}}" "-mabi" "ilp32d" "-march" "rv32g"
 
-// MABI-ILP64: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64"
-// MABI-ILP64-MARCH-G: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64" "-march" "rv64g"
+
+// 64-bit checks
+
+// Check default on riscv64-unknown-elf
+// RUN: %clang -target riscv64-unknown-elf -fno-integrated-as %s -### -c \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV64IMAC-LP64 %s
+
+// Check default on riscv64-unknown-linux-gnu
+// RUN: %clang -target riscv64-unknown-linux-gnu -fno-integrated-as %s -### -c \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV64IMAFDC-LP64D %s
+
+// Check default when -march=rv64g specified
+// RUN: %clang -target riscv64 -fno-integrated-as %s -### -c -march=rv64g \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-RV64G-LP64D %s
+
+// CHECK-RV64IMAC-LP64: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64" "-march" "rv64imac"
+// CHECK-RV64IMAFDC-LP64D: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64d" "-march" "rv64imafdc"
+// CHECK-RV64G-LP64D: "{{.*}}as{{(.exe)?}}" "-mabi" "lp64d" "-march" "rv64g"
Index: clang/test/Driver/riscv-abi.c
===
--- clang/test/Driver/riscv-abi.c
+++ clang/test/Driver/riscv-abi.c
@@ -16,6 +16,10 @@
 
 // RUN: %clang -target riscv32-unknown-elf %s -### -o %t.o -march=rv32ifd -mabi=ilp32d 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-ILP32D %s
+// RUN: %clang -target riscv32-unknown-linux-gnu %s -### -o %t.o 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-ILP32D %s
+// RUN: %clang -target riscv32-unknown-linux-gnu -x assembler %s -### -o %t.o 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-ILP32D %s
 
 // CHECK-ILP32D: "-target-abi" "ilp32d"
 
@@ -42,6 +46,10 @@
 
 // RUN: %clang -target riscv64-unknown-elf %s -### -o %t.o -march=rv64d -mabi=lp64d 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHECK-LP64D %s
+// RUN: %clang -target riscv64-unknown-linux-gnu %s -### -o %t.o 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-LP64D %s
+// RUN: %clang -target riscv64-unknown-linux-gnu -x assembler %s -### -o %t.o 2>&1 \
+// RUN:   | FileCheck -check-prefix=CHECK-LP64D  %s
 
 // CHECK-LP64D: "-target-abi" "lp64d"
 
Index: clang/lib/Driver/ToolChains/Gnu.cpp
===
--- clang/lib/Driver/ToolChains/Gnu.cpp
+++ clang/lib/Driver/ToolChains/Gnu.cpp
@@ -709,11 +709,9 @@
 StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple());
 CmdArgs.push_back("-mabi");
 CmdArgs.push_back(ABIName.data());
-if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
-  StringRef MArch = A->getValue();
-  CmdArgs.push_back("-march");
-  CmdArgs.push_back(MArch.data());
-}
+StringRef MArchName = riscv:

[PATCH] D69938: [OpenCL] Use __generic addr space when generating internal representation of lambda

2019-11-11 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia marked an inline comment as done.
Anastasia added a comment.

In D69938#1737196 , @rjmccall wrote:

> It does make logical sense to be able to qualify the call operator of a 
> lambda.  The lambda always starts as a temporary, so presumably we want the 
> default address space qualifier on lambdas to be compatible with the address 
> space of temporaries.  However, that's probably also true of the default 
> address qualifier on methods in general or you wouldn't be able to call them 
> on temporaries and locals.  Thus, we should be able to use the same default 
> in both cases, which seems to be what you've implemented.
>
> It even makes sense to be able to qualify a lambda with an address space 
> that's not compatible with the address space of temporaries; that just means 
> that the lambda has to be copied elsewhere before it can be invoked.


Just to clarify... Do you mean we should be able to compile this example:

  [&] __global {
i++;
  } ();

Or should this result in a diagnostic about an addr space mismatch?

> The right place to write the qualifier is the same place where you have to 
> write attributes and/or `mutable`, i.e. in the lambda declarator, something 
> like `[]() __local { ... }`.
> 
> Arguably there ought to be a special-case rule allowing lambdas with no 
> captures to be called in an arbitrary address space, but I don't think we 
> need to go there in this patch.

I am trying to understand what are the limitations here. Once we add ability to 
qualify lambdas with an addr space it should just work? But also it should be 
ok for all lambdas? Apart from captures won'twork for `__constant` addr space 
in OpenCL.

To summarize what has to be done overall to support addr spaces with lambdas:

1. Add default AS on object param of internal lambda class member functions.

2. Allow addr space qualifier on lambda expression.

Example:

  [&]() __local  {i++;};

3. Diagnose address space mismatch between variable decl and lambda expr 
qualifier

Example:

  __private auto  llambda = [&]() __local {i++;}; // error no legal conversion 
b/w __private and __local

I think 1 is covered by this patch. I would like to implement 2 as a separate 
patch though to be able to commit fix for 1 earlier and unblock some developers 
waiting for the fix. I think 3 already works and I will just update the 
diagnostic in a separate patch too.




Comment at: clang/test/SemaOpenCLCXX/address-space-lambda.cl:13
+  __constant auto err = [&]() {}; //expected-note-re{{candidate function not 
viable: address space mismatch in 'this' argument ('__constant (lambda at 
{{.*}})'), parameter type must be 'const __generic (lambda at {{.*}})'}}
+  err(); //expected-error-re{{no matching function for call to object of type 
'__constant (lambda at {{.*}})'}}
+}

rjmccall wrote:
> Can we get a better diagnostic here when a candidate would have succeeded 
> except for an address-space mismatch?  Something like "candidate function not 
> viable: cannot convert 'this' from '__constant' address space to 
> '__generic'"?  You can do that in a separate patch, of course.
Sure. Makes sense!


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

https://reviews.llvm.org/D69938



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


[PATCH] D70094: [clang-tidy] new altera ID dependent backward branch check

2019-11-11 Thread Frank Derry Wanye via Phabricator via cfe-commits
ffrankies created this revision.
ffrankies added reviewers: alexfh, jdoerfert, hokein, aaron.ballman.
ffrankies added projects: clang-tools-extra, clang, LLVM.
Herald added subscribers: mgehre, arphaman, xazax.hun, Anastasia, mgorny.

This lint check is a part of the FLOCL (FPGA Linters for OpenCL) project out of 
the Synergy Lab at Virginia Tech.

FLOCL is a set of lint checks aimed at FPGA developers who write code in OpenCL.

The altera ID dependent backward branch lint check finds ID dependent variables 
and fields used within loops, and warns of their usage. Using these variables 
in loops can lead to performance degradation.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D70094

Files:
  clang-tidy/CMakeLists.txt
  clang-tidy/ClangTidyForceLinker.h
  clang-tidy/altera/AlteraTidyModule.cpp
  clang-tidy/altera/CMakeLists.txt
  clang-tidy/altera/IdDependentBackwardBranchCheck.cpp
  clang-tidy/altera/IdDependentBackwardBranchCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/altera-id-dependent-backward-branch.rst
  docs/clang-tidy/index.rst
  test/clang-tidy/checkers/altera-id-dependent-backward-branch.cpp

Index: test/clang-tidy/checkers/altera-id-dependent-backward-branch.cpp
===
--- /dev/null
+++ test/clang-tidy/checkers/altera-id-dependent-backward-branch.cpp
@@ -0,0 +1,83 @@
+// RUN: %check_clang_tidy %s altera-id-dependent-backward-branch %t -- -header-filter=.* "--" -cl-std=CL1.2 -c --include opencl-c.h
+
+typedef struct ExampleStruct {
+  int IDDepField;
+} ExampleStruct;
+
+void error() {
+  //  Assignments 
+  int ThreadID = get_local_id(0); 
+// CHECK-NOTES: :[[@LINE-1]]:3: warning: assignment of ID-dependent variable ThreadID [altera-id-dependent-backward-branch]
+
+  ExampleStruct Example;
+  Example.IDDepField = get_local_id(0);
+// CHECK-NOTES: :[[@LINE-1]]:3: warning: assignment of ID-dependent field IDDepField [altera-id-dependent-backward-branch]
+
+  //  Inferred Assignments 
+  int ThreadID2 = ThreadID * get_local_size(0);
+// CHECK-NOTES: :[[@LINE-1]]:3: warning: inferred assignment of ID-dependent value from ID-dependent variable ThreadID [altera-id-dependent-backward-branch]
+  
+  int ThreadID3 = Example.IDDepField;  // OK: not used in any loops
+
+  ExampleStruct UnusedStruct = {
+ThreadID * 2  // OK: not used in any loops
+  };
+
+  //  Conditional Expressions 
+  int accumulator = 0;
+  for (int i = 0; i < get_local_id(0); i++) {
+// CHECK-NOTES: :[[@LINE-1]]:19: warning: backward branch (for loop) is ID-dependent due to ID function call and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  int j = 0;
+  while (j < get_local_id(0)) {
+// CHECK-NOTES: :[[@LINE-1]]:10: warning: backward branch (while loop) is ID-dependent due to ID function call and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  do {
+accumulator++;
+  } while (j < get_local_id(0));
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: backward branch (do loop) is ID-dependent due to ID function call and may cause performance degradation [altera-id-dependent-backward-branch]
+  
+  for (int i = 0; i < ThreadID2; i++) {
+// CHECK-NOTES: :[[@LINE-1]]:19: warning: backward branch (for loop) is ID-dependent due to variable reference to 'ThreadID2' and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  while (j < ThreadID) {
+// CHECK-NOTES: :[[@LINE-1]]:10: warning: backward branch (while loop) is ID-dependent due to variable reference to 'ThreadID' and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  do {
+accumulator++;
+  } while (j < ThreadID);
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: backward branch (do loop) is ID-dependent due to variable reference to 'ThreadID' and may cause performance degradation [altera-id-dependent-backward-branch]
+  
+  for (int i = 0; i < Example.IDDepField; i++) {
+// CHECK-NOTES: :[[@LINE-1]]:19: warning: backward branch (for loop) is ID-dependent due to member reference to 'IDDepField' and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  while (j < Example.IDDepField) {
+// CHECK-NOTES: :[[@LINE-1]]:10: warning: backward branch (while loop) is ID-dependent due to member reference to 'IDDepField' and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  do {
+accumulator++;
+  } while (j < Example.IDDepField);
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: backward branch (do loop) is ID-dependent due to member reference to 'IDDepField' and may cause performance degradation [altera-id-dependent-backward-branch]
+}
+
+void success() {
+  int accumulator = 0;
+
+  for (int i = 0; i < 1000; i++) {
+if (i < get_local_id(0)) {
+  a

[PATCH] D69825: [Clang][Driver] Bypass cc1 process and re-enter driver main

2019-11-11 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea updated this revision to Diff 228729.
aganea marked 2 inline comments as done.
aganea added a comment.

Addressed comments & finished the Linux part. All tests pass.

@Meinersbur : Just to show the difference between Windows & Linux, here's some 
timings for running the tests over the same `git checkout`, compiled with 
clang-9.
Everything was already built, I used `ninja check-all` and only the tests ran.
`LLVM_ENABLE_PROJECTS = "clang;lld;clang-tools-extra;compiler-rt"`

| 6-core Intel(R) Xeon(R) CPU E5-1650 0 @ 3.20GHz | Ubuntu 18.04  | 
770.07s (12 min 50 sec)  | 59182 tests ran |
| 6-core Intel(R) Xeon(R) W-2135 CPU @ 3.70GHz| Windows 10 build 1903 | 
1779.83s (29 min 39 sec) | 56589 tests ran |
|

This patch does not make much difference for running the tests on Windows (it's 
saving only 30 sec). The friction in the OS is so high, improving just 
clang.exe does not change much.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69825

Files:
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Job.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/Job.cpp
  clang/tools/driver/driver.cpp
  llvm/include/llvm/Support/CrashRecoveryContext.h
  llvm/lib/Support/CrashRecoveryContext.cpp
  llvm/lib/Support/Unix/Signals.inc
  llvm/lib/Support/Windows/Signals.inc

Index: llvm/lib/Support/Windows/Signals.inc
===
--- llvm/lib/Support/Windows/Signals.inc
+++ llvm/lib/Support/Windows/Signals.inc
@@ -187,7 +187,7 @@
 using namespace llvm;
 
 // Forward declare.
-static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
+LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep);
 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType);
 
 // The function to call if ctrl-c is pressed.
@@ -521,10 +521,13 @@
 extern "C" VOID WINAPI RtlCaptureContext(PCONTEXT ContextRecord);
 #endif
 
-void llvm::sys::PrintStackTrace(raw_ostream &OS) {
-  STACKFRAME64 StackFrame = {};
-  CONTEXT Context = {};
-  ::RtlCaptureContext(&Context);
+static void LocalPrintStackTrace(raw_ostream &OS, PCONTEXT C) {
+  STACKFRAME64 StackFrame{};
+  CONTEXT Context{};
+  if (!C) {
+::RtlCaptureContext(&Context);
+C = &Context;
+  }
 #if defined(_M_X64)
   StackFrame.AddrPC.Offset = Context.Rip;
   StackFrame.AddrStack.Offset = Context.Rsp;
@@ -546,9 +549,12 @@
   StackFrame.AddrStack.Mode = AddrModeFlat;
   StackFrame.AddrFrame.Mode = AddrModeFlat;
   PrintStackTraceForThread(OS, GetCurrentProcess(), GetCurrentThread(),
-   StackFrame, &Context);
+   StackFrame, C);
 }
 
+void llvm::sys::PrintStackTrace(raw_ostream &OS) {
+  LocalPrintStackTrace(OS, nullptr);
+}
 
 void llvm::sys::SetInterruptFunction(void (*IF)()) {
   RegisterHandler();
@@ -785,7 +791,7 @@
   return std::error_code();
 }
 
-static LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
+LONG WINAPI LLVMUnhandledExceptionFilter(LPEXCEPTION_POINTERS ep) {
   Cleanup();
 
   // We'll automatically write a Minidump file here to help diagnose
@@ -803,42 +809,9 @@
<< "\n";
   }
 
-  // Initialize the STACKFRAME structure.
-  STACKFRAME64 StackFrame = {};
-
-#if defined(_M_X64)
-  StackFrame.AddrPC.Offset = ep->ContextRecord->Rip;
-  StackFrame.AddrPC.Mode = AddrModeFlat;
-  StackFrame.AddrStack.Offset = ep->ContextRecord->Rsp;
-  StackFrame.AddrStack.Mode = AddrModeFlat;
-  StackFrame.AddrFrame.Offset = ep->ContextRecord->Rbp;
-  StackFrame.AddrFrame.Mode = AddrModeFlat;
-#elif defined(_M_IX86)
-  StackFrame.AddrPC.Offset = ep->ContextRecord->Eip;
-  StackFrame.AddrPC.Mode = AddrModeFlat;
-  StackFrame.AddrStack.Offset = ep->ContextRecord->Esp;
-  StackFrame.AddrStack.Mode = AddrModeFlat;
-  StackFrame.AddrFrame.Offset = ep->ContextRecord->Ebp;
-  StackFrame.AddrFrame.Mode = AddrModeFlat;
-#elif defined(_M_ARM64) || defined(_M_ARM)
-  StackFrame.AddrPC.Offset = ep->ContextRecord->Pc;
-  StackFrame.AddrPC.Mode = AddrModeFlat;
-  StackFrame.AddrStack.Offset = ep->ContextRecord->Sp;
-  StackFrame.AddrStack.Mode = AddrModeFlat;
-#if defined(_M_ARM64)
-  StackFrame.AddrFrame.Offset = ep->ContextRecord->Fp;
-#else
-  StackFrame.AddrFrame.Offset = ep->ContextRecord->R11;
-#endif
-  StackFrame.AddrFrame.Mode = AddrModeFlat;
-#endif
-
-  HANDLE hProcess = GetCurrentProcess();
-  HANDLE hThread = GetCurrentThread();
-  PrintStackTraceForThread(llvm::errs(), hProcess, hThread, StackFrame,
-   ep->ContextRecord);
+  LocalPrintStackTrace(llvm::errs(), ep ? ep->ContextRecord : nullptr);
 
-  _exit(ep->ExceptionRecord->ExceptionCode);
+  return EXCEPTION_EXECUTE_HANDLER;
 }
 
 static BOOL WINAPI LLVMConsoleCtrlHandler(DWORD dwCtrlType) {
Index: llvm/lib/Support/Unix/Signals.inc
===
--- llvm/lib/Support/Unix/Signals.inc
+++

[PATCH] D62731: Add support for options -frounding-math, -ftrapping-math, -ffp-model=, and -ffp-exception-behavior=, : Specify floating point behavior

2019-11-11 Thread Melanie Blower via Phabricator via cfe-commits
mibintc closed this revision.
mibintc added a comment.

Don't know why the commit id didn't get linked when I pushed the change. Here's 
the closure info:

commit af57dbf12e54f3a8ff48534bf1078f4de104c1cd 

Author: Melanie Blower 
Date:   Tue Nov 5 13:41:21 2019 -0800

  Add support for options -frounding-math, ftrapping-math, -ffp-model=, and 
-ffp-exception-behavior=


Repository:
  rL LLVM

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

https://reviews.llvm.org/D62731



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


[PATCH] D70094: [clang-tidy] new altera ID dependent backward branch check

2019-11-11 Thread Frank Derry Wanye via Phabricator via cfe-commits
ffrankies updated this revision to Diff 228743.

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

https://reviews.llvm.org/D70094

Files:
  clang-tidy/CMakeLists.txt
  clang-tidy/ClangTidyForceLinker.h
  clang-tidy/altera/AlteraTidyModule.cpp
  clang-tidy/altera/CMakeLists.txt
  clang-tidy/altera/IdDependentBackwardBranchCheck.cpp
  clang-tidy/altera/IdDependentBackwardBranchCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/altera-id-dependent-backward-branch.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/index.rst
  test/clang-tidy/checkers/altera-id-dependent-backward-branch.cpp

Index: test/clang-tidy/checkers/altera-id-dependent-backward-branch.cpp
===
--- /dev/null
+++ test/clang-tidy/checkers/altera-id-dependent-backward-branch.cpp
@@ -0,0 +1,83 @@
+// RUN: %check_clang_tidy %s altera-id-dependent-backward-branch %t -- -header-filter=.* "--" -cl-std=CL1.2 -c --include opencl-c.h
+
+typedef struct ExampleStruct {
+  int IDDepField;
+} ExampleStruct;
+
+void error() {
+  //  Assignments 
+  int ThreadID = get_local_id(0); 
+// CHECK-NOTES: :[[@LINE-1]]:3: warning: assignment of ID-dependent variable ThreadID [altera-id-dependent-backward-branch]
+
+  ExampleStruct Example;
+  Example.IDDepField = get_local_id(0);
+// CHECK-NOTES: :[[@LINE-1]]:3: warning: assignment of ID-dependent field IDDepField [altera-id-dependent-backward-branch]
+
+  //  Inferred Assignments 
+  int ThreadID2 = ThreadID * get_local_size(0);
+// CHECK-NOTES: :[[@LINE-1]]:3: warning: inferred assignment of ID-dependent value from ID-dependent variable ThreadID [altera-id-dependent-backward-branch]
+  
+  int ThreadID3 = Example.IDDepField;  // OK: not used in any loops
+
+  ExampleStruct UnusedStruct = {
+ThreadID * 2  // OK: not used in any loops
+  };
+
+  //  Conditional Expressions 
+  int accumulator = 0;
+  for (int i = 0; i < get_local_id(0); i++) {
+// CHECK-NOTES: :[[@LINE-1]]:19: warning: backward branch (for loop) is ID-dependent due to ID function call and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  int j = 0;
+  while (j < get_local_id(0)) {
+// CHECK-NOTES: :[[@LINE-1]]:10: warning: backward branch (while loop) is ID-dependent due to ID function call and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  do {
+accumulator++;
+  } while (j < get_local_id(0));
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: backward branch (do loop) is ID-dependent due to ID function call and may cause performance degradation [altera-id-dependent-backward-branch]
+  
+  for (int i = 0; i < ThreadID2; i++) {
+// CHECK-NOTES: :[[@LINE-1]]:19: warning: backward branch (for loop) is ID-dependent due to variable reference to 'ThreadID2' and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  while (j < ThreadID) {
+// CHECK-NOTES: :[[@LINE-1]]:10: warning: backward branch (while loop) is ID-dependent due to variable reference to 'ThreadID' and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  do {
+accumulator++;
+  } while (j < ThreadID);
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: backward branch (do loop) is ID-dependent due to variable reference to 'ThreadID' and may cause performance degradation [altera-id-dependent-backward-branch]
+  
+  for (int i = 0; i < Example.IDDepField; i++) {
+// CHECK-NOTES: :[[@LINE-1]]:19: warning: backward branch (for loop) is ID-dependent due to member reference to 'IDDepField' and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  while (j < Example.IDDepField) {
+// CHECK-NOTES: :[[@LINE-1]]:10: warning: backward branch (while loop) is ID-dependent due to member reference to 'IDDepField' and may cause performance degradation [altera-id-dependent-backward-branch]
+accumulator++;
+  }
+
+  do {
+accumulator++;
+  } while (j < Example.IDDepField);
+  // CHECK-NOTES: :[[@LINE-1]]:12: warning: backward branch (do loop) is ID-dependent due to member reference to 'IDDepField' and may cause performance degradation [altera-id-dependent-backward-branch]
+}
+
+void success() {
+  int accumulator = 0;
+
+  for (int i = 0; i < 1000; i++) {
+if (i < get_local_id(0)) {
+  accumulator++;
+}
+  }
+}
Index: docs/clang-tidy/index.rst
===
--- docs/clang-tidy/index.rst
+++ docs/clang-tidy/index.rst
@@ -59,6 +59,7 @@
 == =
 ``abseil-``Checks related to Abseil library.
 ``android-``   Checks related to Android.
+``altera-``Checks related to OpenCL programming for FPGAs.
 ``boost-`` Checks related to Boost library.
 `

[PATCH] D69952: [OPENMP50]Generalize handling of context matching/scoring.

2019-11-11 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69952



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


[clang] f8c12ed - [OPENMP50]Add support for nested atomic and simd constructs in

2019-11-11 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2019-11-11T14:28:28-05:00
New Revision: f8c12edd1a5200a2c8da754d6a3bfa7545a0

URL: 
https://github.com/llvm/llvm-project/commit/f8c12edd1a5200a2c8da754d6a3bfa7545a0
DIFF: 
https://github.com/llvm/llvm-project/commit/f8c12edd1a5200a2c8da754d6a3bfa7545a0.diff

LOG: [OPENMP50]Add support for nested atomic and simd constructs in
simd-based directives.

According to OpenMP 5.0 standard, ordered simd, atomic and simd
directives are allowed as nested directives in the simd-based
directives.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaOpenMP.cpp
clang/test/OpenMP/nesting_of_regions.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 42df65217cbb..e5085c4ab4cc 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9312,7 +9312,7 @@ def err_omp_prohibited_region : Error<
   "; perhaps you forget to enclose 'omp %3' directive into a target region?|"
   "; perhaps you forget to enclose 'omp %3' directive into a teams region?}2">;
 def err_omp_prohibited_region_simd : Error<
-  "OpenMP constructs may not be nested inside a simd region">;
+  "OpenMP constructs may not be nested inside a simd region%select{| except 
for ordered simd, simd or atomic directive}0">;
 def err_omp_prohibited_region_atomic : Error<
   "OpenMP constructs may not be nested inside an atomic region">;
 def err_omp_prohibited_region_critical_same_name : Error<

diff  --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 7ed582f8446f..5c1b39e0b392 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -3799,7 +3799,10 @@ static bool checkNestingOfRegions(Sema &SemaRef, const 
DSAStackTy *Stack,
   ShouldBeInTargetRegion,
   ShouldBeInTeamsRegion
 } Recommend = NoRecommend;
-if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
+if (isOpenMPSimdDirective(ParentRegion) &&
+((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
+ (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
+  CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
   // OpenMP [2.16, Nesting of Regions]
   // OpenMP constructs may not be nested inside a simd region.
   // OpenMP [2.8.1,simd Construct, Restrictions]
@@ -3808,9 +3811,14 @@ static bool checkNestingOfRegions(Sema &SemaRef, const 
DSAStackTy *Stack,
   // Allowing a SIMD construct nested in another SIMD construct is an
   // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
   // message.
+  // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
+  // The only OpenMP constructs that can be encountered during execution of
+  // a simd region are the atomic construct, the loop construct, the simd
+  // construct and the ordered construct with the simd clause.
   SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  ? diag::err_omp_prohibited_region_simd
- : diag::warn_omp_nesting_simd);
+ : diag::warn_omp_nesting_simd)
+  << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
   return CurrentRegion != OMPD_simd;
 }
 if (ParentRegion == OMPD_atomic) {
@@ -8165,7 +8173,8 @@ StmtResult 
Sema::ActOnOpenMPOrderedDirective(ArrayRef Clauses,
 // OpenMP [2.8.1,simd Construct, Restrictions]
 // An ordered construct with the simd clause is the only OpenMP construct
 // that can appear in the simd region.
-Diag(StartLoc, diag::err_omp_prohibited_region_simd);
+Diag(StartLoc, diag::err_omp_prohibited_region_simd)
+<< (LangOpts.OpenMP >= 50 ? 1 : 0);
 ErrorFound = true;
   } else if (DependFound && (TC || SC)) {
 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)

diff  --git a/clang/test/OpenMP/nesting_of_regions.cpp 
b/clang/test/OpenMP/nesting_of_regions.cpp
index fc9230c6870c..9aa7814c6c75 100644
--- a/clang/test/OpenMP/nesting_of_regions.cpp
+++ b/clang/test/OpenMP/nesting_of_regions.cpp
@@ -1,6 +1,8 @@
-// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify=expected,omp45 %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=50 
-verify=expected,omp50 %s
 
-// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -verify %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -verify=expected,omp45 %s
+// RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=50 
-verify=expected,omp50 %s
 // SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
 
 void bar();
@@ -227,7 +229,7 @@ void foo() {
   }
 #pragma omp simd
   for (int i = 0; i < 10; ++i) {
-#pragma omp simd // expected-warning {{OpenMP

[clang] fde11e9 - [OPENMP50]Generalize handling of context matching/scoring.

2019-11-11 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2019-11-11T14:41:10-05:00
New Revision: fde11e9f23a3bf6c78ec0bcfa92e9759ee8b5054

URL: 
https://github.com/llvm/llvm-project/commit/fde11e9f23a3bf6c78ec0bcfa92e9759ee8b5054
DIFF: 
https://github.com/llvm/llvm-project/commit/fde11e9f23a3bf6c78ec0bcfa92e9759ee8b5054.diff

LOG: [OPENMP50]Generalize handling of context matching/scoring.

Summary:
Untie context matching/scoring from the attribute for declare variant
directive to simplify future uses in other context-dependent directives.

Reviewers: jdoerfert

Subscribers: guansong, kkwli0, caomhin, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/OpenMPKinds.def
clang/include/clang/Basic/OpenMPKinds.h
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/Basic/OpenMPKinds.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/Parse/ParseOpenMP.cpp
clang/lib/Sema/SemaOpenMP.cpp
clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 0d25e775e2af..f12ebdc126a4 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3305,24 +3305,14 @@ def OMPDeclareVariant : InheritableAttr {
   let Documentation = [OMPDeclareVariantDocs];
   let Args = [
 ExprArgument<"VariantFuncRef">,
-ExprArgument<"Score">,
-EnumArgument<"CtxSelectorSet", "CtxSelectorSetType",
- [ "", "implementation"
- ],
- [
-   "CtxSetUnknown", "CtxSetImplementation"
- ]>,
-EnumArgument<"CtxSelector", "CtxSelectorType",
- [ "", "vendor"
- ],
- [
-   "CtxUnknown", "CtxVendor"
- ]>,
+VariadicExprArgument<"Scores">,
+VariadicUnsignedArgument<"CtxSelectorSets">,
+VariadicUnsignedArgument<"CtxSelectors">,
 VariadicStringArgument<"ImplVendors">
   ];
   let AdditionalMembers = [{
-void printScore(raw_ostream & OS, const PrintingPolicy &Policy) const {
-  if (const Expr *E = getScore()) {
+void printScore(raw_ostream & OS, const PrintingPolicy &Policy, unsigned 
I) const {
+  if (const Expr *E = *std::next(scores_begin(), I)) {
 OS << "score(";
 E->printPretty(OS, nullptr, Policy);
 OS << "):";
@@ -3330,8 +3320,6 @@ def OMPDeclareVariant : InheritableAttr {
 }
 void printPrettyPragma(raw_ostream & OS, const PrintingPolicy &Policy)
 const {
-  assert(getCtxSelectorSet() != CtxSetUnknown &&
- getCtxSelector() != CtxUnknown && "Unknown context selector.");
   if (const Expr *E = getVariantFuncRef()) {
 OS << "(";
 E->printPretty(OS, nullptr, Policy);
@@ -3339,27 +3327,35 @@ def OMPDeclareVariant : InheritableAttr {
   }
   // TODO: add printing of real context selectors.
   OS << " match(";
-  switch (getCtxSelectorSet()) {
-  case CtxSetImplementation:
-OS << "implementation={";
-switch (getCtxSelector()) {
-case CtxVendor:
-  OS << "vendor(";
-  printScore(OS, Policy);
-  if (implVendors_size() > 0) {
-OS << *implVendors(). begin();
-for (StringRef VendorName : llvm::drop_begin(implVendors(), 1))
-  OS << ", " << VendorName;
+  for (unsigned I = 0, E = ctxSelectorSets_size(); I < E; ++I) {
+auto CtxSet = static_cast(
+*std::next(ctxSelectorSets_begin(), I));
+auto Ctx = static_cast(
+*std::next(ctxSelectors_begin(), I));
+assert(CtxSet != OMP_CTX_SET_unknown && Ctx != OMP_CTX_unknown &&
+   "Unknown context selector.");
+switch (CtxSet) {
+case OMP_CTX_SET_implementation:
+  OS << "implementation={";
+  switch (Ctx) {
+  case OMP_CTX_vendor:
+OS << "vendor(";
+printScore(OS, Policy, I);
+if (implVendors_size() > 0) {
+  OS << *implVendors(). begin();
+  for (StringRef VendorName : llvm::drop_begin(implVendors(), 1))
+OS << ", " << VendorName;
+}
+OS << ")";
+break;
+  case OMP_CTX_unknown:
+llvm_unreachable("Unknown context selector.");
   }
-  OS << ")";
+  OS << "}";
   break;
-case CtxUnknown:
-  llvm_unreachable("Unknown context selector.");
+case OMP_CTX_SET_unknown:
+  llvm_unreachable("Unknown context selector set.");
 }
-OS << "}";
-break;
-  case CtxSetUnknown:
-llvm_unreachable("Unknown context selector set.");
   }
   OS << ")";
 }

diff  --git a/clang/include/clan

[PATCH] D69952: [OPENMP50]Generalize handling of context matching/scoring.

2019-11-11 Thread Alexey Bataev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGfde11e9f23a3: [OPENMP50]Generalize handling of context 
matching/scoring. (authored by ABataev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69952

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/OpenMPKinds.def
  clang/include/clang/Basic/OpenMPKinds.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -388,22 +388,36 @@
   if (Expr *E = Attr.getVariantFuncRef())
 VariantFuncRef = Subst(E);
 
-  ExprResult Score;
-  if (Expr *E = Attr.getScore())
-Score = Subst(E);
-
   // Check function/variant ref.
   Optional> DeclVarData =
   S.checkOpenMPDeclareVariantFunction(
   S.ConvertDeclToDeclGroup(New), VariantFuncRef.get(), Attr.getRange());
   if (!DeclVarData)
 return;
-  // Instantiate the attribute.
-  Sema::OpenMPDeclareVariantCtsSelectorData Data(
-  Attr.getCtxSelectorSet(), Attr.getCtxSelector(),
-  llvm::makeMutableArrayRef(Attr.implVendors_begin(),
-Attr.implVendors_size()),
-  Score);
+  SmallVector Data;
+  for (unsigned I = 0, E = Attr.scores_size(); I < E; ++I) {
+ExprResult Score;
+if (Expr *E = *std::next(Attr.scores_begin(), I))
+  Score = Subst(E);
+// Instantiate the attribute.
+auto CtxSet = static_cast(
+*std::next(Attr.ctxSelectorSets_begin(), I));
+auto Ctx = static_cast(
+*std::next(Attr.ctxSelectors_begin(), I));
+switch (CtxSet) {
+case OMP_CTX_SET_implementation:
+  switch (Ctx) {
+  case OMP_CTX_vendor:
+Data.emplace_back(CtxSet, Ctx, Score, Attr.implVendors());
+break;
+  case OMP_CTX_unknown:
+llvm_unreachable("Unexpected context selector kind.");
+  }
+  break;
+case OMP_CTX_SET_unknown:
+  llvm_unreachable("Unexpected context selector set kind.");
+}
+  }
   S.ActOnOpenMPDeclareVariantDirective(DeclVarData.getValue().first,
DeclVarData.getValue().second,
Attr.getRange(), Data);
Index: clang/lib/Sema/SemaOpenMP.cpp
===
--- clang/lib/Sema/SemaOpenMP.cpp
+++ clang/lib/Sema/SemaOpenMP.cpp
@@ -5200,28 +5200,59 @@
 
 void Sema::ActOnOpenMPDeclareVariantDirective(
 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
-const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
-  if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
-  Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
+ArrayRef Data) {
+  if (Data.empty())
 return;
-  Expr *Score = nullptr;
-  if (Data.CtxScore.isUsable()) {
-Score = Data.CtxScore.get();
-if (!Score->isTypeDependent() && !Score->isValueDependent() &&
-!Score->isInstantiationDependent() &&
-!Score->containsUnexpandedParameterPack()) {
-  llvm::APSInt Result;
-  ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
-  if (ICE.isInvalid())
-return;
+  SmallVector CtxScores;
+  SmallVector CtxSets;
+  SmallVector Ctxs;
+  SmallVector ImplVendors;
+  bool IsError = false;
+  for (const OMPCtxSelectorData &D : Data) {
+OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
+OpenMPContextSelectorKind Ctx = D.Ctx;
+if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
+  return;
+Expr *Score = nullptr;
+if (D.Score.isUsable()) {
+  Score = D.Score.get();
+  if (!Score->isTypeDependent() && !Score->isValueDependent() &&
+  !Score->isInstantiationDependent() &&
+  !Score->containsUnexpandedParameterPack()) {
+Score =
+PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
+.get();
+if (Score)
+  Score = VerifyIntegerConstantExpression(Score).get();
+  }
+} else {
+  Score = ActOnIntegerConstant(SourceLocation(), 0).get();
 }
-  } else {
-Score = ActOnIntegerConstant(SourceLocation(), 0).get();
+switch (CtxSet) {
+case OMP_CTX_SET_implementation:
+  switch (Ctx) {
+  case OMP_CTX_vendor:
+ImplVendors.append(D.Names.begin(), D.Names.end());
+break;
+  case OMP_CTX_unknown:
+llvm_unreachable("Unexpected context selector kind.");
+  }
+  break;
+case OMP_CTX_SET_unknown:
+  llvm_unreachable("Unexpected context selector set kind.");
+}
+IsError = IsError || 

[PATCH] D69785: [OpenMP] Introduce the OpenMP-IR-Builder

2019-11-11 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 228754.
jdoerfert marked an inline comment as done.
jdoerfert added a comment.

Make attributes opt-in


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69785

Files:
  llvm/include/llvm/IR/OpenMPConstants.h
  llvm/include/llvm/IR/OpenMPIRBuilder.h
  llvm/include/llvm/IR/OpenMPKinds.def
  llvm/lib/IR/CMakeLists.txt
  llvm/lib/IR/OpenMPConstants.cpp
  llvm/lib/IR/OpenMPIRBuilder.cpp
  llvm/unittests/IR/CMakeLists.txt
  llvm/unittests/IR/IRBuilderTest.cpp
  llvm/unittests/IR/OpenMPIRBuilderTest.cpp

Index: llvm/unittests/IR/OpenMPIRBuilderTest.cpp
===
--- /dev/null
+++ llvm/unittests/IR/OpenMPIRBuilderTest.cpp
@@ -0,0 +1,133 @@
+//===- llvm/unittest/IR/OpenMPIRBuilderTest.cpp - OpenMPIRBuilder tests ---===//
+//
+// 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 "llvm/IR/OpenMPIRBuilder.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/DIBuilder.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/OpenMPConstants.h"
+#include "llvm/IR/Verifier.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace omp;
+using namespace types;
+
+namespace {
+
+class OpenMPIRBuilderTest : public testing::Test {
+protected:
+  void SetUp() override {
+M.reset(new Module("MyModule", Ctx));
+FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx),
+  /*isVarArg=*/false);
+F = Function::Create(FTy, Function::ExternalLinkage, "", M.get());
+BB = BasicBlock::Create(Ctx, "", F);
+  }
+
+  void TearDown() override {
+BB = nullptr;
+M.reset();
+uninitializeTypes();
+  }
+
+  LLVMContext Ctx;
+  std::unique_ptr M;
+  Function *F;
+  BasicBlock *BB;
+};
+
+TEST_F(OpenMPIRBuilderTest, CreateBarrier) {
+  OpenMPIRBuilder OMPBuilder(*M);
+  OMPBuilder.initialize();
+
+  IRBuilder<> Builder(BB);
+
+  OMPBuilder.CreateBarrier({IRBuilder<>::InsertPoint()}, OMPD_for);
+  EXPECT_TRUE(M->global_empty());
+  EXPECT_EQ(M->size(), 1U);
+  EXPECT_EQ(F->size(), 1U);
+  EXPECT_EQ(BB->size(), 0U);
+
+  OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP()});
+  OMPBuilder.CreateBarrier(Loc, OMPD_for);
+  EXPECT_FALSE(M->global_empty());
+  EXPECT_EQ(M->size(), 3U);
+  EXPECT_EQ(F->size(), 1U);
+  EXPECT_EQ(BB->size(), 2U);
+
+  CallInst *GTID = dyn_cast(&BB->front());
+  EXPECT_NE(GTID, nullptr);
+  EXPECT_EQ(GTID->getNumArgOperands(), 1U);
+  EXPECT_EQ(GTID->getCalledFunction()->getName(), "__kmpc_global_thread_num");
+  EXPECT_FALSE(GTID->getCalledFunction()->doesNotAccessMemory());
+  EXPECT_FALSE(GTID->getCalledFunction()->doesNotFreeMemory());
+
+  CallInst *Barrier = dyn_cast(GTID->getNextNode());
+  EXPECT_NE(Barrier, nullptr);
+  EXPECT_EQ(Barrier->getNumArgOperands(), 2U);
+  EXPECT_EQ(Barrier->getCalledFunction()->getName(), "__kmpc_barrier");
+  EXPECT_FALSE(Barrier->getCalledFunction()->doesNotAccessMemory());
+  EXPECT_FALSE(Barrier->getCalledFunction()->doesNotFreeMemory());
+
+  EXPECT_EQ(cast(Barrier)->getArgOperand(1), GTID);
+
+  Builder.CreateUnreachable();
+  EXPECT_FALSE(verifyModule(*M));
+}
+
+TEST_F(OpenMPIRBuilderTest, DbgLoc) {
+  OpenMPIRBuilder OMPBuilder(*M);
+  OMPBuilder.initialize();
+  F->setName("func");
+
+  IRBuilder<> Builder(BB);
+
+  DIBuilder DIB(*M);
+  auto File = DIB.createFile("test.dbg", "/");
+  auto CU =
+  DIB.createCompileUnit(dwarf::DW_LANG_C, File, "llvm-C", true, "", 0);
+  auto Type = DIB.createSubroutineType(DIB.getOrCreateTypeArray(None));
+  auto SP = DIB.createFunction(
+  CU, "foo", "", File, 1, Type, 1, DINode::FlagZero,
+  DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
+  F->setSubprogram(SP);
+  auto Scope = DIB.createLexicalBlockFile(SP, File, 0);
+  DIB.finalize();
+
+  DebugLoc DL = DebugLoc::get(3, 7, Scope);
+  OpenMPIRBuilder::LocationDescription Loc({Builder.saveIP(), DL});
+  OMPBuilder.CreateBarrier(Loc, OMPD_for);
+  CallInst *GTID = dyn_cast(&BB->front());
+  CallInst *Barrier = dyn_cast(GTID->getNextNode());
+  EXPECT_EQ(GTID->getDebugLoc(), DL);
+  EXPECT_EQ(Barrier->getDebugLoc(), DL);
+  EXPECT_TRUE(isa(Barrier->getOperand(0)));
+  if (!isa(Barrier->getOperand(0)))
+return;
+  GlobalVariable *Ident = cast(Barrier->getOperand(0));
+  EXPECT_TRUE(Ident->hasInitializer());
+  if (!Ident->hasInitializer())
+return;
+  Constant *Initializer = Ident->getInitializer();
+  EXPECT_TRUE(
+  isa(Initializer->getOperand(4)->stripPointerCasts()));
+  GlobalVariable *SrcStrGlob =
+  cast(Initializer->getOperand(4)->stripPointerCasts());
+  if (!SrcStrGlob)
+  

[PATCH] D69935: [DeclCXX] Remove unknown external linkage specifications

2019-11-11 Thread Ehud Katz via Phabricator via cfe-commits
ekatz updated this revision to Diff 228755.
ekatz added a comment.

Removed DWARF reference from LinkageSpecDecl::LanguageIDs.


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

https://reviews.llvm.org/D69935

Files:
  clang/include/clang/AST/DeclCXX.h
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/JSONNodeDumper.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaModule.cpp

Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -31,8 +31,6 @@
 ExternCLoc = LSD->getBeginLoc();
   break;
 case LinkageSpecDecl::lang_cxx:
-case LinkageSpecDecl::lang_cxx_11:
-case LinkageSpecDecl::lang_cxx_14:
   break;
 }
 DC = LSD->getParent();
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -14205,10 +14205,6 @@
 Language = LinkageSpecDecl::lang_c;
   else if (Lang == "C++")
 Language = LinkageSpecDecl::lang_cxx;
-  else if (Lang == "C++11")
-Language = LinkageSpecDecl::lang_cxx_11;
-  else if (Lang == "C++14")
-Language = LinkageSpecDecl::lang_cxx_14;
   else {
 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
   << LangStr->getSourceRange();
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -5191,9 +5191,7 @@
 // EmitLinkageSpec - Emit all declarations in a linkage spec.
 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
-  LSD->getLanguage() != LinkageSpecDecl::lang_cxx &&
-  LSD->getLanguage() != LinkageSpecDecl::lang_cxx_11 &&
-  LSD->getLanguage() != LinkageSpecDecl::lang_cxx_14) {
+  LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
 ErrorUnsupported(LSD, "linkage spec");
 return;
   }
Index: clang/lib/AST/TextNodeDumper.cpp
===
--- clang/lib/AST/TextNodeDumper.cpp
+++ clang/lib/AST/TextNodeDumper.cpp
@@ -1769,12 +1769,6 @@
   case LinkageSpecDecl::lang_cxx:
 OS << " C++";
 break;
-  case LinkageSpecDecl::lang_cxx_11:
-OS << " C++11";
-break;
-  case LinkageSpecDecl::lang_cxx_14:
-OS << " C++14";
-break;
   }
 }
 
Index: clang/lib/AST/JSONNodeDumper.cpp
===
--- clang/lib/AST/JSONNodeDumper.cpp
+++ clang/lib/AST/JSONNodeDumper.cpp
@@ -874,12 +874,6 @@
   switch (LSD->getLanguage()) {
   case LinkageSpecDecl::lang_c: Lang = "C"; break;
   case LinkageSpecDecl::lang_cxx: Lang = "C++"; break;
-  case LinkageSpecDecl::lang_cxx_11:
-Lang = "C++11";
-break;
-  case LinkageSpecDecl::lang_cxx_14:
-Lang = "C++14";
-break;
   }
   JOS.attribute("language", Lang);
   attributeOnlyIfTrue("hasBraces", LSD->hasBraces());
Index: clang/lib/AST/DeclPrinter.cpp
===
--- clang/lib/AST/DeclPrinter.cpp
+++ clang/lib/AST/DeclPrinter.cpp
@@ -1001,19 +1001,12 @@
 
 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
   const char *l;
-  switch (D->getLanguage()) {
-  case LinkageSpecDecl::lang_c:
+  if (D->getLanguage() == LinkageSpecDecl::lang_c)
 l = "C";
-break;
-  case LinkageSpecDecl::lang_cxx_14:
-l = "C++14";
-break;
-  case LinkageSpecDecl::lang_cxx_11:
-l = "C++11";
-break;
-  case LinkageSpecDecl::lang_cxx:
+  else {
+assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
+   "unknown language in linkage specification");
 l = "C++";
-break;
   }
 
   Out << "extern \"" << l << "\" ";
Index: clang/include/clang/AST/DeclCXX.h
===
--- clang/include/clang/AST/DeclCXX.h
+++ clang/include/clang/AST/DeclCXX.h
@@ -42,7 +42,6 @@
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/iterator_range.h"
-#include "llvm/BinaryFormat/Dwarf.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/PointerLikeTypeTraits.h"
@@ -2758,15 +2757,8 @@
   /// Represents the language in a linkage specification.
   ///
   /// The values are part of the serialization ABI for
-  /// ASTs and cannot be changed without altering that ABI.  To help
-  /// ensure a stable ABI for this, we choose the DW_LANG_ encodings
-  /// from the dwarf standard.
-  enum LanguageIDs {
-lang_c = llvm::dwarf::DW_LANG_C,
-lang_cxx = llvm::dwarf::DW_LANG_C_plus_plus,
-lang_cxx_11 = llvm::dwarf::DW_LANG_C_plus_plus_11,
-lang_cxx_14 = llvm::dwarf::DW_LANG_C_plus_plus_14
-  };
+  /// ASTs and c

[PATCH] D70052: [clang-tidy] Add misc-mutating-copy check

2019-11-11 Thread Gabor Bencze via Phabricator via cfe-commits
gbencze added a comment.

In D70052#1740235 , @Eugene.Zelenko 
wrote:

> If this is CERT rule, why check is not placed in relevant module?


To be honest I was hoping for some feedback on this as I wasn't sure what the 
best place for this check would be. Quite a few CERT rules seem to be 
implemented in other modules and have cert aliases. 
Do you think this check should be moved there or should I just add an alias?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D70052



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


[PATCH] D69770: Add recoverable string parsing errors to APFloat

2019-11-11 Thread Ehud Katz via Phabricator via cfe-commits
ekatz added a comment.

Ping


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

https://reviews.llvm.org/D69770



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


[PATCH] D70052: [clang-tidy] Add misc-mutating-copy check

2019-11-11 Thread Gabor Bencze via Phabricator via cfe-commits
gbencze updated this revision to Diff 228758.
gbencze added a comment.

Update documentation and release notes.


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

https://reviews.llvm.org/D70052

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/clang-tidy/misc/MutatingCopyCheck.cpp
  clang-tools-extra/clang-tidy/misc/MutatingCopyCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc-mutating-copy.rst
  clang-tools-extra/test/clang-tidy/misc-mutating-copy.cpp

Index: clang-tools-extra/test/clang-tidy/misc-mutating-copy.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/misc-mutating-copy.cpp
@@ -0,0 +1,107 @@
+// RUN: %check_clang_tidy %s misc-mutating-copy %t -std=c++11-or-later
+
+// Example test cases from CERT rule
+// https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP58-CPP.+Copy+operations+must+not+mutate+the+source+object
+namespace test_mutating_noncompliant_example {
+class A {
+  mutable int m;
+
+public:
+  A() : m(0) {}
+  explicit A(int m) : m(m) {}
+
+  A(const A &other) : m(other.m) {
+other.m = 0;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+  }
+
+  A &operator=(const A &other) {
+if (&other != this) {
+  m = other.m;
+  other.m = 0;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: mutating copied object
+}
+return *this;
+  }
+
+  int get_m() const { return m; }
+};
+} // namespace test_mutating_noncompliant_example
+
+namespace test_mutating_compliant_example {
+class B {
+  int m;
+
+public:
+  B() : m(0) {}
+  explicit B(int m) : m(m) {}
+
+  B(const B &other) : m(other.m) {}
+  B(B &&other) : m(other.m) {
+other.m = 0; //no-warning: mutation allowed in move constructor
+  }
+
+  B &operator=(const B &other) {
+if (&other != this) {
+  m = other.m;
+}
+return *this;
+  }
+
+  B &operator=(B &&other) {
+m = other.m;
+other.m = 0; //no-warning: mutation allowed in move assignment operator
+return *this;
+  }
+
+  int get_m() const { return m; }
+};
+} // namespace test_mutating_compliant_example
+
+namespace test_mutating_pointer {
+class C {
+  C *ptr;
+  int value;
+
+  C();
+  C(C &other) {
+other = {};
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+other.ptr = nullptr;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+other.value = 0;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+
+// no-warning: mutating a pointee is allowed
+other.ptr->value = 0;
+*other.ptr = {};
+  }
+};
+} // namespace test_mutating_pointer
+
+namespace test_mutating_indirect_member {
+struct S {
+  int x;
+};
+
+class D {
+  S s;
+  D(D &other) {
+other.s = {};
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+other.s.x = 0;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: mutating copied object
+  }
+};
+} // namespace test_mutating_indirect_member
+
+namespace test_mutating_other_object {
+class E {
+  E();
+  E(E &other) {
+E tmp;
+// no-warning: mutating an object that is not the source is allowed
+tmp = {};
+  }
+};
+} // namespace test_mutating_other_object
Index: clang-tools-extra/docs/clang-tidy/checks/misc-mutating-copy.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/misc-mutating-copy.rst
@@ -0,0 +1,11 @@
+.. title:: clang-tidy - misc-mutating-copy
+
+misc-mutating-copy
+==
+
+Finds assignments to the copied object and its direct or indirect members
+in copy constructors and copy assignment operators.
+
+This check corresponds to the CERT C Coding Standard rule
+`OOP58-CPP. Copy operations must not mutate the source object
+`_.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -283,6 +283,7 @@
llvm-twine-local
misc-definitions-in-headers
misc-misplaced-const
+   misc-mutating-copy
misc-new-delete-overloads
misc-non-copyable-objects
misc-non-private-member-variables-in-classes
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -120,6 +120,12 @@
   Finds historical use of ``unsigned`` to hold vregs and physregs and rewrites
   them to use ``Register``
 
+- New :doc:`misc-mutating-copy
+  ` check.
+
+  Finds assignments to the copied object 

[PATCH] D69935: [DeclCXX] Remove unknown external linkage specifications

2019-11-11 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D69935#1739235 , @dblaikie wrote:

> In D69935#1738273 , @uabelho wrote:
>
> > Don't you need to also remove
> >
> >   case LinkageSpecDecl::lang_cxx_11:
> >   case LinkageSpecDecl::lang_cxx_14:
> >   
> >
> > from VisitLinkageSpecDecl in clang-tools-extra/modularize/Modularize.cpp? 
> > (added in r372714 / e07376a320d to silence a clang warning).
> >  I can't see how that code would compile otherwise?
>
>
> +1 to this & then it seems fine (probably without a committed test, but I 
> wouldn't mind a copy/paste of clang's behavior before/after this patch posted 
> to this review to demonstrate what is being fixed)


Waiting on this bit.


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

https://reviews.llvm.org/D69935



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


[clang] 152e83f - clang-format: fix a typo introduced by the previous change

2019-11-11 Thread Sylvestre Ledru via cfe-commits

Author: Sylvestre Ledru
Date: 2019-11-11T21:52:08+01:00
New Revision: 152e83fc59af7d255df10c0f56c8fbb14dc1dea2

URL: 
https://github.com/llvm/llvm-project/commit/152e83fc59af7d255df10c0f56c8fbb14dc1dea2
DIFF: 
https://github.com/llvm/llvm-project/commit/152e83fc59af7d255df10c0f56c8fbb14dc1dea2.diff

LOG: clang-format: fix a typo introduced by the previous change

Added: 


Modified: 
clang/docs/ClangFormat.rst

Removed: 




diff  --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index 73dbe509efbe..7fe050ec9e29 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -83,7 +83,7 @@ to format C/C++/Java/JavaScript/Objective-C/Protobuf/C# code.
   Generic Options:
 
 --help - Display available options (--help-hidden for 
more)
---help-list- Display list of available options 
(--help-list-hidden for moOAre)
+--help-list- Display list of available options 
(--help-list-hidden for more)
 --version  - Display the version of this program
 
 



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


  1   2   >