[PATCH] D42895: [libclang] Add `CXSymbolRole role` to CXIdxEntityRefInfo

2018-02-05 Thread Ivan Donchevskii via Phabricator via cfe-commits
yvvan added a comment.

I feel quite ok about this patch.

Can you please add unit-tests?


Repository:
  rC Clang

https://reviews.llvm.org/D42895



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


[PATCH] D42947: Support special acronyms inside property names and allow plural forms

2018-02-05 Thread Yan Zhang via Phabricator via cfe-commits
Wizard updated this revision to Diff 132938.
Wizard added a comment.

resolve conflict in doc


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42947

Files:
  clang-tidy/objc/PropertyDeclarationCheck.cpp
  test/clang-tidy/objc-property-declaration.m


Index: test/clang-tidy/objc-property-declaration.m
===
--- test/clang-tidy/objc-property-declaration.m
+++ test/clang-tidy/objc-property-declaration.m
@@ -14,6 +14,7 @@
 @property(strong, nonatomic) UIViewController *notificationsVC;
 @property(strong, nonatomic) NSString *URL_string;
 // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: property name 'URL_string' not 
using lowerCamelCase style or not prefixed in a category, according to the 
Apple Coding Guidelines [objc-property-declaration]
+@property(strong, nonatomic) NSString *supportURLsCamelCase;
 @end
 
 @interface Foo (Bar)
Index: clang-tidy/objc/PropertyDeclarationCheck.cpp
===
--- clang-tidy/objc/PropertyDeclarationCheck.cpp
+++ clang-tidy/objc/PropertyDeclarationCheck.cpp
@@ -12,8 +12,8 @@
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "llvm/ADT/STLExtras.h"
 #include "clang/Basic/CharInfo.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Regex.h"
 
@@ -118,6 +118,15 @@
   return FixItHint();
 }
 
+std::string AcronymsGroupRegex(llvm::ArrayRef EscapedAcronyms,
+   bool SupportPlural) {
+  std::string Spliter = SupportPlural ? "s?|" : "|";
+  std::string RegexEnd = SupportPlural ? "s?)" : ")";
+  return "(" +
+ llvm::join(EscapedAcronyms.begin(), EscapedAcronyms.end(), Spliter) +
+ RegexEnd;
+}
+
 std::string validPropertyNameRegex(llvm::ArrayRef EscapedAcronyms,
bool UsedInMatcher) {
   // Allow any of these names:
@@ -130,11 +139,9 @@
   // bundleID
   std::string StartMatcher = UsedInMatcher ? "::" : "^";
 
-  return StartMatcher + "((" +
- llvm::join(EscapedAcronyms.begin(), EscapedAcronyms.end(), "|") +
- ")[A-Z]?)?[a-z]+[a-z0-9]*([A-Z][a-z0-9]+)*" + "(" +
- llvm::join(EscapedAcronyms.begin(), EscapedAcronyms.end(), "|") +
- ")?$";
+  return StartMatcher + "(" + AcronymsGroupRegex(EscapedAcronyms, false) +
+ "[A-Z]?)?[a-z]+[a-z0-9]*(" +
+ AcronymsGroupRegex(EscapedAcronyms, true) + "|([A-Z][a-z0-9]+))*$";
 }
 
 bool hasCategoryPropertyPrefix(llvm::StringRef PropertyName) {


Index: test/clang-tidy/objc-property-declaration.m
===
--- test/clang-tidy/objc-property-declaration.m
+++ test/clang-tidy/objc-property-declaration.m
@@ -14,6 +14,7 @@
 @property(strong, nonatomic) UIViewController *notificationsVC;
 @property(strong, nonatomic) NSString *URL_string;
 // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: property name 'URL_string' not using lowerCamelCase style or not prefixed in a category, according to the Apple Coding Guidelines [objc-property-declaration]
+@property(strong, nonatomic) NSString *supportURLsCamelCase;
 @end
 
 @interface Foo (Bar)
Index: clang-tidy/objc/PropertyDeclarationCheck.cpp
===
--- clang-tidy/objc/PropertyDeclarationCheck.cpp
+++ clang-tidy/objc/PropertyDeclarationCheck.cpp
@@ -12,8 +12,8 @@
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "llvm/ADT/STLExtras.h"
 #include "clang/Basic/CharInfo.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Regex.h"
 
@@ -118,6 +118,15 @@
   return FixItHint();
 }
 
+std::string AcronymsGroupRegex(llvm::ArrayRef EscapedAcronyms,
+   bool SupportPlural) {
+  std::string Spliter = SupportPlural ? "s?|" : "|";
+  std::string RegexEnd = SupportPlural ? "s?)" : ")";
+  return "(" +
+ llvm::join(EscapedAcronyms.begin(), EscapedAcronyms.end(), Spliter) +
+ RegexEnd;
+}
+
 std::string validPropertyNameRegex(llvm::ArrayRef EscapedAcronyms,
bool UsedInMatcher) {
   // Allow any of these names:
@@ -130,11 +139,9 @@
   // bundleID
   std::string StartMatcher = UsedInMatcher ? "::" : "^";
 
-  return StartMatcher + "((" +
- llvm::join(EscapedAcronyms.begin(), EscapedAcronyms.end(), "|") +
- ")[A-Z]?)?[a-z]+[a-z0-9]*([A-Z][a-z0-9]+)*" + "(" +
- llvm::join(EscapedAcronyms.begin(), EscapedAcronyms.end(), "|") +
- ")?$";
+  return StartMatcher + "(" + AcronymsGroupRegex(EscapedAcronyms, false) +
+ "[A-Z]?)?[a-z]+[a-z0-9]*(" +
+ AcronymsGroupRegex(EscapedAcronyms, true) + "|([A-Z][a-z0-9]+))*$";
 }
 
 bool hasCategoryPropertyPrefix(llvm::StringRef PropertyName) {

[PATCH] D42947: Support special acronyms inside property names and allow plural forms

2018-02-05 Thread Yan Zhang via Phabricator via cfe-commits
Wizard created this revision.
Herald added subscribers: cfe-commits, klimek.

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42947

Files:
  clang-tidy/objc/PropertyDeclarationCheck.cpp
  docs/clang-tidy/checks/objc-property-declaration.rst
  test/clang-tidy/objc-property-declaration.m


Index: test/clang-tidy/objc-property-declaration.m
===
--- test/clang-tidy/objc-property-declaration.m
+++ test/clang-tidy/objc-property-declaration.m
@@ -14,6 +14,7 @@
 @property(strong, nonatomic) UIViewController *notificationsVC;
 @property(strong, nonatomic) NSString *URL_string;
 // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: property name 'URL_string' not 
using lowerCamelCase style or not prefixed in a category, according to the 
Apple Coding Guidelines [objc-property-declaration]
+@property(strong, nonatomic) NSString *supportURLsCamelCase;
 @end
 
 @interface Foo (Bar)
Index: docs/clang-tidy/checks/objc-property-declaration.rst
===
--- docs/clang-tidy/checks/objc-property-declaration.rst
+++ docs/clang-tidy/checks/objc-property-declaration.rst
@@ -36,8 +36,12 @@
 lowercase letters followed by a '_' to avoid naming conflict. For example:
 
 .. code-block:: objc
+<<< HEAD
+@property(nonatomic, assign) int abc_lowerCamelCase;
+===
 
@property(nonatomic, assign) int abc_lowerCamelCase;
+>>> d0b498636947064abd7c3ea08e728cf668b54e14
 
 The corresponding style rule: 
https://developer.apple.com/library/content/qa/qa1908/_index.html
 
Index: clang-tidy/objc/PropertyDeclarationCheck.cpp
===
--- clang-tidy/objc/PropertyDeclarationCheck.cpp
+++ clang-tidy/objc/PropertyDeclarationCheck.cpp
@@ -12,8 +12,8 @@
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "llvm/ADT/STLExtras.h"
 #include "clang/Basic/CharInfo.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Regex.h"
 
@@ -118,6 +118,15 @@
   return FixItHint();
 }
 
+std::string AcronymsGroupRegex(llvm::ArrayRef EscapedAcronyms,
+   bool SupportPlural) {
+  std::string Spliter = SupportPlural ? "s?|" : "|";
+  std::string RegexEnd = SupportPlural ? "s?)" : ")";
+  return "(" +
+ llvm::join(EscapedAcronyms.begin(), EscapedAcronyms.end(), Spliter) +
+ RegexEnd;
+}
+
 std::string validPropertyNameRegex(llvm::ArrayRef EscapedAcronyms,
bool UsedInMatcher) {
   // Allow any of these names:
@@ -130,11 +139,9 @@
   // bundleID
   std::string StartMatcher = UsedInMatcher ? "::" : "^";
 
-  return StartMatcher + "((" +
- llvm::join(EscapedAcronyms.begin(), EscapedAcronyms.end(), "|") +
- ")[A-Z]?)?[a-z]+[a-z0-9]*([A-Z][a-z0-9]+)*" + "(" +
- llvm::join(EscapedAcronyms.begin(), EscapedAcronyms.end(), "|") +
- ")?$";
+  return StartMatcher + "(" + AcronymsGroupRegex(EscapedAcronyms, false) +
+ "[A-Z]?)?[a-z]+[a-z0-9]*(" +
+ AcronymsGroupRegex(EscapedAcronyms, true) + "|([A-Z][a-z0-9]+))*$";
 }
 
 bool hasCategoryPropertyPrefix(llvm::StringRef PropertyName) {


Index: test/clang-tidy/objc-property-declaration.m
===
--- test/clang-tidy/objc-property-declaration.m
+++ test/clang-tidy/objc-property-declaration.m
@@ -14,6 +14,7 @@
 @property(strong, nonatomic) UIViewController *notificationsVC;
 @property(strong, nonatomic) NSString *URL_string;
 // CHECK-MESSAGES: :[[@LINE-1]]:40: warning: property name 'URL_string' not using lowerCamelCase style or not prefixed in a category, according to the Apple Coding Guidelines [objc-property-declaration]
+@property(strong, nonatomic) NSString *supportURLsCamelCase;
 @end
 
 @interface Foo (Bar)
Index: docs/clang-tidy/checks/objc-property-declaration.rst
===
--- docs/clang-tidy/checks/objc-property-declaration.rst
+++ docs/clang-tidy/checks/objc-property-declaration.rst
@@ -36,8 +36,12 @@
 lowercase letters followed by a '_' to avoid naming conflict. For example:
 
 .. code-block:: objc
+<<< HEAD
+@property(nonatomic, assign) int abc_lowerCamelCase;
+===
 
@property(nonatomic, assign) int abc_lowerCamelCase;
+>>> d0b498636947064abd7c3ea08e728cf668b54e14
 
 The corresponding style rule: https://developer.apple.com/library/content/qa/qa1908/_index.html
 
Index: clang-tidy/objc/PropertyDeclarationCheck.cpp
===
--- clang-tidy/objc/PropertyDeclarationCheck.cpp
+++ clang-tidy/objc/PropertyDeclarationCheck.cpp
@@ -12,8 +12,8 @@
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "llvm/ADT/STLExtras.h"
 #include 

[PATCH] D42945: [libc++] Fix misleading indentation.

2018-02-05 Thread Bruce Mitchener via Phabricator via cfe-commits
brucem created this revision.
Herald added a reviewer: EricWF.

This was picked up via clang-tidy's readability-misleading-indentation
check.


Repository:
  rCXX libc++

https://reviews.llvm.org/D42945

Files:
  include/__string
  include/algorithm


Index: include/algorithm
===
--- include/algorithm
+++ include/algorithm
@@ -4705,7 +4705,7 @@
 case 2:
__destruct_n __d(0);
 unique_ptr __h2(__first2, __d);
- if (__comp(*--__last1, *__first1))
+if (__comp(*--__last1, *__first1))
 {
 ::new(__first2) value_type(_VSTD::move(*__last1));
 __d.__incr((value_type*)0);
Index: include/__string
===
--- include/__string
+++ include/__string
@@ -374,7 +374,7 @@
 if (__n == 0)
 return NULL;
 #if __has_feature(cxx_constexpr_string_builtins)
-return __builtin_wmemchr(__s, __a, __n);
+return __builtin_wmemchr(__s, __a, __n);
 #elif _LIBCPP_STD_VER <= 14
 return wmemchr(__s, __a, __n);
 #else


Index: include/algorithm
===
--- include/algorithm
+++ include/algorithm
@@ -4705,7 +4705,7 @@
 case 2:
__destruct_n __d(0);
 unique_ptr __h2(__first2, __d);
- if (__comp(*--__last1, *__first1))
+if (__comp(*--__last1, *__first1))
 {
 ::new(__first2) value_type(_VSTD::move(*__last1));
 __d.__incr((value_type*)0);
Index: include/__string
===
--- include/__string
+++ include/__string
@@ -374,7 +374,7 @@
 if (__n == 0)
 return NULL;
 #if __has_feature(cxx_constexpr_string_builtins)
-return __builtin_wmemchr(__s, __a, __n);
+return __builtin_wmemchr(__s, __a, __n);
 #elif _LIBCPP_STD_VER <= 14
 return wmemchr(__s, __a, __n);
 #else
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] r324312 - No, really this time mark 3034 as 'Patch Ready'

2018-02-05 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Mon Feb  5 19:24:21 2018
New Revision: 324312

URL: http://llvm.org/viewvc/llvm-project?rev=324312=rev
Log:
No, really this time mark 3034 as 'Patch Ready'

Modified:
libcxx/trunk/www/upcoming_meeting.html

Modified: libcxx/trunk/www/upcoming_meeting.html
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/www/upcoming_meeting.html?rev=324312=324311=324312=diff
==
--- libcxx/trunk/www/upcoming_meeting.html (original)
+++ libcxx/trunk/www/upcoming_meeting.html Mon Feb  5 19:24:21 2018
@@ -82,7 +82,7 @@
 https://wg21.link/LWG3020;>3020[networking.ts] 
Remove spurious nested value_type buffer sequence 
requirementJacksonville
 https://wg21.link/LWG3026;>3026filesystem::weakly_canonical
 still defined in terms of canonical(p, 
base)Jacksonville
 https://wg21.link/LWG3030;>3030Who shall meet 
the requirements of try_lock?JacksonvilleNothing 
to do
-https://wg21.link/LWG3034;>3034P0767R1 breaks 
previously-standard-layout typesJacksonville
+https://wg21.link/LWG3034;>3034P0767R1 breaks 
previously-standard-layout typesJacksonvillePatch 
Ready
 https://wg21.link/LWG3035;>3035std::allocator's 
constructors should be constexprJacksonvillePatch 
Ready
 https://wg21.link/LWG3039;>3039Unnecessary 
decay in thread and 
packaged_taskJacksonvillePatch Ready
 https://wg21.link/LWG3041;>3041Unnecessary 
decay in 
reference_wrapperJacksonvillePatch 
Ready
@@ -130,7 +130,7 @@
  3020 - No networking TS implementation yet
  3026 - I think this is just wording cleanup - Eric?
  3030 - Wording changes only
- 3034 - Need to check if our tests are correct.
+ 3034 - Patch Ready
  3035 - Patch Ready
  3039 - Patch Ready
  3041 - Patch Ready


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


[libcxx] r324310 - Mark issue 3034 as 'Patch Ready'

2018-02-05 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Mon Feb  5 19:23:16 2018
New Revision: 324310

URL: http://llvm.org/viewvc/llvm-project?rev=324310=rev
Log:
Mark issue 3034 as 'Patch Ready'

Modified:
libcxx/trunk/www/upcoming_meeting.html

Modified: libcxx/trunk/www/upcoming_meeting.html
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/www/upcoming_meeting.html?rev=324310=324309=324310=diff
==
--- libcxx/trunk/www/upcoming_meeting.html (original)
+++ libcxx/trunk/www/upcoming_meeting.html Mon Feb  5 19:23:16 2018
@@ -81,7 +81,7 @@
 https://wg21.link/LWG3017;>3017list 
splice functions should use 
addressofJacksonville
 https://wg21.link/LWG3020;>3020[networking.ts] 
Remove spurious nested value_type buffer sequence 
requirementJacksonville
 https://wg21.link/LWG3026;>3026filesystem::weakly_canonical
 still defined in terms of canonical(p, 
base)Jacksonville
-https://wg21.link/LWG3030;>3030Who shall meet 
the requirements of try_lock?Jacksonville
+https://wg21.link/LWG3030;>3030Who shall meet 
the requirements of try_lock?JacksonvilleNothing 
to do
 https://wg21.link/LWG3034;>3034P0767R1 breaks 
previously-standard-layout typesJacksonville
 https://wg21.link/LWG3035;>3035std::allocator's 
constructors should be constexprJacksonvillePatch 
Ready
 https://wg21.link/LWG3039;>3039Unnecessary 
decay in thread and 
packaged_taskJacksonvillePatch Ready
@@ -129,7 +129,7 @@
  3017 - We don't do the splicing stuff yet
  3020 - No networking TS implementation yet
  3026 - I think this is just wording cleanup - Eric?
- 3030 - Wording changes only?? Do we handle exceptions correctly here?
+ 3030 - Wording changes only
  3034 - Need to check if our tests are correct.
  3035 - Patch Ready
  3039 - Patch Ready


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


Re: [libcxx] r324182 - [libc++] Fix PR35491 - std::array of zero-size doesn't work with non-default constructible types.

2018-02-05 Thread Eric Fiselier via cfe-commits
Sorry about that guys, I was AFK most of the day today.

Thanks for cleaning up my mess.



On Feb 5, 2018 7:08 PM, "Nirav Davé"  wrote:

> I reverted r324182, r324185, and r324192 in r324309. Things should be
> unstuck now.
>
> -Nirav
>
> On Mon, Feb 5, 2018 at 9:06 PM, Nirav Davé  wrote:
>
>> It looks like we need to revert 324182 and 324194. I'll revert on I
>> reverify on trunk.
>>
>>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [libcxx] r324182 - [libc++] Fix PR35491 - std::array of zero-size doesn't work with non-default constructible types.

2018-02-05 Thread Nirav Davé via cfe-commits
I reverted r324182, r324185, and r324192 in r324309. Things should be
unstuck now.

-Nirav

On Mon, Feb 5, 2018 at 9:06 PM, Nirav Davé  wrote:

> It looks like we need to revert 324182 and 324194. I'll revert on I
> reverify on trunk.
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] r324309 - Revert "[libc++] Fix PR35491 - std::array of zero-size doesn't work with non-default constructible types."

2018-02-05 Thread Nirav Dave via cfe-commits
Author: niravd
Date: Mon Feb  5 19:03:37 2018
New Revision: 324309

URL: http://llvm.org/viewvc/llvm-project?rev=324309=rev
Log:
Revert "[libc++] Fix PR35491 - std::array of zero-size doesn't work with 
non-default constructible types."
Revert "Fix initialization of array with GCC."
Revert "Make array non-CopyAssignable and make swap and fill 
ill-formed."

This reverts commit r324182, r324185, and r324194 which were causing issues 
with zero-length std::arrays.

Removed:

libcxx/trunk/test/std/containers/sequences/array/array.cons/implicit_copy.pass.cpp
libcxx/trunk/test/std/containers/sequences/array/array.fill/fill.fail.cpp
libcxx/trunk/test/std/containers/sequences/array/array.swap/swap.fail.cpp
Modified:
libcxx/trunk/include/array
libcxx/trunk/test/std/containers/sequences/array/array.cons/default.pass.cpp
libcxx/trunk/test/std/containers/sequences/array/array.data/data.pass.cpp

libcxx/trunk/test/std/containers/sequences/array/array.data/data_const.pass.cpp
libcxx/trunk/test/std/containers/sequences/array/begin.pass.cpp

Modified: libcxx/trunk/include/array
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/array?rev=324309=324308=324309=diff
==
--- libcxx/trunk/include/array (original)
+++ libcxx/trunk/include/array Mon Feb  5 19:03:37 2018
@@ -118,57 +118,6 @@ template  c
 _LIBCPP_BEGIN_NAMESPACE_STD
 
 template 
-struct __array_traits {
-  typedef _Tp _StorageT[_Size];
-
-  _LIBCPP_INLINE_VISIBILITY
-  static _LIBCPP_CONSTEXPR_AFTER_CXX14 typename remove_const<_Tp>::type*
-  __data(typename remove_const<_StorageT>::type& __store) {
-return __store;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  static _LIBCPP_CONSTEXPR_AFTER_CXX14 _Tp const* __data(const _StorageT& 
__store) {
-return __store;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  static void __swap(_StorageT& __lhs, _StorageT& __rhs) {
-std::swap_ranges(__lhs, __lhs + _Size, __rhs);
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  static void __fill(_StorageT& __arr, _Tp const& __val) {
-_VSTD::fill_n(__arr, _Size, __val);
-  }
-};
-
-template 
-struct __array_traits<_Tp, 0> {
-  typedef typename aligned_storage::value>::type
-  _NonConstStorageT[1];
-  typedef typename conditional::value, const _NonConstStorageT,
-   _NonConstStorageT>::type _StorageT;
-  typedef typename remove_const<_Tp>::type _NonConstTp;
-
-  _LIBCPP_INLINE_VISIBILITY
-  static _NonConstTp* __data(_NonConstStorageT &__store) {
-return reinterpret_cast<_NonConstTp*>(__store);
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  static const _Tp* __data(const _StorageT &__store) {
-return reinterpret_cast(__store);
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  static void __swap(_StorageT&, _StorageT&) {}
-
-  _LIBCPP_INLINE_VISIBILITY
-  static void __fill(_StorageT&, _Tp const&) {}
-};
-
-template 
 struct _LIBCPP_TEMPLATE_VIS array
 {
 // types:
@@ -185,33 +134,31 @@ struct _LIBCPP_TEMPLATE_VIS array
 typedef std::reverse_iterator   reverse_iterator;
 typedef std::reverse_iterator const_reverse_iterator;
 
-typedef __array_traits<_Tp, _Size> _Traits;
-typename _Traits::_StorageT __elems_;
+value_type __elems_[_Size > 0 ? _Size : 1];
 
 // No explicit construct/copy/destroy for aggregate type
-_LIBCPP_INLINE_VISIBILITY void fill(const value_type& __u) {
-  static_assert(_Size != 0 || !is_const<_Tp>::value,
-"cannot fill zero-sized array of type 'const T'");
-  _Traits::__fill(__elems_, __u);
-}
+_LIBCPP_INLINE_VISIBILITY void fill(const value_type& __u)
+{_VSTD::fill_n(__elems_, _Size, __u);}
+_LIBCPP_INLINE_VISIBILITY
+void swap(array& __a) _NOEXCEPT_(_Size == 0 || 
__is_nothrow_swappable<_Tp>::value)
+{ __swap_dispatch((std::integral_constant()), __a); }
+
+_LIBCPP_INLINE_VISIBILITY
+void __swap_dispatch(std::true_type, array&) {}
 
 _LIBCPP_INLINE_VISIBILITY
-void swap(array& __a)
-_NOEXCEPT_(_Size == 0 || __is_nothrow_swappable<_Tp>::value) {
-  static_assert(_Size != 0 || !is_const<_Tp>::value,
-"cannot swap zero-sized array of type 'const T'");
-  _Traits::__swap(__elems_, __a.__elems_);
-}
+void __swap_dispatch(std::false_type, array& __a)
+{ _VSTD::swap_ranges(__elems_, __elems_ + _Size, __a.__elems_);}
 
 // iterators:
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-iterator begin() _NOEXCEPT {return iterator(data());}
+iterator begin() _NOEXCEPT {return iterator(__elems_);}
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-const_iterator begin() const _NOEXCEPT {return const_iterator(data());}
+const_iterator begin() const _NOEXCEPT {return const_iterator(__elems_);}
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-iterator end() _NOEXCEPT 

r324308 - Fix crash on invalid.

2018-02-05 Thread Richard Trieu via cfe-commits
Author: rtrieu
Date: Mon Feb  5 18:58:21 2018
New Revision: 324308

URL: http://llvm.org/viewvc/llvm-project?rev=324308=rev
Log:
Fix crash on invalid.

Don't call a method when the pointer is null.

Modified:
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/test/SemaCXX/lambda-expressions.cpp

Modified: cfe/trunk/lib/Sema/SemaExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaExpr.cpp?rev=324308=324307=324308=diff
==
--- cfe/trunk/lib/Sema/SemaExpr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaExpr.cpp Mon Feb  5 18:58:21 2018
@@ -14958,7 +14958,8 @@ static void DoMarkVarDeclReferenced(Sema
 if (RefersToEnclosingScope) {
   LambdaScopeInfo *const LSI =
   SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
-  if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
+  if (LSI && (!LSI->CallOperator ||
+  !LSI->CallOperator->Encloses(Var->getDeclContext( {
 // If a variable could potentially be odr-used, defer marking it so
 // until we finish analyzing the full expression for any
 // lvalue-to-rvalue

Modified: cfe/trunk/test/SemaCXX/lambda-expressions.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/lambda-expressions.cpp?rev=324308=324307=324308=diff
==
--- cfe/trunk/test/SemaCXX/lambda-expressions.cpp (original)
+++ cfe/trunk/test/SemaCXX/lambda-expressions.cpp Mon Feb  5 18:58:21 2018
@@ -608,3 +608,18 @@ namespace ConversionOperatorDoesNotHaveD
   // This used to crash in return type deduction for the conversion opreator.
   struct A { int n; void f() { +[](decltype(n)) {}; } };
 }
+
+namespace TypoCorrection {
+template  struct X {};
+// expected-note@-1 {{template parameter is declared here}}
+
+template 
+void Run(const int& points) {
+// expected-note@-1 {{'points' declared here}}
+  auto outer_lambda = []() {
+auto inner_lambda = [](const X&) {};
+// expected-error@-1 {{use of undeclared identifier 'Points'; did you mean 
'points'?}}
+// expected-error@-2 {{template argument for template type parameter must 
be a type}}
+  };
+}
+}


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


[PATCH] D42942: [clangd] Collect definitions when indexing.

2018-02-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This does seem to get at least the simple cases right:

  ID:  0EF8AF4D08B11EBF3FFB8004CE702991B15F
  Name:SymbolsFromYAML
  Scope:   'clang::clangd::'
  SymInfo: 
Kind:Function
Lang:C
  CanonicalDeclaration: 
StartOffset: 956
EndOffset:   1010
FilePath:
/usr/local/google/home/sammccall/src/llvm/tools/clang/tools/extra/clangd/index/SymbolYAML.h
  Definition:  
StartOffset: 4999
EndOffset:   5348
FilePath:
/usr/local/google/home/sammccall/src/llvm/tools/clang/tools/extra/clangd/index/SymbolYAML.cpp
  CompletionLabel: 'SymbolsFromYAML(llvm::StringRef YAMLContent)'
  CompletionFilterText: SymbolsFromYAML
  CompletionPlainInsertText: SymbolsFromYAML
  CompletionSnippetInsertText: 'SymbolsFromYAML(${1:llvm::StringRef 
YAMLContent})'
  Detail:  
Documentation:   ''
CompletionDetail: SymbolSlab


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42942



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


Re: [libcxx] r324182 - [libc++] Fix PR35491 - std::array of zero-size doesn't work with non-default constructible types.

2018-02-05 Thread Nirav Davé via cfe-commits
It looks like we need to revert 324182 and 324194. I'll revert on I
reverify on trunk.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42942: [clangd] Collect definitions when indexing.

2018-02-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: ioeric, hokein.
Herald added subscribers: cfe-commits, jkorous-apple, ilya-biryukov, klimek.

(This isn't done! Needs new tests, and some random cleanups should be split out.
Looking for some early feedback.)

Within a TU:

- as now, collect a declaration from the first occurrence of a symbol (taking 
clang's canonical declaration)
- when we first see a definition occurrence, copy the symbol and add it

Across TUs/sources:

- mergeSymbol in Merge.h is responsible for combining matching Symbols. This 
covers dynamic/static merges and cross-TU merges in the static index.
- it prefers declarations from Symbols that have a definition.
- GlobalSymbolBuilderMain is modified to use mergeSymbol as a reduce step.

Random cleanups (can be pulled out):

- SymbolFromYAML -> SymbolsFromYAML, new singular SymbolFromYAML added
- avoid uninit'd SymbolLocations. Add an idiomatic way to check "absent".
- CanonicalDeclaration (as well as Definition) are mapped as optional in YAML.
- added operator<< for Symbol & SymbolLocation, for debugging


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42942

Files:
  clangd/global-symbol-builder/GlobalSymbolBuilderMain.cpp
  clangd/index/Index.cpp
  clangd/index/Index.h
  clangd/index/Merge.cpp
  clangd/index/SymbolCollector.cpp
  clangd/index/SymbolCollector.h
  clangd/index/SymbolYAML.cpp
  clangd/index/SymbolYAML.h
  clangd/tool/ClangdMain.cpp
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -439,18 +439,18 @@
 ...
 )";
 
-  auto Symbols1 = SymbolFromYAML(YAML1);
+  auto Symbols1 = SymbolsFromYAML(YAML1);
   EXPECT_THAT(Symbols1, UnorderedElementsAre(
 AllOf(QName("clang::Foo1"), Labeled("Foo1-label"),
   Doc("Foo doc"), Detail("int";
-  auto Symbols2 = SymbolFromYAML(YAML2);
+  auto Symbols2 = SymbolsFromYAML(YAML2);
   EXPECT_THAT(Symbols2, UnorderedElementsAre(AllOf(QName("clang::Foo2"),
Labeled("Foo2-label"),
Not(HasDetail();
 
   std::string ConcatenatedYAML =
   SymbolsToYAML(Symbols1) + SymbolsToYAML(Symbols2);
-  auto ConcatenatedSymbols = SymbolFromYAML(ConcatenatedYAML);
+  auto ConcatenatedSymbols = SymbolsFromYAML(ConcatenatedYAML);
   EXPECT_THAT(ConcatenatedSymbols,
   UnorderedElementsAre(QName("clang::Foo1"),
QName("clang::Foo2")));
Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -37,7 +37,7 @@
 llvm::errs() << "Can't open " << YamlSymbolFile << "\n";
 return nullptr;
   }
-  auto Slab = SymbolFromYAML(Buffer.get()->getBuffer());
+  auto Slab = SymbolsFromYAML(Buffer.get()->getBuffer());
   SymbolSlab::Builder SymsBuilder;
   for (auto Sym : Slab)
 SymsBuilder.insert(Sym);
Index: clangd/index/SymbolYAML.h
===
--- clangd/index/SymbolYAML.h
+++ clangd/index/SymbolYAML.h
@@ -25,7 +25,11 @@
 namespace clangd {
 
 // Read symbols from a YAML-format string.
-SymbolSlab SymbolFromYAML(llvm::StringRef YAMLContent);
+SymbolSlab SymbolsFromYAML(llvm::StringRef YAMLContent);
+
+// Read one symbol from a YAML-format string, backed by the arena.
+Symbol SymbolFromYAML(llvm::StringRef YAMLContent,
+  llvm::BumpPtrAllocator );
 
 // Convert a single symbol to YAML-format string.
 // The YAML result is safe to concatenate.
Index: clangd/index/SymbolYAML.cpp
===
--- clangd/index/SymbolYAML.cpp
+++ clangd/index/SymbolYAML.cpp
@@ -97,7 +97,9 @@
 IO.mapRequired("Name", Sym.Name);
 IO.mapRequired("Scope", Sym.Scope);
 IO.mapRequired("SymInfo", Sym.SymInfo);
-IO.mapRequired("CanonicalDeclaration", Sym.CanonicalDeclaration);
+IO.mapOptional("CanonicalDeclaration", Sym.CanonicalDeclaration,
+   SymbolLocation());
+IO.mapOptional("Definition", Sym.Definition, SymbolLocation());
 IO.mapRequired("CompletionLabel", Sym.CompletionLabel);
 IO.mapRequired("CompletionFilterText", Sym.CompletionFilterText);
 IO.mapRequired("CompletionPlainInsertText", Sym.CompletionPlainInsertText);
@@ -160,7 +162,7 @@
 namespace clang {
 namespace clangd {
 
-SymbolSlab SymbolFromYAML(llvm::StringRef YAMLContent) {
+SymbolSlab SymbolsFromYAML(llvm::StringRef YAMLContent) {
   // Store data of pointer fields (excl. `StringRef`) like `Detail`.
   llvm::BumpPtrAllocator Arena;
   llvm::yaml::Input Yin(YAMLContent, );
@@ -173,6 +175,14 @@
   return std::move(Syms).build();
 }
 
+Symbol 

[libcxx] r324307 - More patches ready

2018-02-05 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Mon Feb  5 17:59:28 2018
New Revision: 324307

URL: http://llvm.org/viewvc/llvm-project?rev=324307=rev
Log:
More patches ready

Modified:
libcxx/trunk/www/upcoming_meeting.html

Modified: libcxx/trunk/www/upcoming_meeting.html
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/www/upcoming_meeting.html?rev=324307=324306=324307=diff
==
--- libcxx/trunk/www/upcoming_meeting.html (original)
+++ libcxx/trunk/www/upcoming_meeting.html Mon Feb  5 17:59:28 2018
@@ -63,8 +63,8 @@
 https://wg21.link/LWG2243;>2243istream::putback 
problemJacksonvilleComplete
 https://wg21.link/LWG2816;>2816resize_file has 
impossible postconditionJacksonvilleNothing to 
do
 https://wg21.link/LWG2843;>2843Unclear behavior 
of 
std::pmr::memory_resource::do_allocate()Jacksonville
-https://wg21.link/LWG2849;>2849Why does 
!is_regular_file(from) cause copy_file to report a "file 
already exists" error?JacksonvilleNothing to do
-https://wg21.link/LWG2851;>2851std::filesystem enum 
classes are now underspecifiedJacksonvilleNothing to 
do
+https://wg21.link/LWG2849;>2849Why does 
!is_regular_file(from) cause copy_file to report a "file 
already exists" error?JacksonvilleNothing to 
do
+https://wg21.link/LWG2851;>2851std::filesystem enum 
classes are now underspecifiedJacksonvilleNothing to 
do
 https://wg21.link/LWG2969;>2969polymorphic_allocator::construct()
 shouldn't pass resource()Jacksonville
 https://wg21.link/LWG2975;>2975Missing case for 
pair construction in scoped and polymorphic 
allocatorsJacksonville
 https://wg21.link/LWG2989;>2989path's 
stream insertion operator lets you insert everything under the 
sunJacksonvilleCompleted
@@ -77,15 +77,15 @@
 https://wg21.link/LWG3010;>3010[networking.ts] 
uses_executor says "if a type T::executor_type 
exists"Jacksonville
 https://wg21.link/LWG3013;>3013(recursive_)directory_iterator
 construction and traversal should not be 
noexceptJacksonvilleComplete
 https://wg21.link/LWG3014;>3014More 
noexcept issues with filesystem 
operationsJacksonvilleComplete
-  https://wg21.link/LWG3015;>3015copy_options::unspecified
 underspecifiedJacksonvilleNothing to do
+https://wg21.link/LWG3015;>3015copy_options::unspecified
 underspecifiedJacksonvilleNothing to do
 https://wg21.link/LWG3017;>3017list 
splice functions should use 
addressofJacksonville
 https://wg21.link/LWG3020;>3020[networking.ts] 
Remove spurious nested value_type buffer sequence 
requirementJacksonville
 https://wg21.link/LWG3026;>3026filesystem::weakly_canonical
 still defined in terms of canonical(p, 
base)Jacksonville
 https://wg21.link/LWG3030;>3030Who shall meet 
the requirements of try_lock?Jacksonville
 https://wg21.link/LWG3034;>3034P0767R1 breaks 
previously-standard-layout typesJacksonville
-https://wg21.link/LWG3035;>3035std::allocator's 
constructors should be 
constexprJacksonville
-https://wg21.link/LWG3039;>3039Unnecessary 
decay in thread and 
packaged_taskJacksonville
-https://wg21.link/LWG3041;>3041Unnecessary 
decay in 
reference_wrapperJacksonville
+https://wg21.link/LWG3035;>3035std::allocator's 
constructors should be constexprJacksonvillePatch 
Ready
+https://wg21.link/LWG3039;>3039Unnecessary 
decay in thread and 
packaged_taskJacksonvillePatch Ready
+https://wg21.link/LWG3041;>3041Unnecessary 
decay in 
reference_wrapperJacksonvillePatch 
Ready
 https://wg21.link/LWG3042;>3042is_literal_type_v 
should be inlineJacksonvilleComplete
 https://wg21.link/LWG3043;>3043Bogus 
postcondition for filesystem_error 
constructorJacksonville
 https://wg21.link/LWG3045;>3045atomicfloating-point
 doesn't have value_type or 
difference_typeJacksonville
@@ -131,7 +131,7 @@
  3026 - I think this is just wording cleanup - Eric?
  3030 - Wording changes only?? Do we handle exceptions correctly here?
  3034 - Need to check if our tests are correct.
- 3035 - Easy to do
+ 3035 - Patch Ready
  3039 - Patch Ready
  3041 - Patch Ready
  3042 - We already do this.


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


[PATCH] D42876: [analyzer] Support returning objects by value.

2018-02-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ planned changes to this revision.
NoQ added a comment.

Destructor for the returned temporary is still evaluated conservatively:

  class C {
  public:
int , 
C(int &_x, int &_y) : x(_x), y(_y) { ++x; }
C(const C ) : x(c.x), y(c.y) { ++x; }
~C() { ++y; }
  };
  
  C make(int , int ) {
return { x, y };
  }
  
  void test() {
int x = 0, y = 0;
{
  C c = make(x, y);
}
clang_analyzer_dump(x); // 2 S32b
clang_analyzer_dump(y); // 1 S32b
  }

Also there's a weird rebound at the call site - from the 
callee-context-temporary to the caller-context-temporary - which is currently 
implemented as a trivial copy and not a full-featured constructor call. I guess 
there shouldn't be a copy here (because there is no constructor or assignment 
operator), so i suspect we should directly construct into the caller context's 
temporary for the call-expression.

These issues are known, i'm just pointing out that we'd need to tackle them to 
make at least this simple example work correctly.


Repository:
  rC Clang

https://reviews.llvm.org/D42876



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


[PATCH] D42768: AST: add an extension to support SwiftCC on MS ABI

2018-02-05 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

The Itanium C++ ABI specifies a convention of using the source-level syntax in 
the mangling of vendor extensions. This gives a fairly natural naming 
convention for such extensions. That would suggest that the identifier to use 
here is `__swiftcall__`, not `__swift_cc` / `__Swift`. Given that the MS ABI 
mangles return types even for non-template functions, one consistent place to 
put this marker would be on the return type. That is, mangle 
`__attribute__((__swiftcall__)) T f(...)` as if it were `__swiftcall__ 
f(...)`, and likewise for function pointer types.


Repository:
  rC Clang

https://reviews.llvm.org/D42768



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


[PATCH] D40903: [Sanitizers] Basic Solaris sanitizer support (PR 33274)

2018-02-05 Thread Aleksey Shlyapnikov via Phabricator via cfe-commits
alekseyshl added a comment.

Rainer, check https://reviews.llvm.org/rC324302 out, you probably want to add 
test cases for Solaris to test/Driver/sanitizer-ld.c too.


Repository:
  rC Clang

https://reviews.llvm.org/D40903



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


[PATCH] D42938: [Sema] Emit -Winteger-overflow for arguments in function calls, ObjC messages.

2018-02-05 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai updated this revision to Diff 132917.
vsapsai added a comment.

- Improve tests: check when function argument is a function call itself.


https://reviews.llvm.org/D42938

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/integer-overflow.c
  clang/test/SemaCXX/integer-overflow.cpp
  clang/test/SemaObjC/integer-overflow.m

Index: clang/test/SemaObjC/integer-overflow.m
===
--- /dev/null
+++ clang/test/SemaObjC/integer-overflow.m
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -Wno-objc-root-class -fsyntax-only -verify %s
+
+@interface Foo
+@end
+
+@implementation Foo
+- (int)add:(int)a with:(int)b {
+  return a + b;
+}
+
+- (void)testIntegerOverflows {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (void)[self add:0 with:4608 * 1024 * 1024];
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (void)[self add:0 with:[self add:4608 * 1024 * 1024 with:0]];
+}
+@end
Index: clang/test/SemaCXX/integer-overflow.cpp
===
--- clang/test/SemaCXX/integer-overflow.cpp
+++ clang/test/SemaCXX/integer-overflow.cpp
@@ -169,3 +169,18 @@
 // expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
   return ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024)));
 }
+
+void check_integer_overflows_in_function_calls() {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (void)f0(4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  uint64_t x = f0(4608 * 1024 * 1024);
+
+// expected-warning@+2 {{overflow in expression; result is 536870912 with type 'int'}}
+  uint64_t (*f0_ptr)(uint64_t) = 
+  (void)(*f0_ptr)(4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (void)f2(0, f0(4608 * 1024 * 1024));
+}
Index: clang/test/Sema/integer-overflow.c
===
--- clang/test/Sema/integer-overflow.c
+++ clang/test/Sema/integer-overflow.c
@@ -158,6 +158,21 @@
   return ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024)));
 }
 
+void check_integer_overflows_in_function_calls() {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (void)f0(4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  uint64_t x = f0(4608 * 1024 * 1024);
+
+// expected-warning@+2 {{overflow in expression; result is 536870912 with type 'int'}}
+  uint64_t (*f0_ptr)(uint64_t) = 
+  (void)(*f0_ptr)(4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (void)f2(0, f0(4608 * 1024 * 1024));
+}
+
 struct s {
   unsigned x;
   unsigned y;
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -10201,18 +10201,22 @@
   SmallVector Exprs(1, E);
 
   do {
-Expr *E = Exprs.pop_back_val();
+Expr *OriginalE = Exprs.pop_back_val();
+Expr *E = OriginalE->IgnoreParenCasts();
 
-if (isa(E->IgnoreParenCasts())) {
-  E->IgnoreParenCasts()->EvaluateForOverflow(Context);
+if (isa(E)) {
+  E->EvaluateForOverflow(Context);
   continue;
 }
 
-if (auto InitList = dyn_cast(E))
+if (auto InitList = dyn_cast(OriginalE))
   Exprs.append(InitList->inits().begin(), InitList->inits().end());
-
-if (isa(E))
-  E->IgnoreParenCasts()->EvaluateForOverflow(Context);
+else if (isa(OriginalE))
+  E->EvaluateForOverflow(Context);
+else if (auto Call = dyn_cast(E))
+  Exprs.append(Call->arg_begin(), Call->arg_end());
+else if (auto Message = dyn_cast(E))
+  Exprs.append(Message->arg_begin(), Message->arg_end());
   } while (!Exprs.empty());
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r324302 - Fix test/Driver/sanitizer-ld.c broken by D40903

2018-02-05 Thread Alex Shlyapnikov via cfe-commits
Author: alekseyshl
Date: Mon Feb  5 16:50:18 2018
New Revision: 324302

URL: http://llvm.org/viewvc/llvm-project?rev=324302=rev
Log:
Fix test/Driver/sanitizer-ld.c broken by D40903

Differential revision: https://reviews.llvm.org/D40903

Modified:
cfe/trunk/test/Driver/sanitizer-ld.c

Modified: cfe/trunk/test/Driver/sanitizer-ld.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/sanitizer-ld.c?rev=324302=324301=324302=diff
==
--- cfe/trunk/test/Driver/sanitizer-ld.c (original)
+++ cfe/trunk/test/Driver/sanitizer-ld.c Mon Feb  5 16:50:18 2018
@@ -9,9 +9,9 @@
 // CHECK-ASAN-LINUX: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
 // CHECK-ASAN-LINUX-NOT: "-lc"
 // CHECK-ASAN-LINUX: libclang_rt.asan-i386.a"
-// CHECK-ASAN-LINUX-NOT: "-export-dynamic"
+// CHECK-ASAN-LINUX-NOT: "--export-dynamic"
 // CHECK-ASAN-LINUX: "--dynamic-list={{.*}}libclang_rt.asan-i386.a.syms"
-// CHECK-ASAN-LINUX-NOT: "-export-dynamic"
+// CHECK-ASAN-LINUX-NOT: "--export-dynamic"
 // CHECK-ASAN-LINUX: "-lpthread"
 // CHECK-ASAN-LINUX: "-lrt"
 // CHECK-ASAN-LINUX: "-ldl"
@@ -39,11 +39,11 @@
 // CHECK-SHARED-ASAN-LINUX-NOT: "-lc"
 // CHECK-SHARED-ASAN-LINUX-NOT: libclang_rt.asan-i386.a"
 // CHECK-SHARED-ASAN-LINUX: libclang_rt.asan-i386.so"
-// CHECK-SHARED-ASAN-LINUX: "-whole-archive" 
"{{.*}}libclang_rt.asan-preinit-i386.a" "-no-whole-archive"
+// CHECK-SHARED-ASAN-LINUX: "--whole-archive" 
"{{.*}}libclang_rt.asan-preinit-i386.a" "--no-whole-archive"
 // CHECK-SHARED-ASAN-LINUX-NOT: "-lpthread"
 // CHECK-SHARED-ASAN-LINUX-NOT: "-lrt"
 // CHECK-SHARED-ASAN-LINUX-NOT: "-ldl"
-// CHECK-SHARED-ASAN-LINUX-NOT: "-export-dynamic"
+// CHECK-SHARED-ASAN-LINUX-NOT: "--export-dynamic"
 // CHECK-SHARED-ASAN-LINUX-NOT: "--dynamic-list"
 
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.so -shared 2>&1 \
@@ -60,7 +60,7 @@
 // CHECK-DSO-SHARED-ASAN-LINUX-NOT: "-lpthread"
 // CHECK-DSO-SHARED-ASAN-LINUX-NOT: "-lrt"
 // CHECK-DSO-SHARED-ASAN-LINUX-NOT: "-ldl"
-// CHECK-DSO-SHARED-ASAN-LINUX-NOT: "-export-dynamic"
+// CHECK-DSO-SHARED-ASAN-LINUX-NOT: "--export-dynamic"
 // CHECK-DSO-SHARED-ASAN-LINUX-NOT: "--dynamic-list"
 
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
@@ -75,7 +75,7 @@
 // CHECK-ASAN-FREEBSD: freebsd{{/|\\+}}libclang_rt.asan-i386.a"
 // CHECK-ASAN-FREEBSD-NOT: libclang_rt.asan_cxx
 // CHECK-ASAN-FREEBSD-NOT: "--dynamic-list"
-// CHECK-ASAN-FREEBSD: "-export-dynamic"
+// CHECK-ASAN-FREEBSD: "--export-dynamic"
 // CHECK-ASAN-FREEBSD: "-lpthread"
 // CHECK-ASAN-FREEBSD: "-lrt"
 
@@ -96,10 +96,10 @@
 //
 // CHECK-ASAN-LINUX-CXX: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
 // CHECK-ASAN-LINUX-CXX-NOT: "-lc"
-// CHECK-ASAN-LINUX-CXX: "-whole-archive" "{{.*}}libclang_rt.asan-i386.a" 
"-no-whole-archive"
-// CHECK-ASAN-LINUX-CXX: "-whole-archive" "{{.*}}libclang_rt.asan_cxx-i386.a" 
"-no-whole-archive"
+// CHECK-ASAN-LINUX-CXX: "--whole-archive" "{{.*}}libclang_rt.asan-i386.a" 
"--no-whole-archive"
+// CHECK-ASAN-LINUX-CXX: "--whole-archive" "{{.*}}libclang_rt.asan_cxx-i386.a" 
"--no-whole-archive"
 // CHECK-ASAN-LINUX-CXX-NOT: "--dynamic-list"
-// CHECK-ASAN-LINUX-CXX: "-export-dynamic"
+// CHECK-ASAN-LINUX-CXX: "--export-dynamic"
 // CHECK-ASAN-LINUX-CXX: stdc++
 // CHECK-ASAN-LINUX-CXX: "-lpthread"
 // CHECK-ASAN-LINUX-CXX: "-lrt"
@@ -112,7 +112,7 @@
 //
 // CHECK-ASAN-LINUX-CXX-STATIC: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
 // CHECK-ASAN-LINUX-CXX-STATIC-NOT: stdc++
-// CHECK-ASAN-LINUX-CXX-STATIC: "-whole-archive" 
"{{.*}}libclang_rt.asan-i386.a" "-no-whole-archive"
+// CHECK-ASAN-LINUX-CXX-STATIC: "--whole-archive" 
"{{.*}}libclang_rt.asan-i386.a" "--no-whole-archive"
 // CHECK-ASAN-LINUX-CXX-STATIC: stdc++
 
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
@@ -227,11 +227,11 @@
 //
 // CHECK-TSAN-LINUX-CXX: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
 // CHECK-TSAN-LINUX-CXX-NOT: stdc++
-// CHECK-TSAN-LINUX-CXX: "-whole-archive" "{{.*}}libclang_rt.tsan-x86_64.a" 
"-no-whole-archive"
+// CHECK-TSAN-LINUX-CXX: "--whole-archive" "{{.*}}libclang_rt.tsan-x86_64.a" 
"--no-whole-archive"
 // CHECK-TSAN-LINUX-CXX: "--dynamic-list={{.*}}libclang_rt.tsan-x86_64.a.syms"
-// CHECK-TSAN-LINUX-CXX: "-whole-archive" 
"{{.*}}libclang_rt.tsan_cxx-x86_64.a" "-no-whole-archive"
+// CHECK-TSAN-LINUX-CXX: "--whole-archive" 
"{{.*}}libclang_rt.tsan_cxx-x86_64.a" "--no-whole-archive"
 // CHECK-TSAN-LINUX-CXX: 
"--dynamic-list={{.*}}libclang_rt.tsan_cxx-x86_64.a.syms"
-// CHECK-TSAN-LINUX-CXX-NOT: "-export-dynamic"
+// CHECK-TSAN-LINUX-CXX-NOT: "--export-dynamic"
 // CHECK-TSAN-LINUX-CXX: stdc++
 // CHECK-TSAN-LINUX-CXX: "-lpthread"
 // CHECK-TSAN-LINUX-CXX: "-lrt"
@@ -246,11 +246,11 @@
 //
 // CHECK-MSAN-LINUX-CXX: "{{(.*[^-.0-9A-Z_a-z])?}}ld{{(.exe)?}}"
 // CHECK-MSAN-LINUX-CXX-NOT: stdc++
-// CHECK-MSAN-LINUX-CXX: "-whole-archive" "{{.*}}libclang_rt.msan-x86_64.a" 
"-no-whole-archive"
+// CHECK-MSAN-LINUX-CXX: "--whole-archive" 

[PATCH] D42672: [CFG] [analyzer] Heavier CFGConstructor elements.

2018-02-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: include/clang/Analysis/CFG.h:153
+
+  ConstructionContext() = default;
+  ConstructionContext(CXXConstructExpr *Constructor, Stmt *Trigger)

xazax.hun wrote:
> Maybe I am getting this wrong, but I think in this case the members will be 
> default initialized and will get indeterminate values.
> See: http://en.cppreference.com/w/cpp/language/default_initialization
> > Default initialization is performed in three situations:
> > ..
> > 3) when a base class or a non-static data member is not mentioned in a 
> > constructor initializer list and that constructor is called.
> > 
> > 
> > The effects of default initialization are:
> > 
> > if T is a non-POD (until C++11) class type ...
> > 
> > if T is an array type, every element of the array is default-initialized;
> > 
> > otherwise, nothing is done: the objects with automatic storage duration 
> > (and their subobjects) are initialized to indeterminate values. 
Ew, right. I should be more careful (no idea how it works).



Comment at: lib/Analysis/CFG.cpp:4402
+  stmt = SE->getStmt();
+else if (auto CE = BI->getAs())
+  stmt = CE->getConstructor();

xazax.hun wrote:
> So this is one of the places where subclassing would help? Could you measure 
> the compile time regression after making `CFGStmt`'s `isKind` more complex?
Yeah, any user of the new mode would be surprised that constructors are not 
statements, which is indeed annoying. But i wanted to play super safe.

I'm not seeing any compile time regressions yet after making `isKind` more 
complex - i.e. ran "`clang sqlite3.c`" release-without-asserts 100 times before 
and 100 times after, mean compilation time difference around 0.04% (in the bad 
direction, i.e. after-time is 0.04% worse than before-time), p-value (Welch's 
t-test) around 0.7. I guess i could probably run llvm compilation before and 
after for more coverage, but that wouldn't be statistically reliable.

Do we have any more reliable benchmarks?


https://reviews.llvm.org/D42672



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


[PATCH] D42938: [Sema] Emit -Winteger-overflow for arguments in function calls, ObjC messages.

2018-02-05 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added reviewers: ahatanak, nicholas, rsmith.
Herald added a subscriber: jkorous-apple.

Objective-C properties aren't handled on purpose as they require
different approach.

rdar://problem/35539384


https://reviews.llvm.org/D42938

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/integer-overflow.c
  clang/test/SemaCXX/integer-overflow.cpp
  clang/test/SemaObjC/integer-overflow.m


Index: clang/test/SemaObjC/integer-overflow.m
===
--- /dev/null
+++ clang/test/SemaObjC/integer-overflow.m
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -Wno-objc-root-class -fsyntax-only -verify %s
+
+@interface Foo
+@end
+
+@implementation Foo
+- (int)add:(int)a with:(int)b {
+  return a + b;
+}
+
+- (void)testIntegerOverflows {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 
'int'}}
+  (void)[self add:0 with:4608 * 1024 * 1024];
+}
+@end
Index: clang/test/SemaCXX/integer-overflow.cpp
===
--- clang/test/SemaCXX/integer-overflow.cpp
+++ clang/test/SemaCXX/integer-overflow.cpp
@@ -169,3 +169,15 @@
 // expected-warning@+1 2{{overflow in expression; result is 536870912 with 
type 'int'}}
   return ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024)));
 }
+
+void check_integer_overflows_in_function_calls() {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 
'int'}}
+  (void)f0(4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 
'int'}}
+  uint64_t x = f0(4608 * 1024 * 1024);
+
+// expected-warning@+2 {{overflow in expression; result is 536870912 with type 
'int'}}
+  uint64_t (*f0_ptr)(uint64_t) = 
+  (void)(*f0_ptr)(4608 * 1024 * 1024);
+}
Index: clang/test/Sema/integer-overflow.c
===
--- clang/test/Sema/integer-overflow.c
+++ clang/test/Sema/integer-overflow.c
@@ -158,6 +158,18 @@
   return ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024)));
 }
 
+void check_integer_overflows_in_function_calls() {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 
'int'}}
+  (void)f0(4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 
'int'}}
+  uint64_t x = f0(4608 * 1024 * 1024);
+
+// expected-warning@+2 {{overflow in expression; result is 536870912 with type 
'int'}}
+  uint64_t (*f0_ptr)(uint64_t) = 
+  (void)(*f0_ptr)(4608 * 1024 * 1024);
+}
+
 struct s {
   unsigned x;
   unsigned y;
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -10201,18 +10201,22 @@
   SmallVector Exprs(1, E);
 
   do {
-Expr *E = Exprs.pop_back_val();
+Expr *OriginalE = Exprs.pop_back_val();
+Expr *E = OriginalE->IgnoreParenCasts();
 
-if (isa(E->IgnoreParenCasts())) {
-  E->IgnoreParenCasts()->EvaluateForOverflow(Context);
+if (isa(E)) {
+  E->EvaluateForOverflow(Context);
   continue;
 }
 
-if (auto InitList = dyn_cast(E))
+if (auto InitList = dyn_cast(OriginalE))
   Exprs.append(InitList->inits().begin(), InitList->inits().end());
-
-if (isa(E))
-  E->IgnoreParenCasts()->EvaluateForOverflow(Context);
+else if (isa(OriginalE))
+  E->EvaluateForOverflow(Context);
+else if (auto Call = dyn_cast(E))
+  Exprs.append(Call->arg_begin(), Call->arg_end());
+else if (auto Message = dyn_cast(E))
+  Exprs.append(Message->arg_begin(), Message->arg_end());
   } while (!Exprs.empty());
 }
 


Index: clang/test/SemaObjC/integer-overflow.m
===
--- /dev/null
+++ clang/test/SemaObjC/integer-overflow.m
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -Wno-objc-root-class -fsyntax-only -verify %s
+
+@interface Foo
+@end
+
+@implementation Foo
+- (int)add:(int)a with:(int)b {
+  return a + b;
+}
+
+- (void)testIntegerOverflows {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (void)[self add:0 with:4608 * 1024 * 1024];
+}
+@end
Index: clang/test/SemaCXX/integer-overflow.cpp
===
--- clang/test/SemaCXX/integer-overflow.cpp
+++ clang/test/SemaCXX/integer-overflow.cpp
@@ -169,3 +169,15 @@
 // expected-warning@+1 2{{overflow in expression; result is 536870912 with type 'int'}}
   return ((4608 * 1024 * 1024) + ((uint64_t)(4608 * 1024 * 1024)));
 }
+
+void check_integer_overflows_in_function_calls() {
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  (void)f0(4608 * 1024 * 1024);
+
+// expected-warning@+1 {{overflow in expression; result is 536870912 with type 'int'}}
+  uint64_t x = f0(4608 * 1024 * 1024);
+
+// expected-warning@+2 {{overflow in 

[PATCH] D42672: [CFG] [analyzer] Heavier CFGConstructor elements.

2018-02-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 132908.
NoQ marked an inline comment as done.
NoQ added a comment.

Fix uninitialized variables.


https://reviews.llvm.org/D42672

Files:
  include/clang/Analysis/AnalysisDeclContext.h
  include/clang/Analysis/CFG.h
  include/clang/StaticAnalyzer/Core/AnalyzerOptions.h
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/Analysis/AnalysisDeclContext.cpp
  lib/Analysis/CFG.cpp
  lib/Analysis/LiveVariables.cpp
  lib/StaticAnalyzer/Core/AnalysisManager.cpp
  lib/StaticAnalyzer/Core/AnalyzerOptions.cpp
  lib/StaticAnalyzer/Core/CoreEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngine.cpp
  lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
  lib/StaticAnalyzer/Core/PathDiagnostic.cpp
  test/Analysis/analyzer-config.c
  test/Analysis/analyzer-config.cpp
  test/Analysis/cfg-rich-constructors.cpp
  test/Analysis/cfg.cpp

Index: test/Analysis/cfg.cpp
===
--- test/Analysis/cfg.cpp
+++ test/Analysis/cfg.cpp
@@ -1,5 +1,16 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 %s > %t 2>&1
-// RUN: FileCheck --input-file=%t %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 -analyzer-config cfg-rich-constructors=false %s > %t 2>&1
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,WARNINGS %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 -analyzer-config cfg-rich-constructors=true %s > %t 2>&1
+// RUN: FileCheck --input-file=%t -check-prefixes=CHECK,ANALYZER %s
+
+// This file tests how we construct two different flavors of the Clang CFG -
+// the CFG used by the Sema analysis-based warnings and the CFG used by the
+// static analyzer. The difference in the behavior is checked via FileCheck
+// prefixes (WARNINGS and ANALYZER respectively). When introducing new analyzer
+// flags, no new run lines should be added - just these flags would go to the
+// respective line depending on where is it turned on and where is it turned
+// off. Feel free to add tests that test only one of the CFG flavors if you're
+// not sure how the other flavor is supposed to work in your case.
 
 // CHECK-LABEL: void checkWrap(int i)
 // CHECK: ENTRY
@@ -116,7 +127,8 @@
 // CHECK-NEXT:   Succs (1): B1
 // CHECK: [B1]
 // CHECK-NEXT:   1:  CFGNewAllocator(A *)
-// CHECK-NEXT:   2:  (CXXConstructExpr, class A)
+// WARNINGS-NEXT:   2:  (CXXConstructExpr, class A)
+// ANALYZER-NEXT:   2:  (CXXConstructExpr, [B1.3], class A)
 // CHECK-NEXT:   3: new A([B1.2])
 // CHECK-NEXT:   4: A *a = new A();
 // CHECK-NEXT:   5: a
@@ -138,7 +150,8 @@
 // CHECK: [B1]
 // CHECK-NEXT:   1: 5
 // CHECK-NEXT:   2: CFGNewAllocator(A *)
-// CHECK-NEXT:   3:  (CXXConstructExpr, class A [5])
+// WARNINGS-NEXT:   3:  (CXXConstructExpr, class A [5])
+// ANALYZER-NEXT:   3:  (CXXConstructExpr, [B1.4], class A [5])
 // CHECK-NEXT:   4: new A {{\[\[}}B1.1]]
 // CHECK-NEXT:   5: A *a = new A [5];
 // CHECK-NEXT:   6: a
@@ -331,7 +344,8 @@
 // CHECK-NEXT:  3: [B1.2] (ImplicitCastExpr, ArrayToPointerDecay, int *)
 // CHECK-NEXT:  4: [B1.3] (ImplicitCastExpr, BitCast, void *)
 // CHECK-NEXT:  5: CFGNewAllocator(MyClass *)
-// CHECK-NEXT:  6:  (CXXConstructExpr, class MyClass)
+// WARNINGS-NEXT:  6:  (CXXConstructExpr, class MyClass)
+// ANALYZER-NEXT:  6:  (CXXConstructExpr, [B1.7], class MyClass)
 // CHECK-NEXT:  7: new ([B1.4]) MyClass([B1.6])
 // CHECK-NEXT:  8: MyClass *obj = new (buffer) MyClass();
 // CHECK-NEXT:  Preds (1): B2
@@ -363,7 +377,8 @@
 // CHECK-NEXT:  4: [B1.3] (ImplicitCastExpr, BitCast, void *)
 // CHECK-NEXT:  5: 5
 // CHECK-NEXT:  6: CFGNewAllocator(MyClass *)
-// CHECK-NEXT:  7:  (CXXConstructExpr, class MyClass [5])
+// WARNINGS-NEXT:  7:  (CXXConstructExpr, class MyClass [5])
+// ANALYZER-NEXT:  7:  (CXXConstructExpr, [B1.8], class MyClass [5])
 // CHECK-NEXT:  8: new ([B1.4]) MyClass {{\[\[}}B1.5]]
 // CHECK-NEXT:  9: MyClass *obj = new (buffer) MyClass [5];
 // CHECK-NEXT:  Preds (1): B2
Index: test/Analysis/cfg-rich-constructors.cpp
===
--- /dev/null
+++ test/Analysis/cfg-rich-constructors.cpp
@@ -0,0 +1,46 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=debug.DumpCFG -triple x86_64-apple-darwin12 -analyzer-config cfg-temporary-dtors=true -std=c++11 %s > %t 2>&1
+// RUN: FileCheck --input-file=%t %s
+
+class C {
+public:
+  C();
+  C(C *);
+};
+
+typedef __typeof(sizeof(int)) size_t;
+void *operator new(size_t size, void *placement);
+
+namespace operator_new {
+
+// CHECK: void operatorNewWithConstructor()
+// CHECK:  1: CFGNewAllocator(C *)
+// CHECK-NEXT: 2:  (CXXConstructExpr, [B1.3], class C)
+// CHECK-NEXT: 3: new C([B1.2])
+void operatorNewWithConstructor() {
+  new C();
+}
+
+// 

r324296 - [Sanitizers] Basic Solaris sanitizer support (PR 33274)

2018-02-05 Thread Alex Shlyapnikov via cfe-commits
Author: alekseyshl
Date: Mon Feb  5 15:59:13 2018
New Revision: 324296

URL: http://llvm.org/viewvc/llvm-project?rev=324296=rev
Log:
[Sanitizers] Basic Solaris sanitizer support (PR 33274)

Summary:
This patch (on top of https://reviews.llvm.org/D35755) provides the clang side 
necessary
to enable the Solaris port of the sanitizers implemented by 
https://reviews.llvm.org/D40898,
https://reviews.llvm.org/D40899, and https://reviews.llvm.org/D40900).

A few features of note:

* While compiler-rt cmake/base-config-ix.cmake (COMPILER_RT_OS_DIR) places
  the runtime libs in a tolower(CMAKE_SYSTEM_NAME) directory, clang defaults to
  the OS part of the target triplet (solaris2.11 in the case at hand).  The 
patch makes
  them agree on compiler-rt's idea.

* While Solaris ld accepts a considerable number of GNU ld options for 
compatibility,
  it only does so for the double-dash forms.  clang unfortunately is 
inconsistent here
  and sometimes uses the double-dash form, sometimes the single-dash one that
  confuses the hell out of Solaris ld.  I've changed the affected places to use 
the double-dash
  form that should always work.

* As described in https://reviews.llvm.org/D40899, Solaris ld doesn't create the
  __start___sancov_guards/__stop___sancov_guards labels gld/gold/lld do, so I'm
  including additional runtime libs into the link that provide them.

* One test uses -fstack-protector, but unlike other systems libssp hasn't been 
folded
  into Solaris libc, but needs to be linked with separately.

* For now, only 32-bit x86 asan is enabled on Solaris.  64-bit x86 should 
follow, but
  sparc (which requires additional compiler-rt changes not yet submitted) fails 
miserably
  due to a llvmsparc backend limitation:

fatal error: error in backend: Function 
"_ZN7testing8internal16BoolFromGTestEnvEPKcb": over-aligned dynamic alloca not 
supported.

  However, inside the gcc tree, Solaris/sparc asan works almost as well as x86.

Reviewers: rsmith, alekseyshl

Reviewed By: alekseyshl

Subscribers: jyknight, fedor.sergeev, cfe-commits

Tags: #sanitizers

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

Modified:
cfe/trunk/include/clang/Driver/ToolChain.h
cfe/trunk/lib/Driver/ToolChain.cpp
cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp
cfe/trunk/lib/Driver/ToolChains/Solaris.cpp
cfe/trunk/lib/Driver/ToolChains/Solaris.h

Modified: cfe/trunk/include/clang/Driver/ToolChain.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/ToolChain.h?rev=324296=324295=324296=diff
==
--- cfe/trunk/include/clang/Driver/ToolChain.h (original)
+++ cfe/trunk/include/clang/Driver/ToolChain.h Mon Feb  5 15:59:13 2018
@@ -355,6 +355,9 @@ public:
   // as OpenMP) to find arch-specific libraries.
   std::string getArchSpecificLibPath() const;
 
+  // Returns  part of above.
+  StringRef getOSLibName() const;
+
   /// needsProfileRT - returns true if instrumentation profile is on.
   static bool needsProfileRT(const llvm::opt::ArgList );
 

Modified: cfe/trunk/lib/Driver/ToolChain.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChain.cpp?rev=324296=324295=324296=diff
==
--- cfe/trunk/lib/Driver/ToolChain.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChain.cpp Mon Feb  5 15:59:13 2018
@@ -323,13 +323,23 @@ static StringRef getArchNameForCompilerR
   return llvm::Triple::getArchTypeName(TC.getArch());
 }
 
+StringRef ToolChain::getOSLibName() const {
+  switch (Triple.getOS()) {
+  case llvm::Triple::FreeBSD:
+return "freebsd";
+  case llvm::Triple::Solaris:
+return "sunos";
+  default:
+return getOS();
+  }
+}
+
 std::string ToolChain::getCompilerRTPath() const {
   SmallString<128> Path(getDriver().ResourceDir);
   if (Triple.isOSUnknown()) {
 llvm::sys::path::append(Path, "lib");
   } else {
-StringRef OSLibName = Triple.isOSFreeBSD() ? "freebsd" : getOS();
-llvm::sys::path::append(Path, "lib", OSLibName);
+llvm::sys::path::append(Path, "lib", getOSLibName());
   }
   return Path.str();
 }
@@ -360,8 +370,7 @@ const char *ToolChain::getCompilerRTArgS
 
 std::string ToolChain::getArchSpecificLibPath() const {
   SmallString<128> Path(getDriver().ResourceDir);
-  StringRef OSLibName = getTriple().isOSFreeBSD() ? "freebsd" : getOS();
-  llvm::sys::path::append(Path, "lib", OSLibName,
+  llvm::sys::path::append(Path, "lib", getOSLibName(),
   llvm::Triple::getArchTypeName(getArch()));
   return Path.str();
 }

Modified: cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp?rev=324296=324295=324296=diff
==
--- cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/CommonArgs.cpp Mon 

[PATCH] D40903: [Sanitizers] Basic Solaris sanitizer support (PR 33274)

2018-02-05 Thread Aleksey Shlyapnikov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC324296: [Sanitizers] Basic Solaris sanitizer support (PR 
33274) (authored by alekseyshl, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D40903

Files:
  include/clang/Driver/ToolChain.h
  lib/Driver/ToolChain.cpp
  lib/Driver/ToolChains/CommonArgs.cpp
  lib/Driver/ToolChains/Solaris.cpp
  lib/Driver/ToolChains/Solaris.h

Index: lib/Driver/ToolChains/Solaris.h
===
--- lib/Driver/ToolChains/Solaris.h
+++ lib/Driver/ToolChains/Solaris.h
@@ -65,6 +65,7 @@
   addLibStdCxxIncludePaths(const llvm::opt::ArgList ,
llvm::opt::ArgStringList ) const override;
 
+  SanitizerMask getSupportedSanitizers() const override;
   unsigned GetDefaultDwarfVersion() const override { return 2; }
 
 protected:
Index: lib/Driver/ToolChains/Solaris.cpp
===
--- lib/Driver/ToolChains/Solaris.cpp
+++ lib/Driver/ToolChains/Solaris.cpp
@@ -92,24 +92,48 @@
 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
   }
 
+  // Provide __start___sancov_guards.  Solaris ld doesn't automatically create
+  // __start_SECNAME labels.
+  CmdArgs.push_back("--whole-archive");
+  CmdArgs.push_back(
+  getToolChain().getCompilerRTArgString(Args, "sancov_begin", false));
+  CmdArgs.push_back("--no-whole-archive");
+
   getToolChain().AddFilePathLibArgs(Args, CmdArgs);
 
   Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
 options::OPT_e, options::OPT_r});
 
+  bool NeedsSanitizerDeps = addSanitizerRuntimes(getToolChain(), Args, CmdArgs);
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
 
   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
 if (getToolChain().ShouldLinkCXXStdlib(Args))
   getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
+if (Args.hasArg(options::OPT_fstack_protector) ||
+Args.hasArg(options::OPT_fstack_protector_strong) ||
+Args.hasArg(options::OPT_fstack_protector_all)) {
+  // Explicitly link ssp libraries, not folded into Solaris libc.
+  CmdArgs.push_back("-lssp_nonshared");
+  CmdArgs.push_back("-lssp");
+}
 CmdArgs.push_back("-lgcc_s");
 CmdArgs.push_back("-lc");
 if (!Args.hasArg(options::OPT_shared)) {
   CmdArgs.push_back("-lgcc");
   CmdArgs.push_back("-lm");
 }
+if (NeedsSanitizerDeps)
+  linkSanitizerRuntimeDeps(getToolChain(), CmdArgs);
   }
 
+  // Provide __stop___sancov_guards.  Solaris ld doesn't automatically create
+  // __stop_SECNAME labels.
+  CmdArgs.push_back("--whole-archive");
+  CmdArgs.push_back(
+  getToolChain().getCompilerRTArgString(Args, "sancov_end", false));
+  CmdArgs.push_back("--no-whole-archive");
+
   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
 CmdArgs.push_back(
 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
@@ -165,6 +189,17 @@
   addPathIfExists(D, D.SysRoot + "/usr/lib" + LibSuffix, Paths);
 }
 
+SanitizerMask Solaris::getSupportedSanitizers() const {
+  const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
+  SanitizerMask Res = ToolChain::getSupportedSanitizers();
+  // FIXME: Omit X86_64 until 64-bit support is figured out.
+  if (IsX86) {
+Res |= SanitizerKind::Address;
+  }
+  Res |= SanitizerKind::Vptr;
+  return Res;
+}
+
 Tool *Solaris::buildAssembler() const {
   return new tools::solaris::Assembler(*this);
 }
Index: lib/Driver/ToolChains/CommonArgs.cpp
===
--- lib/Driver/ToolChains/CommonArgs.cpp
+++ lib/Driver/ToolChains/CommonArgs.cpp
@@ -508,9 +508,9 @@
 bool IsShared, bool IsWhole) {
   // Wrap any static runtimes that must be forced into executable in
   // whole-archive.
-  if (IsWhole) CmdArgs.push_back("-whole-archive");
+  if (IsWhole) CmdArgs.push_back("--whole-archive");
   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
-  if (IsWhole) CmdArgs.push_back("-no-whole-archive");
+  if (IsWhole) CmdArgs.push_back("--no-whole-archive");
 
   if (IsShared) {
 addArchSpecificRPath(TC, Args, CmdArgs);
@@ -522,6 +522,10 @@
 static bool addSanitizerDynamicList(const ToolChain , const ArgList ,
 ArgStringList ,
 StringRef Sanitizer) {
+  // Solaris ld defaults to --export-dynamic behaviour but doesn't support
+  // the option, so don't try to pass it.
+  if (TC.getTriple().getOS() == llvm::Triple::Solaris)
+return true;
   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
   if (llvm::sys::fs::exists(SanRT + ".syms")) {
 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
@@ -692,7 +696,7 @@
   // If there is a static runtime with no dynamic 

[PATCH] D42933: [Sema] Avoid -Wformat warning for NSInteger/NSUInteger 'int' values with %zu/%zi long specifiers

2018-02-05 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added subscribers: compnerd, smeenai.
smeenai added a comment.

This seems ... suboptimal. It breaks existing code in the sense that their code 
was already broken, and the compiler is just diagnosing it correctly now. Note 
that Apple themselves recommend casting and using a proper printf specifier: 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
 (under Platform Dependencies).


Repository:
  rC Clang

https://reviews.llvm.org/D42933



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


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

2018-02-05 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman updated this revision to Diff 132901.
arphaman marked 4 inline comments as done.
arphaman added a comment.
Herald added a subscriber: jkorous-apple.

Address review comments and fix the inverted check case.


https://reviews.llvm.org/D42561

Files:
  lib/Sema/SemaChecking.cpp
  test/Sema/compare.c


Index: test/Sema/compare.c
===
--- test/Sema/compare.c
+++ test/Sema/compare.c
@@ -391,3 +391,16 @@
 void test12(unsigned a) {
   if (0 && -1 > a) { }
 }
+
+// PR36008
+
+enum PR36008EnumTest {
+  kPR36008Value = 0,
+};
+
+void pr36008(enum PR36008EnumTest lhs) {
+  __typeof__(lhs) x = lhs;
+  __typeof__(kPR36008Value) y = (kPR36008Value);
+  if (x == y) x = y; // no warning
+  if (y == x) y = x; // no warning
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -8955,6 +8955,16 @@
   LHS = LHS->IgnoreParenImpCasts();
   RHS = RHS->IgnoreParenImpCasts();
 
+  if (!S.getLangOpts().CPlusPlus) {
+// Avoid warning about comparison of integers with different signs when
+// RHS/LHS has a `typeof(E)` type whose sign is different to the sign of 
the
+// type of `E`.
+if (const auto *TET = dyn_cast(LHS->getType()))
+  LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
+if (const auto *TET = dyn_cast(RHS->getType()))
+  RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
+  }
+
   // Check to see if one of the (unmodified) operands is of different
   // signedness.
   Expr *signedOperand, *unsignedOperand;


Index: test/Sema/compare.c
===
--- test/Sema/compare.c
+++ test/Sema/compare.c
@@ -391,3 +391,16 @@
 void test12(unsigned a) {
   if (0 && -1 > a) { }
 }
+
+// PR36008
+
+enum PR36008EnumTest {
+  kPR36008Value = 0,
+};
+
+void pr36008(enum PR36008EnumTest lhs) {
+  __typeof__(lhs) x = lhs;
+  __typeof__(kPR36008Value) y = (kPR36008Value);
+  if (x == y) x = y; // no warning
+  if (y == x) y = x; // no warning
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -8955,6 +8955,16 @@
   LHS = LHS->IgnoreParenImpCasts();
   RHS = RHS->IgnoreParenImpCasts();
 
+  if (!S.getLangOpts().CPlusPlus) {
+// Avoid warning about comparison of integers with different signs when
+// RHS/LHS has a `typeof(E)` type whose sign is different to the sign of the
+// type of `E`.
+if (const auto *TET = dyn_cast(LHS->getType()))
+  LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
+if (const auto *TET = dyn_cast(RHS->getType()))
+  RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
+  }
+
   // Check to see if one of the (unmodified) operands is of different
   // signedness.
   Expr *signedOperand, *unsignedOperand;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] r324292 - Add issues in 'Review'

2018-02-05 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Mon Feb  5 15:50:49 2018
New Revision: 324292

URL: http://llvm.org/viewvc/llvm-project?rev=324292=rev
Log:
Add issues in 'Review'

Modified:
libcxx/trunk/www/upcoming_meeting.html

Modified: libcxx/trunk/www/upcoming_meeting.html
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/www/upcoming_meeting.html?rev=324292=324291=324292=diff
==
--- libcxx/trunk/www/upcoming_meeting.html (original)
+++ libcxx/trunk/www/upcoming_meeting.html Mon Feb  5 15:50:49 2018
@@ -94,6 +94,17 @@
 
   
 
+Issues to "Review"
+
+Issue #Issue NameMeetingStatus
+https://wg21.link/LWG2412;>2412promise::set_value() 
and promise::get_future() should not 
raceJacksonville
+https://wg21.link/LWG2682;>2682filesystem::copy()
 won't create a symlink to a directoryJacksonville
+https://wg21.link/LWG2697;>2697[concurr.ts] 
Behavior of future/shared_future unwrapping constructor when given an 
invalid futureJacksonville
+https://wg21.link/LWG2708;>2708recursive_directory_iterator::recursion_pending()
 is incorrectly specifiedJacksonville
+https://wg21.link/LWG2936;>2936Path comparison 
is defined in terms of the generic 
formatJacksonville
+
+
+
 Comments about the issues
 
  2164 - Writing tests here will be fun.
@@ -121,8 +132,8 @@
  3030 - Wording changes only?? Do we handle exceptions correctly here?
  3034 - Need to check if our tests are correct.
  3035 - Easy to do
- 3039 - We should implement P0777 first.
- 3041 - We should implement P0777 first.
+ 3039 - Patch Ready
+ 3041 - Patch Ready
  3042 - We already do this.
  3043 - We have a 'TODO(ericwf)' here
  3045 - We haven't done the atomic rework yet.
@@ -130,7 +141,16 @@
  3051 - Fixing an inadvertent wording change
 
 
-Last Updated: 29-Jan-2018
+Comments about the "Review" issues
+
+ 2412 - 
+ 2682 - 
+ 2697 - 
+ 2708 - 
+ 2936 - 
+
+
+Last Updated: 5-Feb-2018
 
 
 


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


[libcxx] r324290 - Remove ; use instead. See https://libcxx.llvm.org/TS_deprecation.html

2018-02-05 Thread Marshall Clow via cfe-commits
Author: marshall
Date: Mon Feb  5 15:43:34 2018
New Revision: 324290

URL: http://llvm.org/viewvc/llvm-project?rev=324290=rev
Log:
Remove ; use  instead. See 
https://libcxx.llvm.org/TS_deprecation.html

Removed:
libcxx/trunk/test/std/experimental/string.view/
Modified:
libcxx/trunk/include/experimental/string_view
libcxx/trunk/include/module.modulemap
libcxx/trunk/test/libcxx/double_include.sh.cpp
libcxx/trunk/test/libcxx/min_max_macros.sh.cpp
libcxx/trunk/test/std/experimental/nothing_to_do.pass.cpp

Modified: libcxx/trunk/include/experimental/string_view
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/experimental/string_view?rev=324290=324289=324290=diff
==
--- libcxx/trunk/include/experimental/string_view (original)
+++ libcxx/trunk/include/experimental/string_view Mon Feb  5 15:43:34 2018
@@ -8,811 +8,4 @@
 //
 
//===--===//
 
-#ifndef _LIBCPP_LFTS_STRING_VIEW
-#define _LIBCPP_LFTS_STRING_VIEW
-
-/*
-string_view synopsis
-
-namespace std {
- namespace experimental {
-  inline namespace library_fundamentals_v1 {
-
-// 7.2, Class template basic_string_view
-template>
-class basic_string_view;
-
-// 7.9, basic_string_view non-member comparison functions
-template
-constexpr bool operator==(basic_string_view x,
-  basic_string_view y) noexcept;
-template
-constexpr bool operator!=(basic_string_view x,
-  basic_string_view y) noexcept;
-template
-constexpr bool operator< (basic_string_view x,
- basic_string_view y) noexcept;
-template
-constexpr bool operator> (basic_string_view x,
-  basic_string_view y) noexcept;
-template
-constexpr bool operator<=(basic_string_view x,
- basic_string_view y) noexcept;
-template
-constexpr bool operator>=(basic_string_view x,
-  basic_string_view y) noexcept;
-// see below, sufficient additional overloads of comparison functions
-
-// 7.10, Inserters and extractors
-template
-  basic_ostream&
-operator<<(basic_ostream& os,
-   basic_string_view str);
-
-// basic_string_view typedef names
-typedef basic_string_view string_view;
-typedef basic_string_view u16string_view;
-typedef basic_string_view u32string_view;
-typedef basic_string_view wstring_view;
-
-template>
-class basic_string_view {
-  public:
-  // types
-  typedef traits traits_type;
-  typedef charT value_type;
-  typedef charT* pointer;
-  typedef const charT* const_pointer;
-  typedef charT& reference;
-  typedef const charT& const_reference;
-  typedef implementation-defined const_iterator;
-  typedef const_iterator iterator;
-  typedef reverse_iterator const_reverse_iterator;
-  typedef const_reverse_iterator reverse_iterator;
-  typedef size_t size_type;
-  typedef ptrdiff_t difference_type;
-  static constexpr size_type npos = size_type(-1);
-
-  // 7.3, basic_string_view constructors and assignment operators
-  constexpr basic_string_view() noexcept;
-  constexpr basic_string_view(const basic_string_view&) noexcept = default;
-  basic_string_view& operator=(const basic_string_view&) noexcept = 
default;
-  template
-  basic_string_view(const basic_string& str) 
noexcept;
-  constexpr basic_string_view(const charT* str);
-  constexpr basic_string_view(const charT* str, size_type len);
-
-  // 7.4, basic_string_view iterator support
-  constexpr const_iterator begin() const noexcept;
-  constexpr const_iterator end() const noexcept;
-  constexpr const_iterator cbegin() const noexcept;
-  constexpr const_iterator cend() const noexcept;
-  const_reverse_iterator rbegin() const noexcept;
-  const_reverse_iterator rend() const noexcept;
-  const_reverse_iterator crbegin() const noexcept;
-  const_reverse_iterator crend() const noexcept;
-
-  // 7.5, basic_string_view capacity
-  constexpr size_type size() const noexcept;
-  constexpr size_type length() const noexcept;
-  constexpr size_type max_size() const noexcept;
-  constexpr bool empty() const noexcept;
-
-  // 7.6, basic_string_view element access
-  constexpr const_reference operator[](size_type pos) const;
-  constexpr const_reference at(size_type pos) const;
-  constexpr const_reference front() const;
-  constexpr const_reference back() const;
-  

r324286 - IRGen: Move vtable load after argument evaluation.

2018-02-05 Thread Peter Collingbourne via cfe-commits
Author: pcc
Date: Mon Feb  5 15:09:13 2018
New Revision: 324286

URL: http://llvm.org/viewvc/llvm-project?rev=324286=rev
Log:
IRGen: Move vtable load after argument evaluation.

This change reduces the live range of the loaded function pointer,
resulting in a slight code size decrease (~10KB in clang), and also
improves the security of CFI for virtual calls by making it less
likely that the function pointer will be spilled, and ensuring that
it is not spilled across a function call boundary.

Fixes PR35353.

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

Added:
cfe/trunk/test/CodeGenCXX/cfi-vcall-check-after-args.cpp
Modified:
cfe/trunk/lib/CodeGen/CGCXXABI.h
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/CodeGen/CGCall.h
cfe/trunk/lib/CodeGen/CGExprCXX.cpp
cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
cfe/trunk/test/CodeGenCXX/cxx2a-destroying-delete.cpp
cfe/trunk/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
cfe/trunk/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp

cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-multiple-nonvirtual-inheritance-this-adjustment.cpp

Modified: cfe/trunk/lib/CodeGen/CGCXXABI.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCXXABI.h?rev=324286=324285=324286=diff
==
--- cfe/trunk/lib/CodeGen/CGCXXABI.h (original)
+++ cfe/trunk/lib/CodeGen/CGCXXABI.h Mon Feb  5 15:09:13 2018
@@ -413,11 +413,10 @@ public:
 CharUnits VPtrOffset) = 0;
 
   /// Build a virtual function pointer in the ABI-specific way.
-  virtual CGCallee getVirtualFunctionPointer(CodeGenFunction ,
- GlobalDecl GD,
- Address This,
- llvm::Type *Ty,
- SourceLocation Loc) = 0;
+  virtual llvm::Value *getVirtualFunctionPointer(CodeGenFunction ,
+ GlobalDecl GD, Address This,
+ llvm::Type *Ty,
+ SourceLocation Loc) = 0;
 
   /// Emit the ABI-specific virtual destructor call.
   virtual llvm::Value *

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=324286=324285=324286=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Mon Feb  5 15:09:13 2018
@@ -3728,7 +3728,7 @@ RValue CodeGenFunction::EmitCall(const C
  SourceLocation Loc) {
   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
 
-  assert(Callee.isOrdinary());
+  assert(Callee.isOrdinary() || Callee.isVirtual());
 
   // Handle struct-return functions by passing a pointer to the
   // location that we would like to return into.
@@ -4052,7 +4052,14 @@ RValue CodeGenFunction::EmitCall(const C
 }
   }
 
-  llvm::Value *CalleePtr = Callee.getFunctionPointer();
+  llvm::Value *CalleePtr;
+  if (Callee.isVirtual()) {
+const CallExpr *CE = Callee.getVirtualCallExpr();
+CalleePtr = CGM.getCXXABI().getVirtualFunctionPointer(
+*this, Callee.getVirtualMethodDecl(), Callee.getThisAddress(),
+Callee.getFunctionType(), CE ? CE->getLocStart() : SourceLocation());
+  } else
+CalleePtr = Callee.getFunctionPointer();
 
   // If we're using inalloca, set up that argument.
   if (ArgMemory.isValid()) {

Modified: cfe/trunk/lib/CodeGen/CGCall.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.h?rev=324286=324285=324286=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.h (original)
+++ cfe/trunk/lib/CodeGen/CGCall.h Mon Feb  5 15:09:13 2018
@@ -18,6 +18,7 @@
 #include "CGValue.h"
 #include "EHScopeStack.h"
 #include "clang/AST/CanonicalType.h"
+#include "clang/AST/GlobalDecl.h"
 #include "clang/AST/Type.h"
 #include "llvm/IR/Value.h"
 
@@ -68,8 +69,9 @@ public:
   Invalid,
   Builtin,
   PseudoDestructor,
+  Virtual,
 
-  Last = PseudoDestructor
+  Last = Virtual
 };
 
 struct BuiltinInfoStorage {
@@ -79,12 +81,19 @@ public:
 struct PseudoDestructorInfoStorage {
   const CXXPseudoDestructorExpr *Expr;
 };
+struct VirtualInfoStorage {
+  const CallExpr *CE;
+  GlobalDecl MD;
+  Address Addr;
+  llvm::FunctionType *FTy;
+};
 
 SpecialKind KindOrFunctionPointer;
 union {
   CGCalleeInfo AbstractInfo;
   BuiltinInfoStorage BuiltinInfo;
   PseudoDestructorInfoStorage PseudoDestructorInfo;
+  VirtualInfoStorage VirtualInfo;
 };
 
 explicit CGCallee(SpecialKind 

[PATCH] D42725: IRGen: Move vtable load after argument evaluation.

2018-02-05 Thread Peter Collingbourne via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL324286: IRGen: Move vtable load after argument evaluation. 
(authored by pcc, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42725?vs=132094=132895#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42725

Files:
  cfe/trunk/lib/CodeGen/CGCXXABI.h
  cfe/trunk/lib/CodeGen/CGCall.cpp
  cfe/trunk/lib/CodeGen/CGCall.h
  cfe/trunk/lib/CodeGen/CGExprCXX.cpp
  cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
  cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
  cfe/trunk/test/CodeGenCXX/cfi-vcall-check-after-args.cpp
  cfe/trunk/test/CodeGenCXX/cxx2a-destroying-delete.cpp
  cfe/trunk/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
  cfe/trunk/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
  
cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-multiple-nonvirtual-inheritance-this-adjustment.cpp

Index: cfe/trunk/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
===
--- cfe/trunk/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
+++ cfe/trunk/test/CodeGenCXX/microsoft-abi-multiple-nonvirtual-inheritance.cpp
@@ -114,16 +114,15 @@
 // the caller site.
 //
 // CHECK: %[[CHILD_i8:.*]] = bitcast %struct.ChildOverride* %[[CHILD]] to i8*
+// CHECK: %[[RIGHT:.*]] = getelementptr inbounds i8, i8* %[[CHILD_i8]], i32 4
 //
+// CHECK: %[[CHILD_i8:.*]] = bitcast %struct.ChildOverride* %[[CHILD]] to i8*
 // CHECK: %[[VFPTR_i8:.*]] = getelementptr inbounds i8, i8* %[[CHILD_i8]], i32 4
 // CHECK: %[[VFPTR:.*]] = bitcast i8* %[[VFPTR_i8]] to void (i8*)***
 // CHECK: %[[VFTABLE:.*]] = load void (i8*)**, void (i8*)*** %[[VFPTR]]
 // CHECK: %[[VFUN:.*]] = getelementptr inbounds void (i8*)*, void (i8*)** %[[VFTABLE]], i64 0
 // CHECK: %[[VFUN_VALUE:.*]] = load void (i8*)*, void (i8*)** %[[VFUN]]
 //
-// CHECK: %[[CHILD_i8:.*]] = bitcast %struct.ChildOverride* %[[CHILD]] to i8*
-// CHECK: %[[RIGHT:.*]] = getelementptr inbounds i8, i8* %[[CHILD_i8]], i32 4
-//
 // CHECK: call x86_thiscallcc void %[[VFUN_VALUE]](i8* %[[RIGHT]])
 // CHECK: ret
 }
Index: cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-multiple-nonvirtual-inheritance-this-adjustment.cpp
===
--- cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-multiple-nonvirtual-inheritance-this-adjustment.cpp
+++ cfe/trunk/test/CodeGenCXX/microsoft-abi-vtables-multiple-nonvirtual-inheritance-this-adjustment.cpp
@@ -156,23 +156,17 @@
 
 // BITCODE-LABEL: define {{.*}}\01?ffun@test4@@YAXAAUC@1@@Z
 void ffun(C ) {
-  // BITCODE: load
-  // BITCODE: bitcast
-  // BITCODE: bitcast
   // BITCODE: [[THIS1:%.+]] = bitcast %"struct.test4::C"* {{.*}} to i8*
   // BITCODE: [[THIS2:%.+]] = getelementptr inbounds i8, i8* [[THIS1]], i32 4
-  // BITCODE-NEXT: call x86_thiscallcc {{.*}}(i8* [[THIS2]])
+  // BITCODE: call x86_thiscallcc {{.*}}(i8* [[THIS2]])
   c.bar();
 }
 
 // BITCODE-LABEL: define {{.*}}\01?fop@test4@@YAXAAUC@1@@Z
 void fop(C ) {
-  // BITCODE: load
-  // BITCODE: bitcast
-  // BITCODE: bitcast
   // BITCODE: [[THIS1:%.+]] = bitcast %"struct.test4::C"* {{.*}} to i8*
   // BITCODE: [[THIS2:%.+]] = getelementptr inbounds i8, i8* [[THIS1]], i32 4
-  // BITCODE-NEXT: call x86_thiscallcc {{.*}}(i8* [[THIS2]])
+  // BITCODE: call x86_thiscallcc {{.*}}(i8* [[THIS2]])
   -c;
 }
 
Index: cfe/trunk/test/CodeGenCXX/cfi-vcall-check-after-args.cpp
===
--- cfe/trunk/test/CodeGenCXX/cfi-vcall-check-after-args.cpp
+++ cfe/trunk/test/CodeGenCXX/cfi-vcall-check-after-args.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -flto -flto-unit -triple x86_64-unknown-linux -fvisibility hidden -fsanitize=cfi-vcall -fsanitize-trap=cfi-vcall -emit-llvm -o - %s | FileCheck %s
+
+struct A {
+  virtual void f(int);
+};
+
+int g();
+void f(A *a) {
+  // CHECK: call i32 @_Z1gv()
+  // CHECK: call i1 @llvm.type.test
+  a->f(g());
+}
Index: cfe/trunk/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
===
--- cfe/trunk/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
+++ cfe/trunk/test/CodeGenCXX/microsoft-abi-virtual-inheritance.cpp
@@ -163,20 +163,20 @@
 // CHECK: %[[VBENTRY:.*]] = getelementptr inbounds i32, i32* %[[VBTABLE]], i32 1
 // CHECK: %[[VBOFFSET32:.*]] = load i32, i32* %[[VBENTRY]]
 // CHECK: %[[VBOFFSET:.*]] = add nsw i32 0, %[[VBOFFSET32]]
-// CHECK: %[[VBASE_i8:.*]] = getelementptr inbounds i8, i8* %[[OBJ_i8]], i32 %[[VBOFFSET]]
-// CHECK: %[[VFPTR:.*]] = bitcast i8* %[[VBASE_i8]] to void (i8*)***
-// CHECK: %[[VFTABLE:.*]] = load void (i8*)**, void (i8*)*** %[[VFPTR]]
-// CHECK: %[[VFUN:.*]] = getelementptr inbounds void (i8*)*, void (i8*)** %[[VFTABLE]], i64 2
-// CHECK: %[[VFUN_VALUE:.*]] = load void (i8*)*, void (i8*)** %[[VFUN]]
+// CHECK: %[[VBASE:.*]] = 

[PATCH] D42704: [clang-format] Do not break Objective-C string literals inside array literals

2018-02-05 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added a comment.

@stephanemoore: It appears all warnings are enabled by default unless they are 
in class `DefaultIgnore`:

https://github.com/llvm-mirror/clang/blob/6de2efd1953adaa9a190b2cdfbe7b5c15f6d6efe/include/clang/Basic/Diagnostic.td#L105

This diagnostic is not in `DefaultIgnore`:

https://github.com/llvm-mirror/clang/blob/a58d0437d1e17d53d7bffea598d77789dd6d28b6/include/clang/Basic/DiagnosticGroups.td#L933

In fact, the `All` class is specifically for warnings which *are* in 
`DefaultIgnore` but which should be emitted with `-Wall`:

https://github.com/llvm-mirror/clang/blob/a58d0437d1e17d53d7bffea598d77789dd6d28b6/include/clang/Basic/DiagnosticGroups.td#L782

  // Note that putting warnings in -Wall will not disable them by default. If a
  // warning should be active _only_ when -Wall is passed in, mark it as
  // DefaultIgnore in addition to putting it here.


Repository:
  rC Clang

https://reviews.llvm.org/D42704



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


[PATCH] D42933: [Sema] Avoid -Wformat warning for NSInteger/NSUInteger 'int' values with %zu/%zi long specifiers

2018-02-05 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman created this revision.
arphaman added reviewers: ahatanak, vsapsai.
Herald added subscribers: jkorous-apple, kristof.beyls, aemerson.

The -Wformat recently started warning for the following code because of the 
added support for analysis for the '%zi' specifier.

  NSInteger i = NSIntegerMax;
  NSLog(@"max NSInteger = %zi", i);

The problem is that on armv7 %zi is 'long', and NSInteger is typedefed to 'int' 
in Foundation. We should avoid this warning as it's inconvenient to our users: 
it's target specific (happens only on armv7 and not arm64), and breaks their 
existing code. We should also silence the warning for the '%zu' specifier to 
ensure consistency.

rdar://36874921


Repository:
  rC Clang

https://reviews.llvm.org/D42933

Files:
  include/clang/Analysis/Analyses/FormatString.h
  lib/Analysis/PrintfFormatString.cpp
  lib/Sema/SemaChecking.cpp
  test/SemaObjC/format-size-spec-nsinteger.m

Index: test/SemaObjC/format-size-spec-nsinteger.m
===
--- /dev/null
+++ test/SemaObjC/format-size-spec-nsinteger.m
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple thumbv7-apple-ios -Wformat -fsyntax-only -fblocks -verify -Wno-objc-root-class %s
+// RUN: %clang_cc1 -triple arm64-apple-ios -Wformat -fsyntax-only -fblocks -verify -Wno-objc-root-class %s
+// expected-no-diagnostics
+
+#if __LP64__
+typedef unsigned long NSUInteger;
+typedef long NSInteger;
+#else
+typedef unsigned int NSUInteger;
+typedef int NSInteger;
+#endif
+
+@class NSString;
+
+extern void NSLog(NSString *format, ...);
+
+void testSizeSpecifier() {
+  NSInteger i = 0;
+  NSUInteger j = 0;
+  NSLog(@"max NSInteger = %zi", i);
+  NSLog(@"max NSUinteger = %zu", j);
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -6374,6 +6374,11 @@
 QualType CastTy;
 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
 if (!CastTy.isNull()) {
+  // %zi/%zu are ok to use for NSInteger/NSUInteger of type int
+  // (long in ASTContext).
+  if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
+  AT.isSizeT() && AT.matchesType(S.Context, CastTy))
+return true;
   IntendedTy = CastTy;
   ShouldNotPrintDirectly = true;
 }
Index: lib/Analysis/PrintfFormatString.cpp
===
--- lib/Analysis/PrintfFormatString.cpp
+++ lib/Analysis/PrintfFormatString.cpp
@@ -466,7 +466,7 @@
   case LengthModifier::AsIntMax:
 return ArgType(Ctx.getIntMaxType(), "intmax_t");
   case LengthModifier::AsSizeT:
-return ArgType(Ctx.getSignedSizeType(), "ssize_t");
+return ArgType::makeSizeT(ArgType(Ctx.getSignedSizeType(), "ssize_t"));
   case LengthModifier::AsInt3264:
 return Ctx.getTargetInfo().getTriple().isArch64Bit()
? ArgType(Ctx.LongLongTy, "__int64")
@@ -499,7 +499,7 @@
   case LengthModifier::AsIntMax:
 return ArgType(Ctx.getUIntMaxType(), "uintmax_t");
   case LengthModifier::AsSizeT:
-return ArgType(Ctx.getSizeType(), "size_t");
+return ArgType::makeSizeT(ArgType(Ctx.getSizeType(), "size_t"));
   case LengthModifier::AsInt3264:
 return Ctx.getTargetInfo().getTriple().isArch64Bit()
? ArgType(Ctx.UnsignedLongLongTy, "unsigned __int64")
Index: include/clang/Analysis/Analyses/FormatString.h
===
--- include/clang/Analysis/Analyses/FormatString.h
+++ include/clang/Analysis/Analyses/FormatString.h
@@ -257,25 +257,36 @@
   const Kind K;
   QualType T;
   const char *Name;
-  bool Ptr;
+  bool Ptr, IsSizeT;
+
 public:
   ArgType(Kind k = UnknownTy, const char *n = nullptr)
-  : K(k), Name(n), Ptr(false) {}
+  : K(k), Name(n), Ptr(false), IsSizeT(false) {}
   ArgType(QualType t, const char *n = nullptr)
-  : K(SpecificTy), T(t), Name(n), Ptr(false) {}
-  ArgType(CanQualType t) : K(SpecificTy), T(t), Name(nullptr), Ptr(false) {}
+  : K(SpecificTy), T(t), Name(n), Ptr(false), IsSizeT(false) {}
+  ArgType(CanQualType t)
+  : K(SpecificTy), T(t), Name(nullptr), Ptr(false), IsSizeT(false) {}
 
   static ArgType Invalid() { return ArgType(InvalidTy); }
   bool isValid() const { return K != InvalidTy; }
 
+  bool isSizeT() const { return IsSizeT; }
+
   /// Create an ArgType which corresponds to the type pointer to A.
   static ArgType PtrTo(const ArgType& A) {
 assert(A.K >= InvalidTy && "ArgType cannot be pointer to invalid/unknown");
 ArgType Res = A;
 Res.Ptr = true;
 return Res;
   }
 
+  /// Create an ArgType which corresponds to the size_t/ssize_t type.
+  static ArgType makeSizeT(const ArgType ) {
+ArgType Res = A;
+Res.IsSizeT = true;
+return Res;
+  }
+
   MatchKind matchesType(ASTContext , QualType argTy) const;
 
   

[PATCH] D42915: [clangd] Use URIs in index symbols.

2018-02-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This looks OK so far, where is it going? It doesn't make sense to put URIs in 
if we only ever use `file:`.
I guess others will be produced by some kind of extension point on 
SymbolCollector. That will specify URI schemes we should try, allow you to 
replace the whole `toFileURI`, or something else?

Unfortunately there's a bunch of `Uri`s here, where the existing code uses 
`URI`...




Comment at: clangd/index/Index.h:27
+  // The URI of the source file where a symbol occurs.
+  llvm::StringRef FileUri;
   // The 0-based offset to the first character of the symbol from the beginning

nit: FileURI?
(The other style is OK too, though I personally find it harder to read. But the 
class is `URI` and we should be consistent)



Comment at: clangd/index/SymbolCollector.cpp:28
+// current working directory of the given SourceManager if the Path is not an
+// absolute path. If failed, this combine relative paths with \p FallbackDir to
+// get an absolute path.

this combines

or better, "resolves relative paths against \p FallbackDir"



Comment at: clangd/index/SymbolCollector.cpp:33
 // the SourceManager.
-std::string makeAbsolutePath(const SourceManager , StringRef Path,
- StringRef FallbackDir) {
+std::string toFileUri(const SourceManager , StringRef Path,
+  StringRef FallbackDir) {

also URI here, and below



Comment at: clangd/index/SymbolCollector.cpp:201
+std::string Uri;
+S.CanonicalDeclaration = GetSymbolLocation(ND, SM, Opts.FallbackDir, Uri);
 

while here, would you mind changing GetSymbolLocation -> getSymbolLocation?



Comment at: clangd/index/SymbolYAML.cpp:51
 IO.mapRequired("EndOffset", Value.EndOffset);
-IO.mapRequired("FilePath", Value.FilePath);
+IO.mapRequired("FileUri", Value.FileUri);
   }

more URI


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42915



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


[PATCH] D41889: [libcxxabi][demangler] Clean up and llvm-ify the type parser

2018-02-05 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL324282: [demangler] Refactor the type parser (authored by 
epilk, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D41889?vs=132747=132891#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D41889

Files:
  libcxxabi/trunk/src/cxa_demangle.cpp

Index: libcxxabi/trunk/src/cxa_demangle.cpp
===
--- libcxxabi/trunk/src/cxa_demangle.cpp
+++ libcxxabi/trunk/src/cxa_demangle.cpp
@@ -340,20 +340,17 @@
 
 class VendorExtQualType final : public Node {
   const Node *Ty;
-  const Node *Ext;
+  StringView Ext;
 
 public:
-  VendorExtQualType(Node *Ty_, Node *Ext_)
-  : Node(KVendorExtQualType,
- std::min(Ty_->ParameterPackSize, Ext_->ParameterPackSize)),
+  VendorExtQualType(Node *Ty_, StringView Ext_)
+  : Node(KVendorExtQualType, Ty_->ParameterPackSize),
 Ty(Ty_), Ext(Ext_) {}
 
-  const Node* getQual() const { return Ext; }
-
   void printLeft(OutputStream ) const override {
 Ty->print(S);
 S += " ";
-Ext->print(S);
+S += Ext;
   }
 };
 
@@ -465,12 +462,12 @@
 
 class ObjCProtoName : public Node {
   Node *Ty;
-  Node *Protocol;
+  StringView Protocol;
 
   friend class PointerType;
 
 public:
-  ObjCProtoName(Node *Ty_, Node *Protocol_)
+  ObjCProtoName(Node *Ty_, StringView Protocol_)
   : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
 
   bool isObjCObject() const {
@@ -481,7 +478,7 @@
   void printLeft(OutputStream ) const override {
 Ty->print(S);
 S += "<";
-Protocol->print(S);
+S += Protocol;
 S += ">";
   }
 };
@@ -512,7 +509,7 @@
 } else {
   const auto *objcProto = static_cast(Pointee);
   s += "id<";
-  objcProto->Protocol->print(s);
+  s += objcProto->Protocol;
   s += ">";
 }
   }
@@ -1958,6 +1955,8 @@
 
   StringView parseNumber(bool AllowNegative = false);
   Qualifiers parseCVQualifiers();
+  bool parsePositiveInteger(size_t *Out);
+  StringView parseBareSourceName();
 
   /// Parse the  production.
   Node *parseExpr();
@@ -1970,6 +1969,15 @@
   Node *parseNewExpr();
   Node *parseConversionExpr();
 
+  /// Parse the  production.
+  Node *parseType();
+  Node *parseFunctionType();
+  Node *parseVectorType();
+  Node *parseDecltype();
+  Node *parseArrayType();
+  Node *parsePointerToMemberType();
+  Node *parseClassEnumType();
+
   // FIXME: remove this when all the parse_* functions have been rewritten.
   template 
   Node *legacyParse() {
@@ -1983,6 +1991,18 @@
 Names.pop_back();
 return R;
   }
+  template 
+  Node *legacyParse() {
+size_t BeforeType = Names.size();
+const char *OrigFirst = First;
+const char *T = parse_fn(First, Last, *this, nullptr);
+if (T == OrigFirst || BeforeType + 1 != Names.size())
+  return nullptr;
+First = T;
+Node *R = Names.back();
+Names.pop_back();
+return R;
+  }
 };
 
 const char *parse_expression(const char *first, const char *last, Db ) {
@@ -2005,6 +2025,26 @@
   return db.First;
 }
 
+const char *parse_type(const char *first, const char *last, Db ) {
+  db.First = first;
+  db.Last = last;
+  Node *R = db.parseType();
+  if (R == nullptr)
+return first;
+  db.Names.push_back(R);
+  return db.First;
+}
+
+const char *parse_decltype(const char *first, const char *last, Db ) {
+  db.First = first;
+  db.Last = last;
+  Node *R = db.parseDecltype();
+  if (R == nullptr)
+return first;
+  db.Names.push_back(R);
+  return db.First;
+}
+
 const char *parse_type(const char *first, const char *last, Db );
 const char *parse_encoding(const char *first, const char *last, Db );
 const char *parse_name(const char *first, const char *last, Db ,
@@ -2015,6 +2055,7 @@
 const char *parse_unqualified_name(const char *first, const char *last, Db );
 const char *parse_decltype(const char *first, const char *last, Db );
 const char *parse_unresolved_name(const char *, const char *, Db &);
+const char *parse_substitution(const char *, const char *, Db &);
 
 //  ::= [n] 
 StringView Db::parseNumber(bool AllowNegative) {
@@ -2028,6 +2069,539 @@
   return StringView(Tmp, First);
 }
 
+//  ::= [0-9]*
+bool Db::parsePositiveInteger(size_t *Out) {
+  *Out = 0;
+  if (look() < '0' || look() > '9')
+return true;
+  while (look() >= '0' && look() <= '9') {
+*Out *= 10;
+*Out += static_cast(consume() - '0');
+  }
+  return false;
+}
+
+StringView Db::parseBareSourceName() {
+  size_t Int = 0;
+  if (parsePositiveInteger() || numLeft() < Int)
+return StringView();
+  StringView R(First, First + Int);
+  First += Int;
+  return R;
+}
+
+//  ::= F [Y]  [] E
+//
+//   ::= R   # & ref-qualifier
+//   ::= O   # && ref-qualifier
+Node *Db::parseFunctionType() {
+  if (!consumeIf('F'))
+return nullptr;
+  consumeIf('Y'); // extern "C"
+  Node *ReturnType = parseType();
+  if 

[libcxxabi] r324282 - [demangler] Refactor the type parser

2018-02-05 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Mon Feb  5 14:41:20 2018
New Revision: 324282

URL: http://llvm.org/viewvc/llvm-project?rev=324282=rev
Log:
[demangler] Refactor the type parser

Differential revision: https://reviews.llvm.org/D41889

Modified:
libcxxabi/trunk/src/cxa_demangle.cpp

Modified: libcxxabi/trunk/src/cxa_demangle.cpp
URL: 
http://llvm.org/viewvc/llvm-project/libcxxabi/trunk/src/cxa_demangle.cpp?rev=324282=324281=324282=diff
==
--- libcxxabi/trunk/src/cxa_demangle.cpp (original)
+++ libcxxabi/trunk/src/cxa_demangle.cpp Mon Feb  5 14:41:20 2018
@@ -340,20 +340,17 @@ public:
 
 class VendorExtQualType final : public Node {
   const Node *Ty;
-  const Node *Ext;
+  StringView Ext;
 
 public:
-  VendorExtQualType(Node *Ty_, Node *Ext_)
-  : Node(KVendorExtQualType,
- std::min(Ty_->ParameterPackSize, Ext_->ParameterPackSize)),
+  VendorExtQualType(Node *Ty_, StringView Ext_)
+  : Node(KVendorExtQualType, Ty_->ParameterPackSize),
 Ty(Ty_), Ext(Ext_) {}
 
-  const Node* getQual() const { return Ext; }
-
   void printLeft(OutputStream ) const override {
 Ty->print(S);
 S += " ";
-Ext->print(S);
+S += Ext;
   }
 };
 
@@ -465,12 +462,12 @@ public:
 
 class ObjCProtoName : public Node {
   Node *Ty;
-  Node *Protocol;
+  StringView Protocol;
 
   friend class PointerType;
 
 public:
-  ObjCProtoName(Node *Ty_, Node *Protocol_)
+  ObjCProtoName(Node *Ty_, StringView Protocol_)
   : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
 
   bool isObjCObject() const {
@@ -481,7 +478,7 @@ public:
   void printLeft(OutputStream ) const override {
 Ty->print(S);
 S += "<";
-Protocol->print(S);
+S += Protocol;
 S += ">";
   }
 };
@@ -512,7 +509,7 @@ public:
 } else {
   const auto *objcProto = static_cast(Pointee);
   s += "id<";
-  objcProto->Protocol->print(s);
+  s += objcProto->Protocol;
   s += ">";
 }
   }
@@ -1958,6 +1955,8 @@ struct Db {
 
   StringView parseNumber(bool AllowNegative = false);
   Qualifiers parseCVQualifiers();
+  bool parsePositiveInteger(size_t *Out);
+  StringView parseBareSourceName();
 
   /// Parse the  production.
   Node *parseExpr();
@@ -1970,6 +1969,15 @@ struct Db {
   Node *parseNewExpr();
   Node *parseConversionExpr();
 
+  /// Parse the  production.
+  Node *parseType();
+  Node *parseFunctionType();
+  Node *parseVectorType();
+  Node *parseDecltype();
+  Node *parseArrayType();
+  Node *parsePointerToMemberType();
+  Node *parseClassEnumType();
+
   // FIXME: remove this when all the parse_* functions have been rewritten.
   template 
   Node *legacyParse() {
@@ -1983,6 +1991,18 @@ struct Db {
 Names.pop_back();
 return R;
   }
+  template 
+  Node *legacyParse() {
+size_t BeforeType = Names.size();
+const char *OrigFirst = First;
+const char *T = parse_fn(First, Last, *this, nullptr);
+if (T == OrigFirst || BeforeType + 1 != Names.size())
+  return nullptr;
+First = T;
+Node *R = Names.back();
+Names.pop_back();
+return R;
+  }
 };
 
 const char *parse_expression(const char *first, const char *last, Db ) {
@@ -2005,6 +2025,26 @@ const char *parse_expr_primary(const cha
   return db.First;
 }
 
+const char *parse_type(const char *first, const char *last, Db ) {
+  db.First = first;
+  db.Last = last;
+  Node *R = db.parseType();
+  if (R == nullptr)
+return first;
+  db.Names.push_back(R);
+  return db.First;
+}
+
+const char *parse_decltype(const char *first, const char *last, Db ) {
+  db.First = first;
+  db.Last = last;
+  Node *R = db.parseDecltype();
+  if (R == nullptr)
+return first;
+  db.Names.push_back(R);
+  return db.First;
+}
+
 const char *parse_type(const char *first, const char *last, Db );
 const char *parse_encoding(const char *first, const char *last, Db );
 const char *parse_name(const char *first, const char *last, Db ,
@@ -2015,6 +2055,7 @@ const char *parse_operator_name(const ch
 const char *parse_unqualified_name(const char *first, const char *last, Db 
);
 const char *parse_decltype(const char *first, const char *last, Db );
 const char *parse_unresolved_name(const char *, const char *, Db &);
+const char *parse_substitution(const char *, const char *, Db &);
 
 //  ::= [n] 
 StringView Db::parseNumber(bool AllowNegative) {
@@ -2028,6 +2069,539 @@ StringView Db::parseNumber(bool AllowNeg
   return StringView(Tmp, First);
 }
 
+//  ::= [0-9]*
+bool Db::parsePositiveInteger(size_t *Out) {
+  *Out = 0;
+  if (look() < '0' || look() > '9')
+return true;
+  while (look() >= '0' && look() <= '9') {
+*Out *= 10;
+*Out += static_cast(consume() - '0');
+  }
+  return false;
+}
+
+StringView Db::parseBareSourceName() {
+  size_t Int = 0;
+  if (parsePositiveInteger() || numLeft() < Int)
+return StringView();
+  StringView R(First, First + Int);
+  First += Int;
+  return R;
+}
+
+//  ::= F [Y]  [] E
+//
+//   ::= R  

[PATCH] D41102: Setup clang-doc frontend framework

2018-02-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a subscriber: bkramer.
sammccall added a comment.

In https://reviews.llvm.org/D41102#998180, @thakis wrote:

> This should be in clang-tools-extra next to clang-tidy, clang-include-fixer, 
> clangd etc, not in the main compiler repo, right?


I agree. I see there was earlier discussion on this, which concluded that 
clang-tools-extra was going to merge into clang.
From talking to people working in c-t-e (particularly @bkramer), it sounds like:

- a merge isn't likely to happen soon
- clang-tools is appropriate as tools are mature, support the platforms clang 
does, and part of more developers' workflows (e.g. clang-format)
- new things should probably go in c-t-e if possible

Sorry for the back and forth :-\


https://reviews.llvm.org/D41102



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


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

2018-02-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Very nice! Thanks for adding the docs to TUScheduler implementation, makes a 
big difference.

Rest is almost all readability/comment bits. Substantive stuff is:

- getUsedBytes() looks racy
- I'm not sure we're choosing the right preamble

My understanding is the threading-related bits of CppFile (locking, and 
deferRebuild etc) are obsolete after this patch.
It's fine not to delete them here (I guess there could be some fallout), but 
maybe you want to add a comment in this patch marking them as obsolete?

Testing: I think this is mostly covered by the existing TUScheduler tests. I'd 
suggest adding a unit test to AsyncTaskRunner though: e.g. start a bunch of 
threads while holding a mutex that prevents them from making progress (to 
verify actually async), then have them increment a counter and verify that the 
counter is N after waitForAll() returns.




Comment at: clangd/ASTWorker.cpp:102
+  // not waste time on it.
+  LastUpdateCF->cancel();
+}

ilya-biryukov wrote:
> sammccall wrote:
> > This strategy has some upsides:
> >  - we eventually get diagnostics for the latest version
> >  - we don't begin building an AST that we know can never be read
> >  - we don't "wait" when there's something useful to do
> >  - it's simple to implement (apart from cancellation)
> > And downsides:
> >  - diagnostics are built on the first keystroke
> >  - indexing blocks interactive actions, because we don't (and can't 
> > reasonably) respect cancellation before calling OnUpdated
> >  - it requires CancellationFlag even though our actions aren't cancelable
> > 
> > What's the goal here - is this a strategy to keep? Or a placeholder? Or 
> > trying to maximize compatibility with the previous code?
> Trying to maximize the compatibility with existing code. There are certainly 
> other strategies to schedule updates.
> I'm perfectly happy to explore those, but would try to keep it out of this 
> patch, it's touching quite a lot of things already. And we should probably 
> remove the callback from update in order to make implementing the timeouts 
> simpler
This sounds fine - can you add a little bit of this rationale and things we 
might want to change? Maybe at the end of the header comment?

As it stands, it would be very easy for us to land this, move onto other things 
for a month, and lose the reasoning why the strategy is this way.



Comment at: clangd/TUScheduler.cpp:38
+  // Wait for all in-flight tasks to finish.
+  Tasks.waitForAll();
+}

ilya-biryukov wrote:
> sammccall wrote:
> > destructor will do this
> It's much safer to call it explicitly to not depend no the order of fields in 
> the class.
Hmm, not sure it's much safer than putting a comment on a member, but up to you.

If we're not using the destructor-blocking behavior, remove the destructor or 
replace with an assert?



Comment at: clangd/TUScheduler.cpp:9
+//===--===//
+// For each file, managed by TUScheduler, we store a single ASTWorker that
+// manages an AST for that file. All operations that modify or read the AST are

nit: store -> create? storage is a bit more complicated, but doesn't need to 
clutter the opening sentence.



Comment at: clangd/TUScheduler.cpp:11
+// manages an AST for that file. All operations that modify or read the AST are
+// run on a separate dedicated thread asynchronously in FIFO order. The
+// ASTWorker that manages the AST is owned both by the processing thread and 
the

nit: blank line after "...FIFO order"? separating "this is the hierarchy" from 
"this is how we manage lifetimes".

In fact, I'd consider moving the whole lifetime explanation down and merging it 
with the ASTWorker class comment. It's more detail than strategy.



Comment at: clangd/TUScheduler.cpp:12
+// run on a separate dedicated thread asynchronously in FIFO order. The
+// ASTWorker that manages the AST is owned both by the processing thread and 
the
+// TUScheduler. Therefore the destructor of ASTWorker to not block, as it is

is shared by?



Comment at: clangd/TUScheduler.cpp:13
+// ASTWorker that manages the AST is owned both by the processing thread and 
the
+// TUScheduler. Therefore the destructor of ASTWorker to not block, as it is
+// always run after the processing loop is finished. When the TUScheduler gives

I can't really follow these two sentences.  I think we may want to give a 
little motivation (it's not clear why the destructor needs to not block) before 
introducing ASTWorkerHandle. e.g.

// The TUScheduler should discard an ASTWorker when remove() is called, but its 
thread may 
// be busy and we don't want to block. So the workers are accessed via an 
ASTWorkerHandle.
// Destroying the handle signals the worker to exit its 

[PATCH] D41240: [Solaris] __float128 is supported on Solaris/x86

2018-02-05 Thread Rainer Orth via Phabricator via cfe-commits
ro added a comment.

ping^2


Repository:
  rC Clang

https://reviews.llvm.org/D41240



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


[PATCH] D41241: [Solaris] Only define _REENTRANT if -pthread

2018-02-05 Thread Rainer Orth via Phabricator via cfe-commits
ro added a comment.

ping^4


Repository:
  rC Clang

https://reviews.llvm.org/D41241



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


[PATCH] D40903: [Sanitizers] Basic Solaris sanitizer support (PR 33274)

2018-02-05 Thread Rainer Orth via Phabricator via cfe-commits
ro added a comment.

Could anyone please commit this for me?

Thanks.

  Rainer


Repository:
  rC Clang

https://reviews.llvm.org/D40903



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


[PATCH] D41242: [Solaris] Silence -pthread warning on Solaris

2018-02-05 Thread Rainer Orth via Phabricator via cfe-commits
ro added a comment.

Could anyone please commit this for me?

Thanks.

  Rainer


Repository:
  rC Clang

https://reviews.llvm.org/D41242



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


[PATCH] D42704: [clang-format] Do not break Objective-C string literals inside array literals

2018-02-05 Thread Stephane Moore via Phabricator via cfe-commits
stephanemoore added a comment.

The summary states that -Wobjc-string-concatenation is enabled by default? I 
looked through `include/clang/Basic/DiagnosticGroups.td` and did not see 
evidence that `ObjCStringConcatenation` is under `All`. Am I missing something? 
Is -Wobjc-string-concatenation enabled by default through some other mechanism?


Repository:
  rC Clang

https://reviews.llvm.org/D42704



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


[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-05 Thread Greg Rodgers via Phabricator via cfe-commits
gregrodgers added a comment.

Here my replys to the inline comments.   Everything should be fixed in the next 
revision.




Comment at: include/clang/Basic/Cuda.h:79
   COMPUTE_72,
+  COMPUTE_GCN,
 };

t-tye wrote:
> Suggest using amdgcn which matches the architecture name in 
> https://llvm.org/docs/AMDGPUUsage.html#processors .
Yes,  I will add them in the update.



Comment at: include/clang/Basic/Cuda.h:79
   COMPUTE_72,
+  COMPUTE_GCN,
 };

gregrodgers wrote:
> t-tye wrote:
> > Suggest using amdgcn which matches the architecture name in 
> > https://llvm.org/docs/AMDGPUUsage.html#processors .
> Yes,  I will add them in the update.
Done in next update



Comment at: lib/Basic/Targets/AMDGPU.cpp:437
+  case CudaArch::UNKNOWN:
+assert(false && "No GPU arch when compiling CUDA device code.");
+return "";

arsenm wrote:
> llvm_unreachable
Fixed in next update




Comment at: lib/Basic/Targets/AMDGPU.h:85
 return TT.getEnvironmentName() == "amdgiz" ||
+   TT.getOS() == llvm::Triple::CUDA ||
TT.getEnvironmentName() == "amdgizcl";

yaxunl wrote:
> t-tye wrote:
> > We still want to use the amdhsa OS for amdgpu which currently supports the 
> > different environments. So can cuda simply support the same environments? 
> > Is the plan is to eliminate the environments and simply always use the 
> > default address space for generic so this code is no longer needed?
> Currently we already use amdgiz by default. This is no longer needed.
removed in next update



Comment at: lib/Driver/ToolChains/Cuda.cpp:359-361
+  addBCLib(C, Args, CmdArgs, LibraryPaths, "opencl.amdgcn.bc");
+  addBCLib(C, Args, CmdArgs, LibraryPaths, "ockl.amdgcn.bc");
+  addBCLib(C, Args, CmdArgs, LibraryPaths, "irif.amdgcn.bc");

arsenm wrote:
> Why is this done under an NVPTX:: class
Because we are not creating a new toolchain for AMDGCN.  We modify the logic in 
the tool constructor as needed for AMDGCN, keeping the ability to provide a set 
of mixed targets. 



Comment at: lib/Driver/ToolChains/Cuda.cpp:403-415
+  // If Verbose, save input for llc in /tmp and print all symbols
+  if (Args.hasArg(options::OPT_v)) {
+ArgStringList nmArgs;
+nmArgs.push_back(ResultingBitcodeF);
+nmArgs.push_back("-debug-syms");
+const char *nmExec = Args.MakeArgString(C.getDriver().Dir + "/llvm-nm");
+C.addCommand(llvm::make_unique(JA, *this, nmExec, nmArgs, 
Inputs));

Hahnfeld wrote:
> This never gets cleaned up!
OK, Deleted in revision. 



Comment at: lib/Driver/ToolChains/Cuda.cpp:531-534
+  SmallString<256> OutputFileName(Output.getFilename());
+  if (JA.isOffloading(Action::OFK_OpenMP))
+llvm::sys::path::replace_extension(OutputFileName, "cubin");
+  CmdArgs.push_back(Args.MakeArgString(OutputFileName));

Hahnfeld wrote:
> That is already done in `TC.getInputFilename(Output)` (since rC318763), the 
> same function call that you are removing here...
Fixed in next update



Comment at: lib/Driver/ToolChains/Cuda.cpp:639-640
+CmdArgs2.push_back(Args.MakeArgString(Output.getFilename()));
+const char *Exec2 =
+Args.MakeArgString(C.getDriver().Dir + "/clang-fixup-fatbin");
+C.addCommand(

Hahnfeld wrote:
> `clang-fixup-fatbin` is not upstreamed and won't work. Sounds like a horrible 
> name btw...
Major cleanup here in the next update.  It is not a bad name when you see the 
update and the comments in the update. 



Comment at: lib/Driver/ToolChains/Cuda.cpp:788-793
+  // Do not add -link-cuda-bitcode or ptx42 features if gfx
+  for (Arg *A : DriverArgs)
+if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) &&
+StringRef(A->getValue()).startswith("gfx"))
+  return;
+

Hahnfeld wrote:
> You should use `GpuArch` which comes from `DriverArgs.getLastArgValue`: The 
> last `-march` overrides previous arguments.
Nice catch.  I will fix this in the next update. 


https://reviews.llvm.org/D42800



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


[clang-tools-extra] r324277 - [clangd] Add a cstring include for strerror.

2018-02-05 Thread Benjamin Kramer via cfe-commits
Author: d0k
Date: Mon Feb  5 14:10:39 2018
New Revision: 324277

URL: http://llvm.org/viewvc/llvm-project?rev=324277=rev
Log:
[clangd] Add a cstring include for strerror.

Apparently this doesn't get included transitively on some systems.

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

Modified: clang-tools-extra/trunk/clangd/Context.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/Context.cpp?rev=324277=324276=324277=diff
==
--- clang-tools-extra/trunk/clangd/Context.cpp (original)
+++ clang-tools-extra/trunk/clangd/Context.cpp Mon Feb  5 14:10:39 2018
@@ -19,6 +19,7 @@
 // It requires support from the runtime: __cxa_thread_atexit.
 // Rather than detect this, we use the pthread API where available.
 #include 
+#include 
 static clang::clangd::Context () {
   using clang::clangd::Context;
   static pthread_key_t CtxKey;


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


[PATCH] D42887: [Driver] Add option to manually control discarding value names in LLVM IR.

2018-02-05 Thread Justin Bogner via Phabricator via cfe-commits
bogner added inline comments.



Comment at: lib/Driver/ToolChains/Clang.cpp:3269-3274
+  const bool IsAssertBuild =
 #ifdef NDEBUG
-  CmdArgs.push_back("-disable-llvm-verifier");
-  // Discard LLVM value names in -asserts builds.
-  CmdArgs.push_back("-discard-value-names");
+  false;
+#else
+  true;
 #endif

It might be a few more characters, but I feel like this is more readable if you 
put entire statements in the branches of the #if, ie:

#ifdef NDEBUG
  const bool IsAssertBuild = false;
#else
  const bool IsAssertBuild = true;
#endif


https://reviews.llvm.org/D42887



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


[PATCH] D42745: [analyzer] Add support for __builtin_constant_p to BuiltinFunctionChecker

2018-02-05 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Oh, i see what you did here. I thought you're evaluating the argument, but 
you're evaluating the whole builtin function call. In this case you don't need 
the else-branch: `EvaluateAsInt` will always succeed. Moreover, you can merge 
your code with the `BI__builtin_object_size` case, which is also fully 
evaluated at compile-time.

Actually, maybe we should use that approach to evaluate more builtin functions, 
and all C++ //constexpr// function calls as well, in the engine or in a 
checker. It would be a nice thing to tackle eventually.


https://reviews.llvm.org/D42745



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


[PATCH] D42704: [clang-format] Do not break Objective-C string literals inside array literals

2018-02-05 Thread Ben Hamilton via Phabricator via cfe-commits
benhamilton added a comment.

Ping ping!


Repository:
  rC Clang

https://reviews.llvm.org/D42704



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


[PATCH] D41102: Setup clang-doc frontend framework

2018-02-05 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

This should be in clang-tools-extra next to clang-tidy, clang-include-fixer, 
clangd etc, not in the main compiler repo, right?


https://reviews.llvm.org/D41102



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


[PATCH] D41102: Setup clang-doc frontend framework

2018-02-05 Thread Jake Ehrlich via Phabricator via cfe-commits
jakehehrlich added a comment.

Additional note: This diff is a diff from your last commit not the full diff 
relative to origin/master which is what should be up here.




Comment at: tools/clang-doc/ClangDoc.cpp:34
 
-bool ClangDocVisitor::VisitNamespaceDecl(const NamespaceDecl *D) {
+template <>
+void ClangDocCallback::processMatchedDecl(

I can't think of a good way to dedup these two methods at the moment. Can you 
put a TODO here to deduplicate these two specializations?



Comment at: tools/clang-doc/ClangDoc.h:69
 
-private:
-  ClangDocVisitor Visitor;
-  ClangDocReporter 
-};
-
-class ClangDocAction : public clang::ASTFrontendAction {
-public:
-  ClangDocAction(ClangDocReporter ) : Reporter(Reporter) {}
-
-  virtual std::unique_ptr
-  CreateASTConsumer(clang::CompilerInstance , llvm::StringRef InFile);
+  virtual void HandleTranslationUnit(clang::ASTContext ) {
+Finder->matchAST(Context);

This should be moved to the .cpp file. Because there is no key function 
(https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vague-vtable) this method 
will be redefined in every translation unit that includes this header.



Comment at: tools/clang-doc/ClangDocReporter.cpp:422
+void ClangDocReporter::serializeLLVM(StringRef RootDir) {
+  // TODO: Implement.
+}

jakehehrlich wrote:
> Can you report an error to the user that says something along the lines of 
> "not implemented yet" (leave the TODO as well)
I think it would be better if instead of returning a string, you just fail and 
print a message to the user (well, first print the message and then fail).



Comment at: tools/clang-doc/ClangDocReporter.cpp:41
+  Docs.Files[Filename] = llvm::make_unique();
+  Docs.Files[Filename]->Filename = Filename;
 }

nit: Can this just do one lookup?

```
auto F = llvm::make_unique();
F->Filename = Filename;
Docs.Files[Filename] = std::move(Filename);
```



Comment at: tools/clang-doc/ClangDocReporter.cpp:136
+  if (NS == Docs.Namespaces.end()) {
+Docs.Namespaces[Namespace] = llvm::make_unique();
+Docs.Namespaces[Namespace]->FullyQualifiedName = Namespace;

nit: could you rewrite with a single lookup.



Comment at: tools/clang-doc/ClangDocReporter.cpp:190
 return;
-  CommentInfo CI;
-  parseFullComment(C, CI);
-  I.Descriptions.push_back(CI);
+  I.Descriptions.push_back(std::move(parseFullComment(C)));
 }

If you use emplace_back here you don't need the explicit std::move



Comment at: tools/clang-doc/ClangDocReporter.cpp:281-288
+  sys::path::native(RootDir, FilePath);
+  sys::path::append(FilePath, "files.yaml");
+  raw_fd_ostream FileOS(FilePath, OutErrorInfo, sys::fs::F_None);
+  if (OutErrorInfo != OK) {
+errs() << OutErrorInfo.message();
+errs() << " Error opening documentation file.\n";
+return;

You use the same basic code 3 times for different file names. Can you factor 
that out into a function? Also in this block you output the OutErrorInfo 
message but in blocks below you don't. You should always output that message.



Comment at: tools/clang-doc/ClangDocReporter.cpp:335
+  RootCI->Kind = C->getCommentKindName();
+  CurrentCI = RootCI.get();
+  ConstCommentVisitor::visit(C);

Instead of assigning a CI like this, could you construct a new 
ClangDocCommentVisitor on the stack? The idea would be that you could would 
still have a "CI" member variable that would be set in the 
ClangDocCommentVisitor's constructor. That way it never has to change and each 
visitor is just responsible for constructing one CommentInfo





Comment at: tools/clang-doc/ClangDocReporter.h:168
 private:
+  template 
+  void createInfo(llvm::StringMap , const C *D,

If you add a public "using DeclType = FooDecl;" to each "FooInfo" you can 
eliminate the second template argument and make the intent of this code more 
clear. This also formalizes the connection these types have to each other.



Comment at: tools/clang-doc/tool/ClangDocMain.cpp:76
+  if (DirectoryStatus != OK) {
+errs() << "Unable to create documentation directories.\n";
+return 1;

Can you convert this error_code to a message and display that to the user?


https://reviews.llvm.org/D41102



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


Re: [libcxx] r324182 - [libc++] Fix PR35491 - std::array of zero-size doesn't work with non-default constructible types.

2018-02-05 Thread Nirav Davé via cfe-commits
https://bugs.llvm.org/show_bug.cgi?id=36241


On Mon, Feb 5, 2018 at 10:20 AM Hans Wennborg via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> This broke the Chromium build, see
> https://bugs.chromium.org/p/chromium/issues/detail?id=809050#c2
>
> I see there were a lot of changes landed around the same time, so I'm
> not sure what to revert here exactly.
>
> On Sun, Feb 4, 2018 at 2:03 AM, Eric Fiselier via cfe-commits
>  wrote:
> > Author: ericwf
> > Date: Sat Feb  3 17:03:08 2018
> > New Revision: 324182
> >
> > URL: http://llvm.org/viewvc/llvm-project?rev=324182=rev
> > Log:
> > [libc++] Fix PR35491 - std::array of zero-size doesn't work with
> non-default constructible types.
> >
> > Summary:
> > This patch fixes llvm.org/PR35491 and LWG2157  (
> https://cplusplus.github.io/LWG/issue2157)
> >
> > The fix attempts to maintain ABI compatibility by replacing the array
> with a instance of `aligned_storage`.
> >
> > Reviewers: mclow.lists, EricWF
> >
> > Reviewed By: EricWF
> >
> > Subscribers: lichray, cfe-commits
> >
> > Differential Revision: https://reviews.llvm.org/D41223
> >
> > Modified:
> > libcxx/trunk/include/array
> >
>  libcxx/trunk/test/std/containers/sequences/array/array.cons/default.pass.cpp
> >
>  libcxx/trunk/test/std/containers/sequences/array/array.data/data.pass.cpp
> >
>  
> libcxx/trunk/test/std/containers/sequences/array/array.data/data_const.pass.cpp
> > libcxx/trunk/test/std/containers/sequences/array/begin.pass.cpp
> >
> > Modified: libcxx/trunk/include/array
> > URL:
> http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/array?rev=324182=324181=324182=diff
> >
> ==
> > --- libcxx/trunk/include/array (original)
> > +++ libcxx/trunk/include/array Sat Feb  3 17:03:08 2018
> > @@ -118,6 +118,55 @@ template  c
> >  _LIBCPP_BEGIN_NAMESPACE_STD
> >
> >  template 
> > +struct __array_traits {
> > +  typedef _Tp _StorageT[_Size];
> > +
> > +  _LIBCPP_INLINE_VISIBILITY
> > +  static _LIBCPP_CONSTEXPR_AFTER_CXX14 _Tp* __data(_StorageT& __store) {
> > +return __store;
> > +  }
> > +
> > +  _LIBCPP_INLINE_VISIBILITY
> > +  static _LIBCPP_CONSTEXPR_AFTER_CXX14 _Tp const* __data(const
> _StorageT& __store) {
> > +return __store;
> > +  }
> > +
> > +  _LIBCPP_INLINE_VISIBILITY
> > +  static void __swap(_StorageT& __lhs, _StorageT& __rhs) {
> > +std::swap_ranges(__lhs, __lhs + _Size, __rhs);
> > +  }
> > +
> > +  _LIBCPP_INLINE_VISIBILITY
> > +  static void __fill(_StorageT& __arr, _Tp const& __val) {
> > +_VSTD::fill_n(__arr, _Size, __val);
> > +  }
> > +};
> > +
> > +template 
> > +struct __array_traits<_Tp, 0> {
> > +  typedef typename aligned_storage alignment_of<_Tp>::value>::type _StorageT;
> > +
> > +  _LIBCPP_INLINE_VISIBILITY
> > +  static _Tp* __data(_StorageT& __store) {
> > +_StorageT *__ptr = std::addressof(__store);
> > +return reinterpret_cast<_Tp*>(__ptr);
> > +  }
> > +
> > +  _LIBCPP_INLINE_VISIBILITY
> > +  static const _Tp* __data(const _StorageT& __store) {
> > +const _StorageT *__ptr = std::addressof(__store);
> > +return reinterpret_cast(__ptr);
> > +  }
> > +
> > +  _LIBCPP_INLINE_VISIBILITY
> > +  static void __swap(_StorageT&, _StorageT&) {}
> > +
> > +  _LIBCPP_INLINE_VISIBILITY
> > +  static void __fill(_StorageT&, _Tp const&) {
> > +  }
> > +};
> > +
> > +template 
> >  struct _LIBCPP_TEMPLATE_VIS array
> >  {
> >  // types:
> > @@ -134,31 +183,26 @@ struct _LIBCPP_TEMPLATE_VIS array
> >  typedef std::reverse_iterator   reverse_iterator;
> >  typedef std::reverse_iterator
> const_reverse_iterator;
> >
> > -value_type __elems_[_Size > 0 ? _Size : 1];
> > +typedef __array_traits<_Tp, _Size> _Traits;
> > +typename _Traits::_StorageT __elems_;
> >
> >  // No explicit construct/copy/destroy for aggregate type
> >  _LIBCPP_INLINE_VISIBILITY void fill(const value_type& __u)
> > -{_VSTD::fill_n(__elems_, _Size, __u);}
> > -_LIBCPP_INLINE_VISIBILITY
> > -void swap(array& __a) _NOEXCEPT_(_Size == 0 ||
> __is_nothrow_swappable<_Tp>::value)
> > -{ __swap_dispatch((std::integral_constant()),
> __a); }
> > +{_Traits::__fill(__elems_, __u);}
> >
> >  _LIBCPP_INLINE_VISIBILITY
> > -void __swap_dispatch(std::true_type, array&) {}
> > -
> > -_LIBCPP_INLINE_VISIBILITY
> > -void __swap_dispatch(std::false_type, array& __a)
> > -{ _VSTD::swap_ranges(__elems_, __elems_ + _Size, __a.__elems_);}
> > +void swap(array& __a) _NOEXCEPT_(_Size == 0 ||
> __is_nothrow_swappable<_Tp>::value)
> > +{ _Traits::__swap(__elems_, __a.__elems_); }
> >
> >  // iterators:
> >  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
> > -iterator begin() _NOEXCEPT {return iterator(__elems_);}
> > +iterator begin() _NOEXCEPT {return iterator(data());}
> >  _LIBCPP_INLINE_VISIBILITY 

[PATCH] D41039: Add support for attribute "trivial_abi"

2018-02-05 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL324269: Add support for attribute trivial_abi. 
(authored by ahatanak, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D41039?vs=129397=132881#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D41039

Files:
  cfe/trunk/include/clang/AST/ASTContext.h
  cfe/trunk/include/clang/AST/Decl.h
  cfe/trunk/include/clang/AST/DeclCXX.h
  cfe/trunk/include/clang/AST/Type.h
  cfe/trunk/include/clang/Basic/Attr.td
  cfe/trunk/include/clang/Basic/AttrDocs.td
  cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
  cfe/trunk/include/clang/Sema/Sema.h
  cfe/trunk/lib/AST/ASTContext.cpp
  cfe/trunk/lib/AST/DeclCXX.cpp
  cfe/trunk/lib/AST/Type.cpp
  cfe/trunk/lib/CodeGen/CGCall.cpp
  cfe/trunk/lib/CodeGen/CGDecl.cpp
  cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
  cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
  cfe/trunk/lib/Sema/SemaChecking.cpp
  cfe/trunk/lib/Sema/SemaDeclAttr.cpp
  cfe/trunk/lib/Sema/SemaDeclCXX.cpp
  cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
  cfe/trunk/lib/Sema/SemaType.cpp
  cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
  cfe/trunk/lib/Serialization/ASTWriter.cpp
  cfe/trunk/lib/Serialization/ASTWriterDecl.cpp
  cfe/trunk/test/CodeGenCXX/trivial_abi.cpp
  cfe/trunk/test/CodeGenObjCXX/trivial_abi.mm
  cfe/trunk/test/Misc/pragma-attribute-supported-attributes-list.test
  cfe/trunk/test/SemaObjCXX/attr-trivial-abi.mm

Index: cfe/trunk/include/clang/AST/DeclCXX.h
===
--- cfe/trunk/include/clang/AST/DeclCXX.h
+++ cfe/trunk/include/clang/AST/DeclCXX.h
@@ -437,14 +437,25 @@
 /// which have been declared but not yet defined.
 unsigned HasTrivialSpecialMembers : 6;
 
+/// These bits keep track of the triviality of special functions for the
+/// purpose of calls. Only the bits corresponding to SMF_CopyConstructor,
+/// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
+unsigned HasTrivialSpecialMembersForCall : 6;
+
 /// \brief The declared special members of this class which are known to be
 /// non-trivial.
 ///
 /// This excludes any user-declared but not user-provided special members
 /// which have been declared but not yet defined, and any implicit special
 /// members which have not yet been declared.
 unsigned DeclaredNonTrivialSpecialMembers : 6;
 
+/// These bits keep track of the declared special members that are
+/// non-trivial for the purpose of calls.
+/// Only the bits corresponding to SMF_CopyConstructor,
+/// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
+unsigned DeclaredNonTrivialSpecialMembersForCall : 6;
+
 /// \brief True when this class has a destructor with no semantic effect.
 unsigned HasIrrelevantDestructor : 1;
 
@@ -1349,28 +1360,50 @@
 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
   }
 
+  bool hasTrivialCopyConstructorForCall() const {
+return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
+  }
+
   /// \brief Determine whether this class has a non-trivial copy constructor
   /// (C++ [class.copy]p6, C++11 [class.copy]p12)
   bool hasNonTrivialCopyConstructor() const {
 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
!hasTrivialCopyConstructor();
   }
 
+  bool hasNonTrivialCopyConstructorForCall() const {
+return (data().DeclaredNonTrivialSpecialMembersForCall &
+SMF_CopyConstructor) ||
+   !hasTrivialCopyConstructorForCall();
+  }
+
   /// \brief Determine whether this class has a trivial move constructor
   /// (C++11 [class.copy]p12)
   bool hasTrivialMoveConstructor() const {
 return hasMoveConstructor() &&
(data().HasTrivialSpecialMembers & SMF_MoveConstructor);
   }
 
+  bool hasTrivialMoveConstructorForCall() const {
+return hasMoveConstructor() &&
+   (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
+  }
+
   /// \brief Determine whether this class has a non-trivial move constructor
   /// (C++11 [class.copy]p12)
   bool hasNonTrivialMoveConstructor() const {
 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
(needsImplicitMoveConstructor() &&
 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
   }
 
+  bool hasNonTrivialMoveConstructorForCall() const {
+return (data().DeclaredNonTrivialSpecialMembersForCall &
+SMF_MoveConstructor) ||
+   (needsImplicitMoveConstructor() &&
+!(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
+  }
+
   /// \brief Determine whether this class has a trivial copy assignment operator
   /// (C++ [class.copy]p11, C++11 [class.copy]p25)
   bool hasTrivialCopyAssignment() const {
@@ -1405,12 +1438,25 @@
 return data().HasTrivialSpecialMembers & SMF_Destructor;
   }
 
+ 

[PATCH] D41039: Add support for attribute "trivial_abi"

2018-02-05 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
ahatanak marked 2 inline comments as done.
Closed by commit rC324269: Add support for attribute trivial_abi. 
(authored by ahatanak, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D41039?vs=129397=132880#toc

Repository:
  rC Clang

https://reviews.llvm.org/D41039

Files:
  include/clang/AST/ASTContext.h
  include/clang/AST/Decl.h
  include/clang/AST/DeclCXX.h
  include/clang/AST/Type.h
  include/clang/Basic/Attr.td
  include/clang/Basic/AttrDocs.td
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Sema/Sema.h
  lib/AST/ASTContext.cpp
  lib/AST/DeclCXX.cpp
  lib/AST/Type.cpp
  lib/CodeGen/CGCall.cpp
  lib/CodeGen/CGDecl.cpp
  lib/CodeGen/ItaniumCXXABI.cpp
  lib/CodeGen/MicrosoftCXXABI.cpp
  lib/Sema/SemaChecking.cpp
  lib/Sema/SemaDeclAttr.cpp
  lib/Sema/SemaDeclCXX.cpp
  lib/Sema/SemaTemplateInstantiate.cpp
  lib/Sema/SemaType.cpp
  lib/Serialization/ASTReaderDecl.cpp
  lib/Serialization/ASTWriter.cpp
  lib/Serialization/ASTWriterDecl.cpp
  test/CodeGenCXX/trivial_abi.cpp
  test/CodeGenObjCXX/trivial_abi.mm
  test/Misc/pragma-attribute-supported-attributes-list.test
  test/SemaObjCXX/attr-trivial-abi.mm

Index: include/clang/Sema/Sema.h
===
--- include/clang/Sema/Sema.h
+++ include/clang/Sema/Sema.h
@@ -2236,7 +2236,17 @@
 
   bool CheckNontrivialField(FieldDecl *FD);
   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
+
+  enum TrivialABIHandling {
+/// The triviality of a method unaffected by "trivial_abi".
+TAH_IgnoreTrivialABI,
+
+/// The triviality of a method affected by "trivial_abi".
+TAH_ConsiderTrivialABI
+  };
+
   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
+  TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
   bool Diagnose = false);
   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
   void ActOnLastBitfield(SourceLocation DeclStart,
@@ -5796,6 +5806,11 @@
   SourceLocation BaseLoc);
 
   void CheckCompletedCXXClass(CXXRecordDecl *Record);
+
+  /// Check that the C++ class annoated with "trivial_abi" satisfies all the
+  /// conditions that are needed for the attribute to have an effect.
+  void checkIllFormedTrivialABIStruct(CXXRecordDecl );
+
   void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
  Decl *TagDecl,
  SourceLocation LBrac,
Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -2881,6 +2881,9 @@
 def err_invalid_attribute_on_virtual_function : Error<
   "%0 attribute cannot be applied to virtual functions">;
 
+def ext_cannot_use_trivial_abi : ExtWarn<
+  "'trivial_abi' cannot be applied to %0">, InGroup;
+
 // Availability attribute
 def warn_availability_unknown_platform : Warning<
   "unknown platform %0 in availability macro">, InGroup;
Index: include/clang/Basic/AttrDocs.td
===
--- include/clang/Basic/AttrDocs.td
+++ include/clang/Basic/AttrDocs.td
@@ -2242,6 +2242,48 @@
   }];
 }
 
+def TrivialABIDocs : Documentation {
+  let Category = DocCatVariable;
+  let Content = [{
+The ``trivial_abi`` attribute can be applied to a C++ class, struct, or union.
+It instructs the compiler to pass and return the type using the C ABI for the
+underlying type when the type would otherwise be considered non-trivial for the
+purpose of calls.
+A class annotated with `trivial_abi` can have non-trivial destructors or copy/move constructors without automatically becoming non-trivial for the purposes of calls. For example:
+
+  .. code-block:: c++
+
+// A is trivial for the purposes of calls because `trivial_abi` makes the
+// user-provided special functions trivial.
+struct __attribute__((trivial_abi)) A {
+  ~A();
+  A(const A &);
+  A(A &&);
+  int x;
+};
+
+// B's destructor and copy/move constructor are considered trivial for the
+// purpose of calls because A is trivial.
+struct B {
+  A a;
+};
+
+If a type is trivial for the purposes of calls, has a non-trivial destructor,
+and is passed as an argument by value, the convention is that the callee will
+destroy the object before returning.
+
+Attribute ``trivial_abi`` has no effect in the following cases:
+
+- The class directly declares a virtual base or virtual methods.
+- The class has a base class that is non-trivial for the purposes of calls.
+- The class has a non-static data member whose type is non-trivial for the
+purposes of calls, which includes:
+ - classes that are non-trivial for the purposes of calls
+ - __weak-qualified types in Objective-C++
+ - 

r324269 - Add support for attribute 'trivial_abi'.

2018-02-05 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Mon Feb  5 12:23:22 2018
New Revision: 324269

URL: http://llvm.org/viewvc/llvm-project?rev=324269=rev
Log:
Add support for attribute 'trivial_abi'.

The 'trivial_abi' attribute can be applied to a C++ class, struct, or
union. It makes special functions of the annotated class (the destructor
and copy/move constructors) to be trivial for the purpose of calls and,
as a result, enables the annotated class or containing classes to be
passed or returned using the C ABI for the underlying type.

When a type that is considered trivial for the purpose of calls despite
having a non-trivial destructor (which happens only when the class type
or one of its subobjects is a 'trivial_abi' class) is passed to a
function, the callee is responsible for destroying the object.

For more background, see the discussions that took place on the mailing
list:

http://lists.llvm.org/pipermail/cfe-dev/2017-November/055955.html
http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20180101/thread.html#214043

rdar://problem/35204524

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

Added:
cfe/trunk/test/CodeGenCXX/trivial_abi.cpp
cfe/trunk/test/CodeGenObjCXX/trivial_abi.mm
cfe/trunk/test/SemaObjCXX/attr-trivial-abi.mm
Modified:
cfe/trunk/include/clang/AST/ASTContext.h
cfe/trunk/include/clang/AST/Decl.h
cfe/trunk/include/clang/AST/DeclCXX.h
cfe/trunk/include/clang/AST/Type.h
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/AST/ASTContext.cpp
cfe/trunk/lib/AST/DeclCXX.cpp
cfe/trunk/lib/AST/Type.cpp
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/CodeGen/CGDecl.cpp
cfe/trunk/lib/CodeGen/ItaniumCXXABI.cpp
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
cfe/trunk/lib/Sema/SemaChecking.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaDeclCXX.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
cfe/trunk/lib/Sema/SemaType.cpp
cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
cfe/trunk/lib/Serialization/ASTWriter.cpp
cfe/trunk/lib/Serialization/ASTWriterDecl.cpp
cfe/trunk/test/Misc/pragma-attribute-supported-attributes-list.test

Modified: cfe/trunk/include/clang/AST/ASTContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=324269=324268=324269=diff
==
--- cfe/trunk/include/clang/AST/ASTContext.h (original)
+++ cfe/trunk/include/clang/AST/ASTContext.h Mon Feb  5 12:23:22 2018
@@ -1179,6 +1179,10 @@ public:
const FunctionProtoType::ExceptionSpecInfo ,
bool AsWritten = false);
 
+  /// Determine whether a type is a class that should be detructed in the
+  /// callee function.
+  bool isParamDestroyedInCallee(QualType T) const;
+
   /// \brief Return the uniqued reference to the type for a complex
   /// number with the specified element type.
   QualType getComplexType(QualType T) const;

Modified: cfe/trunk/include/clang/AST/Decl.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=324269=324268=324269=diff
==
--- cfe/trunk/include/clang/AST/Decl.h (original)
+++ cfe/trunk/include/clang/AST/Decl.h Mon Feb  5 12:23:22 2018
@@ -1731,6 +1731,12 @@ private:
   unsigned HasWrittenPrototype : 1;
   unsigned IsDeleted : 1;
   unsigned IsTrivial : 1; // sunk from CXXMethodDecl
+
+  /// This flag indicates whether this function is trivial for the purpose of
+  /// calls. This is meaningful only when this function is a copy/move
+  /// constructor or a destructor.
+  unsigned IsTrivialForCall : 1;
+
   unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
   unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
   unsigned HasImplicitReturnZero : 1;
@@ -1845,7 +1851,8 @@ protected:
 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
 HasInheritedPrototype(false), HasWrittenPrototype(true),
-IsDeleted(false), IsTrivial(false), IsDefaulted(false),
+IsDeleted(false), IsTrivial(false), IsTrivialForCall(false),
+IsDefaulted(false),
 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
 InstantiationIsPending(false), UsesSEHTry(false), 
HasSkippedBody(false),
@@ -2010,6 +2017,9 @@ public:
   bool isTrivial() const { return IsTrivial; }
   void setTrivial(bool IT) { IsTrivial = IT; }
 
+  bool isTrivialForCall() const { return IsTrivialForCall; }
+  void setTrivialForCall(bool IT) { IsTrivialForCall = IT; }
+
   /// Whether this function is defaulted per C++0x. Only valid for
   

[PATCH] D42680: [ThinLTO] Ignore object files with no ThinLTO modules if -fthinlto-index= is set

2018-02-05 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka updated this revision to Diff 132876.
vitalybuka marked 3 inline comments as done.
vitalybuka added a comment.

empty file test


https://reviews.llvm.org/D42680

Files:
  clang/include/clang/CodeGen/BackendUtil.h
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CodeGenAction.cpp
  clang/test/CodeGen/thinlto_backend.ll


Index: clang/test/CodeGen/thinlto_backend.ll
===
--- clang/test/CodeGen/thinlto_backend.ll
+++ clang/test/CodeGen/thinlto_backend.ll
@@ -20,6 +20,13 @@
 ; CHECK-OBJ-IGNORE-EMPTY: T f1
 ; CHECK-OBJ-IGNORE-EMPTY: U f2
 
+; Ensure we don't fail with index and non-ThinLTO object file, and output must
+; be empty file.
+; RUN: opt -o %t5.o %s
+; RUN: %clang -target x86_64-unknown-linux-gnu -O2 -o %t4.o -x ir %t5.o -c 
-fthinlto-index=%t.thinlto.bc
+; RUN: wc -c < %t4.o | FileCheck %s --check-prefix=CHECK-SIZE
+; CHECK-SIZE: {{^0$}}
+
 ; Ensure f2 was imported
 ; RUN: %clang -target x86_64-unknown-linux-gnu -O2 -o %t3.o -x ir %t1.o -c 
-fthinlto-index=%t.thinlto.bc
 ; RUN: llvm-nm %t3.o | FileCheck --check-prefix=CHECK-OBJ %s
Index: clang/lib/CodeGen/CodeGenAction.cpp
===
--- clang/lib/CodeGen/CodeGenAction.cpp
+++ clang/lib/CodeGen/CodeGenAction.cpp
@@ -947,12 +947,18 @@
   return {};
 };
 
-Expected BMOrErr = FindThinLTOModule(MBRef);
-if (!BMOrErr)
-  return DiagErrors(BMOrErr.takeError());
-
+Expected BMsOrErr = 
getBitcodeModuleList(MBRef);
+if (!BMsOrErr)
+  return DiagErrors(BMsOrErr.takeError());
+BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr);
+// We have nothing to do if the file contains no ThinLTO module. This is
+// possible if ThinLTO compilation was not able to split module. Content of
+// the file was already processed by indexing and will be passed to the
+// linker using merged object file.
+if (!Bm)
+  return {};
 Expected MOrErr =
-BMOrErr->parseModule(*VMContext);
+Bm->parseModule(*VMContext);
 if (!MOrErr)
   return DiagErrors(MOrErr.takeError());
 return std::move(*MOrErr);
Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -1025,16 +1025,22 @@
 
   // The bitcode file may contain multiple modules, we want the one that is
   // marked as being the ThinLTO module.
-  for (BitcodeModule  : *BMsOrErr) {
-Expected LTOInfo = BM.getLTOInfo();
-if (LTOInfo && LTOInfo->IsThinLTO)
-  return BM;
-  }
+  if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
+return *Bm;
 
   return make_error("Could not find module summary",
  inconvertibleErrorCode());
 }
 
+BitcodeModule *clang::FindThinLTOModule(MutableArrayRef BMs) {
+  for (BitcodeModule  : BMs) {
+Expected LTOInfo = BM.getLTOInfo();
+if (LTOInfo && LTOInfo->IsThinLTO)
+  return 
+  }
+  return nullptr;
+}
+
 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
   const HeaderSearchOptions ,
   const CodeGenOptions ,
Index: clang/include/clang/CodeGen/BackendUtil.h
===
--- clang/include/clang/CodeGen/BackendUtil.h
+++ clang/include/clang/CodeGen/BackendUtil.h
@@ -49,6 +49,8 @@
 
   llvm::Expected
   FindThinLTOModule(llvm::MemoryBufferRef MBRef);
+  llvm::BitcodeModule *
+  FindThinLTOModule(llvm::MutableArrayRef BMs);
 }
 
 #endif


Index: clang/test/CodeGen/thinlto_backend.ll
===
--- clang/test/CodeGen/thinlto_backend.ll
+++ clang/test/CodeGen/thinlto_backend.ll
@@ -20,6 +20,13 @@
 ; CHECK-OBJ-IGNORE-EMPTY: T f1
 ; CHECK-OBJ-IGNORE-EMPTY: U f2
 
+; Ensure we don't fail with index and non-ThinLTO object file, and output must
+; be empty file.
+; RUN: opt -o %t5.o %s
+; RUN: %clang -target x86_64-unknown-linux-gnu -O2 -o %t4.o -x ir %t5.o -c -fthinlto-index=%t.thinlto.bc
+; RUN: wc -c < %t4.o | FileCheck %s --check-prefix=CHECK-SIZE
+; CHECK-SIZE: {{^0$}}
+
 ; Ensure f2 was imported
 ; RUN: %clang -target x86_64-unknown-linux-gnu -O2 -o %t3.o -x ir %t1.o -c -fthinlto-index=%t.thinlto.bc
 ; RUN: llvm-nm %t3.o | FileCheck --check-prefix=CHECK-OBJ %s
Index: clang/lib/CodeGen/CodeGenAction.cpp
===
--- clang/lib/CodeGen/CodeGenAction.cpp
+++ clang/lib/CodeGen/CodeGenAction.cpp
@@ -947,12 +947,18 @@
   return {};
 };
 
-Expected BMOrErr = FindThinLTOModule(MBRef);
-if (!BMOrErr)
-  return DiagErrors(BMOrErr.takeError());
-
+Expected BMsOrErr = getBitcodeModuleList(MBRef);
+if (!BMsOrErr)
+  return DiagErrors(BMsOrErr.takeError());
+BitcodeModule *Bm = 

[PATCH] D42645: New simple Checker for mmap calls

2018-02-05 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 132873.

Repository:
  rC Clang

https://reviews.llvm.org/D42645

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
  test/Analysis/mmap-writeexec.c

Index: test/Analysis/mmap-writeexec.c
===
--- test/Analysis/mmap-writeexec.c
+++ test/Analysis/mmap-writeexec.c
@@ -0,0 +1,31 @@
+// RUN: %clang_analyze_cc1 -triple i686-unknown-linux -analyzer-checker=security.MmapWriteExec -verify %s
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-apple-darwin10 -analyzer-checker=security.MmapWriteExec -verify %s
+
+#define PROT_READ   0x01
+#define PROT_WRITE  0x02
+#define PROT_EXEC   0x04
+#define MAP_PRIVATE 0x0002
+#define MAP_ANON0x1000
+#define MAP_FIXED   0x0010
+#define NULL((void *)0)
+
+typedef __typeof(sizeof(int)) size_t;
+void *mmap(void *, size_t, int, int, int, long);
+
+void f1()
+{
+  void *a = mmap(NULL, 16, PROT_READ | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); // no-warning
+  void *b = mmap(a, 16, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANON, -1, 0); // no-warning
+  void *c = mmap(NULL, 32, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); // expected-warning{{Both PROT_WRITE and PROT_EXEC flags are set. This can lead to exploitable memory regions, which could be overwritten with malicious code}}
+  (void)a;
+  (void)b;
+  (void)c;
+}
+
+void f2()
+{
+  void *(*callm)(void *, size_t, int, int, int, long);
+  callm = mmap;
+  int prot = PROT_WRITE | PROT_EXEC;
+  (void)callm(NULL, 1024, prot, MAP_PRIVATE | MAP_ANON, -1, 0); // expected-warning{{Both PROT_WRITE and PROT_EXEC flags are set. This can lead to exploitable memory regions, which could be overwritten with malicious code}}
+}
Index: lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
+++ lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
@@ -0,0 +1,75 @@
+// MmapWriteExecChecker.cpp - Check for the prot argument -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This checker tests the 3rd argument of mmap's calls to check if
+// it is writable and executable in the same time. It's somehow
+// an optional checker since for example in JIT libraries it is pretty common.
+//
+//===--===//
+
+#include "ClangSACheckers.h"
+
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+using llvm::APSInt;
+
+namespace {
+class MmapWriteExecChecker : public Checker {
+  CallDescription MmapFn;
+  static int ProtWrite;
+  static int ProtExec;
+  mutable std::unique_ptr BT;
+public:
+  MmapWriteExecChecker() : MmapFn("mmap", 6) {}
+  void checkPreCall(const CallEvent , CheckerContext ) const;
+};
+}
+
+int MmapWriteExecChecker::ProtWrite = 0x02;
+int MmapWriteExecChecker::ProtExec  = 0x04;
+
+void MmapWriteExecChecker::checkPreCall(const CallEvent ,
+ CheckerContext ) const {
+  if (Call.isCalled(MmapFn)) {
+llvm::Triple Triple = C.getASTContext().getTargetInfo().getTriple();
+
+if (Triple.isOSGlibc())
+  ProtExec = 0x01;
+
+SVal ProtVal = Call.getArgSVal(2); 
+Optional ProtLoc = ProtVal.getAs();
+int64_t Prot = ProtLoc->getValue().getSExtValue();
+
+if ((Prot & (ProtWrite | ProtExec)) == (ProtWrite | ProtExec)) {
+  if (!BT)
+BT.reset(new BugType(this, "W^X check fails, Write Exec prot flags set", "Security"));
+
+  ExplodedNode *N = C.generateNonFatalErrorNode();
+  if (!N)
+return;
+
+  auto Report = llvm::make_unique(
+  *BT, "Both PROT_WRITE and PROT_EXEC flags are set. This can "
+   "lead to exploitable memory regions, which could be overwritten "
+   "with malicious code", N);
+  Report->addRange(Call.getArgSourceRange(2));
+  C.emitReport(std::move(Report));
+}
+  }
+}
+
+void ento::registerMmapWriteExecChecker(CheckerManager ) {
+  mgr.registerChecker();
+}
Index: lib/StaticAnalyzer/Checkers/CMakeLists.txt
===
--- lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -49,6 +49,7 @@
   MallocChecker.cpp
   

[PATCH] D42924: Don't pass ForDefinition_t in places it is redundant.

2018-02-05 Thread Rafael Avila de Espindola via Phabricator via cfe-commits
espindola created this revision.
espindola added reviewers: sfertile, rnk.

I found this while looking at the ppc failures caused by the  dso_local change.

The issue was that the patch would produce the wrong answer for 
available_externally. Having ForDefinition_t available in places where the code 
can just check the linkage is a bit of a foot gun.

This patch removes the ForDefiniton_t argument in places where the linkage is 
already know.


https://reviews.llvm.org/D42924

Files:
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGVTT.cpp
  clang/lib/CodeGen/CGVTables.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/CodeGen/ItaniumCXXABI.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/CodeGen/TargetInfo.h

Index: clang/lib/CodeGen/TargetInfo.h
===
--- clang/lib/CodeGen/TargetInfo.h
+++ clang/lib/CodeGen/TargetInfo.h
@@ -57,8 +57,7 @@
   /// setTargetAttributes - Provides a convenient hook to handle extra
   /// target-specific attributes for the given global.
   virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
-   CodeGen::CodeGenModule ,
-   ForDefinition_t IsForDefinition) const {}
+   CodeGen::CodeGenModule ) const {}
 
   /// emitTargetMD - Provides a convenient hook to handle extra
   /// target-specific metadata for the given global.
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -1052,8 +1052,7 @@
   const llvm::Triple , const CodeGenOptions );
 
   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
-   CodeGen::CodeGenModule ,
-   ForDefinition_t IsForDefinition) const override;
+   CodeGen::CodeGenModule ) const override;
 
   int getDwarfEHStackPointer(CodeGen::CodeGenModule ) const override {
 // Darwin uses different dwarf register numbers for EH.
@@ -1920,9 +1919,8 @@
 }
 
 void X86_32TargetCodeGenInfo::setTargetAttributes(
-const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule ,
-ForDefinition_t IsForDefinition) const {
-  if (!IsForDefinition)
+const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule ) const {
+  if (GV->isDeclaration())
 return;
   if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
 if (FD->hasAttr()) {
@@ -2279,9 +2277,8 @@
   }
 
   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
-   CodeGen::CodeGenModule ,
-   ForDefinition_t IsForDefinition) const override {
-if (!IsForDefinition)
+   CodeGen::CodeGenModule ) const override {
+if (GV->isDeclaration())
   return;
 if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
   if (FD->hasAttr()) {
@@ -2339,8 +2336,7 @@
 Win32StructABI, NumRegisterParameters, false) {}
 
   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
-   CodeGen::CodeGenModule ,
-   ForDefinition_t IsForDefinition) const override;
+   CodeGen::CodeGenModule ) const override;
 
   void getDependentLibraryOption(llvm::StringRef Lib,
  llvm::SmallString<24> ) const override {
@@ -2369,10 +2365,9 @@
 }
 
 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
-const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule ,
-ForDefinition_t IsForDefinition) const {
-  X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
-  if (!IsForDefinition)
+const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule ) const {
+  X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
+  if (GV->isDeclaration())
 return;
   addStackProbeSizeTargetAttribute(D, GV, CGM);
 }
@@ -2384,8 +2379,7 @@
   : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
 
   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
-   CodeGen::CodeGenModule ,
-   ForDefinition_t IsForDefinition) const override;
+   CodeGen::CodeGenModule ) const override;
 
   int getDwarfEHStackPointer(CodeGen::CodeGenModule ) const override {
 return 7;
@@ -2415,10 +2409,9 @@
 };
 
 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
-const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule ,
-ForDefinition_t IsForDefinition) const {
-  TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
-  if (!IsForDefinition)
+const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule ) const {
+  TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
+  if (GV->isDeclaration())
 return;
   if (const FunctionDecl *FD = dyn_cast_or_null(D)) {
 if 

[PATCH] D42922: [CUDA] Register relocatable GPU binaries

2018-02-05 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld planned changes to this revision.
Hahnfeld added a comment.

I didn't write tests for this yet, but I wanted to get some early feedback on 
this and show what I have in mind.




Comment at: lib/CodeGen/CGCUDANV.cpp:330-331
   // the GPU side.
   for (const std::string  :
CGM.getCodeGenOpts().CudaGpuBinaryFileNames) {
 llvm::ErrorOr GpuBinaryOrErr =

Can we actually have multiple GPU binaries here? If yes, how do I get there?



Comment at: lib/CodeGen/CGCUDANV.cpp:342-343
+if (RelocatableDeviceCode)
+  // TODO: Figure out how this is called on mac OS!
+  FatbinConstantName = "__nv_relfatbin";
+else

@jlebar Could yo help me here as I don't have a Mac? I'd guess it's 
`__NV_CUDA,__nv_relfatbin` but I'd feel better if I can get a confirmation...



Comment at: lib/CodeGen/CGCUDANV.cpp:350-351
 CGM.getTriple().isMacOSX() ? "__NV_CUDA,__fatbin" : ".nvFatBinSegment";
+// TODO: Figure out how this is called on mac OS!
+const char *NVModuleIDSectionName = "__nv_module_id";
 

@jlebar The same here, probably `__NV_CUDA,__nv_module_id`?


Repository:
  rC Clang

https://reviews.llvm.org/D42922



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


[PATCH] D42923: [CUDA] Allow external variables in separate compilation

2018-02-05 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld created this revision.
Hahnfeld added reviewers: jlebar, tra, hfinkel.
Herald added a subscriber: cfe-commits.

According to the CUDA Programming Guide this is prohibited in
whole program compilation mode. This makes sense because external
references cannot be satisfied in that mode anyway. However,
such variables are allowed in separate compilation mode which
is a valid use case.


Repository:
  rC Clang

https://reviews.llvm.org/D42923

Files:
  lib/Sema/SemaDeclAttr.cpp
  test/SemaCUDA/extern-shared.cu


Index: test/SemaCUDA/extern-shared.cu
===
--- test/SemaCUDA/extern-shared.cu
+++ test/SemaCUDA/extern-shared.cu
@@ -1,5 +1,9 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
 // RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -verify %s
+// These declarations are fine in separate compilation mode!
+// RUN: %clang_cc1 -fsyntax-only -fcuda-rdc -verify=rdc %s
+// RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -fcuda-rdc -verify=rdc %s
+// rdc-no-diagnostics
 
 #include "Inputs/cuda.h"
 
Index: lib/Sema/SemaDeclAttr.cpp
===
--- lib/Sema/SemaDeclAttr.cpp
+++ lib/Sema/SemaDeclAttr.cpp
@@ -4112,7 +4112,8 @@
   auto *VD = cast(D);
   // extern __shared__ is only allowed on arrays with no length (e.g.
   // "int x[]").
-  if (VD->hasExternalStorage() && !isa(VD->getType())) {
+  if (!S.getLangOpts().CUDARelocatableDeviceCode && VD->hasExternalStorage() &&
+  !isa(VD->getType())) {
 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
 return;
   }


Index: test/SemaCUDA/extern-shared.cu
===
--- test/SemaCUDA/extern-shared.cu
+++ test/SemaCUDA/extern-shared.cu
@@ -1,5 +1,9 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
 // RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -verify %s
+// These declarations are fine in separate compilation mode!
+// RUN: %clang_cc1 -fsyntax-only -fcuda-rdc -verify=rdc %s
+// RUN: %clang_cc1 -fsyntax-only -fcuda-is-device -fcuda-rdc -verify=rdc %s
+// rdc-no-diagnostics
 
 #include "Inputs/cuda.h"
 
Index: lib/Sema/SemaDeclAttr.cpp
===
--- lib/Sema/SemaDeclAttr.cpp
+++ lib/Sema/SemaDeclAttr.cpp
@@ -4112,7 +4112,8 @@
   auto *VD = cast(D);
   // extern __shared__ is only allowed on arrays with no length (e.g.
   // "int x[]").
-  if (VD->hasExternalStorage() && !isa(VD->getType())) {
+  if (!S.getLangOpts().CUDARelocatableDeviceCode && VD->hasExternalStorage() &&
+  !isa(VD->getType())) {
 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
 return;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42922: [CUDA] Register relocatable GPU binaries

2018-02-05 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld created this revision.
Hahnfeld added reviewers: jlebar, tra, hfinkel.
Herald added a subscriber: cfe-commits.

nvcc generates a unique registration function for each object file
that contains relocatable device code. Unique names are achieved
with a module id that is also reflected in the function's name.


Repository:
  rC Clang

https://reviews.llvm.org/D42922

Files:
  lib/CodeGen/CGCUDANV.cpp

Index: lib/CodeGen/CGCUDANV.cpp
===
--- lib/CodeGen/CGCUDANV.cpp
+++ lib/CodeGen/CGCUDANV.cpp
@@ -15,12 +15,13 @@
 #include "CGCUDARuntime.h"
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
-#include "clang/CodeGen/ConstantInitBuilder.h"
 #include "clang/AST/Decl.h"
+#include "clang/CodeGen/ConstantInitBuilder.h"
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/CallSite.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
+#include "llvm/Support/Format.h"
 
 using namespace clang;
 using namespace CodeGen;
@@ -45,9 +46,12 @@
   /// ModuleCtorFunction() and used to create corresponding cleanup calls in
   /// ModuleDtorFunction()
   llvm::SmallVector GpuBinaryHandles;
+  /// Whether we generate relocatable device code.
+  bool RelocatableDeviceCode;
 
   llvm::Constant *getSetupArgumentFn() const;
   llvm::Constant *getLaunchFn() const;
+  llvm::FunctionType *getRegisterGlobalsFnTy() const;
 
   /// Creates a function to register all kernel stubs generated in this module.
   llvm::Function *makeRegisterGlobalsFn();
@@ -71,7 +75,23 @@
 
 return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
 ConstStr.getPointer(), Zeros);
- }
+  }
+
+  /// Helper function that generates an empty dummy function returning void.
+  llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
+assert(FnTy->getReturnType()->isVoidType() &&
+   "Can only generate dummy functions returning void!");
+llvm::Function *DummyFunc = llvm::Function::Create(
+FnTy, llvm::GlobalValue::InternalLinkage, "dummy", );
+
+llvm::BasicBlock *DummyBlock =
+llvm::BasicBlock::Create(Context, "", DummyFunc);
+CGBuilderTy FuncBuilder(CGM, Context);
+FuncBuilder.SetInsertPoint(DummyBlock);
+FuncBuilder.CreateRetVoid();
+
+return DummyFunc;
+  }
 
   void emitDeviceStubBody(CodeGenFunction , FunctionArgList );
 
@@ -93,7 +113,8 @@
 
 CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule )
 : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
-  TheModule(CGM.getModule()) {
+  TheModule(CGM.getModule()),
+  RelocatableDeviceCode(CGM.getLangOpts().CUDARelocatableDeviceCode) {
   CodeGen::CodeGenTypes  = CGM.getTypes();
   ASTContext  = CGM.getContext();
 
@@ -161,6 +182,10 @@
   CGF.EmitBlock(EndBlock);
 }
 
+llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
+  return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false);
+}
+
 /// Creates a function that sets up state on the host side for CUDA objects that
 /// have a presence on both the host and device sides. Specifically, registers
 /// the host side of kernel functions and device global variables with the CUDA
@@ -181,8 +206,8 @@
 return nullptr;
 
   llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
-  llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
-  llvm::GlobalValue::InternalLinkage, "__cuda_register_globals", );
+  getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
+  "__cuda_register_globals", );
   llvm::BasicBlock *EntryBB =
   llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
   CGBuilderTy Builder(CGM, Context);
@@ -257,8 +282,29 @@
   if (CGM.getCodeGenOpts().CudaGpuBinaryFileNames.empty())
 return nullptr;
 
+  llvm::FunctionType *RegisterGlobalsFnTy;
+  llvm::FunctionType *RegisterLinkedBinaryFnTy;
+  llvm::Function *DummyCallback;
+  if (RelocatableDeviceCode) {
+RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
+
+auto CallbackFnTy = llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
+DummyCallback = makeDummyFunction(CallbackFnTy);
+
+// void __cudaRegisterLinkedBinary%NVModuleID%(void (*)(void *), void *,
+// void *, void (*)(void **))
+llvm::Type *Params[] = {RegisterGlobalsFnTy, VoidPtrTy, VoidPtrTy,
+CallbackFnTy};
+RegisterLinkedBinaryFnTy = llvm::FunctionType::get(VoidTy, Params, false);
+  }
+
   // void __cuda_register_globals(void* handle);
   llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
+  // We always need a function to pass in as callback. Create a dummy
+  // implementation if we don't need to register anything.
+  if (RelocatableDeviceCode && !RegisterGlobalsFunc)
+RegisterGlobalsFunc = makeDummyFunction(RegisterGlobalsFnTy);
+
   // void ** __cudaRegisterFatBinary(void *);
   llvm::Constant *RegisterFatbinFunc = CGM.CreateRuntimeFunction(
   llvm::FunctionType::get(VoidPtrPtrTy, 

[PATCH] D42921: [CUDA] Add option to generate relocatable device code

2018-02-05 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld created this revision.
Hahnfeld added reviewers: jlebar, tra.
Herald added a subscriber: cfe-commits.
Hahnfeld added a dependency: D42920: [CUDA] Fix test cuda-external-tools.cu.
Hahnfeld added a reviewer: hfinkel.

As a first step, pass '-c/--compile-only' to ptxas so that it
doesn't complain about references to external function. This
will successfully generate object files, but they won't work
at runtime because the registration routines need to adapted.


Repository:
  rC Clang

https://reviews.llvm.org/D42921

Files:
  include/clang/Basic/LangOptions.def
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Clang.cpp
  lib/Driver/ToolChains/Cuda.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/Driver/cuda-external-tools.cu

Index: test/Driver/cuda-external-tools.cu
===
--- test/Driver/cuda-external-tools.cu
+++ test/Driver/cuda-external-tools.cu
@@ -24,6 +24,10 @@
 // RUN: %clang -### -target x86_64-linux-gnu -Ofast -c %s 2>&1 \
 // RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
 // RUN: -check-prefix SM20 -check-prefix OPT3 %s
+// Generating relocatable device code
+// RUN: %clang -### -target x86_64-linux-gnu -fcuda-rdc -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix RDC %s
 
 // With debugging enabled, ptxas should be run with with no ptxas optimizations.
 // RUN: %clang -### -target x86_64-linux-gnu --cuda-noopt-device-debug -O2 -c %s 2>&1 \
@@ -53,15 +57,27 @@
 // Regular compile targeting sm_35.
 // RUN: %clang -### -target x86_64-linux-gnu --cuda-gpu-arch=sm_35 -c %s 2>&1 \
 // RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 -check-prefix SM35 %s
+// Separate compilation targeting sm_35.
+// RUN: %clang -### -target x86_64-linux-gnu --cuda-gpu-arch=sm_35 -fcuda-rdc -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM35 -check-prefix RDC %s
 
 // 32-bit compile.
 // RUN: %clang -### -target i386-linux-gnu -c %s 2>&1 \
 // RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH32 -check-prefix SM20 %s
+// 32-bit compile when generating relocatable device code.
+// RUN: %clang -### -target i386-linux-gnu -fcuda-rdc -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH32 \
+// RUN: -check-prefix SM20 -check-prefix RDC %s
 
 // Compile with -fintegrated-as.  This should still cause us to invoke ptxas.
 // RUN: %clang -### -target x86_64-linux-gnu -fintegrated-as -c %s 2>&1 \
 // RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
 // RUN: -check-prefix SM20 -check-prefix OPT0 %s
+// Check that we still pass -c when generating relocatable device code.
+// RUN: %clang -### -target x86_64-linux-gnu -fintegrated-as -fcuda-rdc -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix RDC %s
 
 // Check -Xcuda-ptxas and -Xcuda-fatbinary
 // RUN: %clang -### -target x86_64-linux-gnu -c -Xcuda-ptxas -foo1 \
@@ -78,6 +94,17 @@
 // RUN: %clang -### -target i386-apple-macosx -c %s 2>&1 \
 // RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH32 -check-prefix SM20 %s
 
+// Check relocatable device code generation on MacOS.
+// RUN: %clang -### -target x86_64-apple-macosx -O0 -fcuda-rdc -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix RDC %s
+// RUN: %clang -### -target x86_64-apple-macosx --cuda-gpu-arch=sm_35 -fcuda-rdc -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM35 -check-prefix RDC %s
+// RUN: %clang -### -target i386-apple-macosx -fcuda-rdc -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH32 \
+// RUN: -check-prefix SM20 -check-prefix RDC %s
+
 // Check that CLANG forwards the -v flag to PTXAS.
 // RUN:   %clang -### -save-temps -no-canonical-prefixes -v %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-PTXAS-VERBOSE %s
@@ -90,6 +117,8 @@
 // SM35-SAME: "-target-cpu" "sm_35"
 // SM20-SAME: "-o" "[[PTXFILE:[^"]*]]"
 // SM35-SAME: "-o" "[[PTXFILE:[^"]*]]"
+// RDC-SAME: "-fcuda-rdc"
+// CHECK-NOT: "-fcuda-rdc"
 
 // Match the call to ptxas (which assembles PTX to SASS).
 // CHECK: ptxas
@@ -111,6 +140,8 @@
 // CHECK-SAME: "[[PTXFILE]]"
 // PTXAS-EXTRA-SAME: "-foo1"
 // PTXAS-EXTRA-SAME: "-foo2"
+// RDC-SAME: "-c"
+// CHECK-NOT: "-c"
 
 // Match the call to fatbinary (which combines all our PTX and SASS into one
 // blob).
@@ -131,5 +162,7 @@
 // ARCH64-SAME: "-triple" "x86_64-
 // ARCH32-SAME: "-triple" "i386-
 // CHECK-SAME: "-fcuda-include-gpubinary" "[[FATBINARY]]"
+// RDC-SAME: "-fcuda-rdc"
+// CHECK-NOT: "-fcuda-rdc"
 
 // CHK-PTXAS-VERBOSE: ptxas{{.*}}" "-v"
Index: lib/Frontend/CompilerInvocation.cpp

[PATCH] D42920: [CUDA] Fix test cuda-external-tools.cu

2018-02-05 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld created this revision.
Hahnfeld added reviewers: jlebar, tra.
Herald added a subscriber: cfe-commits.
Hahnfeld added a dependent revision: D42921: [CUDA] Add option to generate 
relocatable device code.

This didn't verify the CHECK prefix before!


Repository:
  rC Clang

https://reviews.llvm.org/D42920

Files:
  test/Driver/cuda-external-tools.cu

Index: test/Driver/cuda-external-tools.cu
===
--- test/Driver/cuda-external-tools.cu
+++ test/Driver/cuda-external-tools.cu
@@ -7,112 +7,129 @@
 
 // Regular compiles with -O{0,1,2,3,4,fast}.  -O4 and -Ofast map to ptxas O3.
 // RUN: %clang -### -target x86_64-linux-gnu -O0 -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT0 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT0 %s
 // RUN: %clang -### -target x86_64-linux-gnu -O1 -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT1 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT1 %s
 // RUN: %clang -### -target x86_64-linux-gnu -O2 -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT2 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT2 %s
 // RUN: %clang -### -target x86_64-linux-gnu -O3 -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT3 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT3 %s
 // RUN: %clang -### -target x86_64-linux-gnu -O4 -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT3 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT3 %s
 // RUN: %clang -### -target x86_64-linux-gnu -Ofast -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT3 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT3 %s
 
 // With debugging enabled, ptxas should be run with with no ptxas optimizations.
 // RUN: %clang -### -target x86_64-linux-gnu --cuda-noopt-device-debug -O2 -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix DBG %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix DBG %s
 
 // --no-cuda-noopt-device-debug overrides --cuda-noopt-device-debug.
 // RUN: %clang -### -target x86_64-linux-gnu --cuda-noopt-device-debug \
 // RUN:   --no-cuda-noopt-device-debug -O2 -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT2 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT2 %s
 
 // Regular compile without -O.  This should result in us passing -O0 to ptxas.
 // RUN: %clang -### -target x86_64-linux-gnu -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT0 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT0 %s
 
 // Regular compiles with -Os and -Oz.  For lack of a better option, we map
 // these to ptxas -O3.
 // RUN: %clang -### -target x86_64-linux-gnu -Os -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT2 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT2 %s
 // RUN: %clang -### -target x86_64-linux-gnu -Oz -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT2 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT2 %s
 
 // Regular compile targeting sm_35.
 // RUN: %clang -### -target x86_64-linux-gnu --cuda-gpu-arch=sm_35 -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM35 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 -check-prefix SM35 %s
 
 // 32-bit compile.
-// RUN: %clang -### -target x86_32-linux-gnu -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH32 -check-prefix SM20 %s
+// RUN: %clang -### -target i386-linux-gnu -c %s 2>&1 \
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH32 -check-prefix SM20 %s
 
 // Compile with -fintegrated-as.  This should still cause us to invoke ptxas.
 // RUN: %clang -### -target x86_64-linux-gnu -fintegrated-as -c %s 2>&1 \
-// RUN: | FileCheck -check-prefix ARCH64 -check-prefix SM20 -check-prefix OPT0 %s
+// RUN: | FileCheck -check-prefix CHECK -check-prefix ARCH64 \
+// RUN: -check-prefix SM20 -check-prefix OPT0 %s
 
 // 

[PATCH] D42919: [clangd] Support simpler JSON-RPC stream parsing for lit tests.

2018-02-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: ioeric.
Herald added subscribers: cfe-commits, jkorous-apple, ilya-biryukov, klimek.

Instead of content-length, we delimit messages with ---.
This also removes the need for (most) dos-formatted test files.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42919

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/JSONRPCDispatcher.cpp
  clangd/JSONRPCDispatcher.h
  clangd/tool/ClangdMain.cpp
  test/clangd/completion.test
  test/clangd/crash-non-added-files.test
  test/clangd/diagnostics.test
  test/clangd/execute-command.test
  test/clangd/extra-flags.test
  test/clangd/fixits.test
  test/clangd/formatting.test
  test/clangd/initialize-params-invalid.test
  test/clangd/initialize-params.test
  test/clangd/rename.test
  test/clangd/shutdown-with-exit.test
  test/clangd/shutdown-without-exit.test
  test/clangd/signature-help.test
  test/clangd/test-uri-posix.test
  test/clangd/test-uri-windows.test
  test/clangd/trace.test
  test/clangd/unsupported-method.test
  test/clangd/xrefs.test

Index: test/clangd/xrefs.test
===
--- test/clangd/xrefs.test
+++ test/clangd/xrefs.test
@@ -1,67 +1,57 @@
-# RUN: clangd -pretty -run-synchronously < %s | FileCheck -strict-whitespace %s
-# It is absolutely vital that this file has CRLF line endings.
-#
-Content-Length: 125
-
-{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
-
-Content-Length: 165
-
-{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":"int x = 0;\nint y = x;"}}}
-
-Content-Length: 148
-
-{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"test:///main.cpp"},"position":{"line":1,"character":8}}}
-#  CHECK:  "id": 1,
-# CHECK-NEXT:  "jsonrpc": "2.0",
-# CHECK-NEXT:  "result": [
-# CHECK-NEXT:{
-# CHECK-NEXT:  "range": {
-# CHECK-NEXT:"end": {
-# CHECK-NEXT:  "character": 9,
-# CHECK-NEXT:  "line": 0
-# CHECK-NEXT:},
-# CHECK-NEXT:"start": {
-# CHECK-NEXT:  "character": 0,
-# CHECK-NEXT:  "line": 0
-# CHECK-NEXT:}
-# CHECK-NEXT:  },
-# CHECK-NEXT:  "uri": "file://{{.*}}/{{([A-Z]:/)?}}main.cpp"
-# CHECK-NEXT:}
-# CHECK-NEXT:  ]
-Content-Length: 155
-
-{"jsonrpc":"2.0","id":1,"method":"textDocument/documentHighlight","params":{"textDocument":{"uri":"test:///main.cpp"},"position":{"line":1,"character":8}}}
-#  CHECK: "id": 1
-# CHECK-NEXT: "jsonrpc": "2.0",
-# CHECK-NEXT: "result": [
-# CHECK-NEXT:   {
-# CHECK-NEXT: "kind": 1,
-# CHECK-NEXT: "range": {
-# CHECK-NEXT:   "end": {
-# CHECK-NEXT: "character": 5,
-# CHECK-NEXT: "line": 0
-# CHECK-NEXT:   },
-# CHECK-NEXT:   "start": {
-# CHECK-NEXT: "character": 4,
-# CHECK-NEXT: "line": 0
-# CHECK-NEXT:   }
-# CHECK-NEXT: }
-# CHECK-NEXT:   },
-# CHECK-NEXT:   {
-# CHECK-NEXT: "kind": 2,
-# CHECK-NEXT: "range": {
-# CHECK-NEXT:   "end": {
-# CHECK-NEXT: "character": 9,
-# CHECK-NEXT: "line": 1
-# CHECK-NEXT:   },
-# CHECK-NEXT:   "start": {
-# CHECK-NEXT: "character": 8,
-# CHECK-NEXT: "line": 1
-# CHECK-NEXT:   }
-# CHECK-NEXT: }
-# CHECK-NEXT:   }
-# CHECK-NEXT: ]
-Content-Length: 48
-
-{"jsonrpc":"2.0","id":1,"method":"shutdown"}
+# RUN: clangd -test < %s | FileCheck -strict-whitespace %s
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+---
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"test:///main.cpp","languageId":"cpp","version":1,"text":"int x = 0;\nint y = x;"}}}
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/definition","params":{"textDocument":{"uri":"test:///main.cpp"},"position":{"line":1,"character":8}}}
+#  CHECK:  "id": 1,
+# CHECK-NEXT:  "jsonrpc": "2.0",
+# CHECK-NEXT:  "result": [
+# CHECK-NEXT:{
+# CHECK-NEXT:  "range": {
+# CHECK-NEXT:"end": {
+# CHECK-NEXT:  "character": 9,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:},
+# CHECK-NEXT:"start": {
+# CHECK-NEXT:  "character": 0,
+# CHECK-NEXT:  "line": 0
+# CHECK-NEXT:}
+# CHECK-NEXT:  },
+# CHECK-NEXT:  "uri": "file://{{.*}}/{{([A-Z]:/)?}}main.cpp"
+# CHECK-NEXT:}
+# CHECK-NEXT:  ]
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/documentHighlight","params":{"textDocument":{"uri":"test:///main.cpp"},"position":{"line":1,"character":8}}}
+#  CHECK: "id": 1
+# CHECK-NEXT: "jsonrpc": "2.0",
+# CHECK-NEXT: "result": [
+# CHECK-NEXT:   {
+# CHECK-NEXT: "kind": 1,
+# CHECK-NEXT: "range": {
+# CHECK-NEXT:   "end": {
+# CHECK-NEXT: "character": 5,
+# 

[PATCH] D42918: [clang-tidy] Update fuchsia-multiple-inheritance to check for templates

2018-02-05 Thread Julie Hockett via Phabricator via cfe-commits
juliehockett created this revision.
juliehockett added reviewers: aaron.ballman, alexfh, hokein.
Herald added a subscriber: xazax.hun.

Updating fuchsia-multiple-inheritance to not crash when a record inherits a 
template.

Fixes PR36052.


https://reviews.llvm.org/D42918

Files:
  clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
  test/clang-tidy/fuchsia-multiple-inheritance.cpp


Index: test/clang-tidy/fuchsia-multiple-inheritance.cpp
===
--- test/clang-tidy/fuchsia-multiple-inheritance.cpp
+++ test/clang-tidy/fuchsia-multiple-inheritance.cpp
@@ -129,3 +129,5 @@
 struct V14 : virtual Static_Base_2 { static void g(); };
 struct D8 : V13, V14 {};
 
+template struct A : T {};
+template struct B : virtual T {};
Index: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
===
--- clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
+++ clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
@@ -64,7 +64,7 @@
 
   // To be an interface, all base classes must be interfaces as well.
   for (const auto  : Node->bases()) {
-if (I.isVirtual()) continue;  
+if (I.isVirtual()) continue;
 const auto *Ty = I.getType()->getAs();
 assert(Ty && "RecordType of base class is unknown");
 const RecordDecl *D = Ty->getDecl()->getDefinition();
@@ -96,7 +96,7 @@
 // concrete classes
 unsigned NumConcrete = 0;
 for (const auto  : D->bases()) {
-  if (I.isVirtual()) continue;
+  if (I.isVirtual() || I.getType()->getAs()) 
continue;
   const auto *Ty = I.getType()->getAs();
   assert(Ty && "RecordType of base class is unknown");
   const auto *Base = cast(Ty->getDecl()->getDefinition());


Index: test/clang-tidy/fuchsia-multiple-inheritance.cpp
===
--- test/clang-tidy/fuchsia-multiple-inheritance.cpp
+++ test/clang-tidy/fuchsia-multiple-inheritance.cpp
@@ -129,3 +129,5 @@
 struct V14 : virtual Static_Base_2 { static void g(); };
 struct D8 : V13, V14 {};
 
+template struct A : T {};
+template struct B : virtual T {};
Index: clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
===
--- clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
+++ clang-tidy/fuchsia/MultipleInheritanceCheck.cpp
@@ -64,7 +64,7 @@
 
   // To be an interface, all base classes must be interfaces as well.
   for (const auto  : Node->bases()) {
-if (I.isVirtual()) continue;  
+if (I.isVirtual()) continue;
 const auto *Ty = I.getType()->getAs();
 assert(Ty && "RecordType of base class is unknown");
 const RecordDecl *D = Ty->getDecl()->getDefinition();
@@ -96,7 +96,7 @@
 // concrete classes
 unsigned NumConcrete = 0;
 for (const auto  : D->bases()) {
-  if (I.isVirtual()) continue;
+  if (I.isVirtual() || I.getType()->getAs()) continue;
   const auto *Ty = I.getType()->getAs();
   assert(Ty && "RecordType of base class is unknown");
   const auto *Base = cast(Ty->getDecl()->getDefinition());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D41834: [Lex] Fix handling numerical literals ending with ' and signed exponent.

2018-02-05 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

Ping.


https://reviews.llvm.org/D41834



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


[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-05 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: lib/Basic/Targets/AMDGPU.h:85
 return TT.getEnvironmentName() == "amdgiz" ||
+   TT.getOS() == llvm::Triple::CUDA ||
TT.getEnvironmentName() == "amdgizcl";

t-tye wrote:
> We still want to use the amdhsa OS for amdgpu which currently supports the 
> different environments. So can cuda simply support the same environments? Is 
> the plan is to eliminate the environments and simply always use the default 
> address space for generic so this code is no longer needed?
Currently we already use amdgiz by default. This is no longer needed.


https://reviews.llvm.org/D42800



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


[PATCH] D42800: Let CUDA toolchain support amdgpu target

2018-02-05 Thread Tony Tye via Phabricator via cfe-commits
t-tye added inline comments.



Comment at: include/clang/Basic/Cuda.h:49-57
+  GFX700,
+  GFX701,
+  GFX800,
+  GFX801,
+  GFX802,
+  GFX803,
+  GFX810,

Should complete list of processors for the amdgcn architecture be included? See 
https://llvm.org/docs/AMDGPUUsage.html#processors .



Comment at: include/clang/Basic/Cuda.h:79
   COMPUTE_72,
+  COMPUTE_GCN,
 };

Suggest using amdgcn which matches the architecture name in 
https://llvm.org/docs/AMDGPUUsage.html#processors .



Comment at: lib/Basic/Targets/AMDGPU.h:85
 return TT.getEnvironmentName() == "amdgiz" ||
+   TT.getOS() == llvm::Triple::CUDA ||
TT.getEnvironmentName() == "amdgizcl";

We still want to use the amdhsa OS for amdgpu which currently supports the 
different environments. So can cuda simply support the same environments? Is 
the plan is to eliminate the environments and simply always use the default 
address space for generic so this code is no longer needed?


https://reviews.llvm.org/D42800



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


r324259 - [Options] Make --cuda-path-ignore-env a Flag, NFCI.

2018-02-05 Thread Jonas Hahnfeld via cfe-commits
Author: hahnfeld
Date: Mon Feb  5 10:19:40 2018
New Revision: 324259

URL: http://llvm.org/viewvc/llvm-project?rev=324259=rev
Log:
[Options] Make --cuda-path-ignore-env a Flag, NFCI.

This option doesn't take an argument!

Modified:
cfe/trunk/include/clang/Driver/Options.td

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=324259=324258=324259=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Mon Feb  5 10:19:40 2018
@@ -556,7 +556,7 @@ def no_cuda_version_check : Flag<["--"],
 def no_cuda_noopt_device_debug : Flag<["--"], "no-cuda-noopt-device-debug">;
 def cuda_path_EQ : Joined<["--"], "cuda-path=">, Group,
   HelpText<"CUDA installation path">;
-def cuda_path_ignore_env : Joined<["--"], "cuda-path-ignore-env">, 
Group,
+def cuda_path_ignore_env : Flag<["--"], "cuda-path-ignore-env">, 
Group,
   HelpText<"Ignore environment variables to detect CUDA installation">;
 def ptxas_path_EQ : Joined<["--"], "ptxas-path=">, Group,
   HelpText<"Path to ptxas (used for compiling CUDA code)">;


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


[PATCH] D42758: Support `#pragma comment(lib, "name")` in the frontend for ELF

2018-02-05 Thread David Majnemer via Phabricator via cfe-commits
majnemer added a comment.

docs/LanguageExtensions.html should be updated to mention that we support this 
extension on all ELF targets.


Repository:
  rC Clang

https://reviews.llvm.org/D42758



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


[PATCH] D42813: [Debug] Annotate compiler generated range-for loop variables.

2018-02-05 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

Seems plausible - maybe walking the scopes to count the range-for loops would 
produce a better number, but would be slower. :/ Dunno.




Comment at: lib/Sema/SemaStmt.cpp:2346
+// Assume the variables are nested in the inner scope (loop body).
+const auto DepthStr = std::to_string(S->getDepth() >> 1);
 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,

Why shifted right/divided by two? (I'd probably write this as "/ 2" rather 
thane ">> 1" if this is what's)

I guess this is because a range-for introduces two (actually 3, I think) scopes?

But what about if there are other random scopes that could be present? Does 
that adversely affect anything here?


https://reviews.llvm.org/D42813



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


[PATCH] D42645: New simple Checker for mmap calls

2018-02-05 Thread Aleksei Sidorin via Phabricator via cfe-commits
a.sidorin added a comment.

Hi David! The patch looks almost OK.




Comment at: lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp:65
+  *BT, "Both PROT_WRITE and PROT_EXEC flags are set. This can "
+   "lead to exploitable memory regions, which could be overwritten 
with malicious code"
+ , N);

This line violates 80-char limit. Next line starts with comma which is not good.



Comment at: test/Analysis/mmap-writeexec.c:1
+// RUN: %clang_analyze_cc1 -triple i686-unknown-freebsd 
-analyzer-checker=security.MmapWriteExec -verify %s
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-apple-darwin10 
-analyzer-checker=security.MmapWriteExec -verify %s

Do you try to test  `if (Triple.isOSGlibc())` branch here? If so, 
`i686-unknown-freebsd` doesn't look like an appropriate target (it is not 
kFreeBSD). You can use `-triple=x86_64-pc-kfreebsd-gnu` or just 
`i686-unknown-linux`.


Repository:
  rC Clang

https://reviews.llvm.org/D42645



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


[PATCH] D42758: Support `#pragma comment(lib, "name")` in the frontend for ELF

2018-02-05 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd updated this revision to Diff 132853.
compnerd added a comment.

clang-format missed line, simplify some checks


Repository:
  rC Clang

https://reviews.llvm.org/D42758

Files:
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/CodeGenModule.h
  lib/Parse/ParsePragma.cpp
  test/CodeGen/elf-linker-options.c
  test/CodeGen/pragma-comment.c

Index: test/CodeGen/pragma-comment.c
===
--- test/CodeGen/pragma-comment.c
+++ test/CodeGen/pragma-comment.c
@@ -23,10 +23,9 @@
 // CHECK: ![[bar]] = !{!" /bar=2"}
 // CHECK: ![[foo]] = !{!" /foo=\22foo bar\22"}

-// LINUX: !{!"-lmsvcrt.lib"}
-// LINUX: !{!"-lkernel32"}
-// LINUX: !{!"-lUSER32.LIB"}
-// LINUX: !{!" /bar=2"}
+// LINUX: !{!"lib", !"msvcrt.lib"}
+// LINUX: !{!"lib", !"kernel32"}
+// LINUX: !{!"lib", !"USER32.LIB"}

 // PS4: !{!"\01msvcrt.lib"}
 // PS4: !{!"\01kernel32"}
Index: test/CodeGen/elf-linker-options.c
===
--- /dev/null
+++ test/CodeGen/elf-linker-options.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -triple i686---elf -emit-llvm %s -o - | FileCheck %s
+
+#pragma comment(lib, "alpha")
+
+// CHECK: !llvm.linker.options = !{[[NODE:![0-9]+]]}
+// CHECK: [[NODE]] = !{!"lib", !"alpha"}
+
Index: lib/Parse/ParsePragma.cpp
===
--- lib/Parse/ParsePragma.cpp
+++ lib/Parse/ParsePragma.cpp
@@ -295,7 +295,8 @@
 OpenMPHandler.reset(new PragmaNoOpenMPHandler());
   PP.AddPragmaHandler(OpenMPHandler.get());

-  if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) {
+  if (getLangOpts().MicrosoftExt ||
+  getTargetInfo().getTriple().isOSBinFormatELF()) {
 MSCommentHandler.reset(new PragmaCommentHandler(Actions));
 PP.AddPragmaHandler(MSCommentHandler.get());
   }
@@ -377,7 +378,8 @@
   PP.RemovePragmaHandler(OpenMPHandler.get());
   OpenMPHandler.reset();

-  if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) {
+  if (getLangOpts().MicrosoftExt ||
+  getTargetInfo().getTriple().isOSBinFormatELF()) {
 PP.RemovePragmaHandler(MSCommentHandler.get());
 MSCommentHandler.reset();
   }
@@ -2449,6 +2451,12 @@
 return;
   }

+  if (PP.getTargetInfo().getTriple().isOSBinFormatELF() && Kind != PCK_Lib) {
+PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
+<< II->getName();
+return;
+  }
+
   // On PS4, issue a warning about any pragma comments other than
   // #pragma comment lib.
   if (PP.getTargetInfo().getTriple().isPS4() && Kind != PCK_Lib) {
Index: lib/CodeGen/CodeGenModule.h
===
--- lib/CodeGen/CodeGenModule.h
+++ lib/CodeGen/CodeGenModule.h
@@ -1094,6 +1094,8 @@
   /// value.
   void AddDependentLib(StringRef Lib);

+  void AddELFLibDirective(StringRef Lib);
+
   llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD);

   void setFunctionLinkage(GlobalDecl GD, llvm::Function *F) {
Index: lib/CodeGen/CodeGenModule.cpp
===
--- lib/CodeGen/CodeGenModule.cpp
+++ lib/CodeGen/CodeGenModule.cpp
@@ -1411,6 +1411,12 @@
   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
 }

+void CodeGenModule::AddELFLibDirective(StringRef Lib) {
+  auto  = getLLVMContext();
+  LinkerOptionsMetadata.push_back(llvm::MDNode::get(
+  C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
+}
+
 void CodeGenModule::AddDependentLib(StringRef Lib) {
   llvm::SmallString<24> Opt;
   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
@@ -4345,7 +4351,11 @@
   AppendLinkerOptions(PCD->getArg());
   break;
 case PCK_Lib:
-  AddDependentLib(PCD->getArg());
+  if (getTarget().getTriple().isOSBinFormatELF() &&
+  !getTarget().getTriple().isPS4())
+AddELFLibDirective(PCD->getArg());
+  else
+AddDependentLib(PCD->getArg());
   break;
 case PCK_Compiler:
 case PCK_ExeStr:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D42915: [clangd] Use URIs in index symbols.

2018-02-05 Thread Eric Liu via Phabricator via cfe-commits
ioeric created this revision.
ioeric added reviewers: hokein, sammccall.
Herald added subscribers: cfe-commits, jkorous-apple, ilya-biryukov, klimek.

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42915

Files:
  clangd/index/Index.cpp
  clangd/index/Index.h
  clangd/index/Merge.cpp
  clangd/index/SymbolCollector.cpp
  clangd/index/SymbolYAML.cpp
  unittests/clangd/IndexTests.cpp
  unittests/clangd/SymbolCollectorTests.cpp

Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -46,7 +46,7 @@
   return arg.CompletionSnippetInsertText == S;
 }
 MATCHER_P(QName, Name, "") { return (arg.Scope + arg.Name).str() == Name; }
-MATCHER_P(CPath, P, "") { return arg.CanonicalDeclaration.FilePath == P; }
+MATCHER_P(Uri, P, "") { return arg.CanonicalDeclaration.FileUri == P; }
 MATCHER_P(LocationOffsets, Offsets, "") {
   // Offset range in SymbolLocation is [start, end] while in Clangd is [start,
   // end).
@@ -58,8 +58,6 @@
 namespace clangd {
 
 namespace {
-const char TestHeaderName[] = "symbols.h";
-const char TestFileName[] = "symbol.cc";
 class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
 public:
   SymbolIndexActionFactory(SymbolCollector::Options COpts)
@@ -82,6 +80,13 @@
 
 class SymbolCollectorTest : public ::testing::Test {
 public:
+  SymbolCollectorTest()
+  : TestHeaderName(getVirtualTestFilePath("symbol.h").str()),
+TestFileName(getVirtualTestFilePath("symbol.cc").str()) {
+TestHeaderUri = URI::createFile(TestHeaderName).toString();
+TestFileUri = URI::createFile(TestFileName).toString();
+  }
+
   bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode) {
 llvm::IntrusiveRefCntPtr InMemoryFileSystem(
 new vfs::InMemoryFileSystem);
@@ -100,15 +105,21 @@
 
 std::string Content = MainCode;
 if (!HeaderCode.empty())
-  Content = "#include\"" + std::string(TestHeaderName) + "\"\n" + Content;
+  Content = (llvm::Twine("#include\"") +
+ llvm::sys::path::filename(TestHeaderName) + "\"\n" + Content)
+.str();
 InMemoryFileSystem->addFile(TestFileName, 0,
 llvm::MemoryBuffer::getMemBuffer(Content));
 Invocation.run();
 Symbols = Factory->Collector->takeSymbols();
 return true;
   }
 
 protected:
+  std::string TestHeaderName;
+  std::string TestHeaderUri;
+  std::string TestFileName;
+  std::string TestFileUri;
   SymbolSlab Symbols;
   SymbolCollector::Options CollectorOpts;
 };
@@ -165,16 +176,19 @@
   CollectorOpts.IndexMainFiles = false;
   runSymbolCollector("class Foo {};", /*Main=*/"");
   EXPECT_THAT(Symbols,
-  UnorderedElementsAre(AllOf(QName("Foo"), CPath("symbols.h";
+  UnorderedElementsAre(AllOf(QName("Foo"), Uri(TestHeaderUri;
 }
 
 TEST_F(SymbolCollectorTest, SymbolRelativeWithFallback) {
   CollectorOpts.IndexMainFiles = false;
+  TestHeaderName = "x.h";
+  TestFileName = "x.cpp";
+  TestHeaderUri =
+  URI::createFile(getVirtualTestFilePath(TestHeaderName)).toString();
   CollectorOpts.FallbackDir = getVirtualTestRoot();
   runSymbolCollector("class Foo {};", /*Main=*/"");
   EXPECT_THAT(Symbols,
-  UnorderedElementsAre(AllOf(
-  QName("Foo"), CPath(getVirtualTestFilePath("symbols.h");
+  UnorderedElementsAre(AllOf(QName("Foo"), Uri(TestHeaderUri;
 }
 
 TEST_F(SymbolCollectorTest, IncludeEnums) {
@@ -229,14 +243,14 @@
   )");
 
   runSymbolCollector(Header.code(), /*Main=*/"");
-  EXPECT_THAT(Symbols,
-  UnorderedElementsAre(
-  AllOf(QName("abc_Test"),
-LocationOffsets(Header.offsetRange("expansion")),
-CPath(TestHeaderName)),
-  AllOf(QName("Test"),
-LocationOffsets(Header.offsetRange("spelling")),
-CPath(TestHeaderName;
+  EXPECT_THAT(
+  Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("abc_Test"),
+LocationOffsets(Header.offsetRange("expansion")),
+Uri(TestHeaderUri)),
+  AllOf(QName("Test"), LocationOffsets(Header.offsetRange("spelling")),
+Uri(TestHeaderUri;
 }
 
 TEST_F(SymbolCollectorTest, SymbolFormedFromMacroInMainFile) {
@@ -254,14 +268,13 @@
 FF2();
   )");
   runSymbolCollector(/*Header=*/"", Main.code());
-  EXPECT_THAT(Symbols,
-  UnorderedElementsAre(
-  AllOf(QName("abc_Test"),
-LocationOffsets(Main.offsetRange("expansion")),
-CPath(TestFileName)),
-  AllOf(QName("Test"),
-LocationOffsets(Main.offsetRange("spelling")),
-CPath(TestFileName;
+  EXPECT_THAT(Symbols, UnorderedElementsAre(
+ 

[PATCH] D42645: New simple Checker for mmap calls

2018-02-05 Thread David CARLIER via Phabricator via cfe-commits
devnexen added a comment.

Correcting last typos in unit test.


Repository:
  rC Clang

https://reviews.llvm.org/D42645



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


[PATCH] D42645: New simple Checker for mmap calls

2018-02-05 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 132850.
devnexen edited the summary of this revision.

Repository:
  rC Clang

https://reviews.llvm.org/D42645

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
  test/Analysis/mmap-writeexec.c

Index: test/Analysis/mmap-writeexec.c
===
--- test/Analysis/mmap-writeexec.c
+++ test/Analysis/mmap-writeexec.c
@@ -0,0 +1,31 @@
+// RUN: %clang_analyze_cc1 -triple i686-unknown-freebsd -analyzer-checker=security.MmapWriteExec -verify %s
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-apple-darwin10 -analyzer-checker=security.MmapWriteExec -verify %s
+
+#define PROT_READ   0x01
+#define PROT_WRITE  0x02
+#define PROT_EXEC   0x04
+#define MAP_PRIVATE 0x0002
+#define MAP_ANON0x1000
+#define MAP_FIXED   0x0010
+#define NULL((void *)0)
+
+typedef __typeof(sizeof(int)) size_t;
+void *mmap(void *, size_t, int, int, int, long);
+
+void f1()
+{
+  void *a = mmap(NULL, 16, PROT_READ | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); // no-warning
+  void *b = mmap(a, 16, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANON, -1, 0); // no-warning
+  void *c = mmap(NULL, 32, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); // expected-warning{{Both PROT_WRITE and PROT_EXEC flags are set. This can lead to exploitable memory regions, which could be overwritten with malicious code}}
+  (void)a;
+  (void)b;
+  (void)c;
+}
+
+void f2()
+{
+  void *(*callm)(void *, size_t, int, int, int, long);
+  callm = mmap;
+  int prot = PROT_WRITE | PROT_EXEC;
+  (void)callm(NULL, 1024, prot, MAP_PRIVATE | MAP_ANON, -1, 0); // expected-warning{{Both PROT_WRITE and PROT_EXEC flags are set. This can lead to exploitable memory regions, which could be overwritten with malicious code}}
+}
Index: lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
+++ lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
@@ -0,0 +1,75 @@
+// MmapWriteExecChecker.cpp - Check for the prot argument -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This checker tests the 3rd argument of mmap's calls to check if
+// it is writable and executable in the same time. It's somehow
+// an optional checker since for example in JIT libraries it is pretty common.
+//
+//===--===//
+
+#include "ClangSACheckers.h"
+
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+using llvm::APSInt;
+
+namespace {
+class MmapWriteExecChecker : public Checker {
+  CallDescription MmapFn;
+  static int ProtWrite;
+  static int ProtExec;
+  mutable std::unique_ptr BT;
+public:
+  MmapWriteExecChecker() : MmapFn("mmap", 6) {}
+  void checkPreCall(const CallEvent , CheckerContext ) const;
+};
+}
+
+int MmapWriteExecChecker::ProtWrite = 0x02;
+int MmapWriteExecChecker::ProtExec  = 0x04;
+
+void MmapWriteExecChecker::checkPreCall(const CallEvent ,
+ CheckerContext ) const {
+  if (Call.isCalled(MmapFn)) {
+llvm::Triple Triple = C.getASTContext().getTargetInfo().getTriple();
+
+if (Triple.isOSGlibc())
+  ProtExec = 0x01;
+
+SVal ProtVal = Call.getArgSVal(2); 
+Optional ProtLoc = ProtVal.getAs();
+int64_t Prot = ProtLoc->getValue().getSExtValue();
+
+if ((Prot & (ProtWrite | ProtExec)) == (ProtWrite | ProtExec)) {
+  if (!BT)
+BT.reset(new BugType(this, "W^X check fails, Write Exec prot flags set", "Security"));
+
+  ExplodedNode *N = C.generateNonFatalErrorNode();
+  if (!N)
+return;
+
+  auto Report = llvm::make_unique(
+  *BT, "Both PROT_WRITE and PROT_EXEC flags are set. This can "
+   "lead to exploitable memory regions, which could be overwritten with malicious code"
+ , N);
+  Report->addRange(Call.getArgSourceRange(2));
+  C.emitReport(std::move(Report));
+}
+  }
+}
+
+void ento::registerMmapWriteExecChecker(CheckerManager ) {
+  mgr.registerChecker();
+}
Index: lib/StaticAnalyzer/Checkers/CMakeLists.txt
===
--- lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -49,6 +49,7 @@
   

[PATCH] D42758: Support `#pragma comment(lib, "name")` in the frontend for ELF

2018-02-05 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

This seems pretty OK to me.  I'd like to see @probinson s PS4 discussion bottom 
out, but I don't see any reason to hold this up otherwise.

We definitely should leave the format as #pragma comment(keyword, "message"), 
since there is significant prior art here.




Comment at: test/CodeGen/elf-linker-options.c:3
+
+#pragma comment(lib, "alpha")
+

I would like a test for Sema to validate the 'pragma ignored' warning in common 
cases (such as 'Linker').


Repository:
  rC Clang

https://reviews.llvm.org/D42758



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


[PATCH] D42913: [clangd] Fix incorrect file path for symbols defined by the compile command-line option.

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




Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42913

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


Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -82,16 +82,20 @@
 
 class SymbolCollectorTest : public ::testing::Test {
 public:
-  bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode) {
+  bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode,
+  const std::vector  = {}) {
 llvm::IntrusiveRefCntPtr InMemoryFileSystem(
 new vfs::InMemoryFileSystem);
 llvm::IntrusiveRefCntPtr Files(
 new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
 auto Factory = llvm::make_unique(CollectorOpts);
 
+std::vector Args = {"symbol_collector", "-fsyntax-only",
+ "-std=c++11", TestFileName};
+Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
 tooling::ToolInvocation Invocation(
-{"symbol_collector", "-fsyntax-only", "-std=c++11", TestFileName},
+Args,
 Factory->create(), Files.get(),
 std::make_shared());
 
@@ -264,6 +268,24 @@
 CPath(TestFileName;
 }
 
+TEST_F(SymbolCollectorTest, SymbolFormedByCLI) {
+  CollectorOpts.IndexMainFiles = false;
+
+  Annotations Header(R"(
+#ifdef NAME
+$expansion[[class NAME {}]];
+#endif
+  )");
+
+  runSymbolCollector(Header.code(), /*Main=*/"",
+ /*ExtraArgs=*/{"-DNAME=name"});
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  AllOf(QName("name"),
+LocationOffsets(Header.offsetRange("expansion")),
+CPath(TestHeaderName;
+}
+
 TEST_F(SymbolCollectorTest, IgnoreSymbolsInMainFile) {
   CollectorOpts.IndexMainFiles = false;
   const std::string Header = R"(
Index: clangd/index/SymbolCollector.cpp
===
--- clangd/index/SymbolCollector.cpp
+++ clangd/index/SymbolCollector.cpp
@@ -124,10 +124,15 @@
 
   SourceLocation Loc = SM.getSpellingLoc(D->getLocation());
   if (D->getLocation().isMacroID()) {
-// The symbol is formed via macro concatenation, the spelling location will
-// be "", which is not interesting to us, use the expansion
-// location instead.
-if (llvm::StringRef(Loc.printToString(SM)).startswith("getLocation())),
   FallbackDir);


Index: unittests/clangd/SymbolCollectorTests.cpp
===
--- unittests/clangd/SymbolCollectorTests.cpp
+++ unittests/clangd/SymbolCollectorTests.cpp
@@ -82,16 +82,20 @@
 
 class SymbolCollectorTest : public ::testing::Test {
 public:
-  bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode) {
+  bool runSymbolCollector(StringRef HeaderCode, StringRef MainCode,
+  const std::vector  = {}) {
 llvm::IntrusiveRefCntPtr InMemoryFileSystem(
 new vfs::InMemoryFileSystem);
 llvm::IntrusiveRefCntPtr Files(
 new FileManager(FileSystemOptions(), InMemoryFileSystem));
 
 auto Factory = llvm::make_unique(CollectorOpts);
 
+std::vector Args = {"symbol_collector", "-fsyntax-only",
+ "-std=c++11", TestFileName};
+Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
 tooling::ToolInvocation Invocation(
-{"symbol_collector", "-fsyntax-only", "-std=c++11", TestFileName},
+Args,
 Factory->create(), Files.get(),
 std::make_shared());
 
@@ -264,6 +268,24 @@
 CPath(TestFileName;
 }
 
+TEST_F(SymbolCollectorTest, SymbolFormedByCLI) {
+  CollectorOpts.IndexMainFiles = false;
+
+  Annotations Header(R"(
+#ifdef NAME
+$expansion[[class NAME {}]];
+#endif
+  )");
+
+  runSymbolCollector(Header.code(), /*Main=*/"",
+ /*ExtraArgs=*/{"-DNAME=name"});
+  EXPECT_THAT(Symbols,
+  UnorderedElementsAre(
+  

[PATCH] D37813: clang-format: better handle namespace macros

2018-02-05 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 132838.
Typz added a comment.

rebase


https://reviews.llvm.org/D37813

Files:
  include/clang/Format/Format.h
  lib/Format/Format.cpp
  lib/Format/FormatToken.h
  lib/Format/FormatTokenLexer.cpp
  lib/Format/NamespaceEndCommentsFixer.cpp
  lib/Format/TokenAnnotator.cpp
  lib/Format/UnwrappedLineFormatter.cpp
  lib/Format/UnwrappedLineParser.cpp
  unittests/Format/FormatTest.cpp
  unittests/Format/NamespaceEndCommentsFixerTest.cpp

Index: unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -53,6 +53,7 @@
 "  int i;\n"
 "  int j;\n"
 "}"));
+
   EXPECT_EQ("namespace {\n"
 "  int i;\n"
 "  int j;\n"
@@ -249,6 +250,85 @@
 "// unrelated"));
 }
 
+TEST_F(NamespaceEndCommentsFixerTest, AddsMacroEndComment) {
+  FormatStyle Style = getLLVMStyle();
+  Style.NamespaceMacros.push_back("TESTSUITE");
+
+  EXPECT_EQ("TESTSUITE() {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE()",
+fixNamespaceEndComments("TESTSUITE() {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+
+  EXPECT_EQ("TESTSUITE(A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(A)",
+fixNamespaceEndComments("TESTSUITE(A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("inline TESTSUITE(A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(A)",
+fixNamespaceEndComments("inline TESTSUITE(A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(::A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(::A)",
+fixNamespaceEndComments("TESTSUITE(::A) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(::A::B) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(::A::B)",
+fixNamespaceEndComments("TESTSUITE(::A::B) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(/**/::/**/A/**/::/**/B/**/) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(::A::B)",
+fixNamespaceEndComments("TESTSUITE(/**/::/**/A/**/::/**/B/**/) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(A, B) {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(A)",
+fixNamespaceEndComments("TESTSUITE(A, B) {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+  EXPECT_EQ("TESTSUITE(\"Test1\") {\n"
+"  int i;\n"
+"  int j;\n"
+"}// TESTSUITE(\"Test1\")",
+fixNamespaceEndComments("TESTSUITE(\"Test1\") {\n"
+"  int i;\n"
+"  int j;\n"
+"}",
+Style));
+}
+
 TEST_F(NamespaceEndCommentsFixerTest, AddsNewlineIfNeeded) {
   EXPECT_EQ("namespace A {\n"
 "  int i;\n"
@@ -381,6 +461,54 @@
 "}; /* unnamed namespace */"));
 }
 
+TEST_F(NamespaceEndCommentsFixerTest, KeepsValidMacroEndComment) {
+  FormatStyle Style = getLLVMStyle();
+  Style.NamespaceMacros.push_back("TESTSUITE");
+
+  EXPECT_EQ("TESTSUITE() {\n"
+"  int i;\n"
+"} // end anonymous TESTSUITE()",
+fixNamespaceEndComments("TESTSUITE() {\n"
+"  int i;\n"
+"} // end anonymous TESTSUITE()",
+Style));
+  EXPECT_EQ("TESTSUITE(A) {\n"
+"  int i;\n"
+"} /* end of TESTSUITE(A) */",

[PATCH] D33440: clang-format: better handle statement macros

2018-02-05 Thread Francois Ferrand via Phabricator via cfe-commits
Typz updated this revision to Diff 132837.
Typz added a comment.

Use StatementMacro detection to improve brace type detection heuristics (in 
UnwrappedLineParser::calculateBraceTypes).


https://reviews.llvm.org/D33440

Files:
  include/clang/Format/Format.h
  lib/Format/Format.cpp
  lib/Format/FormatToken.h
  lib/Format/FormatTokenLexer.cpp
  lib/Format/FormatTokenLexer.h
  lib/Format/UnwrappedLineParser.cpp
  lib/Format/UnwrappedLineParser.h
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -2420,6 +2420,45 @@
getLLVMStyleWithColumns(40)));
 
   verifyFormat("MACRO(>)");
+
+  // Some macros contain an implicit semicolon
+  FormatStyle Style = getLLVMStyle();
+  Style.StatementMacros.push_back("FOO");
+  verifyFormat("FOO(a) int b = 0;");
+  verifyFormat("FOO(a)\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("FOO(a);\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("FOO()\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("FOO\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("void f() {\n"
+   "  FOO(a)\n"
+   "  return a;\n"
+   "}",
+   Style);
+  verifyFormat("FOO(a)\n"
+   "FOO(b)",
+   Style);
+  verifyFormat("int a = 0;\n"
+   "FOO(b)\n"
+   "int c = 0;",
+   Style);
+  verifyFormat("int a = 0;\n"
+   "int x = FOO(a)\n"
+   "int b = 0;",
+   Style);
+  verifyFormat("void foo(int a) { FOO(a) }\n"
+   "uint32_t bar() {}",
+   Style);
 }
 
 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
@@ -10244,6 +10283,12 @@
   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
   BoostAndQForeach);
 
+  Style.StatementMacros.clear();
+  CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
+  std::vector{"QUNUSED"});
+  CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
+  std::vector({"QUNUSED", "QT_REQUIRE_VERSION"}));
+
   Style.IncludeCategories.clear();
   std::vector ExpectedCategories = {{"abc/.*", 2},
   {".*", 1}};
Index: lib/Format/UnwrappedLineParser.h
===
--- lib/Format/UnwrappedLineParser.h
+++ lib/Format/UnwrappedLineParser.h
@@ -118,6 +118,7 @@
   void parseObjCInterfaceOrImplementation();
   void parseObjCProtocol();
   void parseJavaScriptEs6ImportExport();
+  void parseStatementMacro();
   bool tryToParseLambda();
   bool tryToParseLambdaIntroducer();
   void tryToParseJSFunction();
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -435,6 +435,10 @@
   }
   LBraceStack.pop_back();
   break;
+case tok::identifier:
+  if (!Tok->is(TT_StatementMacro))
+  break;
+  LLVM_FALLTHROUGH;
 case tok::at:
 case tok::semi:
 case tok::kw_if:
@@ -1093,6 +1097,10 @@
 return;
   }
 }
+if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
+  parseStatementMacro();
+  return;
+}
 // In all other cases, parse the declaration.
 break;
   default:
@@ -1242,6 +1250,11 @@
 return;
   }
 
+  if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
+parseStatementMacro();
+return;
+  }
+
   // See if the following token should start a new unwrapped line.
   StringRef Text = FormatTok->TokenText;
   nextToken();
@@ -2191,6 +2204,16 @@
   }
 }
 
+void UnwrappedLineParser::parseStatementMacro()
+{
+  nextToken();
+  if (FormatTok->is(tok::l_paren))
+parseParens();
+  if (FormatTok->is(tok::semi))
+nextToken();
+  addUnwrappedLine();
+}
+
 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine ,
  StringRef Prefix = "") {
   llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
Index: lib/Format/FormatTokenLexer.h
===
--- lib/Format/FormatTokenLexer.h
+++ lib/Format/FormatTokenLexer.h
@@ -22,6 +22,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Format/Format.h"
 #include "llvm/Support/Regex.h"
+#include "llvm/ADT/MapVector.h"
 
 #include 
 
@@ -97,7 +98,8 @@
   // Index (in 'Tokens') of the last token that starts a new line.
   unsigned FirstInLineIndex;
   SmallVector Tokens;
-  SmallVector ForEachMacros;
+
+  llvm::SmallMapVector 

[PATCH] D39571: [clangd] DidChangeConfiguration Notification

2018-02-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: clangd/ClangdLSPServer.cpp:302
 
+// FIXME: This function needs to be properly tested.
+void ClangdLSPServer::onChangeConfiguration(

simark wrote:
> ilya-biryukov wrote:
> > simark wrote:
> > > simark wrote:
> > > > ilya-biryukov wrote:
> > > > > simark wrote:
> > > > > > simark wrote:
> > > > > > > ilya-biryukov wrote:
> > > > > > > > simark wrote:
> > > > > > > > > ilya-biryukov wrote:
> > > > > > > > > > simark wrote:
> > > > > > > > > > > ilya-biryukov wrote:
> > > > > > > > > > > > Are you planning to to address this FIXME before 
> > > > > > > > > > > > checking the code in?
> > > > > > > > > > > Following what you said here:
> > > > > > > > > > > 
> > > > > > > > > > > https://reviews.llvm.org/D39571?id=124024#inline-359345
> > > > > > > > > > > 
> > > > > > > > > > > I have not really looked into what was wrong with the 
> > > > > > > > > > > test, and what is missing in the infrastructure to make 
> > > > > > > > > > > it work.  But I assumed that the situation did not change 
> > > > > > > > > > > since then.  Can you enlighten me on what the problem 
> > > > > > > > > > > was, and what is missing?
> > > > > > > > > > We usually write unittests for that kind of thing, since 
> > > > > > > > > > they allow to plug an in-memory filesystem, but we only 
> > > > > > > > > > test `ClangdServer` (examples are in 
> > > > > > > > > > `unittests/clangd/ClangdTests.cpp`). `ClangdLSPServer` does 
> > > > > > > > > > not allow to plug in a virtual filesystem (vfs). Even if we 
> > > > > > > > > > add vfs, it's still hard to unit-test because we'll have to 
> > > > > > > > > > match the json input/output directly.
> > > > > > > > > > 
> > > > > > > > > > This leaves us with an option of a lit test that runs 
> > > > > > > > > > `clangd` directly, similar to tests in `test/clangd`.
> > > > > > > > > > The lit test would need to create a temporary directory, 
> > > > > > > > > > create proper `compile_commands.json` there, then send the 
> > > > > > > > > > LSP commands with the path to the test to clangd.
> > > > > > > > > > One major complication is that in LSP we have to specify 
> > > > > > > > > > the size of each message, but in our case the size would 
> > > > > > > > > > change depending on created temp path. It means we'll have 
> > > > > > > > > > to patch the test input to setup proper paths and message 
> > > > > > > > > > sizes.
> > > > > > > > > > If we choose to go down this path, 
> > > > > > > > > > `clang-tools-extra/test/clang-tidy/vfsoverlay.cpp` does a 
> > > > > > > > > > similar setup (create temp-dir, patch up some configuration 
> > > > > > > > > > files to point into the temp directory, etc) and could be 
> > > > > > > > > > used as a starting point.
> > > > > > > > > > 
> > > > > > > > > > It's not impossible to write that test, it's just a bit 
> > > > > > > > > > involved. Having a test would be nice, though, to ensure we 
> > > > > > > > > > don't break this method while doing other things. 
> > > > > > > > > > Especially given that this functionality is not used 
> > > > > > > > > > anywhere in clangd.
> > > > > > > > > > We usually write unittests for that kind of thing, since 
> > > > > > > > > > they allow to plug an in-memory filesystem, but we only 
> > > > > > > > > > test ClangdServer (examples are in 
> > > > > > > > > > unittests/clangd/ClangdTests.cpp). ClangdLSPServer does not 
> > > > > > > > > > allow to plug in a virtual filesystem (vfs). Even if we add 
> > > > > > > > > > vfs, it's still hard to unit-test because we'll have to 
> > > > > > > > > > match the json input/output directly.
> > > > > > > > > 
> > > > > > > > > What do you mean by "we'll have to match the json 
> > > > > > > > > input/output directly"?  That we'll have to match the 
> > > > > > > > > complete JSON output textually?  Couldn't the test parse the 
> > > > > > > > > JSON into some data structures, then we could assert specific 
> > > > > > > > > things, like that this particular field is present and 
> > > > > > > > > contains a certain substring, for example?
> > > > > > > > > 
> > > > > > > > > > This leaves us with an option of a lit test that runs 
> > > > > > > > > > clangd directly, similar to tests in test/clangd.
> > > > > > > > > > The lit test would need to create a temporary directory, 
> > > > > > > > > > create proper compile_commands.json there, then send the 
> > > > > > > > > > LSP commands with the path to the test to clangd.
> > > > > > > > > > One major complication is that in LSP we have to specify 
> > > > > > > > > > the size of each message, but in our case the size would 
> > > > > > > > > > change depending on created temp path. It means we'll have 
> > > > > > > > > > to patch the test input to setup proper paths and message 
> > > > > > > > > > sizes.
> > > > > > > > > > If we choose to go down this path, 
> > > > > > > > > > clang-tools-extra/test/clang-tidy/vfsoverlay.cpp does a 

r324246 - [clang-format] Re-land: Fixup #include guard indents after parseFile()

2018-02-05 Thread Mark Zeren via cfe-commits
Author: mzeren-vmw
Date: Mon Feb  5 07:59:00 2018
New Revision: 324246

URL: http://llvm.org/viewvc/llvm-project?rev=324246=rev
Log:
[clang-format] Re-land: Fixup #include guard indents after parseFile()

Summary:
When a preprocessor indent closes after the last line of normal code we do not
correctly fixup include guard indents. For example:

  #ifndef HEADER_H
  #define HEADER_H
  #if 1
  int i;
  #  define A 0
  #endif
  #endif

incorrectly reformats to:

  #ifndef HEADER_H
  #define HEADER_H
  #if 1
  int i;
  #define A 0
  #  endif
  #endif

To resolve this issue we must fixup levels after parseFile(). Delaying
the fixup introduces a new state, so consolidate include guard search
state into an enum.

Reviewers: krasimir, klimek

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/lib/Format/UnwrappedLineParser.h
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=324246=324245=324246=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Mon Feb  5 07:59:00 2018
@@ -234,14 +234,17 @@ UnwrappedLineParser::UnwrappedLineParser
   CurrentLines(), Style(Style), Keywords(Keywords),
   CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
   Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
-  IfNdefCondition(nullptr), FoundIncludeGuardStart(false),
-  IncludeGuardRejected(false), FirstStartColumn(FirstStartColumn) {}
+  IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
+   ? IG_Rejected
+   : IG_Inited),
+  IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
 
 void UnwrappedLineParser::reset() {
   PPBranchLevel = -1;
-  IfNdefCondition = nullptr;
-  FoundIncludeGuardStart = false;
-  IncludeGuardRejected = false;
+  IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None
+ ? IG_Rejected
+ : IG_Inited;
+  IncludeGuardToken = nullptr;
   Line.reset(new UnwrappedLine);
   CommentsBeforeNextToken.clear();
   FormatTok = nullptr;
@@ -264,6 +267,14 @@ void UnwrappedLineParser::parse() {
 
 readToken();
 parseFile();
+
+// If we found an include guard then all preprocessor directives (other 
than
+// the guard) are over-indented by one.
+if (IncludeGuard == IG_Found)
+  for (auto  : Lines)
+if (Line.InPPDirective && Line.Level > 0)
+  --Line.Level;
+
 // Create line with eof token.
 pushToken(FormatTok);
 addUnwrappedLine();
@@ -724,26 +735,27 @@ void UnwrappedLineParser::parsePPIf(bool
   // If there's a #ifndef on the first line, and the only lines before it are
   // comments, it could be an include guard.
   bool MaybeIncludeGuard = IfNDef;
-  if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard) {
+  if (IncludeGuard == IG_Inited && MaybeIncludeGuard)
 for (auto  : Lines) {
   if (!Line.Tokens.front().Tok->is(tok::comment)) {
 MaybeIncludeGuard = false;
-IncludeGuardRejected = true;
+IncludeGuard = IG_Rejected;
 break;
   }
 }
-  }
   --PPBranchLevel;
   parsePPUnknown();
   ++PPBranchLevel;
-  if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard)
-IfNdefCondition = IfCondition;
+  if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
+IncludeGuard = IG_IfNdefed;
+IncludeGuardToken = IfCondition;
+  }
 }
 
 void UnwrappedLineParser::parsePPElse() {
   // If a potential include guard has an #else, it's not an include guard.
-  if (FoundIncludeGuardStart && PPBranchLevel == 0)
-FoundIncludeGuardStart = false;
+  if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
+IncludeGuard = IG_Rejected;
   conditionalCompilationAlternative();
   if (PPBranchLevel > -1)
 --PPBranchLevel;
@@ -757,34 +769,37 @@ void UnwrappedLineParser::parsePPEndIf()
   conditionalCompilationEnd();
   parsePPUnknown();
   // If the #endif of a potential include guard is the last thing in the file,
-  // then we count it as a real include guard and subtract one from every
-  // preprocessor indent.
+  // then we found an include guard.
   unsigned TokenPosition = Tokens->getPosition();
   FormatToken *PeekNext = AllTokens[TokenPosition];
-  if (FoundIncludeGuardStart && PPBranchLevel == -1 && PeekNext->is(tok::eof) 
&&
+  if (IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
+  PeekNext->is(tok::eof) &&
   Style.IndentPPDirectives != FormatStyle::PPDIS_None)
-for (auto  : Lines)
-  if (Line.InPPDirective && Line.Level > 0)
---Line.Level;
+IncludeGuard = IG_Found;
 }
 
 void 

Re: r324062 - [Sema] Add implicit members even for invalid CXXRecordDecls

2018-02-05 Thread Ilya Biryukov via cfe-commits
I'll try to come up with a fix, thanks for spotting that.


On Sat, Feb 3, 2018 at 2:24 AM Eric Fiselier  wrote:

> This causes some stray diagnostics to be emitted in certian cases where a
> base class is already invalid:
>
> Reproducer:
> https://gist.github.com/EricWF/588a361030edeaebbbc1155b8347cab0
>
> On Fri, Feb 2, 2018 at 1:40 AM, Ilya Biryukov via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: ibiryukov
>> Date: Fri Feb  2 00:40:08 2018
>> New Revision: 324062
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=324062=rev
>> Log:
>> [Sema] Add implicit members even for invalid CXXRecordDecls
>>
>> Summary:
>> It should be safe, since other code paths are already generating
>> implicit members even in invalid CXXRecordDecls (e.g. lookup).
>>
>> If we don't generate implicit members on CXXRecordDecl's completion,
>> they will be generated by next lookup of constructors. This causes a
>> crash when the following conditions are met:
>>   - a CXXRecordDecl is invalid,
>>   - it is provided via ExternalASTSource (e.g. from PCH),
>>   - it has inherited constructors (they create ShadowDecls),
>>   - lookup of its constructors was not run before ASTWriter serialized
>> it.
>>
>> This may require the ShadowDecls created for inherited constructors to
>> be removed from the class, but that's no longer possible since class is
>> provided by ExternalASTSource.
>>
>> See provided lit test for an example.
>>
>> Reviewers: bkramer
>>
>> Reviewed By: bkramer
>>
>> Subscribers: cfe-commits
>>
>> Differential Revision: https://reviews.llvm.org/D42810
>>
>> Added:
>> cfe/trunk/test/Index/Inputs/crash-preamble-classes.h
>> cfe/trunk/test/Index/crash-preamble-classes.cpp
>> Modified:
>> cfe/trunk/lib/Sema/SemaDecl.cpp
>>
>> Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=324062=324061=324062=diff
>>
>> ==
>> --- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
>> +++ cfe/trunk/lib/Sema/SemaDecl.cpp Fri Feb  2 00:40:08 2018
>> @@ -15440,10 +15440,10 @@ void Sema::ActOnFields(Scope *S, SourceL
>>CXXRecord->getDestructor());
>>  }
>>
>> -if (!CXXRecord->isInvalidDecl()) {
>> -  // Add any implicitly-declared members to this class.
>> -  AddImplicitlyDeclaredMembersToClass(CXXRecord);
>> +// Add any implicitly-declared members to this class.
>> +AddImplicitlyDeclaredMembersToClass(CXXRecord);
>>
>> +if (!CXXRecord->isInvalidDecl()) {
>>// If we have virtual base classes, we may end up finding
>> multiple
>>// final overriders for a given virtual function. Check for
>> this
>>// problem now.
>>
>> Added: cfe/trunk/test/Index/Inputs/crash-preamble-classes.h
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/Inputs/crash-preamble-classes.h?rev=324062=auto
>>
>> ==
>> --- cfe/trunk/test/Index/Inputs/crash-preamble-classes.h (added)
>> +++ cfe/trunk/test/Index/Inputs/crash-preamble-classes.h Fri Feb  2
>> 00:40:08 2018
>> @@ -0,0 +1,9 @@
>> +struct Incomplete;
>> +
>> +struct X : Incomplete {
>> +  X();
>> +};
>> +
>> +struct Y : X {
>> +  using X::X;
>> +};
>>
>> Added: cfe/trunk/test/Index/crash-preamble-classes.cpp
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/crash-preamble-classes.cpp?rev=324062=auto
>>
>> ==
>> --- cfe/trunk/test/Index/crash-preamble-classes.cpp (added)
>> +++ cfe/trunk/test/Index/crash-preamble-classes.cpp Fri Feb  2 00:40:08
>> 2018
>> @@ -0,0 +1,8 @@
>> +#include "crash-preamble-classes.h"
>> +
>> +struct Z : Y {
>> +  Z() {}
>> +};
>> +
>> +// RUN: env CINDEXTEST_EDITING=1 \
>> +// RUN: c-index-test -test-load-source-reparse 5 local -I %S/Inputs %s
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>>
>
>

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


[PATCH] D42645: New simple Checker for mmap calls

2018-02-05 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 132829.

Repository:
  rC Clang

https://reviews.llvm.org/D42645

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
  test/Analysis/mmap-writeexec.c

Index: test/Analysis/mmap-writeexec.c
===
--- test/Analysis/mmap-writeexec.c
+++ test/Analysis/mmap-writeexec.c
@@ -0,0 +1,28 @@
+// RUN: %clang_analyze_cc1 -triple i686-unknown-freebsd -analyzer-checker=security.MmapWriteExec -verify %s
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-apple-darwin10 -analyzer-checker=security.MmapWriteExec -verify %s
+
+#define PROT_READ   0x01
+#define PROT_WRITE  0x02
+#define PROT_EXEC   0x04
+#define MAP_PRIVATE 0x0002
+#define MAP_ANON0x1000
+#define MAP_FIXED   0x0010
+#define NULL((void *)0)
+
+typedef __typeof(sizeof(int)) size_t;
+void *mmap(void *, size_t, int, int, int, long);
+
+void f1()
+{
+  void *a = mmap(NULL, 16, PROT_READ | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); // no-warning
+  void *b = mmap(a, 16, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANON, -1, 0); // no-warning
+  void *c = mmap(NULL, 32, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); // expected-warning{{Both PROT_WRITE and PROT_EXEC flags are set. This can lead to exploitable memory regions, which could be overwritten with malicious code"}}
+}
+
+void f2()
+{
+  void *(*callm)(void *, size_t, int, int, int, long);
+  callm = mmap;
+  int prot = PROT_WRITE | PROT_EXEC;
+  (void)callm(NULL, 1024, prot, MAP_PRIVATE | MAP_ANON, -1, 0); // expected-warning{{Both PROT_WRITE and PROT_EXEC flags are set. This can lead to exploitable memory regions, overwritten with malicious code}}
+}
Index: lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
+++ lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
@@ -0,0 +1,75 @@
+// MmapWriteExecChecker.cpp - Check for the prot argument -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This checker tests the 3rd argument of mmap's calls to check if
+// it is writable and executable in the same time. It's somehow
+// an optional checker since for example in JIT libraries it is pretty common.
+//
+//===--===//
+
+#include "ClangSACheckers.h"
+
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+using llvm::APSInt;
+
+namespace {
+class MmapWriteExecChecker : public Checker {
+  CallDescription MmapFn;
+  static int ProtWrite;
+  static int ProtExec;
+  mutable std::unique_ptr BT;
+public:
+  MmapWriteExecChecker() : MmapFn("mmap", 6) {}
+  void checkPreCall(const CallEvent , CheckerContext ) const;
+};
+}
+
+int MmapWriteExecChecker::ProtWrite = 0x02;
+int MmapWriteExecChecker::ProtExec  = 0x04;
+
+void MmapWriteExecChecker::checkPreCall(const CallEvent ,
+ CheckerContext ) const {
+  if (Call.isCalled(MmapFn)) {
+llvm::Triple Triple = C.getASTContext().getTargetInfo().getTriple();
+
+if (Triple.isOSGlibc())
+  ProtExec = 0x01;
+
+SVal ProtVal = Call.getArgSVal(2); 
+Optional ProtLoc = ProtVal.getAs();
+int64_t Prot = ProtLoc->getValue().getSExtValue();
+
+if ((Prot & (ProtWrite | ProtExec)) == (ProtWrite | ProtExec)) {
+  if (!BT)
+BT.reset(new BugType(this, "W^X check fails, Write Exec prot flags set", "Security"));
+
+  ExplodedNode *N = C.generateNonFatalErrorNode();
+  if (!N)
+return;
+
+  auto Report = llvm::make_unique(
+  *BT, "Both PROT_WRITE and PROT_EXEC flags are set. This can "
+   "lead to exploitable memory regions, which could be overwritten with malicious code"
+ , N);
+  Report->addRange(Call.getArgSourceRange(2));
+  C.emitReport(std::move(Report));
+}
+  }
+}
+
+void ento::registerMmapWriteExecChecker(CheckerManager ) {
+  mgr.registerChecker();
+}
Index: lib/StaticAnalyzer/Checkers/CMakeLists.txt
===
--- lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -49,6 +49,7 @@
   MallocChecker.cpp
   MallocOverflowSecurityChecker.cpp
   MallocSizeofChecker.cpp
+  

Re: [libcxx] r324182 - [libc++] Fix PR35491 - std::array of zero-size doesn't work with non-default constructible types.

2018-02-05 Thread Hans Wennborg via cfe-commits
This broke the Chromium build, see
https://bugs.chromium.org/p/chromium/issues/detail?id=809050#c2

I see there were a lot of changes landed around the same time, so I'm
not sure what to revert here exactly.

On Sun, Feb 4, 2018 at 2:03 AM, Eric Fiselier via cfe-commits
 wrote:
> Author: ericwf
> Date: Sat Feb  3 17:03:08 2018
> New Revision: 324182
>
> URL: http://llvm.org/viewvc/llvm-project?rev=324182=rev
> Log:
> [libc++] Fix PR35491 - std::array of zero-size doesn't work with non-default 
> constructible types.
>
> Summary:
> This patch fixes llvm.org/PR35491 and LWG2157  
> (https://cplusplus.github.io/LWG/issue2157)
>
> The fix attempts to maintain ABI compatibility by replacing the array with a 
> instance of `aligned_storage`.
>
> Reviewers: mclow.lists, EricWF
>
> Reviewed By: EricWF
>
> Subscribers: lichray, cfe-commits
>
> Differential Revision: https://reviews.llvm.org/D41223
>
> Modified:
> libcxx/trunk/include/array
> 
> libcxx/trunk/test/std/containers/sequences/array/array.cons/default.pass.cpp
> libcxx/trunk/test/std/containers/sequences/array/array.data/data.pass.cpp
> 
> libcxx/trunk/test/std/containers/sequences/array/array.data/data_const.pass.cpp
> libcxx/trunk/test/std/containers/sequences/array/begin.pass.cpp
>
> Modified: libcxx/trunk/include/array
> URL: 
> http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/array?rev=324182=324181=324182=diff
> ==
> --- libcxx/trunk/include/array (original)
> +++ libcxx/trunk/include/array Sat Feb  3 17:03:08 2018
> @@ -118,6 +118,55 @@ template  c
>  _LIBCPP_BEGIN_NAMESPACE_STD
>
>  template 
> +struct __array_traits {
> +  typedef _Tp _StorageT[_Size];
> +
> +  _LIBCPP_INLINE_VISIBILITY
> +  static _LIBCPP_CONSTEXPR_AFTER_CXX14 _Tp* __data(_StorageT& __store) {
> +return __store;
> +  }
> +
> +  _LIBCPP_INLINE_VISIBILITY
> +  static _LIBCPP_CONSTEXPR_AFTER_CXX14 _Tp const* __data(const _StorageT& 
> __store) {
> +return __store;
> +  }
> +
> +  _LIBCPP_INLINE_VISIBILITY
> +  static void __swap(_StorageT& __lhs, _StorageT& __rhs) {
> +std::swap_ranges(__lhs, __lhs + _Size, __rhs);
> +  }
> +
> +  _LIBCPP_INLINE_VISIBILITY
> +  static void __fill(_StorageT& __arr, _Tp const& __val) {
> +_VSTD::fill_n(__arr, _Size, __val);
> +  }
> +};
> +
> +template 
> +struct __array_traits<_Tp, 0> {
> +  typedef typename aligned_storage alignment_of<_Tp>::value>::type _StorageT;
> +
> +  _LIBCPP_INLINE_VISIBILITY
> +  static _Tp* __data(_StorageT& __store) {
> +_StorageT *__ptr = std::addressof(__store);
> +return reinterpret_cast<_Tp*>(__ptr);
> +  }
> +
> +  _LIBCPP_INLINE_VISIBILITY
> +  static const _Tp* __data(const _StorageT& __store) {
> +const _StorageT *__ptr = std::addressof(__store);
> +return reinterpret_cast(__ptr);
> +  }
> +
> +  _LIBCPP_INLINE_VISIBILITY
> +  static void __swap(_StorageT&, _StorageT&) {}
> +
> +  _LIBCPP_INLINE_VISIBILITY
> +  static void __fill(_StorageT&, _Tp const&) {
> +  }
> +};
> +
> +template 
>  struct _LIBCPP_TEMPLATE_VIS array
>  {
>  // types:
> @@ -134,31 +183,26 @@ struct _LIBCPP_TEMPLATE_VIS array
>  typedef std::reverse_iterator   reverse_iterator;
>  typedef std::reverse_iterator const_reverse_iterator;
>
> -value_type __elems_[_Size > 0 ? _Size : 1];
> +typedef __array_traits<_Tp, _Size> _Traits;
> +typename _Traits::_StorageT __elems_;
>
>  // No explicit construct/copy/destroy for aggregate type
>  _LIBCPP_INLINE_VISIBILITY void fill(const value_type& __u)
> -{_VSTD::fill_n(__elems_, _Size, __u);}
> -_LIBCPP_INLINE_VISIBILITY
> -void swap(array& __a) _NOEXCEPT_(_Size == 0 || 
> __is_nothrow_swappable<_Tp>::value)
> -{ __swap_dispatch((std::integral_constant()), 
> __a); }
> +{_Traits::__fill(__elems_, __u);}
>
>  _LIBCPP_INLINE_VISIBILITY
> -void __swap_dispatch(std::true_type, array&) {}
> -
> -_LIBCPP_INLINE_VISIBILITY
> -void __swap_dispatch(std::false_type, array& __a)
> -{ _VSTD::swap_ranges(__elems_, __elems_ + _Size, __a.__elems_);}
> +void swap(array& __a) _NOEXCEPT_(_Size == 0 || 
> __is_nothrow_swappable<_Tp>::value)
> +{ _Traits::__swap(__elems_, __a.__elems_); }
>
>  // iterators:
>  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
> -iterator begin() _NOEXCEPT {return iterator(__elems_);}
> +iterator begin() _NOEXCEPT {return iterator(data());}
>  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
> -const_iterator begin() const _NOEXCEPT {return const_iterator(__elems_);}
> +const_iterator begin() const _NOEXCEPT {return const_iterator(data());}
>  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
> -iterator end() _NOEXCEPT {return iterator(__elems_ + _Size);}
> +iterator end() _NOEXCEPT {return iterator(data() + _Size);}
>  

[PATCH] D42366: [CodeGen] Fix generation of TBAA tags for may-alias accesses

2018-02-05 Thread Ivan Kosarev via Phabricator via cfe-commits
kosarev added a comment.

Hal, will you please take a look?


Repository:
  rL LLVM

https://reviews.llvm.org/D42366



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


[PATCH] D42645: New simple Checker for mmap calls

2018-02-05 Thread David CARLIER via Phabricator via cfe-commits
devnexen updated this revision to Diff 132826.

Repository:
  rC Clang

https://reviews.llvm.org/D42645

Files:
  include/clang/StaticAnalyzer/Checkers/Checkers.td
  lib/StaticAnalyzer/Checkers/CMakeLists.txt
  lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
  test/Analysis/mmap-writeexec.c

Index: test/Analysis/mmap-writeexec.c
===
--- test/Analysis/mmap-writeexec.c
+++ test/Analysis/mmap-writeexec.c
@@ -0,0 +1,28 @@
+// RUN: %clang_analyze_cc1 -triple i686-unknown-freebsd -analyzer-checker=security.MmapWriteExec -verify %s
+// RUN: %clang_analyze_cc1 -triple x86_64-unknown-apple-darwin10 -analyzer-checker=security.MmapWriteExec -verify %s
+
+#define PROT_READ   0x01
+#define PROT_WRITE  0x02
+#define PROT_EXEC   0x04
+#define MAP_PRIVATE 0x0002
+#define MAP_ANON0x1000
+#define MAP_FIXED   0x0010
+#define NULL((void *)0)
+
+typedef __typeof(sizeof(int)) size_t;
+void *mmap(void *, size_t, int, int, int, long);
+
+void f1()
+{
+  void *a = mmap(NULL, 16, PROT_READ | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); // no-warning
+  void *b = mmap(a, 16, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANON, -1, 0); // no-warning
+  void *c = mmap(NULL, 32, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0); // expected-warning{{Both PROT_WRITE and PROT_EXEC flags had been set. It can lead to exploitable memory regions, overwritten with malicious code}}
+}
+
+void f2()
+{
+  void *(*callm)(void *, size_t, int, int, int, long);
+  callm = mmap;
+  int prot = PROT_WRITE | PROT_EXEC;
+  (void)callm(NULL, 1024, prot, MAP_PRIVATE | MAP_ANON, -1, 0); // expected-warning{{Both PROT_WRITE and PROT_EXEC flags had been set. It can lead to exploitable memory regions, overwritten with malicious code}}
+}
Index: lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
===
--- lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
+++ lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp
@@ -0,0 +1,75 @@
+// MmapWriteExecChecker.cpp - Check for the prot argument -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+//
+// This checker tests the 3rd argument of mmap's calls to check if
+// it is writable and executable in the same time. It's somehow
+// an optional checker since for example in JIT libraries it is pretty common.
+//
+//===--===//
+
+#include "ClangSACheckers.h"
+
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+using llvm::APSInt;
+
+namespace {
+class MmapWriteExecChecker : public Checker {
+  CallDescription MmapFn;
+  static int ProtWrite;
+  static int ProtExec;
+  mutable std::unique_ptr BT;
+public:
+  MmapWriteExecChecker() : MmapFn("mmap", 6) {}
+  void checkPreCall(const CallEvent , CheckerContext ) const;
+};
+}
+
+int MmapWriteExecChecker::ProtWrite = 0x02;
+int MmapWriteExecChecker::ProtExec  = 0x04;
+
+void MmapWriteExecChecker::checkPreCall(const CallEvent ,
+ CheckerContext ) const {
+  if (Call.isCalled(MmapFn)) {
+llvm::Triple Triple = C.getASTContext().getTargetInfo().getTriple();
+
+if (Triple.isOSGlibc())
+  ProtExec = 0x01;
+
+SVal ProtVal = Call.getArgSVal(2); 
+Optional ProtLoc = ProtVal.getAs();
+int64_t Prot = ProtLoc->getValue().getSExtValue();
+
+if ((Prot & (ProtWrite | ProtExec)) == (ProtWrite | ProtExec)) {
+  if (!BT)
+BT.reset(new BugType(this, "W^X check fails, Write Exec prot flags set", "Security"));
+
+  ExplodedNode *N = C.generateNonFatalErrorNode();
+  if (!N)
+return;
+
+  auto Report = llvm::make_unique(
+  *BT, "Both PROT_WRITE and PROT_EXEC flags are set. This can "
+   "lead to exploitable memory regions, which could be overwritten with malicious code"
+ , N);
+  Report->addRange(Call.getArgSourceRange(2));
+  C.emitReport(std::move(Report));
+}
+  }
+}
+
+void ento::registerMmapWriteExecChecker(CheckerManager ) {
+  mgr.registerChecker();
+}
Index: lib/StaticAnalyzer/Checkers/CMakeLists.txt
===
--- lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -49,6 +49,7 @@
   MallocChecker.cpp
   MallocOverflowSecurityChecker.cpp
   MallocSizeofChecker.cpp
+  MmapWriteExecChecker.cpp
   

[PATCH] D42645: New simple Checker for mmap calls

2018-02-05 Thread David CARLIER via Phabricator via cfe-commits
devnexen added a comment.

Your remarks make sense. Ok will update the general "tone" accordingly.


Repository:
  rC Clang

https://reviews.llvm.org/D42645



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


[PATCH] D42645: New simple Checker for mmap calls

2018-02-05 Thread Jonathan Roelofs via Phabricator via cfe-commits
jroelofs added inline comments.



Comment at: include/clang/StaticAnalyzer/Checkers/Checkers.td:399
+  def MmapWriteExecChecker : Checker<"MmapWriteExec">,
+HelpText<"Check if mmap() call is not both writable and executable">,
+DescFile<"MmapWriteExecChecker.cpp">;

I'd reword as:

"Warn on mmap() calls that are both writeable and executable"



Comment at: lib/StaticAnalyzer/Checkers/MmapWriteExecChecker.cpp:64
+  auto Report = llvm::make_unique(
+  *BT, "Both PROT_WRITE and PROT_EXEC flags had been set. It can "
+   "lead to exploitable memory regions, overwritten with malicious 
code"

The general style of diagnostics is to write everything in the present tense. 
Talk about how the code is, as the compiler saw it, not how it was.

I'd reword it as:

"Both PROT_WRITE and PROT_EXEC are set. This can lead to exploitable memory 
regions, which could be overwritten with malicious code"


Repository:
  rC Clang

https://reviews.llvm.org/D42645



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


[PATCH] D42736: [DebugInfo] Improvements to representation of enumeration types (PR36168)

2018-02-05 Thread Momchil Velikov via Phabricator via cfe-commits
chill updated this revision to Diff 132822.
chill added a comment.

Changes since last revision:

- Add/update test to check that each enumerator belongs to the right enumeration


https://reviews.llvm.org/D42736

Files:
  lib/CodeGen/CGDebugInfo.cpp
  test/CodeGen/debug-info-enum.cpp
  test/CodeGenCXX/debug-info-enum-class.cpp
  test/CodeGenCXX/debug-info-enum.cpp
  test/Modules/ModuleDebugInfo.cpp

Index: test/Modules/ModuleDebugInfo.cpp
===
--- test/Modules/ModuleDebugInfo.cpp
+++ test/Modules/ModuleDebugInfo.cpp
@@ -48,7 +48,7 @@
 // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type,
 // CHECK-NOT:  name:
 // CHECK-SAME: )
-// CHECK: !DIEnumerator(name: "e5", value: 5)
+// CHECK: !DIEnumerator(name: "e5", value: 5, isUnsigned: true)
 
 // CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "B",
 // no mangled name here yet.
Index: test/CodeGenCXX/debug-info-enum.cpp
===
--- test/CodeGenCXX/debug-info-enum.cpp
+++ test/CodeGenCXX/debug-info-enum.cpp
@@ -11,7 +11,7 @@
 // CHECK-SAME:  identifier: "_ZTSN5test11eE"
 // CHECK: [[TEST1]] = !DINamespace(name: "test1"
 // CHECK: [[TEST1_ENUMS]] = !{[[TEST1_E:![0-9]*]]}
-// CHECK: [[TEST1_E]] = !DIEnumerator(name: "E", value: 0)
+// CHECK: [[TEST1_E]] = !DIEnumerator(name: "E", value: 0, isUnsigned: true)
 enum e { E };
 void foo() {
   int v = E;
Index: test/CodeGenCXX/debug-info-enum-class.cpp
===
--- test/CodeGenCXX/debug-info-enum-class.cpp
+++ test/CodeGenCXX/debug-info-enum-class.cpp
@@ -15,20 +15,20 @@
 // CHECK-SAME: baseType: ![[INT:[0-9]+]]
 // CHECK-SAME: size: 32
 // CHECK-NOT:  offset:
-// CHECK-NOT:  flags:
+// CHECK-SAME: flags: DIFlagFixedEnum
 // CHECK-SAME: ){{$}}
 // CHECK: ![[INT]] = !DIBasicType(name: "int"
 // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "B"
 // CHECK-SAME: line: 4
 // CHECK-SAME: baseType: ![[ULONG:[0-9]+]]
 // CHECK-SAME: size: 64
 // CHECK-NOT:  offset:
-// CHECK-NOT:  flags:
+// CHECK-SAME: flags: DIFlagFixedEnum
 // CHECK-SAME: ){{$}}
 // CHECK: ![[ULONG]] = !DIBasicType(name: "long unsigned int"
 // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "C"
 // CHECK-SAME: line: 5
-// CHECK-NOT:  baseType:
+// CHECK-SAME: baseType: ![[ULONG:[0-9]+]]
 // CHECK-SAME: size: 32
 // CHECK-NOT:  offset:
 // CHECK-NOT:  flags:
Index: test/CodeGen/debug-info-enum.cpp
===
--- /dev/null
+++ test/CodeGen/debug-info-enum.cpp
@@ -0,0 +1,100 @@
+// Test enumeration representation in debuig info metadata:
+// * test value representation for each possible underlying integer type
+// * test the integer type is as expected
+// * test the DW_AT_enum_class attribute is present (resp. absent) as expected.
+
+// RUN: %clang -target x86_64-linux -g -S -emit-llvm -o - %s | FileCheck %s
+
+
+enum class E0 : signed char {
+  A0 = -128,
+  B0 = 127,
+} x0;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E0"
+// CHECK-SAME: baseType: ![[SCHAR:[0-9]+]]
+// CHECK-SAME: DIFlagFixedEnum
+// CHECK-SAME: elements: ![[ELTS0:[0-9]+]]
+// CHECK: ![[SCHAR]] = !DIBasicType(name: "signed char", size: 8, encoding: DW_ATE_signed_char)
+// CHECK: ![[ELTS0]] = !{![[A0:[0-9]+]], ![[B0:[0-9]+]]}
+// CHECK: ![[A0]] = !DIEnumerator(name: "A0", value: -128)
+// CHECK: ![[B0]] = !DIEnumerator(name: "B0", value: 127)
+
+enum class E1 : unsigned char { A1 = 255 } x1;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E1"
+// CHECK-SAME: baseType: ![[UCHAR:[0-9]+]]
+// CHECK-SAME: DIFlagFixedEnum
+// CHECK-SAME: elements: ![[ELTS1:[0-9]+]]
+// CHECK: ![[UCHAR]] = !DIBasicType(name: "unsigned char", size: 8, encoding: DW_ATE_unsigned_char)
+// CHECK: ![[ELTS1]] = !{![[A1:[0-9]+]]}
+// CHECK: ![[A1]] = !DIEnumerator(name: "A1", value: 255, isUnsigned: true)
+
+enum class E2 : signed short {
+  A2 = -32768,
+  B2 = 32767,
+} x2;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E2"
+// CHECK-SAME: baseType: ![[SHORT:[0-9]+]]
+// CHECK-SAME: DIFlagFixedEnum
+// CHECK-SAME: elements: ![[ELTS2:[0-9]+]]
+// CHECK: ![[SHORT]] = !DIBasicType(name: "short", size: 16, encoding: DW_ATE_signed)
+// CHECK: ![[ELTS2]] = !{![[A2:[0-9]+]], ![[B2:[0-9]+]]}
+// CHECK: ![[A2]] = !DIEnumerator(name: "A2", value: -32768)
+// CHECK: ![[B2]] = !DIEnumerator(name: "B2", value: 32767)
+
+enum class E3 : unsigned short { A3 = 65535 } x3;
+// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "E3"
+// CHECK-SAME: baseType: ![[USHORT:[0-9]+]]
+// CHECK-SAME: DIFlagFixedEnum
+// CHECK-SAME: elements: 

[PATCH] D42680: [ThinLTO] Ignore object files with no ThinLTO modules if -fthinlto-index= is set

2018-02-05 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson added a comment.

This looks ok to me, assuming it produces the empty output file as I expect it 
should. Please wait for pcc to take a look as well.




Comment at: clang/lib/CodeGen/CodeGenAction.cpp:959
+if (!Bm)
+  return {};
 Expected MOrErr =

It looks like this should result in an empty .o file being produced, but please 
confirm in the test (otherwise the build system may complain that expected 
output not produced).



Comment at: clang/test/CodeGen/thinlto_backend.ll:24
+; Ensure we don't fail with index and non-ThinLTO object file, and run
+; non-ThinLTO compilation which
+; RUN: opt -o %t5.o %s

comment isn't complete (ends in "which").



Comment at: clang/test/CodeGen/thinlto_backend.ll:26
+; RUN: opt -o %t5.o %s
+; RUN: %clang -target x86_64-unknown-linux-gnu -O2 -o %t4.o -x ir %t5.o -c 
-fthinlto-index=%t.thinlto.bc
+

Check that empty $t4.o is produced.


https://reviews.llvm.org/D42680



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


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

2018-02-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 132821.
ilya-biryukov marked 13 inline comments as done.
ilya-biryukov added a comment.

- Removed ASTWorker files, moved all the code to TUScheduler.cpp
- Renamed setDone to stop
- Added a comment to TUScheduler.cpp
- Addressed other review comments


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.h
  clangd/ClangdUnitStore.cpp
  clangd/ClangdUnitStore.h
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  clangd/Threading.cpp
  clangd/Threading.h

Index: clangd/Threading.h
===
--- clangd/Threading.h
+++ clangd/Threading.h
@@ -12,74 +12,67 @@
 
 #include "Context.h"
 #include "Function.h"
+#include 
+#include 
 #include 
-#include 
+#include 
 #include 
-#include 
 #include 
 
 namespace clang {
 namespace clangd {
-/// A simple fixed-size thread pool implementation.
-class ThreadPool {
+
+/// A shared boolean flag indicating if the computation was cancelled.
+/// Once cancelled, cannot be returned to the previous state.
+/// FIXME: We should split this class it into consumers and producers of the
+/// cancellation flags.
+class CancellationFlag {
 public:
-  /// If \p AsyncThreadsCount is 0, requests added using addToFront and addToEnd
-  /// will be processed synchronously on the calling thread.
-  // Otherwise, \p AsyncThreadsCount threads will be created to schedule the
-  // requests.
-  ThreadPool(unsigned AsyncThreadsCount);
-  /// Destructor blocks until all requests are processed and worker threads are
-  /// terminated.
-  ~ThreadPool();
+  CancellationFlag();
 
-  /// Add a new request to run function \p F with args \p As to the start of the
-  /// queue. The request will be run on a separate thread.
-  template 
-  void addToFront(Func &, Args &&... As) {
-if (RunSynchronously) {
-  std::forward(F)(std::forward(As)...);
-  return;
-}
+  void cancel() {
+assert(WasCancelled && "the object was moved");
+WasCancelled->store(true);
+  }
 
-{
-  std::lock_guard Lock(Mutex);
-  RequestQueue.emplace_front(
-  BindWithForward(std::forward(F), std::forward(As)...),
-  Context::current().clone());
-}
-RequestCV.notify_one();
+  bool isCancelled() const {
+assert(WasCancelled && "the object was moved");
+return WasCancelled->load();
   }
 
-  /// Add a new request to run function \p F with args \p As to the end of the
-  /// queue. The request will be run on a separate thread.
-  template  void addToEnd(Func &, Args &&... As) {
-if (RunSynchronously) {
-  std::forward(F)(std::forward(As)...);
-  return;
-}
+private:
+  std::shared_ptr WasCancelled;
+};
 
-{
-  std::lock_guard Lock(Mutex);
-  RequestQueue.emplace_back(
-  BindWithForward(std::forward(F), std::forward(As)...),
-  Context::current().clone());
-}
-RequestCV.notify_one();
-  }
+/// Limits the number of threads that can acquire the lock at the same time.
+class Semaphore {
+public:
+  Semaphore(std::size_t MaxLocks);
+
+  void lock();
+  void unlock();
+
+private:
+  std::mutex Mutex;
+  std::condition_variable SlotsChanged;
+  std::size_t FreeSlots;
+};
+
+/// Runs tasks on separate (detached) threads and wait for all tasks to finish.
+/// Objects that need to spawn threads can own an AsyncTaskRunner to ensure they
+/// all complete on destruction.
+class AsyncTaskRunner {
+public:
+  /// Destructor waits for all pending tasks to finish.
+  ~AsyncTaskRunner();
+
+  void waitForAll();
+  void runAsync(UniqueFunction Action);
 
 private:
-  bool RunSynchronously;
-  mutable std::mutex Mutex;
-  /// We run some tasks on separate threads(parsing, CppFile cleanup).
-  /// These threads looks into RequestQueue to find requests to handle and
-  /// terminate when Done is set to true.
-  std::vector Workers;
-  /// Setting Done to true will make the worker threads terminate.
-  bool Done = false;
-  /// A queue of requests.
-  std::deque, Context>> RequestQueue;
-  /// Condition variable to wake up worker threads.
-  std::condition_variable RequestCV;
+  std::mutex Mutex;
+  std::condition_variable TasksReachedZero;
+  std::size_t InFlightTasks = 0;
 };
 } // namespace clangd
 } // namespace clang
Index: clangd/Threading.cpp
===
--- clangd/Threading.cpp
+++ clangd/Threading.cpp
@@ -1,63 +1,62 @@
 #include "Threading.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Threading.h"
+#include 
 
 namespace clang {
 namespace clangd {
-ThreadPool::ThreadPool(unsigned AsyncThreadsCount)
-: RunSynchronously(AsyncThreadsCount == 0) {
-  if (RunSynchronously) {
-// Don't start the worker thread if we're running synchronously
-return;
-  }
 
-  Workers.reserve(AsyncThreadsCount);
-  

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

2018-02-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov marked an inline comment as done.
ilya-biryukov added inline comments.



Comment at: clangd/ASTWorker.cpp:1
+//===--- ASTWorker.cpp 
*-C++-*-===//
+//

sammccall wrote:
> This file could really use some high-level comments about the scheduling 
> strategy, throughout
I've added the docs to TUScheduler.cpp



Comment at: clangd/ASTWorker.cpp:102
+  // not waste time on it.
+  LastUpdateCF->cancel();
+}

sammccall wrote:
> This strategy has some upsides:
>  - we eventually get diagnostics for the latest version
>  - we don't begin building an AST that we know can never be read
>  - we don't "wait" when there's something useful to do
>  - it's simple to implement (apart from cancellation)
> And downsides:
>  - diagnostics are built on the first keystroke
>  - indexing blocks interactive actions, because we don't (and can't 
> reasonably) respect cancellation before calling OnUpdated
>  - it requires CancellationFlag even though our actions aren't cancelable
> 
> What's the goal here - is this a strategy to keep? Or a placeholder? Or 
> trying to maximize compatibility with the previous code?
Trying to maximize the compatibility with existing code. There are certainly 
other strategies to schedule updates.
I'm perfectly happy to explore those, but would try to keep it out of this 
patch, it's touching quite a lot of things already. And we should probably 
remove the callback from update in order to make implementing the timeouts 
simpler



Comment at: clangd/ASTWorker.h:45
+
+  std::shared_ptr getPossiblyStalePreamble() const;
+  std::size_t getUsedBytes() const;

sammccall wrote:
> can we reorder/group these by purpose/sequence?
> e.g (no need for the comments, just illustrative).
> 
>   //lifecycle
>   run();
>   setDone();
> 
>   //write
>   update()
> 
>   //read
>   runWithAST()
>   getPossiblyStalePreamble()
> 
>   //misc
>   getUsedBytes()
I used a different grouping:
```
//lifecycle
run();
setDone();

//async write
update()
// async read
runWithAST()

// sync reads
getPossiblyStalePreamble()
getUsedBytes()
```
Does that make sense? Or do you feel read/write vs sync/async is a better 
distinction?



Comment at: clangd/ASTWorker.h:54
+private:
+  using RequestWithCtx = std::pair, Context>;
+

sammccall wrote:
> I think this might actually be easier to read with just  `using Request = 
> UniqueFunction` and then spelling out `pair`. up to 
> you though.
> 
I'd rather keep it as is. I specifically came up with this typedef because I 
got annoyed of typing `pair`.
Happy to change it if you feel that's totally unreadable, of course.



Comment at: clangd/ASTWorker.h:59
+  // File and FileInputs are only accessed on the processing thread from run().
+  // FIXME(ibiryukov): group CppFile and FileInputs into a separate class.
+  const std::shared_ptr File;

sammccall wrote:
> nit: "combine ... into one class"?
> 
> I'd hope we won't end up with ASTWorker, CppFile, FileInputs, *and* another 
> thing?
Removed the FIXME



Comment at: clangd/TUScheduler.cpp:38
+  // Wait for all in-flight tasks to finish.
+  Tasks.waitForAll();
+}

sammccall wrote:
> destructor will do this
It's much safer to call it explicitly to not depend no the order of fields in 
the class.



Comment at: clangd/TUScheduler.h:77
+  /// In destructor, FileData signals to ASTWorker for file that it can exit.
+  struct FileData {
+FileData(ParseInputs Inputs, std::shared_ptr Worker);

sammccall wrote:
> This would be superseded by ASTWorkerHandle, right?
It's still there, stores inputs and `ASTWorkerHandle`.

Inputs in the `ASTWorker` correspond to the latest **processed** update, we 
don't expose them in the API. 
These inputs correspond to the latest inputs of the file (they are used by 
`runWithPreamble` to provide proper inputs).



Comment at: clangd/Threading.h:67
+
+  void waitForAll();
+  void runAsync(UniqueFunction Action);

sammccall wrote:
> any need to expose this separately from the destructor?
It's a useful helper to have.
We can use it to rewrite tests when removing `future` returned from 
`addDocument`/`removeDocument`.
Also see my other comment about calling it in destructor of `TUScheduler`.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573



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


r324239 - Revert "[clang-format] Fixup #include guard indents after parseFile()"

2018-02-05 Thread Mark Zeren via cfe-commits
Author: mzeren-vmw
Date: Mon Feb  5 06:47:04 2018
New Revision: 324239

URL: http://llvm.org/viewvc/llvm-project?rev=324239=rev
Log:
Revert "[clang-format] Fixup #include guard indents after parseFile()"

This reverts r324238 | mzeren-vmw | 2018-02-05 06:35:54 -0800 (Mon, 05 Feb 
2018) | 35 lines

Incorrect version pushed upstream.

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/lib/Format/UnwrappedLineParser.h
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=324239=324238=324239=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Mon Feb  5 06:47:04 2018
@@ -234,15 +234,14 @@ UnwrappedLineParser::UnwrappedLineParser
   CurrentLines(), Style(Style), Keywords(Keywords),
   CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
   Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
-  IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
-   ? IG_Rejected
-   : IG_Inited),
-  IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
+  IfNdefCondition(nullptr), FoundIncludeGuardStart(false),
+  IncludeGuardRejected(false), FirstStartColumn(FirstStartColumn) {}
 
 void UnwrappedLineParser::reset() {
   PPBranchLevel = -1;
-  IncludeGuard = IG_Inited;
-  IncludeGuardToken = nullptr;
+  IfNdefCondition = nullptr;
+  FoundIncludeGuardStart = false;
+  IncludeGuardRejected = false;
   Line.reset(new UnwrappedLine);
   CommentsBeforeNextToken.clear();
   FormatTok = nullptr;
@@ -265,14 +264,6 @@ void UnwrappedLineParser::parse() {
 
 readToken();
 parseFile();
-
-// If we found an include guard then all preprocessor directives (other 
than
-// the guard) are over-indented by one.
-if (IncludeGuard == IG_Found)
-  for (auto  : Lines)
-if (Line.InPPDirective && Line.Level > 0)
-  --Line.Level;
-
 // Create line with eof token.
 pushToken(FormatTok);
 addUnwrappedLine();
@@ -733,11 +724,11 @@ void UnwrappedLineParser::parsePPIf(bool
   // If there's a #ifndef on the first line, and the only lines before it are
   // comments, it could be an include guard.
   bool MaybeIncludeGuard = IfNDef;
-  if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
+  if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard) {
 for (auto  : Lines) {
   if (!Line.Tokens.front().Tok->is(tok::comment)) {
 MaybeIncludeGuard = false;
-IncludeGuard = IG_Rejected;
+IncludeGuardRejected = true;
 break;
   }
 }
@@ -745,16 +736,14 @@ void UnwrappedLineParser::parsePPIf(bool
   --PPBranchLevel;
   parsePPUnknown();
   ++PPBranchLevel;
-  if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
-IncludeGuard = IG_IfNdefed;
-IncludeGuardToken = IfCondition;
-  }
+  if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard)
+IfNdefCondition = IfCondition;
 }
 
 void UnwrappedLineParser::parsePPElse() {
   // If a potential include guard has an #else, it's not an include guard.
-  if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
-IncludeGuard = IG_Rejected;
+  if (FoundIncludeGuardStart && PPBranchLevel == 0)
+FoundIncludeGuardStart = false;
   conditionalCompilationAlternative();
   if (PPBranchLevel > -1)
 --PPBranchLevel;
@@ -768,37 +757,34 @@ void UnwrappedLineParser::parsePPEndIf()
   conditionalCompilationEnd();
   parsePPUnknown();
   // If the #endif of a potential include guard is the last thing in the file,
-  // then we found an include guard.
+  // then we count it as a real include guard and subtract one from every
+  // preprocessor indent.
   unsigned TokenPosition = Tokens->getPosition();
   FormatToken *PeekNext = AllTokens[TokenPosition];
-  if (IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
-  PeekNext->is(tok::eof) &&
+  if (FoundIncludeGuardStart && PPBranchLevel == -1 && PeekNext->is(tok::eof) 
&&
   Style.IndentPPDirectives != FormatStyle::PPDIS_None)
-IncludeGuard = IG_Found;
+for (auto  : Lines)
+  if (Line.InPPDirective && Line.Level > 0)
+--Line.Level;
 }
 
 void UnwrappedLineParser::parsePPDefine() {
   nextToken();
 
   if (FormatTok->Tok.getKind() != tok::identifier) {
-IncludeGuard = IG_Rejected;
-IncludeGuardToken = nullptr;
 parsePPUnknown();
 return;
   }
-
-  if (IncludeGuard == IG_IfNdefed &&
-  IncludeGuardToken->TokenText == FormatTok->TokenText) {
-IncludeGuard = IG_Defined;
-IncludeGuardToken = nullptr;
+  if (IfNdefCondition && IfNdefCondition->TokenText == FormatTok->TokenText) {
+FoundIncludeGuardStart = true;
 for (auto  : Lines) {
   if 

[PATCH] D42035: [clang-format] Fixup #include guard indents after parseFile()

2018-02-05 Thread Mark Zeren via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL324238: [clang-format] Fixup #include guard indents after 
parseFile() (authored by mzeren-vmw, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D42035?vs=132394=132819#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D42035

Files:
  cfe/trunk/lib/Format/UnwrappedLineParser.cpp
  cfe/trunk/lib/Format/UnwrappedLineParser.h
  cfe/trunk/unittests/Format/FormatTest.cpp

Index: cfe/trunk/lib/Format/UnwrappedLineParser.h
===
--- cfe/trunk/lib/Format/UnwrappedLineParser.h
+++ cfe/trunk/lib/Format/UnwrappedLineParser.h
@@ -248,10 +248,23 @@
   // sequence.
   std::stack PPChainBranchIndex;
 
-  // Contains the #ifndef condition for a potential include guard.
-  FormatToken *IfNdefCondition;
-  bool FoundIncludeGuardStart;
-  bool IncludeGuardRejected;
+  // Include guard search state. Used to fixup preprocessor indent levels
+  // so that include guards do not participate in indentation.
+  enum IncludeGuardState {
+IG_Inited,
+IG_IfNdefed,
+IG_Defined,
+IG_Found,
+IG_Rejected,
+  };
+
+  // Current state of include guard search.
+  IncludeGuardState IncludeGuard;
+
+  // Points to the #ifndef condition for a potential include guard. Null unless
+  // IncludeGuardState == IG_IfNdefed.
+  FormatToken *IncludeGuardToken;
+
   // Contains the first start column where the source begins. This is zero for
   // normal source code and may be nonzero when formatting a code fragment that
   // does not start at the beginning of the file.
Index: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
===
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp
@@ -234,14 +234,15 @@
   CurrentLines(), Style(Style), Keywords(Keywords),
   CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
   Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
-  IfNdefCondition(nullptr), FoundIncludeGuardStart(false),
-  IncludeGuardRejected(false), FirstStartColumn(FirstStartColumn) {}
+  IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
+   ? IG_Rejected
+   : IG_Inited),
+  IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
 
 void UnwrappedLineParser::reset() {
   PPBranchLevel = -1;
-  IfNdefCondition = nullptr;
-  FoundIncludeGuardStart = false;
-  IncludeGuardRejected = false;
+  IncludeGuard = IG_Inited;
+  IncludeGuardToken = nullptr;
   Line.reset(new UnwrappedLine);
   CommentsBeforeNextToken.clear();
   FormatTok = nullptr;
@@ -264,6 +265,14 @@
 
 readToken();
 parseFile();
+
+// If we found an include guard then all preprocessor directives (other than
+// the guard) are over-indented by one.
+if (IncludeGuard == IG_Found)
+  for (auto  : Lines)
+if (Line.InPPDirective && Line.Level > 0)
+  --Line.Level;
+
 // Create line with eof token.
 pushToken(FormatTok);
 addUnwrappedLine();
@@ -724,26 +733,28 @@
   // If there's a #ifndef on the first line, and the only lines before it are
   // comments, it could be an include guard.
   bool MaybeIncludeGuard = IfNDef;
-  if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard) {
+  if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
 for (auto  : Lines) {
   if (!Line.Tokens.front().Tok->is(tok::comment)) {
 MaybeIncludeGuard = false;
-IncludeGuardRejected = true;
+IncludeGuard = IG_Rejected;
 break;
   }
 }
   }
   --PPBranchLevel;
   parsePPUnknown();
   ++PPBranchLevel;
-  if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard)
-IfNdefCondition = IfCondition;
+  if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
+IncludeGuard = IG_IfNdefed;
+IncludeGuardToken = IfCondition;
+  }
 }
 
 void UnwrappedLineParser::parsePPElse() {
   // If a potential include guard has an #else, it's not an include guard.
-  if (FoundIncludeGuardStart && PPBranchLevel == 0)
-FoundIncludeGuardStart = false;
+  if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
+IncludeGuard = IG_Rejected;
   conditionalCompilationAlternative();
   if (PPBranchLevel > -1)
 --PPBranchLevel;
@@ -757,34 +768,37 @@
   conditionalCompilationEnd();
   parsePPUnknown();
   // If the #endif of a potential include guard is the last thing in the file,
-  // then we count it as a real include guard and subtract one from every
-  // preprocessor indent.
+  // then we found an include guard.
   unsigned TokenPosition = Tokens->getPosition();
   FormatToken *PeekNext = AllTokens[TokenPosition];
-  if (FoundIncludeGuardStart && PPBranchLevel == -1 && PeekNext->is(tok::eof) &&
+  if (IncludeGuard == IG_Defined && PPBranchLevel == -1 

r324238 - [clang-format] Fixup #include guard indents after parseFile()

2018-02-05 Thread Mark Zeren via cfe-commits
Author: mzeren-vmw
Date: Mon Feb  5 06:35:54 2018
New Revision: 324238

URL: http://llvm.org/viewvc/llvm-project?rev=324238=rev
Log:
[clang-format] Fixup #include guard indents after parseFile()

Summary:
When a preprocessor indent closes after the last line of normal code we do not
correctly fixup include guard indents. For example:

  #ifndef HEADER_H
  #define HEADER_H
  #if 1
  int i;
  #  define A 0
  #endif
  #endif

incorrectly reformats to:

  #ifndef HEADER_H
  #define HEADER_H
  #if 1
  int i;
  #define A 0
  #  endif
  #endif

To resolve this issue we must fixup levels after parseFile(). Delaying
the fixup introduces a new state, so consolidate include guard search
state into an enum.

Reviewers: krasimir, klimek

Reviewed By: krasimir

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/lib/Format/UnwrappedLineParser.h
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=324238=324237=324238=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Mon Feb  5 06:35:54 2018
@@ -234,14 +234,15 @@ UnwrappedLineParser::UnwrappedLineParser
   CurrentLines(), Style(Style), Keywords(Keywords),
   CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
   Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
-  IfNdefCondition(nullptr), FoundIncludeGuardStart(false),
-  IncludeGuardRejected(false), FirstStartColumn(FirstStartColumn) {}
+  IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
+   ? IG_Rejected
+   : IG_Inited),
+  IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
 
 void UnwrappedLineParser::reset() {
   PPBranchLevel = -1;
-  IfNdefCondition = nullptr;
-  FoundIncludeGuardStart = false;
-  IncludeGuardRejected = false;
+  IncludeGuard = IG_Inited;
+  IncludeGuardToken = nullptr;
   Line.reset(new UnwrappedLine);
   CommentsBeforeNextToken.clear();
   FormatTok = nullptr;
@@ -264,6 +265,14 @@ void UnwrappedLineParser::parse() {
 
 readToken();
 parseFile();
+
+// If we found an include guard then all preprocessor directives (other 
than
+// the guard) are over-indented by one.
+if (IncludeGuard == IG_Found)
+  for (auto  : Lines)
+if (Line.InPPDirective && Line.Level > 0)
+  --Line.Level;
+
 // Create line with eof token.
 pushToken(FormatTok);
 addUnwrappedLine();
@@ -724,11 +733,11 @@ void UnwrappedLineParser::parsePPIf(bool
   // If there's a #ifndef on the first line, and the only lines before it are
   // comments, it could be an include guard.
   bool MaybeIncludeGuard = IfNDef;
-  if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard) {
+  if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
 for (auto  : Lines) {
   if (!Line.Tokens.front().Tok->is(tok::comment)) {
 MaybeIncludeGuard = false;
-IncludeGuardRejected = true;
+IncludeGuard = IG_Rejected;
 break;
   }
 }
@@ -736,14 +745,16 @@ void UnwrappedLineParser::parsePPIf(bool
   --PPBranchLevel;
   parsePPUnknown();
   ++PPBranchLevel;
-  if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard)
-IfNdefCondition = IfCondition;
+  if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
+IncludeGuard = IG_IfNdefed;
+IncludeGuardToken = IfCondition;
+  }
 }
 
 void UnwrappedLineParser::parsePPElse() {
   // If a potential include guard has an #else, it's not an include guard.
-  if (FoundIncludeGuardStart && PPBranchLevel == 0)
-FoundIncludeGuardStart = false;
+  if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
+IncludeGuard = IG_Rejected;
   conditionalCompilationAlternative();
   if (PPBranchLevel > -1)
 --PPBranchLevel;
@@ -757,34 +768,37 @@ void UnwrappedLineParser::parsePPEndIf()
   conditionalCompilationEnd();
   parsePPUnknown();
   // If the #endif of a potential include guard is the last thing in the file,
-  // then we count it as a real include guard and subtract one from every
-  // preprocessor indent.
+  // then we found an include guard.
   unsigned TokenPosition = Tokens->getPosition();
   FormatToken *PeekNext = AllTokens[TokenPosition];
-  if (FoundIncludeGuardStart && PPBranchLevel == -1 && PeekNext->is(tok::eof) 
&&
+  if (IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
+  PeekNext->is(tok::eof) &&
   Style.IndentPPDirectives != FormatStyle::PPDIS_None)
-for (auto  : Lines)
-  if (Line.InPPDirective && Line.Level > 0)
---Line.Level;
+IncludeGuard = IG_Found;
 }
 
 void UnwrappedLineParser::parsePPDefine() {
   nextToken();
 
   if 

[clang-tools-extra] r324235 - [clang-tidy] Fix incorrect code indention in the doc.

2018-02-05 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Mon Feb  5 05:23:48 2018
New Revision: 324235

URL: http://llvm.org/viewvc/llvm-project?rev=324235=rev
Log:
[clang-tidy] Fix incorrect code indention in the doc.

Modified:
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst?rev=324235=324234=324235=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst 
(original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst 
Mon Feb  5 05:23:48 2018
@@ -11,13 +11,13 @@ For code:
 
 .. code-block:: objc
 
-@property(nonatomic, assign) int LowerCamelCase;
+   @property(nonatomic, assign) int LowerCamelCase;
 
 The fix will be:
 
 .. code-block:: objc
 
-@property(nonatomic, assign) int lowerCamelCase;
+   @property(nonatomic, assign) int lowerCamelCase;
 
 The check will only fix 'CamelCase' to 'camelCase'. In some other cases we will
 only provide warning messages since the property name could be complicated.
@@ -36,7 +36,8 @@ The check will also accept property decl
 lowercase letters followed by a '_' to avoid naming conflict. For example:
 
 .. code-block:: objc
-@property(nonatomic, assign) int abc_lowerCamelCase;
+
+   @property(nonatomic, assign) int abc_lowerCamelCase;
 
 The corresponding style rule: 
https://developer.apple.com/library/content/qa/qa1908/_index.html
 
@@ -62,9 +63,7 @@ Options
If set to ``1``, the value in ``Acronyms`` is appended to the
default list of acronyms:
 
-   ``ACL;API;ARGB;ASCII;BGRA;CMYK;DNS;FPS;FTP;GIF;GPS;HD;HDR;HTML;HTTP;HTTPS;
-HUD;ID;JPG;JS;LAN;LZW;MDNS;MIDI;OS;PDF;PIN;PNG;POI;PSTN;PTR;QA;QOS;RGB;RGBA;
-RGBX;ROM;RPC;RTF;RTL;SDK;SSO;TCP;TIFF;TTS;UI;URI;URL;VC;VOIP;VPN;VR;WAN;XML``.
+   
``ACL;API;ARGB;ASCII;BGRA;CMYK;DNS;FPS;FTP;GIF;GPS;HD;HDR;HTML;HTTP;HTTPS;HUD;ID;JPG;JS;LAN;LZW;MDNS;MIDI;OS;PDF;PIN;PNG;POI;PSTN;PTR;QA;QOS;RGB;RGBA;RGBX;ROM;RPC;RTF;RTL;SDK;SSO;TCP;TIFF;TTS;UI;URI;URL;VC;VOIP;VPN;VR;WAN;XML``.
 
If set to ``0``, the value in ``Acronyms`` replaces the default list
of acronyms.


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


[PATCH] D42640: [clangd] Prototype: collect symbol #include & insert #include in global code completion.

2018-02-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clangd/ClangdServer.cpp:418
+  } else {
+auto U = URI::parse(HeaderUri);
+if (!U)

Pull out a function to compute ToInclude from a uri/abspath?



Comment at: clangd/ClangdServer.cpp:425
+
+auto FS = FSProvider.getTaggedFileSystem(File).Value;
+tooling::CompileCommand CompileCommand =

Need high-level comments explaining what we're doing to determine the right 
include path.



Comment at: clangd/ClangdServer.cpp:433
+  Argv.push_back(S.c_str());
+llvm::errs() << "~~~ Build dir:" << CompileCommand.Directory << "\n";
+IgnoringDiagConsumer IgnoreDiags;

temporary logs?



Comment at: clangd/ClangdServer.cpp:445
+CI->getFrontendOpts().DisableFree = false;
+CI->getPreprocessorOpts().SingleFileParseMode = true;
+

explain why? (this has implications for direct vs transitive includes I think)



Comment at: clangd/ClangdServer.cpp:447
+
+auto Clang = prepareCompilerInstance(
+std::move(CI), /*Preamble=*/nullptr,

hmm, why are we actually going to run the compiler/preprocessor?
It looks like we just get HeaderMapping out - can we "just" call 
ApplyHeaderSearchOptions instead?



Comment at: clangd/ClangdServer.cpp:465
+auto  = Clang->getPreprocessor().getHeaderSearchInfo();
+std::string Suggested = HeaderSearchInfo.suggestPathToFileForDiagnostics(
+*Resolved, CompileCommand.Directory);

do we handle the case that the suggestion is already included?
(including the case where it's included by a different name)



Comment at: clangd/ClangdServer.cpp:468
+
+llvm::errs() << "Suggested #include is: " << Suggested << "\n";
+ToInclude = "\"" + Suggested + "\"";

leftover?



Comment at: clangd/ClangdServer.cpp:490
+llvm::consumeError(Style.takeError());
+// FIXME(ioeric): support fallback style in clangd server.
+Style = format::getLLVMStyle();

maybe this fixme should just be to have more consistent style support in 
clangdserver?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42640



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


[clang-tools-extra] r324233 - [clang-tidy] tweak "misc-definitions-in-headers" doc, NFC.

2018-02-05 Thread Haojian Wu via cfe-commits
Author: hokein
Date: Mon Feb  5 05:04:41 2018
New Revision: 324233

URL: http://llvm.org/viewvc/llvm-project?rev=324233=rev
Log:
[clang-tidy] tweak "misc-definitions-in-headers" doc, NFC.

Modified:

clang-tools-extra/trunk/docs/clang-tidy/checks/misc-definitions-in-headers.rst

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/misc-definitions-in-headers.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/misc-definitions-in-headers.rst?rev=324233=324232=324233=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/misc-definitions-in-headers.rst 
(original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/misc-definitions-in-headers.rst 
Mon Feb  5 05:04:41 2018
@@ -26,6 +26,7 @@ from multiple translation units.
static int b = 1;
const int c = 1;
const char* const str2 = "foo";
+   constexpr int k = 1;
 
// Warning: function definition.
int g() {
@@ -80,9 +81,7 @@ from multiple translation units.
 
inline int i = 5; // OK: inline variable definition.
 
-   constexpr int k = 1; // OK: constexpr variable has internal linkage.
-
-   constexpr int f10() { return 0; } // OK: constexpr function definition.
+   constexpr int f10() { return 0; } // OK: constexpr function implies inline.
 
 Options
 ---


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


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

2018-02-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 132803.
ilya-biryukov added a comment.

- Changed interface of ASTWorker so that it runs the processing loop itself.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D42573

Files:
  clangd/ASTWorker.cpp
  clangd/ASTWorker.h
  clangd/CMakeLists.txt
  clangd/ClangdServer.h
  clangd/ClangdUnitStore.cpp
  clangd/ClangdUnitStore.h
  clangd/TUScheduler.cpp
  clangd/TUScheduler.h
  clangd/Threading.cpp
  clangd/Threading.h

Index: clangd/Threading.h
===
--- clangd/Threading.h
+++ clangd/Threading.h
@@ -12,74 +12,65 @@
 
 #include "Context.h"
 #include "Function.h"
+#include 
+#include 
 #include 
-#include 
+#include 
 #include 
-#include 
 #include 
 
 namespace clang {
 namespace clangd {
-/// A simple fixed-size thread pool implementation.
-class ThreadPool {
+
+/// A shared boolean flag indicating if the computation was cancelled.
+/// Once cancelled, cannot be returned to the previous state.
+/// FIXME: We should split this class it into consumers and producers of the
+/// cancellation flags.
+class CancellationFlag {
 public:
-  /// If \p AsyncThreadsCount is 0, requests added using addToFront and addToEnd
-  /// will be processed synchronously on the calling thread.
-  // Otherwise, \p AsyncThreadsCount threads will be created to schedule the
-  // requests.
-  ThreadPool(unsigned AsyncThreadsCount);
-  /// Destructor blocks until all requests are processed and worker threads are
-  /// terminated.
-  ~ThreadPool();
+  CancellationFlag();
 
-  /// Add a new request to run function \p F with args \p As to the start of the
-  /// queue. The request will be run on a separate thread.
-  template 
-  void addToFront(Func &, Args &&... As) {
-if (RunSynchronously) {
-  std::forward(F)(std::forward(As)...);
-  return;
-}
+  void cancel() {
+assert(WasCancelled && "the object was moved");
+WasCancelled->store(true);
+  }
 
-{
-  std::lock_guard Lock(Mutex);
-  RequestQueue.emplace_front(
-  BindWithForward(std::forward(F), std::forward(As)...),
-  Context::current().clone());
-}
-RequestCV.notify_one();
+  bool isCancelled() const {
+assert(WasCancelled && "the object was moved");
+return WasCancelled->load();
   }
 
-  /// Add a new request to run function \p F with args \p As to the end of the
-  /// queue. The request will be run on a separate thread.
-  template  void addToEnd(Func &, Args &&... As) {
-if (RunSynchronously) {
-  std::forward(F)(std::forward(As)...);
-  return;
-}
+private:
+  std::shared_ptr WasCancelled;
+};
 
-{
-  std::lock_guard Lock(Mutex);
-  RequestQueue.emplace_back(
-  BindWithForward(std::forward(F), std::forward(As)...),
-  Context::current().clone());
-}
-RequestCV.notify_one();
-  }
+/// Limits the number of threads that can acquire the lock at the same time.
+class Semaphore {
+public:
+  Semaphore(std::size_t MaxLocks);
+
+  void lock();
+  void unlock();
+
+private:
+  std::mutex Mutex;
+  std::condition_variable SlotsChanged;
+  std::size_t FreeSlots;
+};
+
+/// Allows to run tasks on separate (detached) threads and wait for all tasks to
+/// finish.
+class AsyncTaskRunner {
+public:
+  ~AsyncTaskRunner();
+
+  void waitForAll();
+  void runAsync(UniqueFunction Action);
 
 private:
-  bool RunSynchronously;
-  mutable std::mutex Mutex;
-  /// We run some tasks on separate threads(parsing, CppFile cleanup).
-  /// These threads looks into RequestQueue to find requests to handle and
-  /// terminate when Done is set to true.
-  std::vector Workers;
-  /// Setting Done to true will make the worker threads terminate.
-  bool Done = false;
-  /// A queue of requests.
-  std::deque, Context>> RequestQueue;
-  /// Condition variable to wake up worker threads.
-  std::condition_variable RequestCV;
+  std::mutex Mutex;
+  std::condition_variable TasksReachedZero;
+  std::size_t InFlightTasks = 0;
 };
 } // namespace clangd
 } // namespace clang
Index: clangd/Threading.cpp
===
--- clangd/Threading.cpp
+++ clangd/Threading.cpp
@@ -1,63 +1,62 @@
 #include "Threading.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Threading.h"
+#include 
 
 namespace clang {
 namespace clangd {
-ThreadPool::ThreadPool(unsigned AsyncThreadsCount)
-: RunSynchronously(AsyncThreadsCount == 0) {
-  if (RunSynchronously) {
-// Don't start the worker thread if we're running synchronously
-return;
-  }
 
-  Workers.reserve(AsyncThreadsCount);
-  for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
-Workers.push_back(std::thread([this, I]() {
-  llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
-  while (true) {
-UniqueFunction Request;
-Context Ctx;
-

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

2018-02-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Really coming together!




Comment at: clangd/ASTWorker.cpp:1
+//===--- ASTWorker.cpp 
*-C++-*-===//
+//

This file could really use some high-level comments about the scheduling 
strategy, throughout



Comment at: clangd/ASTWorker.cpp:20
+  StartedRunning(false), Done(false) {
+  if (RunSync)
+return;

?!



Comment at: clangd/ASTWorker.cpp:102
+  // not waste time on it.
+  LastUpdateCF->cancel();
+}

This strategy has some upsides:
 - we eventually get diagnostics for the latest version
 - we don't begin building an AST that we know can never be read
 - we don't "wait" when there's something useful to do
 - it's simple to implement (apart from cancellation)
And downsides:
 - diagnostics are built on the first keystroke
 - indexing blocks interactive actions, because we don't (and can't reasonably) 
respect cancellation before calling OnUpdated
 - it requires CancellationFlag even though our actions aren't cancelable

What's the goal here - is this a strategy to keep? Or a placeholder? Or trying 
to maximize compatibility with the previous code?



Comment at: clangd/ASTWorker.h:1
+//===--- ASTWorker.h 
--*-C++-*-===//
+//

ASTWorker is an implementation detail of TUScheduler. Can we move it to 
TUScheduler.cpp, instead of exposing it, and remove this header?



Comment at: clangd/ASTWorker.h:19
+namespace clangd {
+struct InputsAndAST {
+  const ParseInputs 

This seems like an "implementation header" - nobody should depend on ASTWorker 
AIUI.

So InputsAndAST shouldn't really go here, as it's part of the TUScheduler 
public interface.



Comment at: clangd/ASTWorker.h:24
+
+struct InputsAndPreamble {
+  const ParseInputs 

(InputsAndPreamble is entirely unused here, I think)



Comment at: clangd/ASTWorker.h:29
+
+/// Owns one instance of the AST, schedules updated and reads of it.
+/// Also responsible for building and providing access to the preamble.

updated -> updates



Comment at: clangd/ASTWorker.h:38
+
+  // Must be called exactly once on processing thread. Will return after
+  // setDone() is called on a separate thread and all pending requests are

As discussed offline, this lifecycle is a bit complicated :-)
ASTWorker basically manages a thread, and it'd be nice if we could align the 
object lifetime and thread lifetime more closely.

The difficulty seems to be that we want to TUScheduler to be able to discard 
ASTWorkers instantly, even though we can't interrupt them.
After offline brainstorming, we came up with some sort of "ASTWorkerHandle" 
which:
 - owns the thread that run() is called on
 - detaches that thread on destruction
 - has a weak_ptr or shared_ptr to the worker itself, which it exposes

We still have run() and setDone(), but they're private details.



Comment at: clangd/ASTWorker.h:43
+  /// Signal that run() should finish processing pending requests and exit.
+  void setDone();
+

stop()? (or stopSoon/requestStop to be more explicit)



Comment at: clangd/ASTWorker.h:45
+
+  std::shared_ptr getPossiblyStalePreamble() const;
+  std::size_t getUsedBytes() const;

can we reorder/group these by purpose/sequence?
e.g (no need for the comments, just illustrative).

  //lifecycle
  run();
  setDone();

  //write
  update()

  //read
  runWithAST()
  getPossiblyStalePreamble()

  //misc
  getUsedBytes()



Comment at: clangd/ASTWorker.h:54
+private:
+  using RequestWithCtx = std::pair, Context>;
+

I think this might actually be easier to read with just  `using Request = 
UniqueFunction` and then spelling out `pair`. up to 
you though.




Comment at: clangd/ASTWorker.h:59
+  // File and FileInputs are only accessed on the processing thread from run().
+  // FIXME(ibiryukov): group CppFile and FileInputs into a separate class.
+  const std::shared_ptr File;

nit: "combine ... into one class"?

I'd hope we won't end up with ASTWorker, CppFile, FileInputs, *and* another 
thing?



Comment at: clangd/ASTWorker.h:69
+  std::queue Requests; /* GUARDED_BY(Mutex) */
+  // Only set when last request is an update.
+  llvm::Optional LastUpdateCF; /* GUARDED_BY(Mutex) */

Why?
e.g. `This allows us to cancel an update that was never read, if a subsequent 
update comes in`



Comment at: clangd/TUScheduler.cpp:38
+  // Wait for all in-flight tasks to finish.
+  Tasks.waitForAll();
+}

destructor will do this



Comment at: clangd/TUScheduler.h:77
+  /// 

[PATCH] D42901: Test commit - fixing a comment.

2018-02-05 Thread Jacek Olesiak via Phabricator via cfe-commits
jolesiak created this revision.
Herald added subscribers: cfe-commits, klimek.
jolesiak added reviewers: krasimir, benhamilton.

A test commit.


Repository:
  rC Clang

https://reviews.llvm.org/D42901

Files:
  lib/Format/ContinuationIndenter.h


Index: lib/Format/ContinuationIndenter.h
===
--- lib/Format/ContinuationIndenter.h
+++ lib/Format/ContinuationIndenter.h
@@ -314,8 +314,8 @@
   /// the same token.
   bool HasMultipleNestedBlocks : 1;
 
-  // \brief The start of a nested block (e.g. lambda introducer in C++ or
-  // "function" in JavaScript) is not wrapped to a new line.
+  /// \brief The start of a nested block (e.g. lambda introducer in C++ or
+  /// "function" in JavaScript) is not wrapped to a new line.
   bool NestedBlockInlined : 1;
 
   bool operator<(const ParenState ) const {


Index: lib/Format/ContinuationIndenter.h
===
--- lib/Format/ContinuationIndenter.h
+++ lib/Format/ContinuationIndenter.h
@@ -314,8 +314,8 @@
   /// the same token.
   bool HasMultipleNestedBlocks : 1;
 
-  // \brief The start of a nested block (e.g. lambda introducer in C++ or
-  // "function" in JavaScript) is not wrapped to a new line.
+  /// \brief The start of a nested block (e.g. lambda introducer in C++ or
+  /// "function" in JavaScript) is not wrapped to a new line.
   bool NestedBlockInlined : 1;
 
   bool operator<(const ParenState ) const {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >