[libcxx] r338103 - Move Filesystem namespace definition out of a clang specific ifdef block.

2018-07-26 Thread Eric Fiselier via cfe-commits
Author: ericwf
Date: Thu Jul 26 23:12:46 2018
New Revision: 338103

URL: http://llvm.org/viewvc/llvm-project?rev=338103&view=rev
Log:
Move Filesystem namespace definition out of a clang specific ifdef block.

Modified:
libcxx/trunk/include/__config

Modified: libcxx/trunk/include/__config
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/__config?rev=338103&r1=338102&r2=338103&view=diff
==
--- libcxx/trunk/include/__config (original)
+++ libcxx/trunk/include/__config Thu Jul 26 23:12:46 2018
@@ -474,19 +474,6 @@ namespace std {
   }
 }
 
-#if _LIBCPP_STD_VER >= 17
-#define _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM \
-  _LIBCPP_BEGIN_NAMESPACE_STD inline namespace __fs { namespace filesystem {
-#else
-#define _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM \
-  _LIBCPP_BEGIN_NAMESPACE_STD namespace __fs { namespace filesystem {
-#endif
-
-#define _LIBCPP_END_NAMESPACE_FILESYSTEM \
-  _LIBCPP_END_NAMESPACE_STD } }
-
-#define _VSTD_FS _VSTD::__fs::filesystem
-
 #if !defined(_LIBCPP_HAS_NO_ASAN) && !__has_feature(address_sanitizer)
 #define _LIBCPP_HAS_NO_ASAN
 #endif
@@ -659,6 +646,20 @@ namespace std {
 
 #endif // _LIBCPP_COMPILER_[CLANG|GCC|MSVC|IBM]
 
+#if _LIBCPP_STD_VER >= 17
+#define _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM \
+  _LIBCPP_BEGIN_NAMESPACE_STD inline namespace __fs { namespace filesystem {
+#else
+#define _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM \
+  _LIBCPP_BEGIN_NAMESPACE_STD namespace __fs { namespace filesystem {
+#endif
+
+#define _LIBCPP_END_NAMESPACE_FILESYSTEM \
+  _LIBCPP_END_NAMESPACE_STD } }
+
+#define _VSTD_FS _VSTD::__fs::filesystem
+
+
 #if defined(_LIBCPP_OBJECT_FORMAT_COFF)
 
 #ifdef _DLL


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


[PATCH] D49899: Make test/Driver/fuchsia.c(pp) work with lld or gold

2018-07-26 Thread Petr Hosek via Phabricator via cfe-commits
phosek requested changes to this revision.
phosek added a comment.
This revision now requires changes to proceed.

We don't actively support gold in Fuchsia driver and currently have no plans on 
doing so. We should instead modify the driver to always use lld even if gold is 
set as the default Clang linker.


Repository:
  rC Clang

https://reviews.llvm.org/D49899



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


[PATCH] D49862: [clang-tidy] Fix a crash in fuchsia-multiple-inheritance

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

LGTM.




Comment at: test/clang-tidy/fuchsia-multiple-inheritance-crash.cpp:1
+// RUN: clang-tidy -checks='fuchsia-multiple-inheritance' %s --
+template 

nit: instead of create a new file, we can put this test case in the existing 
test/clang-tidy/fuchsia-multiple-inheritance.cpp.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49862



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


[PATCH] D49589: [UBSan] Strengthen pointer checks in 'new' expressions

2018-07-26 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff updated this revision to Diff 157643.
sepavloff added a comment.

Updated patch

Added names for boolean arguments, renamed a field in AggValueSlot.
No functional changes.


Repository:
  rC Clang

https://reviews.llvm.org/D49589

Files:
  lib/CodeGen/CGClass.cpp
  lib/CodeGen/CGExprCXX.cpp
  lib/CodeGen/CGValue.h
  lib/CodeGen/CodeGenFunction.h
  test/CodeGenCXX/ubsan-new-checks.cpp

Index: test/CodeGenCXX/ubsan-new-checks.cpp
===
--- /dev/null
+++ test/CodeGenCXX/ubsan-new-checks.cpp
@@ -0,0 +1,146 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -std=c++11 -S -emit-llvm -fsanitize=alignment %s -o - | FileCheck %s
+
+struct alignas(32) S1 {
+  int x;
+  S1();
+};
+
+struct alignas(32) S2 {
+  int x;
+};
+
+struct alignas(32) S3 {
+  int x;
+  S3(int *p = new int[4]);
+};
+
+struct S4 : public S3 {
+  S4() : S3() {}
+};
+
+typedef __attribute__((ext_vector_type(2), aligned(32))) float float32x2_t;
+
+struct S5 {
+  float32x2_t x;
+};
+
+void *operator new (unsigned long, void *p) { return p; }
+void *operator new[] (unsigned long, void *p) { return p; }
+
+S1 *func_01() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_01v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   call void @_ZN2S1C1Ev(
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret %struct.S1*
+  return new S1[20];
+}
+
+S2 *func_02() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_02v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S2*
+  return new S2;
+}
+
+S2 *func_03() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_03v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret %struct.S2*
+  return new S2[20];
+}
+
+float32x2_t *func_04() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_04v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret <2 x float>*
+  return new float32x2_t;
+}
+
+float32x2_t *func_05() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_05v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret <2 x float>*
+  return new float32x2_t[20];
+}
+
+S3 *func_07() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_07v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   and i64 %{{.*}}, 3, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S3*
+  return new S3;
+}
+
+S3 *func_08() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_08v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   and i64 %{{.*}}, 3, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S3*
+  return new S3[10];
+}
+
+
+S2 *func_10(void *p) {
+  // CHECK-LABEL: define {{.*}} @_Z7func_10Pv
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S2*
+  return new(p) S2;
+}
+
+S2 *func_11(void *p) {
+  // CHECK-LABEL: define {{.*}} @_Z7func_11Pv
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK-NOT:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret %struct.S2*
+  return new(p) S2[10];
+}
+
+float32x2_t *func_12() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_12v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK:   ret <2 x float>*
+  return new float32x2_t;
+}
+
+float32x2_t *func_13() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_13v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret <2 x float>*
+  return new float32x2_t[20];
+}
+
+S4 *func_14() {
+  // CHECK-LABEL: define {{.*}} @_Z7func_14v
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64 %{{.*}}, 31
+  // CHECK:   ret %struct.S4*
+  return new S4;
+}
+
+S5 *func_15(const S5 *ptr) {
+  // CHECK-LABEL: define {{.*}} @_Z7func_15PK2S5
+  // CHECK:   and i64 %{{.*}}, 31, !nosanitize
+  // CHECK:   icmp eq i64 %{{.*}}, 0, !nosanitize
+  // CHECK-NOT:   and i64
+  // CHECK:   ret %struct.S5*
+  return new S5(*ptr);
+}
Index: lib/CodeGen/CodeGenFunction.h
===
--- lib/CodeGen/CodeGenFunction.h
+++ lib/CodeGen/CodeGe

[PATCH] D36357: Added a better diagnostic when using the delete operator with lambdas

2018-07-26 Thread Nicolas Lesser via Phabricator via cfe-commits
Rakete updated this revision to Diff 157642.
Rakete added a comment.

Addressed review comments.

Note that clang doesn't support the fourth kind of lambda yet ([]<>), because 
https://reviews.llvm.org/D36527 hasn't been merged yet, so I didn't add a test 
case for that one.


Repository:
  rC Clang

https://reviews.llvm.org/D36357

Files:
  include/clang/Basic/DiagnosticParseKinds.td
  lib/Parse/ParseExprCXX.cpp
  test/FixIt/fixit-cxx0x.cpp
  test/Parser/cxx0x-lambda-expressions.cpp
  test/SemaCXX/new-delete-0x.cpp

Index: test/SemaCXX/new-delete-0x.cpp
===
--- test/SemaCXX/new-delete-0x.cpp
+++ test/SemaCXX/new-delete-0x.cpp
@@ -34,6 +34,6 @@
 void bad_deletes()
 {
   // 'delete []' is always array delete, per [expr.delete]p1.
-  // FIXME: Give a better diagnostic.
-  delete []{ return (int*)0; }(); // expected-error {{expected expression}}
+  delete []{ return (int*)0; }(); // expected-error {{'[]' after delete interpreted as 'delete[]'}}
 }
+
Index: test/Parser/cxx0x-lambda-expressions.cpp
===
--- test/Parser/cxx0x-lambda-expressions.cpp
+++ test/Parser/cxx0x-lambda-expressions.cpp
@@ -53,8 +53,11 @@
   void delete_lambda(int *p) {
 delete [] p;
 delete [] (int*) { new int }; // ok, compound-literal, not lambda
-delete [] { return new int; } (); // expected-error{{expected expression}}
+delete [] { return new int; } (); // expected-error {{'[]' after delete interpreted as 'delete[]'}}
 delete [&] { return new int; } (); // ok, lambda
+
+delete []() { return new int; }(); // expected-error{{'[]' after delete interpreted as 'delete[]'}}
+delete [](E Enum) { return new int((int)Enum); }(e); // expected-error{{'[]' after delete interpreted as 'delete[]'}}
   }
 
   // We support init-captures in C++11 as an extension.
Index: test/FixIt/fixit-cxx0x.cpp
===
--- test/FixIt/fixit-cxx0x.cpp
+++ test/FixIt/fixit-cxx0x.cpp
@@ -58,6 +58,9 @@
   (void)[&, i, i]{ }; // expected-error{{'i' can appear only once in a capture list}}
   (void)[] mutable { }; // expected-error{{lambda requires '()' before 'mutable'}}
   (void)[] -> int { }; // expected-error{{lambda requires '()' before return type}}
+
+  delete []() { return new int; }(); // expected-error{{'[]' after delete interpreted as 'delete[]'}}
+  delete [] { return new int; }(); // expected-error{{'[]' after delete interpreted as 'delete[]'}}
 }
 
 #define bar "bar"
Index: lib/Parse/ParseExprCXX.cpp
===
--- lib/Parse/ParseExprCXX.cpp
+++ lib/Parse/ParseExprCXX.cpp
@@ -2946,8 +2946,38 @@
 //   [Footnote: A lambda expression with a lambda-introducer that consists
 //  of empty square brackets can follow the delete keyword if
 //  the lambda expression is enclosed in parentheses.]
-// FIXME: Produce a better diagnostic if the '[]' is unambiguously a
-//lambda-introducer.
+
+const Token Next = GetLookAheadToken(2);
+
+// Basic lookahead to check if we have a lambda expression.
+if (Next.isOneOf(tok::l_brace, tok::less) ||
+(Next.is(tok::l_paren) &&
+ (GetLookAheadToken(3).is(tok::r_paren) ||
+  (GetLookAheadToken(3).is(tok::identifier) &&
+   GetLookAheadToken(4).is(tok::identifier) {
+  SourceLocation RightBracketLock = NextToken().getLocation();
+  // Warn if the non-capturing lambda isn't surrounded by parenthesis
+  // to disambiguate it from 'delete[]'.
+  ExprResult Lambda = ParseLambdaExpression();
+  if (Lambda.isInvalid())
+return ExprError();
+
+  SourceLocation StartLoc = Lambda.get()->getLocStart();
+  Diag(Start, diag::err_lambda_after_delete)
+  << SourceRange(Start, RightBracketLock)
+  << FixItHint::CreateInsertion(StartLoc, "(")
+  << FixItHint::CreateInsertion(
+ Lexer::getLocForEndOfToken(Lambda.get()->getLocEnd(), 0,
+Actions.getSourceManager(),
+getLangOpts()),
+ ")");
+
+  // Evaluate any postfix expressions used on the lambda.
+  Lambda = ParsePostfixExpressionSuffix(Lambda);
+  return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
+Lambda.get());
+}
+
 ArrayDelete = true;
 BalancedDelimiterTracker T(*this, tok::l_square);
 
Index: include/clang/Basic/DiagnosticParseKinds.td
===
--- include/clang/Basic/DiagnosticParseKinds.td
+++ include/clang/Basic/DiagnosticParseKinds.td
@@ -99,6 +99,8 @@
   InGroup, DefaultIgnore;
 def ext_alignof_expr : ExtWarn<
   "%0 applied to an expression is a GNU extension">, InGroup;
+def err_lambda_after_delete : Erro

r338098 - [WWW] Fixing file permissions for the .html pages.

2018-07-26 Thread Mike Edwards via cfe-commits
Author: sqlbyme
Date: Thu Jul 26 21:41:37 2018
New Revision: 338098

URL: http://llvm.org/viewvc/llvm-project?rev=338098&view=rev
Log:
[WWW] Fixing file permissions for the .html pages.

Modified:
cfe/trunk/www/OpenProjects.html   (props changed)
cfe/trunk/www/UniversalDriver.html   (props changed)
cfe/trunk/www/clang_video-05-25-2007.html   (props changed)
cfe/trunk/www/clang_video-07-25-2007.html   (props changed)
cfe/trunk/www/comparison.html   (props changed)
cfe/trunk/www/compatibility.html   (props changed)
cfe/trunk/www/cxx_compatibility.html   (props changed)
cfe/trunk/www/cxx_dr_status.html   (props changed)
cfe/trunk/www/cxx_status.html   (props changed)
cfe/trunk/www/diagnostics.html   (props changed)
cfe/trunk/www/features.html   (props changed)
cfe/trunk/www/get_involved.html   (props changed)
cfe/trunk/www/get_started.html   (props changed)
cfe/trunk/www/hacking.html   (props changed)
cfe/trunk/www/index.html   (props changed)
cfe/trunk/www/related.html   (props changed)

Propchange: cfe/trunk/www/OpenProjects.html
--
svn:executable = *

Propchange: cfe/trunk/www/UniversalDriver.html
--
svn:executable = *

Propchange: cfe/trunk/www/clang_video-05-25-2007.html
--
svn:executable = *

Propchange: cfe/trunk/www/clang_video-07-25-2007.html
--
svn:executable = *

Propchange: cfe/trunk/www/comparison.html
--
svn:executable = *

Propchange: cfe/trunk/www/compatibility.html
--
svn:executable = *

Propchange: cfe/trunk/www/cxx_compatibility.html
--
svn:executable = *

Propchange: cfe/trunk/www/cxx_dr_status.html
--
svn:executable = *

Propchange: cfe/trunk/www/cxx_status.html
--
svn:executable = *

Propchange: cfe/trunk/www/diagnostics.html
--
svn:executable = *

Propchange: cfe/trunk/www/features.html
--
svn:executable = *

Propchange: cfe/trunk/www/get_involved.html
--
svn:executable = *

Propchange: cfe/trunk/www/get_started.html
--
svn:executable = *

Propchange: cfe/trunk/www/hacking.html
--
svn:executable = *

Propchange: cfe/trunk/www/index.html
--
svn:executable = *

Propchange: cfe/trunk/www/related.html
--
svn:executable = *


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


[libcxx] r338096 - Add libc++fs to the test deps, and not to the target 'cxx'.

2018-07-26 Thread Eric Fiselier via cfe-commits
Author: ericwf
Date: Thu Jul 26 20:47:46 2018
New Revision: 338096

URL: http://llvm.org/viewvc/llvm-project?rev=338096&view=rev
Log:
Add libc++fs to the test deps, and not to the target 'cxx'.

Modified:
libcxx/trunk/lib/CMakeLists.txt
libcxx/trunk/test/CMakeLists.txt

Modified: libcxx/trunk/lib/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/lib/CMakeLists.txt?rev=338096&r1=338095&r2=338096&view=diff
==
--- libcxx/trunk/lib/CMakeLists.txt (original)
+++ libcxx/trunk/lib/CMakeLists.txt Thu Jul 26 20:47:46 2018
@@ -288,6 +288,9 @@ if (LIBCXX_ENABLE_STATIC)
   endif()
 endif()
 
+# Add a meta-target for both libraries.
+add_custom_target(cxx DEPENDS cxx-headers ${LIBCXX_BUILD_TARGETS})
+
 if (LIBCXX_ENABLE_FILESYSTEM)
   set(LIBCXX_FILESYSTEM_SOURCES
   ../src/filesystem/operations.cpp
@@ -318,7 +321,6 @@ if (LIBCXX_ENABLE_FILESYSTEM)
   COMPILE_FLAGS "${filesystem_flags}"
   OUTPUT_NAME   "c++fs"
   )
-  list(APPEND LIBCXX_BUILD_TARGETS cxx_filesystem)
 endif()
 
 
@@ -341,14 +343,8 @@ if (LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY)
   COMPILE_FLAGS "${experimental_flags}"
   OUTPUT_NAME   "c++experimental"
   )
-  list(APPEND LIBCXX_BUILD_TARGETS cxx_experimental)
 endif()
 
-
-# Add a meta-target for both libraries.
-add_custom_target(cxx DEPENDS cxx-headers ${LIBCXX_BUILD_TARGETS})
-
-
 if (LIBCXX_BUILD_EXTERNAL_THREAD_LIBRARY)
   file(GLOB LIBCXX_EXTERNAL_THREADING_SUPPORT_SOURCES 
../test/support/external_threads.cpp)
 

Modified: libcxx/trunk/test/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/CMakeLists.txt?rev=338096&r1=338095&r2=338096&view=diff
==
--- libcxx/trunk/test/CMakeLists.txt (original)
+++ libcxx/trunk/test/CMakeLists.txt Thu Jul 26 20:47:46 2018
@@ -58,7 +58,10 @@ set(AUTO_GEN_COMMENT "## Autogenerated b
 set(LIBCXX_TEST_DEPS "")
 
 if (LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY)
-  set(LIBCXX_TEST_DEPS cxx_experimental)
+  list(APPEND LIBCXX_TEST_DEPS cxx_experimental)
+endif()
+if (LIBCXX_ENABLE_FILESYSTEM)
+  list(APPEND LIBCXX_TEST_DEPS cxx_filesystem)
 endif()
 
 if (LIBCXX_BUILD_EXTERNAL_THREAD_LIBRARY)


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


[libcxx] r338095 - Attempt to unbreak *all the bots*

2018-07-26 Thread Eric Fiselier via cfe-commits
Author: ericwf
Date: Thu Jul 26 20:42:58 2018
New Revision: 338095

URL: http://llvm.org/viewvc/llvm-project?rev=338095&view=rev
Log:
Attempt to unbreak *all the bots*

The bots were failing to build the cxx_filesystem target, so the
tests were failing. Though this does lead me to wonder how it
was ever working with c++experimental.

Modified:
libcxx/trunk/CMakeLists.txt
libcxx/trunk/include/CMakeLists.txt
libcxx/trunk/lib/CMakeLists.txt
libcxx/trunk/test/CMakeLists.txt

Modified: libcxx/trunk/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/CMakeLists.txt?rev=338095&r1=338094&r2=338095&view=diff
==
--- libcxx/trunk/CMakeLists.txt (original)
+++ libcxx/trunk/CMakeLists.txt Thu Jul 26 20:42:58 2018
@@ -72,7 +72,7 @@ set(ENABLE_FILESYSTEM_DEFAULT ${LIBCXX_E
 if (WIN32)
   set(ENABLE_FILESYSTEM_DEFAULT OFF)
 endif()
-option(LIBCXX_ENABLE_FILESYSTEM "Build filesystem as part of 
libc++experimental.a"
+option(LIBCXX_ENABLE_FILESYSTEM "Build filesystem as part of libc++fs.a"
 ${ENABLE_FILESYSTEM_DEFAULT})
 option(LIBCXX_INCLUDE_TESTS "Build the libc++ tests." ${LLVM_INCLUDE_TESTS})
 
@@ -109,7 +109,7 @@ cmake_dependent_option(LIBCXX_INSTALL_EX
 "LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY;LIBCXX_INSTALL_LIBRARY" OFF)
 cmake_dependent_option(LIBCXX_INSTALL_FILESYSTEM_LIBRARY
 "Install libc++fs.a" ON
-"LIBCXX_ENABLE_FILESYSTEM_LIBRARY;LIBCXX_INSTALL_LIBRARY" OFF)
+"LIBCXX_ENABLE_FILESYSTEM;LIBCXX_INSTALL_LIBRARY" OFF)
 
 if (FUCHSIA)
   set(DEFAULT_ABI_VERSION 2)

Modified: libcxx/trunk/include/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/include/CMakeLists.txt?rev=338095&r1=338094&r2=338095&view=diff
==
--- libcxx/trunk/include/CMakeLists.txt (original)
+++ libcxx/trunk/include/CMakeLists.txt Thu Jul 26 20:42:58 2018
@@ -93,6 +93,7 @@ set(files
   ext/__hash
   ext/hash_map
   ext/hash_set
+  filesystem
   float.h
   forward_list
   fstream

Modified: libcxx/trunk/lib/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/lib/CMakeLists.txt?rev=338095&r1=338094&r2=338095&view=diff
==
--- libcxx/trunk/lib/CMakeLists.txt (original)
+++ libcxx/trunk/lib/CMakeLists.txt Thu Jul 26 20:42:58 2018
@@ -288,10 +288,6 @@ if (LIBCXX_ENABLE_STATIC)
   endif()
 endif()
 
-# Add a meta-target for both libraries.
-add_custom_target(cxx DEPENDS cxx-headers ${LIBCXX_BUILD_TARGETS})
-
-
 if (LIBCXX_ENABLE_FILESYSTEM)
   set(LIBCXX_FILESYSTEM_SOURCES
   ../src/filesystem/operations.cpp
@@ -322,6 +318,7 @@ if (LIBCXX_ENABLE_FILESYSTEM)
   COMPILE_FLAGS "${filesystem_flags}"
   OUTPUT_NAME   "c++fs"
   )
+  list(APPEND LIBCXX_BUILD_TARGETS cxx_filesystem)
 endif()
 
 
@@ -344,9 +341,14 @@ if (LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY)
   COMPILE_FLAGS "${experimental_flags}"
   OUTPUT_NAME   "c++experimental"
   )
+  list(APPEND LIBCXX_BUILD_TARGETS cxx_experimental)
 endif()
 
 
+# Add a meta-target for both libraries.
+add_custom_target(cxx DEPENDS cxx-headers ${LIBCXX_BUILD_TARGETS})
+
+
 if (LIBCXX_BUILD_EXTERNAL_THREAD_LIBRARY)
   file(GLOB LIBCXX_EXTERNAL_THREADING_SUPPORT_SOURCES 
../test/support/external_threads.cpp)
 

Modified: libcxx/trunk/test/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/CMakeLists.txt?rev=338095&r1=338094&r2=338095&view=diff
==
--- libcxx/trunk/test/CMakeLists.txt (original)
+++ libcxx/trunk/test/CMakeLists.txt Thu Jul 26 20:42:58 2018
@@ -105,7 +105,7 @@ if (LIBCXX_CONFIGURE_IDE)
   ${LIBCXX_TESTS} ${LIBCXX_TEST_HEADERS} ${LIBCXX_HEADERS})
   add_dependencies(libcxx_test_objects cxx)
 
-  set(STATIC_ROOT 
${LIBCXX_SOURCE_DIR}/test/std/experimental/filesystem/Inputs/static_test_env)
+  set(STATIC_ROOT 
${LIBCXX_SOURCE_DIR}/test/std/input.output/filesystems/Inputs/static_test_env)
   add_definitions(-DLIBCXX_FILESYSTEM_STATIC_TEST_ROOT="${STATIC_ROOT}")
 
   set(DYNAMIC_ROOT ${LIBCXX_BINARY_DIR}/test/filesystem/Output/dynamic_env)


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


[libcxx] r338094 - Correctly mark the Filesystem status as complete.

2018-07-26 Thread Eric Fiselier via cfe-commits
Author: ericwf
Date: Thu Jul 26 20:16:02 2018
New Revision: 338094

URL: http://llvm.org/viewvc/llvm-project?rev=338094&view=rev
Log:
Correctly mark the Filesystem status as complete.

Modified:
libcxx/trunk/www/cxx1z_status.html

Modified: libcxx/trunk/www/cxx1z_status.html
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/www/cxx1z_status.html?rev=338094&r1=338093&r2=338094&view=diff
==
--- libcxx/trunk/www/cxx1z_status.html (original)
+++ libcxx/trunk/www/cxx1z_status.html Thu Jul 26 20:16:02 2018
@@ -83,8 +83,8 @@

https://wg21.link/P0024R2";>P0024R2LWGThe 
Parallelism TS Should be 
StandardizedJacksonville
https://wg21.link/P0226R1";>P0226R1LWGMathematical 
Special Functions for C++17Jacksonville
-   https://wg21.link/P0220R1";>P0220R1LWGAdopt Library 
Fundamentals V1 TS Components for 
C++17JacksonvilleComplete7.0
-   https://wg21.link/P0218R1";>P0218R1LWGAdopt the File 
System TS for C++17JacksonvilleIn Progress
+   https://wg21.link/P0220R1";>P0220R1LWGAdopt Library 
Fundamentals V1 TS Components for C++17JacksonvilleIn 
Progress
+   https://wg21.link/P0218R1";>P0218R1LWGAdopt the File 
System TS for C++17JacksonvilleComplete7.0
https://wg21.link/P0033R1";>P0033R1LWGRe-enabling 
shared_from_thisJacksonvilleComplete3.9
https://wg21.link/P0005R4";>P0005R4LWGAdopt not_fn 
from Library Fundamentals 2 for 
C++17JacksonvilleComplete3.9
https://wg21.link/P0152R1";>P0152R1LWGconstexpr 
atomic::is_always_lock_freeJacksonvilleComplete3.9


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


[PATCH] D48958: [clang][ubsan] Implicit Cast Sanitizer - integer truncation - clang part

2018-07-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: docs/ReleaseNotes.rst:49-51
+- A new Implicit Cast Sanitizer (``-fsanitize=implicit-cast``) group was added.
+  Please refer to the :ref:`release-notes-ubsan` section of the release notes
+  for the details.

Regarding the name of this sanitizer: C and C++ refer to these as "implicit 
conversions" not "implicit casts", and "implicit cast" is a contradiction in 
terms -- a cast is explicit syntax for performing a conversion. We should use 
the external terminology here ("implicit-conversion") rather than the 
slightly-odd clang-specific convention of calling an implicit conversion an 
"implicit cast".



Comment at: docs/ReleaseNotes.rst:290
+  void test(unsigned long val) {
+if (consume(val)) // the value got silently truncated.
+  store = store + 768; // before addition, 'store' was promoted to int.

got -> may have been



Comment at: docs/ReleaseNotes.rst:292
+  store = store + 768; // before addition, 'store' was promoted to int.
+(void)consume((unsigned int)val); // OK, the truncation is implicit.
+  }

implicit -> explicit



Comment at: docs/UndefinedBehaviorSanitizer.rst:95
+ of bigger bit width to smaller bit width, if that results in data loss.
+ That is, if the demoted value, after casting back to the original width,
+ is not equal to the original value before the downcast. This issue may

erichkeane wrote:
> I think the last 2 commas in this sentence are unnecessary?  
I would parenthesize the "where the demoted value [...] would have a different 
value from the original" clause, since it's just explaining what we mean by 
"data loss".



Comment at: docs/UndefinedBehaviorSanitizer.rst:95
+ of bigger bit width to smaller bit width, if that results in data loss.
+ That is, if the demoted value, after casting back to the original width,
+ is not equal to the original value before the downcast. This issue may

rsmith wrote:
> erichkeane wrote:
> > I think the last 2 commas in this sentence are unnecessary?  
> I would parenthesize the "where the demoted value [...] would have a 
> different value from the original" clause, since it's just explaining what we 
> mean by "data loss".
Is this really the right rule, though? Consider:

```
unsigned int x = 0x81234567;
int y = x; // does the sanitizer catch this or not?
```

Here, the value of `x` is not the same as the value of `y` (assuming 32-bit 
int): `y` is negative. But this is not "data loss" according to the documented 
meaning of the sanitizer. I think we should produce a sanitizer trap on this 
case.



Comment at: docs/UndefinedBehaviorSanitizer.rst:17
 * Signed integer overflow
+* Problematic Implicit Casts (not UB, but not always intentional)
 * Conversion to, from, or between floating-point types which would

Don't use Title Caps here. "Problematic implicit conversions"



Comment at: docs/UndefinedBehaviorSanitizer.rst:131-133
+ overflow in signed division (``INT_MIN / -1``). Please do note that this
+ check does not diagnose lossy implicit integer conversions. Also please be
+ aware of integer conversions, as those may result in an unexpected

Remove the "Please"s here. We don't need to beg the reader to read the rest of 
the sentence. Just "Note that this [...]. Also note that integer conversions 
may result in an unexpected computation result, [...]"



Comment at: docs/UndefinedBehaviorSanitizer.rst:142-147
+ it is often unintentional, so UBSan offers to catch it. Please do note 
that
+ this check does not diagnose lossy implicit integer conversions. Also
+ please be aware of integer conversions, as those may result in an
+ unexpected computation results, even though no overflow happens (signed or
+ unsigned). Both of these two issues are handled by 
``-fsanitize=implicit-cast``
+ group of checks.

Likewise here.



Comment at: include/clang/Basic/Sanitizers.def:134-136
 SANITIZER_GROUP("integer", Integer,
 SignedIntegerOverflow | UnsignedIntegerOverflow | Shift |
 IntegerDivideByZero)

`-fsanitize=integer` should include `-fsanitize=implicit-integer-truncation`.



Comment at: lib/CodeGen/CGExprScalar.cpp:954-955
+  // We only care about int->int casts here, and ignore casts to/from pointer.
+  if (!(isa(SrcTy) && isa(DstTy)))
+return;
+  // We do not care about booleans.

Check the Clang types here, not the LLVM types. There is no guarantee that only 
integer types get converted to LLVM `IntegerType`s. (But if you like, you can 
assert that `SrcTy` and `DstTy` are `IntegerType`s after checking that the 
clang types are both integer types.)


[libcxx] r338093 - Implement

2018-07-26 Thread Eric Fiselier via cfe-commits
Copied: 
libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.factory.pass.cpp
 (from r338006, 
libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/path.factory.pass.cpp)
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.factory.pass.cpp?p2=libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.factory.pass.cpp&p1=libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/path.factory.pass.cpp&r1=338006&r2=338093&rev=338093&view=diff
==
--- 
libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/path.factory.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.factory.pass.cpp
 Thu Jul 26 20:07:09 2018
@@ -9,7 +9,7 @@
 
 // UNSUPPORTED: c++98, c++03
 
-// 
+// 
 
 // template 
 //path u8path(Source const&);

Copied: 
libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.io.pass.cpp
 (from r338006, 
libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/path.io.pass.cpp)
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.io.pass.cpp?p2=libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.io.pass.cpp&p1=libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/path.io.pass.cpp&r1=338006&r2=338093&rev=338093&view=diff
==
--- 
libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/path.io.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.io.pass.cpp
 Thu Jul 26 20:07:09 2018
@@ -9,7 +9,7 @@
 
 // UNSUPPORTED: c++98, c++03
 
-// 
+// 
 
 // class path
 

Copied: 
libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.io.unicode_bug.pass.cpp
 (from r338006, 
libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/path.io.unicode_bug.pass.cpp)
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.io.unicode_bug.pass.cpp?p2=libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.io.unicode_bug.pass.cpp&p1=libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/path.io.unicode_bug.pass.cpp&r1=338006&r2=338093&rev=338093&view=diff
==
--- 
libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/path.io.unicode_bug.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/path.io.unicode_bug.pass.cpp
 Thu Jul 26 20:07:09 2018
@@ -9,7 +9,7 @@
 
 // UNSUPPORTED: c++98, c++03
 
-// 
+// 
 
 // class path
 

Copied: 
libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/swap.pass.cpp
 (from r338006, 
libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/swap.pass.cpp)
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/swap.pass.cpp?p2=libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/swap.pass.cpp&p1=libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/swap.pass.cpp&r1=338006&r2=338093&rev=338093&view=diff
==
--- 
libcxx/trunk/test/std/experimental/filesystem/class.path/path.nonmember/swap.pass.cpp
 (original)
+++ 
libcxx/trunk/test/std/input.output/filesystems/class.path/path.nonmember/swap.pass.cpp
 Thu Jul 26 20:07:09 2018
@@ -9,7 +9,7 @@
 
 // UNSUPPORTED: c++98, c++03
 
-// 
+// 
 
 // void swap(path& lhs, path& rhs) noexcept;
 

Copied: 
libcxx/trunk/test/std/input.output/filesystems/class.path/synop.pass.cpp (from 
r338006, 
libcxx/trunk/test/std/experimental/filesystem/class.path/synop.pass.cpp)
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/test/std/input.output/filesystems/class.path/synop.pass.cpp?p2=libcxx/trunk/test/std/input.output/filesystems/class.path/synop.pass.cpp&p1=libcxx/trunk/test/std/experimental/filesystem/class.path/synop.pass.cpp&r1=338006&r2=338093&rev=338093&view=diff
==
--- libcxx/trunk/test/std/experimental/filesystem/class.path/synop.pass.cpp 
(original)
+++ libcxx/trunk/test/std/input.output/filesystems/class.path/synop.pass.cpp 
Thu Jul 26 20:07:09 2018
@@ -9,7 +9,7 @@
 
 // UNSUPPORTED: c++98, c++03
 
-// 
+// 
 
 // class path
 

Copied: 
libcxx/trunk/test/std/input.output/filesystems/class.rec.dir.itr/rec.dir.itr.members/copy.pass.cpp
 (from r338006, 
libcxx/trunk/test/std/experimental/filesystem/class.rec.dir.itr/rec.dir.itr.members/

[PATCH] D49758: [clangd] allow clients to pass in compilationDatabaseChanges in the 'workspace/didChangeConfiguration' request

2018-07-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added inline comments.



Comment at: clangd/Protocol.h:429
+  // The changes that happened to the compilation database.
+  llvm::Optional>>
+  compilationDatabaseChanges;

ilya-biryukov wrote:
> - Maybe add a comment that the key of the map is a file name?
> - The value does not contain the working directory at the time, but we need 
> that for building `tooling::CompileCommand`, maybe add it?
Could you please elaborate on the issue with the working directory? I didn't 
quite get that concern, sorry.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49758



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


[PATCH] D49899: Make test/Driver/fuchsia.c(pp) work with lld or gold

2018-07-26 Thread David Greene via Phabricator via cfe-commits
greened created this revision.
greened added reviewers: phosek, rsmith.
Herald added subscribers: cfe-commits, dexonsmith, mehdi_amini.

These tests don't appear to depend on lld.  They are invoking lto, so we should 
ensure the linker is capable of that.  Therefore, allow gold in addition to lld 
but nothing else.


Repository:
  rC Clang

https://reviews.llvm.org/D49899

Files:
  test/Driver/fuchsia.c
  test/Driver/fuchsia.cpp


Index: test/Driver/fuchsia.cpp
===
--- test/Driver/fuchsia.cpp
+++ test/Driver/fuchsia.cpp
@@ -6,7 +6,7 @@
 // CHECK: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK: "-internal-isystem" "{{.*[/\\]}}include{{/|}}c++{{/|}}v1"
 // CHECK: "-internal-externc-isystem" "[[SYSROOT]]{{/|}}include"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic"
+// CHECK: {{.*}}ld.{{(lld[^"]*" "-z" "rodynamic"|gold[^"]*")}}
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"
Index: test/Driver/fuchsia.c
===
--- test/Driver/fuchsia.c
+++ test/Driver/fuchsia.c
@@ -15,7 +15,7 @@
 // CHECK: "-fsanitize=safe-stack"
 // CHECK: "-stack-protector" "2"
 // CHECK: "-fno-common"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic"
+// CHECK: {{.*}}ld.{{(lld[^"]*" "-z" "rodynamic"|gold[^"]*")}}
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"


Index: test/Driver/fuchsia.cpp
===
--- test/Driver/fuchsia.cpp
+++ test/Driver/fuchsia.cpp
@@ -6,7 +6,7 @@
 // CHECK: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK: "-internal-isystem" "{{.*[/\\]}}include{{/|}}c++{{/|}}v1"
 // CHECK: "-internal-externc-isystem" "[[SYSROOT]]{{/|}}include"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic"
+// CHECK: {{.*}}ld.{{(lld[^"]*" "-z" "rodynamic"|gold[^"]*")}}
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"
Index: test/Driver/fuchsia.c
===
--- test/Driver/fuchsia.c
+++ test/Driver/fuchsia.c
@@ -15,7 +15,7 @@
 // CHECK: "-fsanitize=safe-stack"
 // CHECK: "-stack-protector" "2"
 // CHECK: "-fno-common"
-// CHECK: {{.*}}ld.lld{{.*}}" "-z" "rodynamic"
+// CHECK: {{.*}}ld.{{(lld[^"]*" "-z" "rodynamic"|gold[^"]*")}}
 // CHECK: "--sysroot=[[SYSROOT]]"
 // CHECK: "-pie"
 // CHECK: "--build-id"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49758: [clangd] allow clients to pass in compilationDatabaseChanges in the 'workspace/didChangeConfiguration' request

2018-07-26 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

In https://reviews.llvm.org/D49758#1174629, @ilya-biryukov wrote:

> The mode of operation where compile commands come from the client seems 
> useful, but I wonder if there's any value in mixing it with 
> `compile_commands.json` and other CDB plugins.
>  Do you plan to use the overridden commands in conjunction with CDB plugins 
> or do you want the client to exclusively control the compile commands?


The client will control the commands exclusively.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49758



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


[PATCH] D49898: Make test/Driver/baremetal.cpp work with linkers other than lld

2018-07-26 Thread David Greene via Phabricator via cfe-commits
greened created this revision.
greened added reviewers: jroelofs, hans, probinson, ismail, rtrieu.
Herald added a subscriber: cfe-commits.

This test fails if clang is configure with, for example, gold as the default 
linker.  It does not appear that this test really relies on lld so make the 
checks accept ld, ld.gold and ld.bfd too.


Repository:
  rC Clang

https://reviews.llvm.org/D49898

Files:
  test/Driver/baremetal.cpp


Index: test/Driver/baremetal.cpp
===
--- test/Driver/baremetal.cpp
+++ test/Driver/baremetal.cpp
@@ -10,7 +10,7 @@
 // CHECK-V6M-C-SAME: "-internal-isystem" 
"[[SYSROOT]]{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1"
 // CHECk-V6M-C-SAME: "-internal-isystem" "[[SYSROOT]]{{[/\\]+}}include"
 // CHECK-V6M-C-SAME: "-x" "c++" "{{.*}}baremetal.cpp"
-// CHECK-V6M-C-NEXT: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-V6M-C-NEXT: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" 
"{{.*}}.o" "-Bstatic"
 // CHECK-V6M-C-SAME: "-L[[RESOURCE_DIR:[^"]+]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-V6M-C-SAME: "-T" "semihosted.lds" 
"-Lsome{{[/\\]+}}directory{{[/\\]+}}user{{[/\\]+}}asked{{[/\\]+}}for"
 // CHECK-V6M-C-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a"
@@ -32,7 +32,7 @@
 // RUN: -target armv6m-none-eabi \
 // RUN: --sysroot=%S/Inputs/baremetal_arm \
 // RUN:   | FileCheck --check-prefix=CHECK-V6M-DEFAULTCXX %s
-// CHECK-V6M-DEFAULTCXX: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-V6M-DEFAULTCXX: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" 
"{{.*}}.o" "-Bstatic"
 // CHECK-V6M-DEFAULTCXX-SAME: 
"-L{{[^"]*}}{{[/\\]+}}lib{{(64)?}}{{[/\\]+}}clang{{[/\\]+}}{{.*}}{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-V6M-DEFAULTCXX-SAME: "-lc++" "-lc++abi" "-lunwind"
 // CHECK-V6M-DEFAULTCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a"
@@ -45,7 +45,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-V6M-LIBCXX %s
 // CHECK-V6M-LIBCXX-NOT: "-internal-isystem" 
"{{[^"]+}}{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}{{[^v].*}}"
 // CHECK-V6M-LIBCXX: "-internal-isystem" 
"{{[^"]+}}{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1"
-// CHECK-V6M-LIBCXX: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-V6M-LIBCXX: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" 
"{{.*}}.o" "-Bstatic"
 // CHECK-V6M-LIBCXX-SAME: 
"-L{{[^"]*}}{{[/\\]+}}lib{{(64)?}}{{[/\\]+}}clang{{[/\\]+}}{{.*}}{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-V6M-LIBCXX-SAME: "-lc++" "-lc++abi" "-lunwind"
 // CHECK-V6M-LIBCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a"
@@ -58,7 +58,7 @@
 // RUN:   | FileCheck --check-prefix=CHECK-V6M-LIBSTDCXX %s
 // CHECK-V6M-LIBSTDCXX-NOT: "-internal-isystem" 
"{{[^"]+}}{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1"
 // CHECK-V6M-LIBSTDCXX: "-internal-isystem" 
"{{[^"]+}}{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}6.0.0"
-// CHECK-V6M-LIBSTDCXX: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-V6M-LIBSTDCXX: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" 
"{{.*}}.o" "-Bstatic"
 // CHECK-V6M-LIBSTDCXX-SAME: 
"-L{{[^"]*}}{{[/\\]+}}lib{{(64)?}}{{[/\\]+}}clang{{[/\\]+}}{{.*}}{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-V6M-LIBSTDCXX-SAME: "-lstdc++" "-lsupc++" "-lunwind"
 // CHECK-V6M-LIBSTDCXX-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a"
@@ -69,7 +69,7 @@
 // RUN: --sysroot=%S/Inputs/baremetal_arm \
 // RUN: -nodefaultlibs \
 // RUN:   | FileCheck --check-prefix=CHECK-V6M-NDL %s
-// CHECK-V6M-NDL: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-V6M-NDL: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" 
"-Bstatic"
 // CHECK-V6M-NDL-SAME: 
"-L{{[^"]*}}{{[/\\]+}}lib{{(64)?}}{{[/\\]+}}clang{{[/\\]+}}{{.*}}{{[/\\]+}}lib{{[/\\]+}}baremetal"
 "-o" "{{.*}}.o"
 
 // RUN: %clangxx -target arm-none-eabi -v 2>&1 \


Index: test/Driver/baremetal.cpp
===
--- test/Driver/baremetal.cpp
+++ test/Driver/baremetal.cpp
@@ -10,7 +10,7 @@
 // CHECK-V6M-C-SAME: "-internal-isystem" "[[SYSROOT]]{{[/\\]+}}include{{[/\\]+}}c++{{[/\\]+}}v1"
 // CHECk-V6M-C-SAME: "-internal-isystem" "[[SYSROOT]]{{[/\\]+}}include"
 // CHECK-V6M-C-SAME: "-x" "c++" "{{.*}}baremetal.cpp"
-// CHECK-V6M-C-NEXT: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-V6M-C-NEXT: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
 // CHECK-V6M-C-SAME: "-L[[RESOURCE_DIR:[^"]+]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
 // CHECK-V6M-C-SAME: "-T" "semihosted.lds" "-Lsome{{[/\\]+}}directory{{[/\\]+}}user{{[/\\]+}}asked{{[/\\]+}}for"
 // CHECK-V6M-C-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m.a"
@@ -32,7 +32,7 @@
 // RUN: -target armv6m-none-eabi \
 // RUN: --sysroot=%S/Inputs/baremetal_arm \
 // RUN:   | FileCheck --check-prefix=CHECK-V6M-DEFAULTCXX %s
-// CHECK-V6M-DEFAULTCXX: "{{[^"]*}}ld.lld{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
+// CHECK-V6M-DEFAULTCXX: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" "{{.*}}.o" "-Bstatic"
 // C

[PATCH] D49897: [WebAssembly] Force use of lld for test/Driver/wasm-toolchain.c(pp)

2018-07-26 Thread David Greene via Phabricator via cfe-commits
greened created this revision.
greened added reviewers: sbc100, sunfish.
Herald added subscribers: cfe-commits, aheejin, jgravelle-google, dschuff.

lld is the only supported linker that works for WebAssembly, so ensure clang is 
using it for this test.  This gets the tests passing when configuring clang to 
use a different linker by default.


Repository:
  rC Clang

https://reviews.llvm.org/D49897

Files:
  test/Driver/wasm-toolchain.c
  test/Driver/wasm-toolchain.cpp


Index: test/Driver/wasm-toolchain.cpp
===
--- test/Driver/wasm-toolchain.cpp
+++ test/Driver/wasm-toolchain.cpp
@@ -12,12 +12,12 @@
 
 // A basic C++ link command-line.
 
-// RUN: %clangxx -### -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo --stdlib=c++ %s 2>&1 | FileCheck -check-prefix=LINK %s
+// RUN: %clangxx -### -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo --stdlib=c++ -fuse-ld=lld %s 2>&1 | FileCheck -check-prefix=LINK 
%s
 // LINK: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK: lld{{.*}}" "-flavor" "wasm" "-L/foo/lib" "crt1.o" "[[temp]]" "-lc++" 
"-lc++abi" "-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // A basic C++ link command-line with optimization.
 
-// RUN: %clangxx -### -O2 -no-canonical-prefixes -target 
wasm32-unknown-unknown --sysroot=/foo %s --stdlib=c++ 2>&1 | FileCheck 
-check-prefix=LINK_OPT %s
+// RUN: %clangxx -### -O2 -no-canonical-prefixes -target 
wasm32-unknown-unknown --sysroot=/foo %s --stdlib=c++ -fuse-ld=lld 2>&1 | 
FileCheck -check-prefix=LINK_OPT %s
 // LINK_OPT: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_OPT: lld{{.*}}" "-flavor" "wasm" "-L/foo/lib" "crt1.o" "[[temp]]" 
"-lc++" "-lc++abi" "-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
Index: test/Driver/wasm-toolchain.c
===
--- test/Driver/wasm-toolchain.c
+++ test/Driver/wasm-toolchain.c
@@ -12,12 +12,12 @@
 
 // A basic C link command-line.
 
-// RUN: %clang -### -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo %s 2>&1 | FileCheck -check-prefix=LINK %s
+// RUN: %clang -### -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo -fuse-ld=lld %s 2>&1 | FileCheck -check-prefix=LINK %s
 // LINK: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK: lld{{.*}}" "-flavor" "wasm" "-L/foo/lib" "crt1.o" "[[temp]]" "-lc" 
"{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // A basic C link command-line with optimization.
 
-// RUN: %clang -### -O2 -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo %s 2>&1 | FileCheck -check-prefix=LINK_OPT %s
+// RUN: %clang -### -O2 -no-canonical-prefixes -target wasm32-unknown-unknown 
--sysroot=/foo -fuse-ld=lld %s 2>&1 | FileCheck -check-prefix=LINK_OPT %s
 // LINK_OPT: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_OPT: lld{{.*}}" "-flavor" "wasm" "-L/foo/lib" "crt1.o" "[[temp]]" 
"-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"


Index: test/Driver/wasm-toolchain.cpp
===
--- test/Driver/wasm-toolchain.cpp
+++ test/Driver/wasm-toolchain.cpp
@@ -12,12 +12,12 @@
 
 // A basic C++ link command-line.
 
-// RUN: %clangxx -### -no-canonical-prefixes -target wasm32-unknown-unknown --sysroot=/foo --stdlib=c++ %s 2>&1 | FileCheck -check-prefix=LINK %s
+// RUN: %clangxx -### -no-canonical-prefixes -target wasm32-unknown-unknown --sysroot=/foo --stdlib=c++ -fuse-ld=lld %s 2>&1 | FileCheck -check-prefix=LINK %s
 // LINK: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK: lld{{.*}}" "-flavor" "wasm" "-L/foo/lib" "crt1.o" "[[temp]]" "-lc++" "-lc++abi" "-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
 
 // A basic C++ link command-line with optimization.
 
-// RUN: %clangxx -### -O2 -no-canonical-prefixes -target wasm32-unknown-unknown --sysroot=/foo %s --stdlib=c++ 2>&1 | FileCheck -check-prefix=LINK_OPT %s
+// RUN: %clangxx -### -O2 -no-canonical-prefixes -target wasm32-unknown-unknown --sysroot=/foo %s --stdlib=c++ -fuse-ld=lld 2>&1 | FileCheck -check-prefix=LINK_OPT %s
 // LINK_OPT: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"]*]]"
 // LINK_OPT: lld{{.*}}" "-flavor" "wasm" "-L/foo/lib" "crt1.o" "[[temp]]" "-lc++" "-lc++abi" "-lc" "{{.*[/\\]}}libclang_rt.builtins-wasm32.a" "-o" "a.out"
Index: test/Driver/wasm-toolchain.c
===
--- test/Driver/wasm-toolchain.c
+++ test/Driver/wasm-toolchain.c
@@ -12,12 +12,12 @@
 
 // A basic C link command-line.
 
-// RUN: %clang -### -no-canonical-prefixes -target wasm32-unknown-unknown --sysroot=/foo %s 2>&1 | FileCheck -check-prefix=LINK %s
+// RUN: %clang -### -no-canonical-prefixes -target wasm32-unknown-unknown --sysroot=/foo -fuse-ld=lld %s 2>&1 | FileCheck -check-prefix=LINK %s
 // LINK: clang{{.*}}" "-cc1" {{.*}} "-o" "[[temp:[^"

[PATCH] D49338: Implement - P0122R7

2018-07-26 Thread Marshall Clow via Phabricator via cfe-commits
mclow.lists closed this revision.
mclow.lists added a comment.

Landed as r337804.


https://reviews.llvm.org/D49338



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


[PATCH] D49890: Clang-Tidy Export Problem

2018-07-26 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: ClangTidy.cpp:612
+
+  FileManager *Files = new FileManager(FileSystemOptions());
+  vfs::FileSystem &FileSystem = *Files->getVirtualFileSystem();

You could use auto here, because type is in new statement.



Comment at: ClangTidy.cpp:614
+  vfs::FileSystem &FileSystem = *Files->getVirtualFileSystem();
+  auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
+  if (!InitialWorkingDir)

Type is not obvious, so please don't use auto.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49890



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


[PATCH] D49890: Clang-Tidy Export Problem

2018-07-26 Thread Ahmad Nouralizadeh via Phabricator via cfe-commits
TheAhmad accepted this revision.
TheAhmad marked 3 inline comments as done.
TheAhmad added a comment.
This revision is now accepted and ready to land.

Thanks Eugene!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49890



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


[PATCH] D49890: Clang-Tidy Export Problem

2018-07-26 Thread Ahmad Nouralizadeh via Phabricator via cfe-commits
TheAhmad updated this revision to Diff 157623.
TheAhmad added a comment.

Ran Clang Format.
Redundant Braces Removed.
Used auto.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49890

Files:
  ClangTidy.cpp


Index: ClangTidy.cpp
===
--- ClangTidy.cpp
+++ ClangTidy.cpp
@@ -608,8 +608,55 @@
 raw_ostream &OS) {
   TranslationUnitDiagnostics TUD;
   TUD.MainSourceFile = MainFilePath;
+
+  FileManager *Files = new FileManager(FileSystemOptions());
+  vfs::FileSystem &FileSystem = *Files->getVirtualFileSystem();
+  auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
+  if (!InitialWorkingDir)
+llvm::report_fatal_error("Cannot get current working path.");
+
+  llvm::StringMap FileReplacements;
+  llvm::StringMap SingleErrors;
   for (const auto &Error : Errors) {
-tooling::Diagnostic Diag = Error;
+if (!Error.BuildDirectory.empty())
+  FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
+
+SmallString<128> ErrorAbsoluteFilePath = (StringRef)Error.Message.FilePath;
+Files->makeAbsolutePath(ErrorAbsoluteFilePath);
+if (SingleErrors.find(ErrorAbsoluteFilePath) == SingleErrors.end()) {
+  ClangTidyError AbsoluteError = Error;
+  AbsoluteError.Message.FilePath = ErrorAbsoluteFilePath.str();
+  AbsoluteError.Fix.clear();
+  SingleErrors.insert(std::pair(
+  ErrorAbsoluteFilePath, AbsoluteError));
+}
+
+for (const auto &FileAndReplacements : Error.Fix) {
+  for (const auto &Repl : FileAndReplacements.second) {
+SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
+Files->makeAbsolutePath(FixAbsoluteFilePath);
+
+tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
+   Repl.getLength(), Repl.getReplacementText());
+
+FileReplacements[R.getFilePath()].add(R);
+  }
+}
+
+FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
+  }
+
+  for (const auto &FileAndReplacements : FileReplacements) {
+StringRef File = FileAndReplacements.first();
+Replacements Repls = FileAndReplacements.second;
+
+ClangTidyError AbsoluteError = SingleErrors.find(File)->second;
+if (SingleErrors.find(File) == SingleErrors.end())
+  llvm::report_fatal_error("Cannot find the containing ClangTidyError.");
+
+AbsoluteError.Fix.insert(std::pair(File, Repls));
+
+tooling::Diagnostic Diag = AbsoluteError;
 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
   }
 


Index: ClangTidy.cpp
===
--- ClangTidy.cpp
+++ ClangTidy.cpp
@@ -608,8 +608,55 @@
 raw_ostream &OS) {
   TranslationUnitDiagnostics TUD;
   TUD.MainSourceFile = MainFilePath;
+
+  FileManager *Files = new FileManager(FileSystemOptions());
+  vfs::FileSystem &FileSystem = *Files->getVirtualFileSystem();
+  auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
+  if (!InitialWorkingDir)
+llvm::report_fatal_error("Cannot get current working path.");
+
+  llvm::StringMap FileReplacements;
+  llvm::StringMap SingleErrors;
   for (const auto &Error : Errors) {
-tooling::Diagnostic Diag = Error;
+if (!Error.BuildDirectory.empty())
+  FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
+
+SmallString<128> ErrorAbsoluteFilePath = (StringRef)Error.Message.FilePath;
+Files->makeAbsolutePath(ErrorAbsoluteFilePath);
+if (SingleErrors.find(ErrorAbsoluteFilePath) == SingleErrors.end()) {
+  ClangTidyError AbsoluteError = Error;
+  AbsoluteError.Message.FilePath = ErrorAbsoluteFilePath.str();
+  AbsoluteError.Fix.clear();
+  SingleErrors.insert(std::pair(
+  ErrorAbsoluteFilePath, AbsoluteError));
+}
+
+for (const auto &FileAndReplacements : Error.Fix) {
+  for (const auto &Repl : FileAndReplacements.second) {
+SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
+Files->makeAbsolutePath(FixAbsoluteFilePath);
+
+tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
+   Repl.getLength(), Repl.getReplacementText());
+
+FileReplacements[R.getFilePath()].add(R);
+  }
+}
+
+FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
+  }
+
+  for (const auto &FileAndReplacements : FileReplacements) {
+StringRef File = FileAndReplacements.first();
+Replacements Repls = FileAndReplacements.second;
+
+ClangTidyError AbsoluteError = SingleErrors.find(File)->second;
+if (SingleErrors.find(File) == SingleErrors.end())
+  llvm::report_fatal_error("Cannot find the containing ClangTidyError.");
+
+AbsoluteError.Fix.insert(std::pair(File, Repls));
+
+tooling::Diagnostic Diag = AbsoluteError;
 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
   }
 
___
cfe-commits mailin

[PATCH] D49890: Clang-Tidy Export Problem

2018-07-26 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: ClangTidy.cpp:620
+  llvm::StringMap SingleErrors;
+  for (const ClangTidyError &Error : Errors) {
+if (!Error.BuildDirectory.empty()) {

You could use auto, since it's iterator over container.



Comment at: ClangTidy.cpp:621
+  for (const ClangTidyError &Error : Errors) {
+if (!Error.BuildDirectory.empty()) {
+  FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);

Curly braces are not necessary.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49890



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


[PATCH] D49890: Clang-Tidy Export Problem

2018-07-26 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: ClangTidy.cpp:627
+Files->makeAbsolutePath(ErrorAbsoluteFilePath);
+if (SingleErrors.find(ErrorAbsoluteFilePath) == SingleErrors.end())
+{

Please run Clang-format.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49890



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


[PATCH] D49895: added shared library to fix buildbot

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rC338091: added shared library to fix buildbot (authored by 
emmettneyman, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D49895?vs=157618&id=157620#toc

Repository:
  rC Clang

https://reviews.llvm.org/D49895

Files:
  tools/clang-fuzzer/handle-llvm/CMakeLists.txt


Index: tools/clang-fuzzer/handle-llvm/CMakeLists.txt
===
--- tools/clang-fuzzer/handle-llvm/CMakeLists.txt
+++ tools/clang-fuzzer/handle-llvm/CMakeLists.txt
@@ -1,7 +1,9 @@
 set(LLVM_LINK_COMPONENTS
+  Analysis
   CodeGen
   Core
   ExecutionEngine
+  IPO
   IRReader
   MC
   MCJIT


Index: tools/clang-fuzzer/handle-llvm/CMakeLists.txt
===
--- tools/clang-fuzzer/handle-llvm/CMakeLists.txt
+++ tools/clang-fuzzer/handle-llvm/CMakeLists.txt
@@ -1,7 +1,9 @@
 set(LLVM_LINK_COMPONENTS
+  Analysis
   CodeGen
   Core
   ExecutionEngine
+  IPO
   IRReader
   MC
   MCJIT
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338091 - added shared library to fix buildbot

2018-07-26 Thread Emmett Neyman via cfe-commits
Author: emmettneyman
Date: Thu Jul 26 17:43:26 2018
New Revision: 338091

URL: http://llvm.org/viewvc/llvm-project?rev=338091&view=rev
Log:
added shared library to fix buildbot

Summary: added shared library to fix buildbot

Subscribers: mgorny, cfe-commits

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

Modified:
cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt

Modified: cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt?rev=338091&r1=338090&r2=338091&view=diff
==
--- cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt (original)
+++ cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt Thu Jul 26 17:43:26 
2018
@@ -1,7 +1,9 @@
 set(LLVM_LINK_COMPONENTS
+  Analysis
   CodeGen
   Core
   ExecutionEngine
+  IPO
   IRReader
   MC
   MCJIT


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


[PATCH] D49895: added shared library to fix buildbot

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
emmettneyman created this revision.
Herald added subscribers: cfe-commits, mgorny.

added shared library to fix buildbot


Repository:
  rC Clang

https://reviews.llvm.org/D49895

Files:
  clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt


Index: clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
===
--- clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
+++ clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
@@ -1,7 +1,9 @@
 set(LLVM_LINK_COMPONENTS
+  Analysis
   CodeGen
   Core
   ExecutionEngine
+  IPO
   IRReader
   MC
   MCJIT


Index: clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
===
--- clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
+++ clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
@@ -1,7 +1,9 @@
 set(LLVM_LINK_COMPONENTS
+  Analysis
   CodeGen
   Core
   ExecutionEngine
+  IPO
   IRReader
   MC
   MCJIT
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D36357: Added a better diagnostic when using the delete operator with lambdas

2018-07-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

This looks good, with some minor changes. Please add more test coverage, 
though, specifically:

- test all four forms of lambda that we recognize after `delete`
- add a test that the FixItHint is correct (maybe in 
test/FixIt/fixit-cxx0x.cpp, which checks that applying the fixes results in 
working code)




Comment at: lib/Parse/ParseExprCXX.cpp:2956
+ GetLookAheadToken(3).isOneOf(tok::r_paren, tok::identifier) &&
+ GetLookAheadToken(4).is(tok::identifier))) {
+  SourceLocation RightBracketLock = NextToken().getLocation();

This doesn't seem quite right now. `[]()` is not recognized as a lambda unless 
it's followed by an identifier. I think we want (and sorry if this is reverting 
to what you had before switching to `isOneOf`):

```
if (Next.isOneOf(tok::l_brace, tok::less) ||
(Next.is(tok::l_paren) &&
 (GetLookAheadToken(3).is(tok::r_paren) ||
  (GetLookAheadToken(3).is(tok::identifier) && 
GetLookAheadToken(4).is(tok::r_paren) {
```
That is, we're matching:
* `[]{`
* `[]<`
* `[]()`
* `[](identifier identifier`




Comment at: lib/Parse/ParseExprCXX.cpp:2969
+  << FixItHint::CreateInsertion(
+ Lexer::getLocForEndOfToken(Lambda.get()->getLocEnd(), 1,
+Actions.getSourceManager(),

The `1` here should be a `0`. Given
```
delete []{return new int;}();
```
this will insert the `)` after the final `;` instead of before it.



Comment at: lib/Parse/ParseExprCXX.cpp:2978
+Lambda.get());
+} else {
+  ArrayDelete = true;

No need for an `else` here, since the `if` block terminates by `return`.


Repository:
  rC Clang

https://reviews.llvm.org/D36357



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


[PATCH] D49114: [clang-tidy] Add a check for "magic numbers"

2018-07-26 Thread Florin Iucha via Phabricator via cfe-commits
0x8000- updated this revision to Diff 157615.
0x8000- marked an inline comment as done.
0x8000- added a comment.

Remove extra verbose namespaces and update documentation to indicate why -1 is 
accepted even when not explicitly called out.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49114

Files:
  clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp
  clang-tidy/readability/CMakeLists.txt
  clang-tidy/readability/MagicNumbersCheck.cpp
  clang-tidy/readability/MagicNumbersCheck.h
  clang-tidy/readability/ReadabilityTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/cppcoreguidelines-avoid-magic-numbers.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/readability-magic-numbers.rst
  test/clang-tidy/readability-magic-numbers.cpp

Index: test/clang-tidy/readability-magic-numbers.cpp
===
--- /dev/null
+++ test/clang-tidy/readability-magic-numbers.cpp
@@ -0,0 +1,192 @@
+// RUN: %check_clang_tidy %s readability-magic-numbers %t \
+// RUN: -config='{CheckOptions: \
+// RUN:  [{key: readability-magic-numbers.IgnoredIntegerValues, value: "0;1;2;10;100;"}]}' \
+// RUN: --
+
+template 
+struct ValueBucket {
+  T value[V];
+};
+
+int BadGlobalInt = 5;
+// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: 5 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+
+int IntSquarer(int param) {
+  return param * param;
+}
+
+void BuggyFunction() {
+  int BadLocalInt = 6;
+  // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 6 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+
+  (void)IntSquarer(7);
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: 7 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+
+  int LocalArray[8];
+  // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: 8 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+
+  for (int ii = 0; ii < 8; ++ii)
+  // CHECK-MESSAGES: :[[@LINE-1]]:25: warning: 8 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+  {
+LocalArray[ii] = 3 * ii;
+// CHECK-MESSAGES: :[[@LINE-1]]:22: warning: 3 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+  }
+
+  ValueBucket Bucket;
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: 4 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+}
+
+class TwoIntContainer {
+public:
+  TwoIntContainer(int val) : anotherMember(val * val), yetAnotherMember(6), anotherConstant(val + val) {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:73: warning: 6 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+
+  int getValue() const;
+
+private:
+  int oneMember = 9;
+  // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: 9 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+
+  int anotherMember;
+
+  int yetAnotherMember;
+
+  const int oneConstant = 2;
+
+  const int anotherConstant;
+};
+
+int ValueArray[] = {3, 5};
+// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: 3 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+// CHECK-MESSAGES: :[[@LINE-2]]:24: warning: 5 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+
+float FloatPiVariable = 3.1415926535f;
+// CHECK-MESSAGES: :[[@LINE-1]]:25: warning: 3.1415926535f is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+double DoublePiVariable = 6.283185307;
+// CHECK-MESSAGES: :[[@LINE-1]]:27: warning: 6.283185307 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+
+int getAnswer() {
+  if (ValueArray[0] < ValueArray[1])
+return ValueArray[1];
+
+  return -3; // FILENOTFOUND
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 3 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
+}
+
+/*
+ * Clean code
+ */
+
+#define INT_MACRO 5
+
+const int GoodGlobalIntConstant = 42;
+
+constexpr int AlsoGoodGlobalIntConstant = 42;
+
+int InitializedByMacro = INT_MACRO;
+
+void SolidFunction() {
+  const int GoodLocalIntConstant = 43;
+
+  (void)IntSquarer(GoodLocalIntConstant);
+
+  int LocalArray[INT_MACRO];
+
+  ValueBucket Bucket;
+}
+
+const int ConstValueArray[] = {7, 9};
+
+const int ConstValueArray2D[2][2] = {{7, 9}, {13, 15}};
+
+/*
+ * no warnings for ignored values (specified in the configuration above)
+ */
+int GrandfatheredValues[] = {0, 1, 2, 10, 100, -1, -10, -100};
+
+/*
+ * no warnings for enums
+ */
+enum Smorgasbord {
+  STARTER,
+  ALPHA = 3,
+  BETA = 1 << 5,
+};
+
+const float FloatPiConstant = 3.1415926535f;
+const double DoublePiConstant = 6.283185307;
+
+const float Angles[] = {45.0f, 90.0f, 135.0f};
+
+double DoubleZeroIsAccepted = 0.0;
+float FloatZero

[PATCH] D49892: Added shared library to fix build bot

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
emmettneyman created this revision.
emmettneyman added a reviewer: morehouse.
Herald added subscribers: cfe-commits, mgorny.

Repository:
  rC Clang

https://reviews.llvm.org/D49892

Files:
  clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
  clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
  clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp

Index: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
===
--- clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
+++ clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
@@ -7,33 +7,48 @@
 //
 //===--===//
 //
-// Implements HandleLLVM for use by the Clang fuzzers. Mimics the llc tool to
-// compile an LLVM IR file to X86_64 assembly.
+// Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
+// vectorizer optimization pass over the given IR code. Then mimics lli on both
+// versions to JIT the generated code and execute it. Currently, functions are 
+// executed on dummy inputs.
 //
 //===--===//
 
 #include "handle_llvm.h"
 
 #include "llvm/ADT/Triple.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/CodeGen/CommandFlags.inc"
 #include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/TargetPassConfig.h"
+#include "llvm/ExecutionEngine/JITEventListener.h"
+#include "llvm/ExecutionEngine/JITSymbol.h"
+#include "llvm/ExecutionEngine/MCJIT.h"
+#include "llvm/ExecutionEngine/ObjectCache.h"
+#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
+#include "llvm/ExecutionEngine/SectionMemoryManager.h"
+#include "llvm/IR/IRPrintingPasses.h"
 #include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/LegacyPassNameParser.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/Pass.h"
 #include "llvm/PassRegistry.h"
-#include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/TargetRegistry.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Target/TargetMachine.h"
-
-#include 
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Vectorize.h"
 
 using namespace llvm;
 
+// Helper function to parse command line args and find the optimization level
 static void getOptLevel(const std::vector &ExtraArgs,
   CodeGenOpt::Level &OLvl) {
   // Find the optimization level from the command line args
@@ -53,59 +68,111 @@
   }
 }
 
-void clang_fuzzer::HandleLLVM(const std::string &S,
-  const std::vector &ExtraArgs) {
-  // Parse ExtraArgs to set the optimization level
-  CodeGenOpt::Level OLvl;
-  getOptLevel(ExtraArgs, OLvl);
+void ErrorAndExit(std::string message) {
+  errs()<< "ERROR: " << message << "\n";
+  std::exit(1);
+}
 
-  // Set the Module to include the the IR code to be compiled
-  SMDiagnostic Err;
+// Helper function to add optimization passes to the TargetMachine at the 
+// specified optimization level, OptLevel
+static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
+  CodeGenOpt::Level OptLevel,
+  unsigned SizeLevel) {
+  // Create and initialize a PassManagerBuilder
+  PassManagerBuilder Builder;
+  Builder.OptLevel = OptLevel;
+  Builder.SizeLevel = SizeLevel;
+  Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
+  Builder.LoopVectorize = true;
+  Builder.populateModulePassManager(MPM);
+}
 
+// Mimics the opt tool to run an optimization pass over the provided IR
+std::string OptLLVM(const std::string &IR, CodeGenOpt::Level OLvl) {
+  // Create a module that will run the optimization passes
+  SMDiagnostic Err;
   LLVMContext Context;
-  std::unique_ptr M = parseIR(MemoryBufferRef(S, "IR"), Err, Context);
-  if (!M) {
-errs() << "error: could not parse IR!\n";
-std::exit(1);
-  }
+  std::unique_ptr M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
+  if (!M || verifyModule(*M, &errs()))
+ErrorAndExit("Could not parse IR");
 
-  // Create a new Target
-  std::string Error;
-  const Target *TheTarget = TargetRegistry::lookupTarget(
-  sys::getDefaultTargetTriple(), Error);
-  if (!TheTarget) {
-errs() << Error;
-std::exit(1);
-  }
+  setFunctionAttributes(getCPUStr(), getFeaturesStr(), *M);
+  
+  legacy::PassManager Passes;
+  Triple ModuleTriple(M->getTargetTriple());
+  
+  Passes.add(new TargetLibraryInfoWrapperPass(ModuleTriple));
+  Passes.add(createTargetTransformInfoWrapperPass(TargetIRAnalysis()));
+  Passes.add(createVerifierPass());
 
-  TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
-
-  // Create a new Machine
-  std:

[PATCH] D49114: [clang-tidy] Add a check for "magic numbers"

2018-07-26 Thread Florin Iucha via Phabricator via cfe-commits
0x8000- marked 3 inline comments as done.
0x8000- added inline comments.



Comment at: docs/clang-tidy/checks/readability-magic-numbers.rst:55
+
+By default only `0`, `1` and `-1` integer values are accepted without a 
warning.
+This can be overridden with the :option:`IgnoredIntegerValues` option.  In 
addition,

JonasToth wrote:
> -1 is not in the default list anymore.
I will update the comment. -1 is still accepted because it is (unary operator) 
- followed by accepted (integer literal) 1.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49114



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


[PATCH] D36357: Added a better diagnostic when using the delete operator with lambdas

2018-07-26 Thread Nicolas Lesser via Phabricator via cfe-commits
Rakete updated this revision to Diff 157611.
Rakete added a comment.

Rebased + friendly ping


Repository:
  rC Clang

https://reviews.llvm.org/D36357

Files:
  include/clang/Basic/DiagnosticParseKinds.td
  lib/Parse/ParseExprCXX.cpp
  test/Parser/cxx0x-lambda-expressions.cpp
  test/SemaCXX/new-delete-0x.cpp


Index: test/SemaCXX/new-delete-0x.cpp
===
--- test/SemaCXX/new-delete-0x.cpp
+++ test/SemaCXX/new-delete-0x.cpp
@@ -34,6 +34,6 @@
 void bad_deletes()
 {
   // 'delete []' is always array delete, per [expr.delete]p1.
-  // FIXME: Give a better diagnostic.
-  delete []{ return (int*)0; }(); // expected-error {{expected expression}}
+  delete []{ return (int*)0; }(); // expected-error {{'[]' after delete 
interpreted as 'delete[]'}}
 }
+
Index: test/Parser/cxx0x-lambda-expressions.cpp
===
--- test/Parser/cxx0x-lambda-expressions.cpp
+++ test/Parser/cxx0x-lambda-expressions.cpp
@@ -53,7 +53,7 @@
   void delete_lambda(int *p) {
 delete [] p;
 delete [] (int*) { new int }; // ok, compound-literal, not lambda
-delete [] { return new int; } (); // expected-error{{expected expression}}
+delete [] { return new int; } (); // expected-error {{'[]' after delete 
interpreted as 'delete[]'}}
 delete [&] { return new int; } (); // ok, lambda
   }
 
Index: lib/Parse/ParseExprCXX.cpp
===
--- lib/Parse/ParseExprCXX.cpp
+++ lib/Parse/ParseExprCXX.cpp
@@ -2946,15 +2946,44 @@
 //   [Footnote: A lambda expression with a lambda-introducer that consists
 //  of empty square brackets can follow the delete keyword if
 //  the lambda expression is enclosed in parentheses.]
-// FIXME: Produce a better diagnostic if the '[]' is unambiguously a
-//lambda-introducer.
-ArrayDelete = true;
-BalancedDelimiterTracker T(*this, tok::l_square);
 
-T.consumeOpen();
-T.consumeClose();
-if (T.getCloseLocation().isInvalid())
-  return ExprError();
+const Token Next = GetLookAheadToken(2);
+
+// Basic lookahead to check if we have a lambda expression.
+if (Next.isOneOf(tok::l_brace, tok::less) ||
+(Next.is(tok::l_paren) &&
+ GetLookAheadToken(3).isOneOf(tok::r_paren, tok::identifier) &&
+ GetLookAheadToken(4).is(tok::identifier))) {
+  SourceLocation RightBracketLock = NextToken().getLocation();
+  // Warn if the non-capturing lambda isn't surrounded by parenthesis
+  // to disambiguate it from 'delete[]'.
+  ExprResult Lambda = ParseLambdaExpression();
+  if (Lambda.isInvalid())
+return ExprError();
+
+  SourceLocation StartLoc = Lambda.get()->getLocStart();
+  Diag(Start, diag::err_lambda_after_delete)
+  << SourceRange(Start, RightBracketLock)
+  << FixItHint::CreateInsertion(StartLoc, "(")
+  << FixItHint::CreateInsertion(
+ Lexer::getLocForEndOfToken(Lambda.get()->getLocEnd(), 1,
+Actions.getSourceManager(),
+getLangOpts()),
+ ")");
+
+  // Evaluate any postfix expressions used on the lambda.
+  Lambda = ParsePostfixExpressionSuffix(Lambda);
+  return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
+Lambda.get());
+} else {
+  ArrayDelete = true;
+  BalancedDelimiterTracker T(*this, tok::l_square);
+
+  T.consumeOpen();
+  T.consumeClose();
+  if (T.getCloseLocation().isInvalid())
+return ExprError();
+}
   }
 
   ExprResult Operand(ParseCastExpression(false));
Index: include/clang/Basic/DiagnosticParseKinds.td
===
--- include/clang/Basic/DiagnosticParseKinds.td
+++ include/clang/Basic/DiagnosticParseKinds.td
@@ -99,6 +99,8 @@
   InGroup, DefaultIgnore;
 def ext_alignof_expr : ExtWarn<
   "%0 applied to an expression is a GNU extension">, 
InGroup;
+def err_lambda_after_delete : Error<
+  "'[]' after delete interpreted as 'delete[]'">;
 
 def warn_microsoft_dependent_exists : Warning<
   "dependent %select{__if_not_exists|__if_exists}0 declarations are ignored">, 


Index: test/SemaCXX/new-delete-0x.cpp
===
--- test/SemaCXX/new-delete-0x.cpp
+++ test/SemaCXX/new-delete-0x.cpp
@@ -34,6 +34,6 @@
 void bad_deletes()
 {
   // 'delete []' is always array delete, per [expr.delete]p1.
-  // FIXME: Give a better diagnostic.
-  delete []{ return (int*)0; }(); // expected-error {{expected expression}}
+  delete []{ return (int*)0; }(); // expected-error {{'[]' after delete interpreted as 'delete[]'}}
 }
+
Index: test/Parser/cxx0x-lambda-expressions.cpp
===
--- 

[PATCH] D49890: Clang-Tidy Export Problem

2018-07-26 Thread Ahmad Nouralizadeh via Phabricator via cfe-commits
TheAhmad created this revision.
TheAhmad added a reviewer: alexfh.
TheAhmad added a project: clang-tools-extra.

Hi.
Clang tidy has problem with compile command databases that do not use 
necassarily absolute file paths. This is common in many projects that use 
makefiles as the build system, whose databases are usually generated using 
Bear. Therefore, I reused some of the code of the in-place fix and revised it 
to generate a YAML export file. The diff is OK, except that the merge conflicts 
are not added, right now.
Thanks!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49890

Files:
  ClangTidy.cpp


Index: ClangTidy.cpp
===
--- ClangTidy.cpp
+++ ClangTidy.cpp
@@ -608,8 +608,58 @@
 raw_ostream &OS) {
   TranslationUnitDiagnostics TUD;
   TUD.MainSourceFile = MainFilePath;
-  for (const auto &Error : Errors) {
-tooling::Diagnostic Diag = Error;
+
+  FileManager *Files = new FileManager(FileSystemOptions());
+  vfs::FileSystem &FileSystem = *Files->getVirtualFileSystem();
+  auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
+  if (!InitialWorkingDir)
+llvm::report_fatal_error("Cannot get current working path.");
+
+  llvm::StringMap FileReplacements;
+  llvm::StringMap SingleErrors;
+  for (const ClangTidyError &Error : Errors) {
+if (!Error.BuildDirectory.empty()) {
+  FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
+}
+
+SmallString<128> ErrorAbsoluteFilePath = (StringRef)Error.Message.FilePath;
+Files->makeAbsolutePath(ErrorAbsoluteFilePath);
+if (SingleErrors.find(ErrorAbsoluteFilePath) == SingleErrors.end())
+{
+  ClangTidyError AbsoluteError = Error;
+  AbsoluteError.Message.FilePath = ErrorAbsoluteFilePath.str();
+  AbsoluteError.Fix.clear();
+  
SingleErrors.insert(std::pair(ErrorAbsoluteFilePath, 
AbsoluteError));
+}
+   
+for (const auto &FileAndReplacements : Error.Fix) {
+  for (const auto &Repl : FileAndReplacements.second) {
+SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
+Files->makeAbsolutePath(FixAbsoluteFilePath);
+
+tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
+ Repl.getLength(),
+ Repl.getReplacementText());
+
+FileReplacements[R.getFilePath()].add(R);
+  }
+}
+
+FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
+  }
+
+  for (const auto &FileAndReplacements : FileReplacements) {
+StringRef File = FileAndReplacements.first();
+Replacements Repls = FileAndReplacements.second;
+
+ClangTidyError  AbsoluteError = SingleErrors.find(File)->second;   
+if (SingleErrors.find(File) == SingleErrors.end())
+{
+  llvm::report_fatal_error("Cannot find the containing ClangTidyError.");
+}
+AbsoluteError.Fix.insert(std::pair(File,Repls));
+
+tooling::Diagnostic Diag = AbsoluteError;
 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
   }
 


Index: ClangTidy.cpp
===
--- ClangTidy.cpp
+++ ClangTidy.cpp
@@ -608,8 +608,58 @@
 raw_ostream &OS) {
   TranslationUnitDiagnostics TUD;
   TUD.MainSourceFile = MainFilePath;
-  for (const auto &Error : Errors) {
-tooling::Diagnostic Diag = Error;
+
+  FileManager *Files = new FileManager(FileSystemOptions());
+  vfs::FileSystem &FileSystem = *Files->getVirtualFileSystem();
+  auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
+  if (!InitialWorkingDir)
+llvm::report_fatal_error("Cannot get current working path.");
+
+  llvm::StringMap FileReplacements;
+  llvm::StringMap SingleErrors;
+  for (const ClangTidyError &Error : Errors) {
+if (!Error.BuildDirectory.empty()) {
+  FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
+}
+
+SmallString<128> ErrorAbsoluteFilePath = (StringRef)Error.Message.FilePath;
+Files->makeAbsolutePath(ErrorAbsoluteFilePath);
+if (SingleErrors.find(ErrorAbsoluteFilePath) == SingleErrors.end())
+{
+  ClangTidyError AbsoluteError = Error;
+  AbsoluteError.Message.FilePath = ErrorAbsoluteFilePath.str();
+  AbsoluteError.Fix.clear();
+  SingleErrors.insert(std::pair(ErrorAbsoluteFilePath, AbsoluteError));
+}
+	
+for (const auto &FileAndReplacements : Error.Fix) {
+  for (const auto &Repl : FileAndReplacements.second) {
+SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
+Files->makeAbsolutePath(FixAbsoluteFilePath);
+
+tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
+		  Repl.getLength(),
+		  Repl.getReplacementText());
+
+FileReplacements[R.getFilePath()].add(R);
+  }
+}
+
+FileSystem.setCurrentWorkingDirectory(Init

[PATCH] D49885: Thread safety analysis: Allow relockable scopes

2018-07-26 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

Imagine having a producer loop, where we check a loop condition while holding a 
mutex, but release it in the loop body to let other producers/consumers do 
their work. In that scenario it makes sense to allow "relocking" a scope.

  RelockableScope Scope(mu);
  while (WorkToDo()) {
  Scope.Unlock();
  // Produce something...
  Scope.Lock();
  PublishWork();
  }




Comment at: lib/Analysis/ThreadSafety.cpp:960-961
+FSet.removeLock(FactMan, !UnderCp);
+FSet.addLock(FactMan, llvm::make_unique(UnderCp, LK,
+   RelockLoc));
+  }

Looks a bit weird, but `clang-format` told me to do that.



Comment at: lib/Analysis/ThreadSafety.cpp:1318-1321
+// FIXME: It's possible to manually destruct the scope and then relock it.
+// Should that be a separate warning? For now we pretend nothing happened.
+// It's undefined behavior, so not related to thread safety.
+return;

Not sure about this part, but it's probably not worth worrying about. A user 
would have to call a member function on a scoped object after manually ending 
its lifetime by calling the destructor, see test 
`RelockableScopedLock::destructLock`.



Comment at: lib/Analysis/ThreadSafety.cpp:1324-1325
+
+  // We should only land here if Cp is a scoped capability, so if we have any
+  // fact, it must be a ScopedLockableFactEntry.
+  auto SLDat = static_cast(LDat);

I hope this reasoning is sufficient to justify the following static_cast, 
otherwise I need to introduce LLVM-style RTTI into `FactEntry`.


Repository:
  rC Clang

https://reviews.llvm.org/D49885



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


[PATCH] D49868: [Sema] Fix a crash by completing a type before using it

2018-07-26 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC338089: [Sema] Fix a crash by completing a type before using 
it (authored by epilk, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D49868?vs=157575&id=157606#toc

Repository:
  rC Clang

https://reviews.llvm.org/D49868

Files:
  lib/Sema/SemaInit.cpp
  test/SemaCXX/cxx1z-class-template-argument-deduction.cpp


Index: lib/Sema/SemaInit.cpp
===
--- lib/Sema/SemaInit.cpp
+++ lib/Sema/SemaInit.cpp
@@ -9130,6 +9130,7 @@
   Expr *E = ListInit->getInit(0);
   auto *RD = E->getType()->getAsCXXRecordDecl();
   if (!isa(E) && RD &&
+  isCompleteType(Kind.getLocation(), E->getType()) &&
   isOrIsDerivedFromSpecializationOf(RD, Template))
 TryListConstructors = false;
 }
Index: test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
===
--- test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
+++ test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
@@ -348,6 +348,31 @@
   };
 }
 
+namespace rdar41903969 {
+template  struct A {};
+template  struct B;
+template  struct C {
+  C(A&);
+  C(B&);
+};
+
+void foo(A &a, B &b) {
+  (void)C{b};
+  (void)C{a};
+}
+
+template struct X {
+  X(std::initializer_list) = delete;
+  X(const X&);
+};
+
+template  struct D : X {};
+
+void bar(D& d) {
+  (void)X{d};
+}
+}
+
 #else
 
 // expected-no-diagnostics


Index: lib/Sema/SemaInit.cpp
===
--- lib/Sema/SemaInit.cpp
+++ lib/Sema/SemaInit.cpp
@@ -9130,6 +9130,7 @@
   Expr *E = ListInit->getInit(0);
   auto *RD = E->getType()->getAsCXXRecordDecl();
   if (!isa(E) && RD &&
+  isCompleteType(Kind.getLocation(), E->getType()) &&
   isOrIsDerivedFromSpecializationOf(RD, Template))
 TryListConstructors = false;
 }
Index: test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
===
--- test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
+++ test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
@@ -348,6 +348,31 @@
   };
 }
 
+namespace rdar41903969 {
+template  struct A {};
+template  struct B;
+template  struct C {
+  C(A&);
+  C(B&);
+};
+
+void foo(A &a, B &b) {
+  (void)C{b};
+  (void)C{a};
+}
+
+template struct X {
+  X(std::initializer_list) = delete;
+  X(const X&);
+};
+
+template  struct D : X {};
+
+void bar(D& d) {
+  (void)X{d};
+}
+}
+
 #else
 
 // expected-no-diagnostics
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338089 - [Sema] Fix a crash by completing a type before using it

2018-07-26 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Thu Jul 26 16:40:42 2018
New Revision: 338089

URL: http://llvm.org/viewvc/llvm-project?rev=338089&view=rev
Log:
[Sema] Fix a crash by completing a type before using it

Only apply this exception on a type that we're able to check.

rdar://41903969

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

Modified:
cfe/trunk/lib/Sema/SemaInit.cpp
cfe/trunk/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp

Modified: cfe/trunk/lib/Sema/SemaInit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaInit.cpp?rev=338089&r1=338088&r2=338089&view=diff
==
--- cfe/trunk/lib/Sema/SemaInit.cpp (original)
+++ cfe/trunk/lib/Sema/SemaInit.cpp Thu Jul 26 16:40:42 2018
@@ -9130,6 +9130,7 @@ QualType Sema::DeduceTemplateSpecializat
   Expr *E = ListInit->getInit(0);
   auto *RD = E->getType()->getAsCXXRecordDecl();
   if (!isa(E) && RD &&
+  isCompleteType(Kind.getLocation(), E->getType()) &&
   isOrIsDerivedFromSpecializationOf(RD, Template))
 TryListConstructors = false;
 }

Modified: cfe/trunk/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp?rev=338089&r1=338088&r2=338089&view=diff
==
--- cfe/trunk/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp 
(original)
+++ cfe/trunk/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp Thu Jul 
26 16:40:42 2018
@@ -348,6 +348,31 @@ namespace member_guides {
   };
 }
 
+namespace rdar41903969 {
+template  struct A {};
+template  struct B;
+template  struct C {
+  C(A&);
+  C(B&);
+};
+
+void foo(A &a, B &b) {
+  (void)C{b};
+  (void)C{a};
+}
+
+template struct X {
+  X(std::initializer_list) = delete;
+  X(const X&);
+};
+
+template  struct D : X {};
+
+void bar(D& d) {
+  (void)X{d};
+}
+}
+
 #else
 
 // expected-no-diagnostics


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


r338087 - [WWW] Removing my test file as the auto-deployment script has been fixed.

2018-07-26 Thread Mike Edwards via cfe-commits
Author: sqlbyme
Date: Thu Jul 26 16:29:54 2018
New Revision: 338087

URL: http://llvm.org/viewvc/llvm-project?rev=338087&view=rev
Log:
[WWW] Removing my test file as the auto-deployment script has been fixed.

Removed:
cfe/trunk/www/test.html

Removed: cfe/trunk/www/test.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/www/test.html?rev=338086&view=auto
==
--- cfe/trunk/www/test.html (original)
+++ cfe/trunk/www/test.html (removed)
@@ -1,6 +0,0 @@
-
-
-
-Hello World!
-
-


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


r338086 - [WWW] Adding a test page to work out an auto-deployment issue.

2018-07-26 Thread Mike Edwards via cfe-commits
Author: sqlbyme
Date: Thu Jul 26 16:23:40 2018
New Revision: 338086

URL: http://llvm.org/viewvc/llvm-project?rev=338086&view=rev
Log:
[WWW] Adding a test page to work out an auto-deployment issue.

Added:
cfe/trunk/www/test.html

Added: cfe/trunk/www/test.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/www/test.html?rev=338086&view=auto
==
--- cfe/trunk/www/test.html (added)
+++ cfe/trunk/www/test.html Thu Jul 26 16:23:40 2018
@@ -0,0 +1,6 @@
+
+
+
+Hello World!
+
+


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


Re: r338057 - [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name

2018-07-26 Thread Reid Kleckner via cfe-commits
I reverted this in r338084 because it broke clang tests on Windows:
http://lab.llvm.org:8011/builders/clang-x86-windows-msvc2015/builds/12916

On Thu, Jul 26, 2018 at 11:55 AM Simon Marchi via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: simark
> Date: Thu Jul 26 11:55:02 2018
> New Revision: 338057
>
> URL: http://llvm.org/viewvc/llvm-project?rev=338057&view=rev
> Log:
> [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the
> requested name
>
> Summary:
>
> InMemoryFileSystem::status behaves differently than
> RealFileSystem::status.  The Name contained in the Status returned by
> RealFileSystem::status will be the path as requested by the caller,
> whereas InMemoryFileSystem::status returns the normalized path.
>
> For example, when requested the status for "../src/first.h",
> RealFileSystem returns a Status with "../src/first.h" as the Name.
> InMemoryFileSystem returns "/absolute/path/to/src/first.h".
>
> The reason for this change is that I want to make a unit test in the
> clangd testsuite (where we use an InMemoryFileSystem) to reproduce a
> bug I get with the clangd program (where a RealFileSystem is used).
> This difference in behavior "hides" the bug in the unit test version.
>
> Reviewers: malaperle, ilya-biryukov, bkramer
>
> Subscribers: cfe-commits, ioeric, ilya-biryukov, bkramer, hokein, omtcyfz
>
> Differential Revision: https://reviews.llvm.org/D48903
>
> Modified:
> cfe/trunk/lib/Basic/FileManager.cpp
> cfe/trunk/lib/Basic/VirtualFileSystem.cpp
> cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp
> cfe/trunk/unittests/Driver/ToolChainTest.cpp
>
> Modified: cfe/trunk/lib/Basic/FileManager.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/FileManager.cpp?rev=338057&r1=338056&r2=338057&view=diff
>
> ==
> --- cfe/trunk/lib/Basic/FileManager.cpp (original)
> +++ cfe/trunk/lib/Basic/FileManager.cpp Thu Jul 26 11:55:02 2018
> @@ -315,9 +315,11 @@ const FileEntry *FileManager::getFile(St
>UFE.InPCH = Data.InPCH;
>UFE.File = std::move(F);
>UFE.IsValid = true;
> -  if (UFE.File)
> -if (auto RealPathName = UFE.File->getName())
> -  UFE.RealPathName = *RealPathName;
> +
> +  SmallString<128> RealPathName;
> +  if (!FS->getRealPath(InterndFileName, RealPathName))
> +UFE.RealPathName = RealPathName.str();
> +
>return &UFE;
>  }
>
>
> Modified: cfe/trunk/lib/Basic/VirtualFileSystem.cpp
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/VirtualFileSystem.cpp?rev=338057&r1=338056&r2=338057&view=diff
>
> ==
> --- cfe/trunk/lib/Basic/VirtualFileSystem.cpp (original)
> +++ cfe/trunk/lib/Basic/VirtualFileSystem.cpp Thu Jul 26 11:55:02 2018
> @@ -474,12 +474,28 @@ class InMemoryNode {
>Status Stat;
>InMemoryNodeKind Kind;
>
> +protected:
> +  /// Return Stat.  This should only be used for internal/debugging use.
> When
> +  /// clients wants the Status of this node, they should use
> +  /// \p getStatus(StringRef).
> +  const Status &getStatus() const { return Stat; }
> +
>  public:
>InMemoryNode(Status Stat, InMemoryNodeKind Kind)
>: Stat(std::move(Stat)), Kind(Kind) {}
>virtual ~InMemoryNode() = default;
>
> -  const Status &getStatus() const { return Stat; }
> +  /// Return the \p Status for this node. \p RequestedName should be the
> name
> +  /// through which the caller referred to this node. It will override
> +  /// \p Status::Name in the return value, to mimic the behavior of \p
> RealFile.
> +  Status getStatus(StringRef RequestedName) const {
> +return Status::copyWithNewName(Stat, RequestedName);
> +  }
> +
> +  /// Get the filename of this node (the name without the directory part).
> +  StringRef getFileName() const {
> +return llvm::sys::path::filename(Stat.getName());
> +  }
>InMemoryNodeKind getKind() const { return Kind; }
>virtual std::string toString(unsigned Indent) const = 0;
>  };
> @@ -504,14 +520,21 @@ public:
>}
>  };
>
> -/// Adapt a InMemoryFile for VFS' File interface.
> +/// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
> +/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
> +/// \p RealFile.
>  class InMemoryFileAdaptor : public File {
>InMemoryFile &Node;
> +  /// The name to use when returning a Status for this file.
> +  std::string RequestedName;
>
>  public:
> -  explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
> +  explicit InMemoryFileAdaptor(InMemoryFile &Node, std::string
> RequestedName)
> +  : Node(Node), RequestedName(std::move(RequestedName)) {}
>
> -  llvm::ErrorOr status() override { return Node.getStatus(); }
> +  llvm::ErrorOr status() override {
> +return Node.getStatus(RequestedName);
> +  }
>
>llvm::ErrorOr>
>getBuffer(const Twine &Name, int64_t FileSize, bool
> RequiresNullTerminator

r338084 - Revert r338057 "[VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name"

2018-07-26 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Thu Jul 26 16:21:51 2018
New Revision: 338084

URL: http://llvm.org/viewvc/llvm-project?rev=338084&view=rev
Log:
Revert r338057 "[VirtualFileSystem] InMemoryFileSystem::status: Return a Status 
with the requested name"

This broke clang/test/PCH/case-insensitive-include.c on Windows.

Modified:
cfe/trunk/lib/Basic/FileManager.cpp
cfe/trunk/lib/Basic/VirtualFileSystem.cpp
cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp
cfe/trunk/unittests/Driver/ToolChainTest.cpp

Modified: cfe/trunk/lib/Basic/FileManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/FileManager.cpp?rev=338084&r1=338083&r2=338084&view=diff
==
--- cfe/trunk/lib/Basic/FileManager.cpp (original)
+++ cfe/trunk/lib/Basic/FileManager.cpp Thu Jul 26 16:21:51 2018
@@ -315,11 +315,9 @@ const FileEntry *FileManager::getFile(St
   UFE.InPCH = Data.InPCH;
   UFE.File = std::move(F);
   UFE.IsValid = true;
-
-  SmallString<128> RealPathName;
-  if (!FS->getRealPath(InterndFileName, RealPathName))
-UFE.RealPathName = RealPathName.str();
-
+  if (UFE.File)
+if (auto RealPathName = UFE.File->getName())
+  UFE.RealPathName = *RealPathName;
   return &UFE;
 }
 

Modified: cfe/trunk/lib/Basic/VirtualFileSystem.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/VirtualFileSystem.cpp?rev=338084&r1=338083&r2=338084&view=diff
==
--- cfe/trunk/lib/Basic/VirtualFileSystem.cpp (original)
+++ cfe/trunk/lib/Basic/VirtualFileSystem.cpp Thu Jul 26 16:21:51 2018
@@ -474,28 +474,12 @@ class InMemoryNode {
   Status Stat;
   InMemoryNodeKind Kind;
 
-protected:
-  /// Return Stat.  This should only be used for internal/debugging use.  When
-  /// clients wants the Status of this node, they should use
-  /// \p getStatus(StringRef).
-  const Status &getStatus() const { return Stat; }
-
 public:
   InMemoryNode(Status Stat, InMemoryNodeKind Kind)
   : Stat(std::move(Stat)), Kind(Kind) {}
   virtual ~InMemoryNode() = default;
 
-  /// Return the \p Status for this node. \p RequestedName should be the name
-  /// through which the caller referred to this node. It will override
-  /// \p Status::Name in the return value, to mimic the behavior of \p 
RealFile.
-  Status getStatus(StringRef RequestedName) const {
-return Status::copyWithNewName(Stat, RequestedName);
-  }
-
-  /// Get the filename of this node (the name without the directory part).
-  StringRef getFileName() const {
-return llvm::sys::path::filename(Stat.getName());
-  }
+  const Status &getStatus() const { return Stat; }
   InMemoryNodeKind getKind() const { return Kind; }
   virtual std::string toString(unsigned Indent) const = 0;
 };
@@ -520,21 +504,14 @@ public:
   }
 };
 
-/// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
-/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
-/// \p RealFile.
+/// Adapt a InMemoryFile for VFS' File interface.
 class InMemoryFileAdaptor : public File {
   InMemoryFile &Node;
-  /// The name to use when returning a Status for this file.
-  std::string RequestedName;
 
 public:
-  explicit InMemoryFileAdaptor(InMemoryFile &Node, std::string RequestedName)
-  : Node(Node), RequestedName(std::move(RequestedName)) {}
+  explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
 
-  llvm::ErrorOr status() override {
-return Node.getStatus(RequestedName);
-  }
+  llvm::ErrorOr status() override { return Node.getStatus(); }
 
   llvm::ErrorOr>
   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
@@ -734,7 +711,7 @@ lookupInMemoryNode(const InMemoryFileSys
 llvm::ErrorOr InMemoryFileSystem::status(const Twine &Path) {
   auto Node = lookupInMemoryNode(*this, Root.get(), Path);
   if (Node)
-return (*Node)->getStatus(Path.str());
+return (*Node)->getStatus();
   return Node.getError();
 }
 
@@ -747,8 +724,7 @@ InMemoryFileSystem::openFileForRead(cons
   // When we have a file provide a heap-allocated wrapper for the memory buffer
   // to match the ownership semantics for File.
   if (auto *F = dyn_cast(*Node))
-return std::unique_ptr(
-new detail::InMemoryFileAdaptor(*F, Path.str()));
+return std::unique_ptr(new detail::InMemoryFileAdaptor(*F));
 
   // FIXME: errc::not_a_file?
   return make_error_code(llvm::errc::invalid_argument);
@@ -760,33 +736,21 @@ namespace {
 class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
   detail::InMemoryDirectory::const_iterator I;
   detail::InMemoryDirectory::const_iterator E;
-  std::string RequestedDirName;
-
-  void setCurrentEntry() {
-if (I != E) {
-  SmallString<256> Path(RequestedDirName);
-  llvm::sys::path::append(Path, I->second->getFileName());
-  CurrentEntry = I->second->getStatus(Path);
-} else {
-  // When we're at the end, make CurrentEntry invalid 

r338083 - [MS] Add L__FUNCSIG__ for compatibility

2018-07-26 Thread Reid Kleckner via cfe-commits
Author: rnk
Date: Thu Jul 26 16:18:44 2018
New Revision: 338083

URL: http://llvm.org/viewvc/llvm-project?rev=338083&view=rev
Log:
[MS] Add L__FUNCSIG__ for compatibility

Clang already has L__FUNCTION__ as a workaround for dealing with
pre-processor code that expects to be able to do L##__FUNCTION__ in a
macro. This patch implements the same logic for __FUNCSIG__.

Fixes PR38295.

Modified:
cfe/trunk/include/clang/AST/Expr.h
cfe/trunk/include/clang/Basic/TokenKinds.def
cfe/trunk/lib/AST/Expr.cpp
cfe/trunk/lib/Parse/ParseExpr.cpp
cfe/trunk/lib/Parse/ParseTentative.cpp
cfe/trunk/lib/Sema/SemaExpr.cpp
cfe/trunk/test/Sema/ms_wide_predefined_expr.cpp

Modified: cfe/trunk/include/clang/AST/Expr.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Expr.h?rev=338083&r1=338082&r2=338083&view=diff
==
--- cfe/trunk/include/clang/AST/Expr.h (original)
+++ cfe/trunk/include/clang/AST/Expr.h Thu Jul 26 16:18:44 2018
@@ -1206,9 +1206,10 @@ public:
   enum IdentType {
 Func,
 Function,
-LFunction,  // Same as Function, but as wide string.
+LFunction, // Same as Function, but as wide string.
 FuncDName,
 FuncSig,
+LFuncSig, // Same as FuncSig, but as as wide string
 PrettyFunction,
 /// The same as PrettyFunction, except that the
 /// 'virtual' keyword is omitted for virtual member functions.

Modified: cfe/trunk/include/clang/Basic/TokenKinds.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/TokenKinds.def?rev=338083&r1=338082&r2=338083&view=diff
==
--- cfe/trunk/include/clang/Basic/TokenKinds.def (original)
+++ cfe/trunk/include/clang/Basic/TokenKinds.def Thu Jul 26 16:18:44 2018
@@ -425,6 +425,7 @@ KEYWORD(typeof  , KE
 KEYWORD(__FUNCDNAME__   , KEYMS)
 KEYWORD(__FUNCSIG__ , KEYMS)
 KEYWORD(L__FUNCTION__   , KEYMS)
+KEYWORD(L__FUNCSIG__, KEYMS)
 TYPE_TRAIT_1(__is_interface_class, IsInterfaceClass, KEYMS)
 TYPE_TRAIT_1(__is_sealed, IsSealed, KEYMS)
 

Modified: cfe/trunk/lib/AST/Expr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Expr.cpp?rev=338083&r1=338082&r2=338083&view=diff
==
--- cfe/trunk/lib/AST/Expr.cpp (original)
+++ cfe/trunk/lib/AST/Expr.cpp Thu Jul 26 16:18:44 2018
@@ -484,6 +484,8 @@ StringRef PredefinedExpr::getIdentTypeNa
 return "__PRETTY_FUNCTION__";
   case FuncSig:
 return "__FUNCSIG__";
+  case LFuncSig:
+return "L__FUNCSIG__";
   case PrettyFunctionNoVirtual:
 break;
   }
@@ -536,7 +538,8 @@ std::string PredefinedExpr::ComputeName(
 return Out.str();
   }
   if (const FunctionDecl *FD = dyn_cast(CurrentDecl)) {
-if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual && IT != FuncSig)
+if (IT != PrettyFunction && IT != PrettyFunctionNoVirtual &&
+IT != FuncSig && IT != LFuncSig)
   return FD->getNameAsString();
 
 SmallString<256> Name;
@@ -561,7 +564,7 @@ std::string PredefinedExpr::ComputeName(
 if (FD->hasWrittenPrototype())
   FT = dyn_cast(AFT);
 
-if (IT == FuncSig) {
+if (IT == FuncSig || IT == LFuncSig) {
   switch (AFT->getCallConv()) {
   case CC_C: POut << "__cdecl "; break;
   case CC_X86StdCall: POut << "__stdcall "; break;
@@ -586,7 +589,8 @@ std::string PredefinedExpr::ComputeName(
   if (FT->isVariadic()) {
 if (FD->getNumParams()) POut << ", ";
 POut << "...";
-  } else if ((IT == FuncSig || !Context.getLangOpts().CPlusPlus) &&
+  } else if ((IT == FuncSig || IT == LFuncSig ||
+  !Context.getLangOpts().CPlusPlus) &&
  !Decl->getNumParams()) {
 POut << "void";
   }

Modified: cfe/trunk/lib/Parse/ParseExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseExpr.cpp?rev=338083&r1=338082&r2=338083&view=diff
==
--- cfe/trunk/lib/Parse/ParseExpr.cpp (original)
+++ cfe/trunk/lib/Parse/ParseExpr.cpp Thu Jul 26 16:18:44 2018
@@ -617,6 +617,8 @@ class CastExpressionIdValidator : public
 /// [GNU]   '__FUNCTION__'
 /// [MS]'__FUNCDNAME__'
 /// [MS]'L__FUNCTION__'
+/// [MS]'__FUNCSIG__'
+/// [MS]'L__FUNCSIG__'
 /// [GNU]   '__PRETTY_FUNCTION__'
 /// [GNU]   '(' compound-statement ')'
 /// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
@@ -1061,6 +1063,7 @@ ExprResult Parser::ParseCastExpression(b
   case tok::kw___FUNCDNAME__:   // primary-expression: __FUNCDNAME__ [MS]
   case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
   case tok::kw_L__FUNCTION__:   // primary-expression: L__FUNCTION__ [MS]
+  case tok::kw_L__FUNCSIG__:// primary-expression: L__FUNCSIG__ [MS]
   

[PATCH] D49885: Thread safety analysis: Allow relockable scopes

2018-07-26 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert created this revision.
aaronpuchert added reviewers: delesley, aaron.ballman.
Herald added a subscriber: cfe-commits.

It's already allowed to prematurely release a scoped lock, now we also
allow relocking it again, possibly even in another mode.

Arguably the solution is not very elegant, but maybe that can only be
solved by comprehensive refactoring.


Repository:
  rC Clang

https://reviews.llvm.org/D49885

Files:
  lib/Analysis/ThreadSafety.cpp
  test/SemaCXX/warn-thread-safety-analysis.cpp

Index: test/SemaCXX/warn-thread-safety-analysis.cpp
===
--- test/SemaCXX/warn-thread-safety-analysis.cpp
+++ test/SemaCXX/warn-thread-safety-analysis.cpp
@@ -2621,6 +2621,154 @@
 } // end namespace ReleasableScopedLock
 
 
+namespace RelockableScopedLock {
+
+class SCOPED_LOCKABLE RelockableExclusiveMutexLock {
+public:
+  RelockableExclusiveMutexLock(Mutex *mu) EXCLUSIVE_LOCK_FUNCTION(mu);
+  ~RelockableExclusiveMutexLock() EXCLUSIVE_UNLOCK_FUNCTION();
+
+  void Lock() EXCLUSIVE_LOCK_FUNCTION();
+  void Unlock() UNLOCK_FUNCTION();
+};
+
+class SCOPED_LOCKABLE RelockableSharedMutexLock {
+public:
+  RelockableSharedMutexLock(Mutex *mu) SHARED_LOCK_FUNCTION(mu);
+  ~RelockableSharedMutexLock() UNLOCK_FUNCTION();
+
+  void Lock() SHARED_LOCK_FUNCTION();
+  void Unlock() UNLOCK_FUNCTION();
+};
+
+class SharedTraits {};
+class ExclusiveTraits {};
+
+class SCOPED_LOCKABLE RelockableMutexLock {
+public:
+  RelockableMutexLock(Mutex *mu, SharedTraits) SHARED_LOCK_FUNCTION(mu);
+  RelockableMutexLock(Mutex *mu, ExclusiveTraits) EXCLUSIVE_LOCK_FUNCTION(mu);
+  ~RelockableMutexLock() UNLOCK_FUNCTION();
+
+  void Lock() EXCLUSIVE_LOCK_FUNCTION();
+  void Unlock() UNLOCK_FUNCTION();
+
+  void ReaderLock() SHARED_LOCK_FUNCTION();
+  void ReaderUnlock() UNLOCK_FUNCTION();
+
+  void PromoteShared() UNLOCK_FUNCTION() EXCLUSIVE_LOCK_FUNCTION();
+  void DemoteExclusive() UNLOCK_FUNCTION() SHARED_LOCK_FUNCTION();
+};
+
+Mutex mu;
+int x GUARDED_BY(mu);
+
+void print(int);
+
+void write() {
+  RelockableExclusiveMutexLock scope(&mu);
+  x = 2;
+  scope.Unlock();
+
+  x = 3; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+
+  scope.Lock();
+  x = 4;
+}
+
+void read() {
+  RelockableSharedMutexLock scope(&mu);
+  print(x);
+  scope.Unlock();
+
+  print(x); // expected-warning {{reading variable 'x' requires holding mutex 'mu'}}
+  x = 3; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+
+  scope.Lock();
+  print(x);
+  x = 4; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+}
+
+void relockExclusive() {
+  RelockableMutexLock scope(&mu, SharedTraits{});
+  print(x);
+  x = 2; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+  scope.ReaderUnlock();
+
+  print(x); // expected-warning {{reading variable 'x' requires holding mutex 'mu'}}
+
+  scope.Lock();
+  print(x);
+  x = 4;
+
+  scope.DemoteExclusive();
+  print(x);
+  x = 5; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+}
+
+void relockShared() {
+  RelockableMutexLock scope(&mu, ExclusiveTraits{});
+  print(x);
+  x = 2;
+  scope.Unlock();
+
+  print(x); // expected-warning {{reading variable 'x' requires holding mutex 'mu'}}
+
+  scope.ReaderLock();
+  print(x);
+  x = 4; // expected-warning {{writing variable 'x' requires holding mutex 'mu' exclusively}}
+
+  scope.PromoteShared();
+  print(x);
+  x = 5;
+}
+
+void doubleUnlock1() {
+  RelockableExclusiveMutexLock scope(&mu);
+  scope.Unlock();
+  scope.Unlock(); // expected-warning {{releasing mutex 'mu' that was not held}}
+}
+
+void doubleUnlock2() {
+  RelockableSharedMutexLock scope(&mu);
+  scope.Unlock();
+  scope.Unlock(); // expected-warning {{releasing mutex 'mu' that was not held}}
+}
+
+void doubleLock1() {
+  RelockableExclusiveMutexLock scope(&mu);
+  scope.Lock(); // expected-warning {{acquiring mutex 'mu' that is already held}}
+}
+
+void doubleLock2() {
+  RelockableSharedMutexLock scope(&mu);
+  scope.Lock(); // expected-warning {{acquiring mutex 'mu' that is already held}}
+}
+
+void doubleLock3() {
+  RelockableExclusiveMutexLock scope(&mu);
+  scope.Unlock();
+  scope.Lock();
+  scope.Lock(); // expected-warning {{acquiring mutex 'mu' that is already held}}
+}
+
+void doubleLock4() {
+  RelockableSharedMutexLock scope(&mu);
+  scope.Unlock();
+  scope.Lock();
+  scope.Lock(); // expected-warning {{acquiring mutex 'mu' that is already held}}
+}
+
+// Doesn't make a lot of sense, just making sure there is no crash.
+void destructLock() {
+  RelockableExclusiveMutexLock scope(&mu);
+  scope.~RelockableExclusiveMutexLock();
+  scope.Lock(); // Maybe this should warn.
+} // expected-warning {{releasing mutex 'scope' that was not held}}
+
+} // end namespace RelockableScopedLock
+
+
 namespace TrylockFunctionTest {
 
 class Foo {
Index: lib/Analysis/Thread

[PATCH] D49868: [Sema] Fix a crash by completing a type before using it

2018-07-26 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

Thanks, LGTM.


https://reviews.llvm.org/D49868



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


r338077 - Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Emmett Neyman via cfe-commits
Author: emmettneyman
Date: Thu Jul 26 15:23:25 2018
New Revision: 338077

URL: http://llvm.org/viewvc/llvm-project?rev=338077&view=rev
Log:
Updated llvm-proto-fuzzer to execute the compiled code

Summary:
Made changes to the llvm-proto-fuzzer
- Added loop vectorizer optimization pass in order to have two IR versions
- Updated old fuzz target to handle two different IR versions
- Wrote code to execute both versions in memory

Reviewers: morehouse, kcc, alexshap

Reviewed By: morehouse

Subscribers: pcc, mgorny, cfe-commits, llvm-commits

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

Modified:
cfe/trunk/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
cfe/trunk/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp

Modified: cfe/trunk/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp?rev=338077&r1=338076&r2=338077&view=diff
==
--- cfe/trunk/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp 
(original)
+++ cfe/trunk/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp Thu 
Jul 26 15:23:25 2018
@@ -16,10 +16,13 @@
 
 #include "fuzzer_initialize.h"
 
+#include "llvm/InitializePasses.h"
+#include "llvm/PassRegistry.h"
 #include "llvm/Support/TargetSelect.h"
 #include 
 
 using namespace clang_fuzzer;
+using namespace llvm;
 
 
 namespace clang_fuzzer {
@@ -33,10 +36,22 @@ const std::vector& GetCLAr
 }
 
 extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
-  llvm::InitializeAllTargets();
-  llvm::InitializeAllTargetMCs();
-  llvm::InitializeAllAsmPrinters();
-  llvm::InitializeAllAsmParsers();
+  InitializeAllTargets();
+  InitializeAllTargetMCs();
+  InitializeAllAsmPrinters();
+  InitializeAllAsmParsers();
+  
+  PassRegistry &Registry = *PassRegistry::getPassRegistry();
+  initializeCore(Registry);
+  initializeScalarOpts(Registry);
+  initializeVectorization(Registry);
+  initializeIPO(Registry);
+  initializeAnalysis(Registry);
+  initializeTransformUtils(Registry);
+  initializeInstCombine(Registry);
+  initializeAggressiveInstCombine(Registry);
+  initializeInstrumentation(Registry);
+  initializeTarget(Registry);
 
   CLArgs.push_back("-O2");
   for (int I = 1; I < *argc; I++) {

Modified: cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt?rev=338077&r1=338076&r2=338077&view=diff
==
--- cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt (original)
+++ cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt Thu Jul 26 15:23:25 
2018
@@ -1,10 +1,18 @@
 set(LLVM_LINK_COMPONENTS
+  CodeGen
   Core
+  ExecutionEngine
   IRReader
   MC
+  MCJIT
+  Object
+  RuntimeDyld
+  SelectionDAG
   Support
-  Analysis
-  )
+  Target
+  TransformUtils
+  native
+)
 
 # Depend on LLVM IR intrinsic generation.
 set(handle_llvm_deps intrinsics_gen)

Modified: cfe/trunk/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp?rev=338077&r1=338076&r2=338077&view=diff
==
--- cfe/trunk/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp (original)
+++ cfe/trunk/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp Thu Jul 26 
15:23:25 2018
@@ -7,8 +7,10 @@
 //
 
//===--===//
 //
-// Implements HandleLLVM for use by the Clang fuzzers. Mimics the llc tool to
-// compile an LLVM IR file to X86_64 assembly.
+// Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
+// vectorizer optimization pass over the given IR code. Then mimics lli on both
+// versions to JIT the generated code and execute it. Currently, functions are 
+// executed on dummy inputs.
 //
 
//===--===//
 
@@ -16,24 +18,37 @@
 
 #include "llvm/ADT/Triple.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/CodeGen/CommandFlags.inc"
 #include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/TargetPassConfig.h"
+#include "llvm/ExecutionEngine/JITEventListener.h"
+#include "llvm/ExecutionEngine/JITSymbol.h"
+#include "llvm/ExecutionEngine/MCJIT.h"
+#include "llvm/ExecutionEngine/ObjectCache.h"
+#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
+#include "llvm/ExecutionEngine/SectionMemoryManager.h"
+#include "llvm/IR/IRPrintingPasses.h"
 #include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/LegacyPassNameParser.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
 #include

[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL338077: Updated llvm-proto-fuzzer to execute the compiled 
code (authored by emmettneyman, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D49526?vs=157577&id=157591#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D49526

Files:
  cfe/trunk/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
  cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
  cfe/trunk/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp

Index: cfe/trunk/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
===
--- cfe/trunk/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
+++ cfe/trunk/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
@@ -16,10 +16,13 @@
 
 #include "fuzzer_initialize.h"
 
+#include "llvm/InitializePasses.h"
+#include "llvm/PassRegistry.h"
 #include "llvm/Support/TargetSelect.h"
 #include 
 
 using namespace clang_fuzzer;
+using namespace llvm;
 
 
 namespace clang_fuzzer {
@@ -33,10 +36,22 @@
 }
 
 extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
-  llvm::InitializeAllTargets();
-  llvm::InitializeAllTargetMCs();
-  llvm::InitializeAllAsmPrinters();
-  llvm::InitializeAllAsmParsers();
+  InitializeAllTargets();
+  InitializeAllTargetMCs();
+  InitializeAllAsmPrinters();
+  InitializeAllAsmParsers();
+  
+  PassRegistry &Registry = *PassRegistry::getPassRegistry();
+  initializeCore(Registry);
+  initializeScalarOpts(Registry);
+  initializeVectorization(Registry);
+  initializeIPO(Registry);
+  initializeAnalysis(Registry);
+  initializeTransformUtils(Registry);
+  initializeInstCombine(Registry);
+  initializeAggressiveInstCombine(Registry);
+  initializeInstrumentation(Registry);
+  initializeTarget(Registry);
 
   CLArgs.push_back("-O2");
   for (int I = 1; I < *argc; I++) {
Index: cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
===
--- cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
+++ cfe/trunk/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
@@ -1,10 +1,18 @@
 set(LLVM_LINK_COMPONENTS
+  CodeGen
   Core
+  ExecutionEngine
   IRReader
   MC
+  MCJIT
+  Object
+  RuntimeDyld
+  SelectionDAG
   Support
-  Analysis
-  )
+  Target
+  TransformUtils
+  native
+)
 
 # Depend on LLVM IR intrinsic generation.
 set(handle_llvm_deps intrinsics_gen)
Index: cfe/trunk/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
===
--- cfe/trunk/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
+++ cfe/trunk/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
@@ -7,33 +7,48 @@
 //
 //===--===//
 //
-// Implements HandleLLVM for use by the Clang fuzzers. Mimics the llc tool to
-// compile an LLVM IR file to X86_64 assembly.
+// Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
+// vectorizer optimization pass over the given IR code. Then mimics lli on both
+// versions to JIT the generated code and execute it. Currently, functions are 
+// executed on dummy inputs.
 //
 //===--===//
 
 #include "handle_llvm.h"
 
 #include "llvm/ADT/Triple.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/CodeGen/CommandFlags.inc"
 #include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/TargetPassConfig.h"
+#include "llvm/ExecutionEngine/JITEventListener.h"
+#include "llvm/ExecutionEngine/JITSymbol.h"
+#include "llvm/ExecutionEngine/MCJIT.h"
+#include "llvm/ExecutionEngine/ObjectCache.h"
+#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
+#include "llvm/ExecutionEngine/SectionMemoryManager.h"
+#include "llvm/IR/IRPrintingPasses.h"
 #include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/LegacyPassNameParser.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/Pass.h"
 #include "llvm/PassRegistry.h"
-#include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/TargetRegistry.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Target/TargetMachine.h"
-
-#include 
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Vectorize.h"
 
 using namespace llvm;
 
+// Helper function to parse command line args and find the optimization level
 static void getOptLevel(const std::vector &ExtraArgs,
   CodeGenOpt::Level &OLvl) {
   // Find the optimization level from the command line args
@@ -53,59 +68,111 @@
   }
 }
 
-void clang_fuzzer::HandleLLVM(const std::string &S,
-  const std::vector &Ext

[PATCH] D48958: [clang][ubsan] Implicit Cast Sanitizer - integer truncation - clang part

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 157585.
lebedev.ri added a comment.

Rebase,
Address @rsmith review notes - just inline https://reviews.llvm.org/D49844.


Repository:
  rC Clang

https://reviews.llvm.org/D48958

Files:
  docs/ReleaseNotes.rst
  docs/UndefinedBehaviorSanitizer.rst
  include/clang/Basic/Sanitizers.def
  include/clang/Basic/Sanitizers.h
  lib/CodeGen/CGExprScalar.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/Driver/SanitizerArgs.cpp
  lib/Driver/ToolChain.cpp
  test/CodeGen/catch-implicit-integer-truncations.c
  test/CodeGenCXX/catch-implicit-integer-truncations.cpp
  test/Driver/fsanitize.c

Index: test/Driver/fsanitize.c
===
--- test/Driver/fsanitize.c
+++ test/Driver/fsanitize.c
@@ -31,6 +31,21 @@
 // RUN: %clang -target x86_64-linux-gnu -fsanitize=integer %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-INTEGER -implicit-check-not="-fsanitize-address-use-after-scope"
 // CHECK-INTEGER: "-fsanitize={{((signed-integer-overflow|unsigned-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent),?){5}"}}
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-RECOVER
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast -fsanitize-recover=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-RECOVER
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast -fno-sanitize-recover=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-NORECOVER
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=implicit-cast -fsanitize-trap=implicit-cast %s -### 2>&1 | FileCheck %s --check-prefixes=CHECK-IMPLICIT-CAST,CHECK-IMPLICIT-CAST-TRAP
+// CHECK-IMPLICIT-CAST: "-fsanitize={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-RECOVER: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-RECOVER-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-RECOVER-NOT: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-NORECOVER-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}} // ???
+// CHECK-IMPLICIT-CAST-NORECOVER-NOT: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-NORECOVER-NOT: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-TRAP: "-fsanitize-trap={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-TRAP-NOT: "-fsanitize-recover={{((implicit-integer-truncation),?){1}"}}
+// CHECK-IMPLICIT-CAST-TRAP-NOT: "-fno-sanitize-recover={{((implicit-integer-truncation),?){1}"}}
+
 // RUN: %clang -fsanitize=bounds -### -fsyntax-only %s 2>&1 | FileCheck %s --check-prefix=CHECK-BOUNDS
 // CHECK-BOUNDS: "-fsanitize={{((array-bounds|local-bounds),?){2}"}}
 
Index: test/CodeGenCXX/catch-implicit-integer-truncations.cpp
===
--- /dev/null
+++ test/CodeGenCXX/catch-implicit-integer-truncations.cpp
@@ -0,0 +1,256 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefix=CHECK
+// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fno-sanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-NORECOVER
+// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-recover=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-ANYRECOVER,CHECK-SANITIZE-RECOVER
+// RUN: %clang_cc1 -fsanitize=implicit-integer-truncation -fsanitize-trap=implicit-integer-truncation -emit-llvm %s -o - -triple x86_64-linux-gnu | FileCheck %s --check-prefixes=CHECK,CHECK-SANITIZE,CHECK-SANITIZE-TRAP
+
+extern "C" { // Disable name mangling.
+
+// == //
+// Check that explicit cast does not interfere with implicit cast
+// == //
+// These contain one implicit truncating cast, and one explicit truncating cast.
+// We want to make sure that we still diagnose the implicit cast.
+
+// Implicit truncation after explicit truncation.
+// CHECK-LABEL: @explicit_cast_interference0
+unsigned char explicit_cast_interference0(unsigned int c) {
+  // CHECK-SANITIZE: %[[ANYEXT:.*]] = zext i8 %[[DST:.*]] to i16, !nosanitize
+  // CHECK-SANITIZE: call
+  // CHECK-SANITIZE-NOT: call
+  // CHECK: }
+  return (unsigned short)c;
+}
+
+// Implicit truncation before explicit truncation.
+// CHECK-LABEL: @explicit_cast_interference1
+unsigned char explicit_cast_interference1(unsigned int c) {
+  // CHECK-SANITIZE: %[[ANYE

r338076 - [ARM64] [Windows] Follow MS X86_64 C++ ABI when passing structs

2018-07-26 Thread Sanjin Sijaric via cfe-commits
Author: ssijaric
Date: Thu Jul 26 15:18:28 2018
New Revision: 338076

URL: http://llvm.org/viewvc/llvm-project?rev=338076&view=rev
Log:
[ARM64] [Windows] Follow MS X86_64 C++ ABI when passing structs

Summary: Microsoft's C++ object model for ARM64 is the same as that for X86_64.
For example, small structs with non-trivial copy constructors or virtual
function tables are passed indirectly.  Currently, they are passed in registers
when compiled with clang.

Reviewers: rnk, mstorsjo, TomTan, haripul, javed.absar

Reviewed By: rnk, mstorsjo

Subscribers: kristof.beyls, chrib, llvm-commits, cfe-commits

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

Modified:
cfe/trunk/include/clang/Basic/TargetInfo.h
cfe/trunk/lib/Basic/Targets/AArch64.cpp
cfe/trunk/lib/Basic/Targets/AArch64.h
cfe/trunk/lib/Basic/Targets/X86.h
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
cfe/trunk/lib/Sema/SemaDeclCXX.cpp
cfe/trunk/test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp

Modified: cfe/trunk/include/clang/Basic/TargetInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/TargetInfo.h?rev=338076&r1=338075&r2=338076&view=diff
==
--- cfe/trunk/include/clang/Basic/TargetInfo.h (original)
+++ cfe/trunk/include/clang/Basic/TargetInfo.h Thu Jul 26 15:18:28 2018
@@ -1223,7 +1223,7 @@ public:
   enum CallingConvKind {
 CCK_Default,
 CCK_ClangABI4OrPS4,
-CCK_MicrosoftX86_64
+CCK_MicrosoftWin64
   };
 
   virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const;

Modified: cfe/trunk/lib/Basic/Targets/AArch64.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/AArch64.cpp?rev=338076&r1=338075&r2=338076&view=diff
==
--- cfe/trunk/lib/Basic/Targets/AArch64.cpp (original)
+++ cfe/trunk/lib/Basic/Targets/AArch64.cpp Thu Jul 26 15:18:28 2018
@@ -533,6 +533,11 @@ void MicrosoftARM64TargetInfo::getTarget
   getVisualStudioDefines(Opts, Builder);
 }
 
+TargetInfo::CallingConvKind
+MicrosoftARM64TargetInfo::getCallingConvKind(bool ClangABICompat4) const {
+  return CCK_MicrosoftWin64;
+}
+
 MinGWARM64TargetInfo::MinGWARM64TargetInfo(const llvm::Triple &Triple,
const TargetOptions &Opts)
 : WindowsARM64TargetInfo(Triple, Opts) {

Modified: cfe/trunk/lib/Basic/Targets/AArch64.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/AArch64.h?rev=338076&r1=338075&r2=338076&view=diff
==
--- cfe/trunk/lib/Basic/Targets/AArch64.h (original)
+++ cfe/trunk/lib/Basic/Targets/AArch64.h Thu Jul 26 15:18:28 2018
@@ -126,6 +126,8 @@ public:
   MacroBuilder &Builder) const;
   void getTargetDefines(const LangOptions &Opts,
 MacroBuilder &Builder) const override;
+  TargetInfo::CallingConvKind
+  getCallingConvKind(bool ClangABICompat4) const override;
 };
 
 // ARM64 MinGW target

Modified: cfe/trunk/lib/Basic/Targets/X86.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/Targets/X86.h?rev=338076&r1=338075&r2=338076&view=diff
==
--- cfe/trunk/lib/Basic/Targets/X86.h (original)
+++ cfe/trunk/lib/Basic/Targets/X86.h Thu Jul 26 15:18:28 2018
@@ -752,7 +752,7 @@ public:
 
   TargetInfo::CallingConvKind
   getCallingConvKind(bool ClangABICompat4) const override {
-return CCK_MicrosoftX86_64;
+return CCK_MicrosoftWin64;
   }
 };
 

Modified: cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp?rev=338076&r1=338075&r2=338076&view=diff
==
--- cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp (original)
+++ cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp Thu Jul 26 15:18:28 2018
@@ -827,6 +827,7 @@ MicrosoftCXXABI::getRecordArgABI(const C
 return RAA_Default;
 
   case llvm::Triple::x86_64:
+  case llvm::Triple::aarch64:
 return !canCopyArgument(RD) ? RAA_Indirect : RAA_Default;
   }
 

Modified: cfe/trunk/lib/Sema/SemaDeclCXX.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclCXX.cpp?rev=338076&r1=338075&r2=338076&view=diff
==
--- cfe/trunk/lib/Sema/SemaDeclCXX.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclCXX.cpp Thu Jul 26 15:18:28 2018
@@ -5831,7 +5831,7 @@ static bool canPassInRegisters(Sema &S,
 return !D->hasNonTrivialDestructorForCall() &&
!D->hasNonTrivialCopyConstructorForCall();
 
-  if (CCK == TargetInfo::CCK_MicrosoftX86_64) {
+  if (CCK == TargetInfo::CCK_MicrosoftWin64) {
 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
 bool DtorIsTrivialForCal

[PATCH] D49770: [ARM64] [Windows] Follow MS X86_64 C++ ABI when passing structs

2018-07-26 Thread Sanjin Sijaric via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC338076: [ARM64] [Windows] Follow MS X86_64 C++ ABI when 
passing structs (authored by ssijaric, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D49770

Files:
  include/clang/Basic/TargetInfo.h
  lib/Basic/Targets/AArch64.cpp
  lib/Basic/Targets/AArch64.h
  lib/Basic/Targets/X86.h
  lib/CodeGen/MicrosoftCXXABI.cpp
  lib/Sema/SemaDeclCXX.cpp
  test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp

Index: include/clang/Basic/TargetInfo.h
===
--- include/clang/Basic/TargetInfo.h
+++ include/clang/Basic/TargetInfo.h
@@ -1223,7 +1223,7 @@
   enum CallingConvKind {
 CCK_Default,
 CCK_ClangABI4OrPS4,
-CCK_MicrosoftX86_64
+CCK_MicrosoftWin64
   };
 
   virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const;
Index: test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp
===
--- test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp
+++ test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp
@@ -2,6 +2,7 @@
 // RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WIN32 %s
 // RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple=thumb-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WOA %s
 // RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple=x86_64-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WIN64 %s
+// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple=aarch64-windows-msvc -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WOA64 %s
 
 struct Empty {};
 
@@ -163,6 +164,9 @@
 // WIN64: define dso_local void @"?small_arg_with_dtor@@YAXUSmallWithDtor@@@Z"(i32 %s.coerce) {{.*}} {
 // WIN64:   call void @"??1SmallWithDtor@@QEAA@XZ"
 // WIN64: }
+// WOA64: define dso_local void @"?small_arg_with_dtor@@YAXUSmallWithDtor@@@Z"(i64 %s.coerce) {{.*}} {
+// WOA64:   call void @"??1SmallWithDtor@@QEAA@XZ"
+// WOA64: }
 
 // FIXME: MSVC incompatible!
 // WOA: define dso_local arm_aapcs_vfpcc void @"?small_arg_with_dtor@@YAXUSmallWithDtor@@@Z"(%struct.SmallWithDtor* %s) {{.*}} {
@@ -227,12 +231,14 @@
 // LINUX-LABEL: define void @_Z22small_arg_with_vftable16SmallWithVftable(%struct.SmallWithVftable* %s)
 // WIN32: define dso_local void @"?small_arg_with_vftable@@YAXUSmallWithVftable@@@Z"(<{ %struct.SmallWithVftable }>* inalloca)
 // WIN64: define dso_local void @"?small_arg_with_vftable@@YAXUSmallWithVftable@@@Z"(%struct.SmallWithVftable* %s)
+// WOA64: define dso_local void @"?small_arg_with_vftable@@YAXUSmallWithVftable@@@Z"(%struct.SmallWithVftable* %s)
 
 void medium_arg_with_copy_ctor(MediumWithCopyCtor s) {}
 // LINUX-LABEL: define void @_Z25medium_arg_with_copy_ctor18MediumWithCopyCtor(%struct.MediumWithCopyCtor* %s)
 // WIN32: define dso_local void @"?medium_arg_with_copy_ctor@@YAXUMediumWithCopyCtor@@@Z"(<{ %struct.MediumWithCopyCtor }>* inalloca)
 // WIN64: define dso_local void @"?medium_arg_with_copy_ctor@@YAXUMediumWithCopyCtor@@@Z"(%struct.MediumWithCopyCtor* %s)
 // WOA: define dso_local arm_aapcs_vfpcc void @"?medium_arg_with_copy_ctor@@YAXUMediumWithCopyCtor@@@Z"(%struct.MediumWithCopyCtor* %s)
+// WOA64: define dso_local void @"?medium_arg_with_copy_ctor@@YAXUMediumWithCopyCtor@@@Z"(%struct.MediumWithCopyCtor* %s)
 
 void big_arg(Big s) {}
 // LINUX-LABEL: define void @_Z7big_arg3Big(%struct.Big* byval align 4 %s)
Index: lib/CodeGen/MicrosoftCXXABI.cpp
===
--- lib/CodeGen/MicrosoftCXXABI.cpp
+++ lib/CodeGen/MicrosoftCXXABI.cpp
@@ -827,6 +827,7 @@
 return RAA_Default;
 
   case llvm::Triple::x86_64:
+  case llvm::Triple::aarch64:
 return !canCopyArgument(RD) ? RAA_Indirect : RAA_Default;
   }
 
Index: lib/Sema/SemaDeclCXX.cpp
===
--- lib/Sema/SemaDeclCXX.cpp
+++ lib/Sema/SemaDeclCXX.cpp
@@ -5831,7 +5831,7 @@
 return !D->hasNonTrivialDestructorForCall() &&
!D->hasNonTrivialCopyConstructorForCall();
 
-  if (CCK == TargetInfo::CCK_MicrosoftX86_64) {
+  if (CCK == TargetInfo::CCK_MicrosoftWin64) {
 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
 bool DtorIsTrivialForCall = false;
 
Index: lib/Basic/Targets/AArch64.h
===
--- lib/Basic/Targets/AArch64.h
+++ lib/Basic/Targets/AArch64.h
@@ -126,6 +126,8 @@
   MacroBuilder &Builder) const;
   void getTargetDefines(const LangOptions &Opts,
 MacroBuilder &Builder) const override;
+  TargetInfo::CallingConvKind
+  getCallingConvKind(bool ClangABICompat4) const override;
 };
 
 // ARM64 MinGW target
Index: lib/Basic/Targets/X86.h
===
--- lib/Basic/Targets

[PATCH] D49876: [Fixed Point Arithmetic] Addition of intrinsic/builtin functions

2018-07-26 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan created this revision.
leonardchan added a project: clang.
Herald added a subscriber: cfe-commits.

This patch is not actually up for review and meant to hold the remaining work 
done after https://reviews.llvm.org/D47017 but haven't submitted for review yet.

This patch contains:

- `mulifx()` family functions. This essentially performs multiplication on 
_Accum/long _Accum types with integers but returns an integer instead of fixed 
point type.
- Intrinsic wrapper functions for `log2()`/`log10()`. These were not specified 
in Embedded-C, but were requested by the networking team. These functions are 
able to calculate a value up to 31 bits of precision (same as the default long 
_Accum scale), and have an error within 1 unit of precision of the true answer 
(error < 1/2^31).
- Intrinsic wrapper function for `pow10()`. Also requested by the networking 
team, and can also calculate a value with up to 31 bits of precision and an 
error within 1 unit of precision of the true answer.
- Corrected logic for scalar conversions between fixed points and floats
- Starting code for `FX_FULL_PRECISION` pragma


Repository:
  rC Clang

https://reviews.llvm.org/D49876

Files:
  include/clang/Basic/Builtins.def
  include/clang/Basic/TokenKinds.def
  include/clang/Parse/Parser.h
  lib/AST/ASTContext.cpp
  lib/CodeGen/CGBuiltin.cpp
  lib/CodeGen/CGExprScalar.cpp
  lib/CodeGen/CodeGenFunction.h
  lib/Parse/ParsePragma.cpp
  lib/Parse/ParseStmt.cpp
  lib/Parse/Parser.cpp
  test/Frontend/fixed_point_all_conversions.c
  test/Frontend/fixed_point_mulifx_validation.c

Index: test/Frontend/fixed_point_mulifx_validation.c
===
--- /dev/null
+++ test/Frontend/fixed_point_mulifx_validation.c
@@ -0,0 +1,332 @@
+// RUN: %clang -ffixed-point --target=x86_64-linux -S -emit-llvm -o - %s | lli -force-interpreter=true
+
+// Check the results of various builtin functions provided under 
+// These tests assume the defualt precision values are used and assumes an int
+// is 32 bits, so target an architecture that supports this.
+
+#define assert(b) if (!(b)) { return 1; }
+
+// TODO: Remove these after implementing the macros for minimum fixed point
+// values.
+#define FRACT_MIN (-0.5r - 0.5r)
+#define LFRACT_MIN (-0.5lr - 0.5lr)
+#define ACCUM_MIN (-32768.0k - 32768.0k)
+#define LACCUM_MIN (-2147483648.0lk - 2147483648.0lk)
+
+int main() {
+  /*** mulir() /
+
+  // Zero
+  assert(mulir(0, 1.0r) == 0);
+  assert(mulir(1, 0.0r) == 0);
+
+  // One
+  assert(mulir(1, 1.0r) == 0);
+  assert(mulir(-1, 1.0r) == -1);
+  assert(mulir(1, FRACT_MIN) == -1);
+  assert(mulir(-1, FRACT_MIN) == 1);
+
+  // Fractional resolves to int
+  assert(mulir(10, 0.5r) == 5);
+  assert(mulir(10, -0.5r) == -5);
+  assert(mulir(-10, 0.5r) == -5);
+  assert(mulir(-10, -0.5r) == 5);
+
+  // Fractional result is missing and value truncates towards zero by default
+  assert(mulir(15, 0.5r) == 7);
+  assert(mulir(15, -0.5r) == -8);
+  assert(mulir(-15, 0.5r) == -8);
+  assert(mulir(-15, -0.5r) == 7);
+
+  // Limited resulution of the _Fract fractional bits does not always allow for
+  // the most precise values. 1.0r resolves to _Fract max.
+  assert(mulir(65536, 1.0r) == 65534);
+  assert(mulir(-65536, 1.0r) == -65534);
+  assert(mulir(65536, FRACT_MIN) == -65536);
+  assert(mulir(-65536, FRACT_MIN) == 65536);
+
+  assert(mulir(2147483647, 1.0r) == 2147418111);
+  assert(mulir(-2147483647, 1.0r) == -2147418112);  // Rounds down
+  assert(mulir(2147483647, FRACT_MIN) == -2147483647);
+  assert(mulir(-2147483647, FRACT_MIN) == 2147483647);
+
+  /*** mulilr() /
+
+  // Zero
+  assert(mulilr(0, 1.0lr) == 0);
+  assert(mulilr(1, 0.0lr) == 0);
+
+  // One
+  assert(mulilr(1, 1.0lr) == 0);
+  assert(mulilr(-1, 1.0lr) == -1);
+  assert(mulilr(1, LFRACT_MIN) == -1);
+  assert(mulilr(-1, LFRACT_MIN) == 1);
+
+  // Fractional resolves to int
+  assert(mulilr(10, 0.5lr) == 5);
+  assert(mulilr(10, -0.5lr) == -5);
+  assert(mulilr(-10, 0.5lr) == -5);
+  assert(mulilr(-10, -0.5lr) == 5);
+
+  // Fractional result is missing and value truncates towards zero
+  assert(mulilr(15, 0.5lr) == 7);
+  assert(mulilr(15, -0.5lr) == -8);
+  assert(mulilr(-15, 0.5lr) == -8);
+  assert(mulilr(-15, -0.5lr) == 7);
+
+  // Limited resulution of the _Fract fractional bits does not always allow for
+  // the most precise values.
+  assert(mulilr(4294967296, 1.0lr) == 4294967294);
+  assert(mulilr(-4294967296, 1.0lr) == -4294967294);
+  assert(mulilr(4294967296, LFRACT_MIN) == -4294967296);
+  assert(mulilr(-4294967296, LFRACT_MIN) == 4294967296);
+
+  assert(mulilr(9223372036854775807, 1.0lr) == 9223372032559808511);
+  assert(mulilr(-9223372036854775807, 1.0lr) == -9223372032559808512);  // Rounds down
+  assert(mulilr(9223372036854775807, LFRACT_MIN) == -9223372036854775807);
+  assert(mulilr(-9223372036854775807, LFRACT_MIN) == 9223372036854775807);
+
+  /*** mulik() ***

[PATCH] D49848: Parse a possible trailing postfix expression suffix after a fold expression

2018-07-26 Thread Nicolas Lesser via Phabricator via cfe-commits
Rakete updated this revision to Diff 157580.
Rakete added a comment.

Add a test without any casts.


Repository:
  rC Clang

https://reviews.llvm.org/D49848

Files:
  include/clang/Parse/Parser.h
  lib/Parse/ParseExpr.cpp
  test/Parser/cxx1z-fold-expressions.cpp


Index: test/Parser/cxx1z-fold-expressions.cpp
===
--- test/Parser/cxx1z-fold-expressions.cpp
+++ test/Parser/cxx1z-fold-expressions.cpp
@@ -60,3 +60,29 @@
 }
 
 static_assert(nestedFoldOperator<3, 1>() == 1);
+
+// A fold-expression is a primary-expression.
+template 
+constexpr auto castSum(Ts... Args) {
+  return (T)(Args + ...).Value; // expected-error{{member reference base type 
'int' is not a structure or union}}
+}
+
+template 
+constexpr auto simpleSum(Ts... Args) {
+  return (... + Args).Value; // expected-error{{member reference base type 
'int' is not a structure or union}}
+}
+
+void prim() {
+  castSum(1, 2);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  simpleSum(1, 2);
+  // expected-note@-1{{in instantiation of function template specialization}}
+
+  struct Number {
+int Value;
+constexpr Number operator+(Number Rhs) const { return {Rhs.Value + Value}; 
}
+  };
+
+  static_assert(castSum(Number{1}, Number{2}) == 3);
+  static_assert(simpleSum(Number{1}, Number{2}) == 3);
+}
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -779,6 +779,10 @@
   // We have parsed the cast-expression and no postfix-expr pieces are
   // following.
   return Res;
+case FoldExpr:
+  // We parsed fold-expression only. There might be postfix-expr pieces
+  // afterwards; parse them now.
+  break;
 }
 
 break;
@@ -2514,6 +2518,7 @@
 }
   } else if (Tok.is(tok::ellipsis) &&
  isFoldOperator(NextToken().getKind())) {
+ExprType = FoldExpr;
 return ParseFoldExpression(ExprResult(), T);
   } else if (isTypeCast) {
 // Parse the expression-list.
@@ -2526,8 +2531,10 @@
   // FIXME: If we ever support comma expressions as operands to
   // fold-expressions, we'll need to allow multiple ArgExprs here.
   if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
-  NextToken().is(tok::ellipsis))
+  NextToken().is(tok::ellipsis)) {
+ExprType = FoldExpr;
 return ParseFoldExpression(ArgExprs[0], T);
+  }
 
   ExprType = SimpleExpr;
   Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
@@ -2544,8 +2551,10 @@
 }
 ExprType = SimpleExpr;
 
-if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
+if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
+  ExprType = FoldExpr;
   return ParseFoldExpression(Result, T);
+}
 
 // Don't build a paren expression unless we actually match a ')'.
 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Index: include/clang/Parse/Parser.h
===
--- include/clang/Parse/Parser.h
+++ include/clang/Parse/Parser.h
@@ -1654,7 +1654,8 @@
 SimpleExpr,  // Only parse '(' expression ')'
 CompoundStmt,// Also allow '(' compound-statement ')'
 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
-CastExpr // Also allow '(' type-name ')' 
+CastExpr,// Also allow '(' type-name ')' 
+FoldExpr // Also allow fold-expression 
   };
   ExprResult ParseParenExpression(ParenParseOption &ExprType,
 bool stopIfCastExpr,


Index: test/Parser/cxx1z-fold-expressions.cpp
===
--- test/Parser/cxx1z-fold-expressions.cpp
+++ test/Parser/cxx1z-fold-expressions.cpp
@@ -60,3 +60,29 @@
 }
 
 static_assert(nestedFoldOperator<3, 1>() == 1);
+
+// A fold-expression is a primary-expression.
+template 
+constexpr auto castSum(Ts... Args) {
+  return (T)(Args + ...).Value; // expected-error{{member reference base type 'int' is not a structure or union}}
+}
+
+template 
+constexpr auto simpleSum(Ts... Args) {
+  return (... + Args).Value; // expected-error{{member reference base type 'int' is not a structure or union}}
+}
+
+void prim() {
+  castSum(1, 2);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  simpleSum(1, 2);
+  // expected-note@-1{{in instantiation of function template specialization}}
+
+  struct Number {
+int Value;
+constexpr Number operator+(Number Rhs) const { return {Rhs.Value + Value}; }
+  };
+
+  static_assert(castSum(Number{1}, Number{2}) == 3);
+  static_assert(simpleSum(Number{1}, Number{2}) == 3);
+}
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -779,6 +779,10 @@
 

[PATCH] D49848: Parse a possible trailing postfix expression suffix after a fold expression

2018-07-26 Thread Nicolas Lesser via Phabricator via cfe-commits
Rakete updated this revision to Diff 157578.
Rakete added a comment.

@rsmith you're right, it should. But it doesn't, because the the fold 
expression is considered to be a cast expression by ParseParenExpression and 
which parses any postfix pieces immediately after a cast, but it doesn't do so 
for fold expression, because they don't (not surprisingly) involve a cast.

I've added a new type of ParenParseOption for fold-expressions for this, which 
makes the patch way more cleaner :) (I didn't want to reuse SimpleExpr for fold 
expressions - conflicts with the docs for it)


Repository:
  rC Clang

https://reviews.llvm.org/D49848

Files:
  include/clang/Parse/Parser.h
  lib/Parse/ParseExpr.cpp
  test/Parser/cxx1z-fold-expressions.cpp


Index: test/Parser/cxx1z-fold-expressions.cpp
===
--- test/Parser/cxx1z-fold-expressions.cpp
+++ test/Parser/cxx1z-fold-expressions.cpp
@@ -60,3 +60,21 @@
 }
 
 static_assert(nestedFoldOperator<3, 1>() == 1);
+
+// A fold-expression is a primary-expression.
+template 
+constexpr auto castSum(Ts... Args) {
+  return (T)(Args + ...).Value; // expected-error{{member reference base type 
'int' is not a structure or union}}
+}
+
+void prim() {
+  castSum(1, 2);
+  // expected-note@-1{{in instantiation of function template specialization}}
+
+  struct Number {
+int Value;
+constexpr Number operator+(Number Rhs) const { return {Rhs.Value + Value}; 
}
+  };
+
+  static_assert(castSum(Number{1}, Number{2}) == 3);
+}
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -779,6 +779,10 @@
   // We have parsed the cast-expression and no postfix-expr pieces are
   // following.
   return Res;
+case FoldExpr:
+  // We parsed fold-expression only. There might be postfix-expr pieces
+  // afterwards; parse them now.
+  break;
 }
 
 break;
@@ -2514,6 +2518,7 @@
 }
   } else if (Tok.is(tok::ellipsis) &&
  isFoldOperator(NextToken().getKind())) {
+ExprType = FoldExpr;
 return ParseFoldExpression(ExprResult(), T);
   } else if (isTypeCast) {
 // Parse the expression-list.
@@ -2526,8 +2531,10 @@
   // FIXME: If we ever support comma expressions as operands to
   // fold-expressions, we'll need to allow multiple ArgExprs here.
   if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
-  NextToken().is(tok::ellipsis))
+  NextToken().is(tok::ellipsis)) {
+ExprType = FoldExpr;
 return ParseFoldExpression(ArgExprs[0], T);
+  }
 
   ExprType = SimpleExpr;
   Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
@@ -2544,8 +2551,10 @@
 }
 ExprType = SimpleExpr;
 
-if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
+if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
+  ExprType = FoldExpr;
   return ParseFoldExpression(Result, T);
+}
 
 // Don't build a paren expression unless we actually match a ')'.
 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Index: include/clang/Parse/Parser.h
===
--- include/clang/Parse/Parser.h
+++ include/clang/Parse/Parser.h
@@ -1654,7 +1654,8 @@
 SimpleExpr,  // Only parse '(' expression ')'
 CompoundStmt,// Also allow '(' compound-statement ')'
 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
-CastExpr // Also allow '(' type-name ')' 
+CastExpr,// Also allow '(' type-name ')' 
+FoldExpr // Also allow fold-expression 
   };
   ExprResult ParseParenExpression(ParenParseOption &ExprType,
 bool stopIfCastExpr,


Index: test/Parser/cxx1z-fold-expressions.cpp
===
--- test/Parser/cxx1z-fold-expressions.cpp
+++ test/Parser/cxx1z-fold-expressions.cpp
@@ -60,3 +60,21 @@
 }
 
 static_assert(nestedFoldOperator<3, 1>() == 1);
+
+// A fold-expression is a primary-expression.
+template 
+constexpr auto castSum(Ts... Args) {
+  return (T)(Args + ...).Value; // expected-error{{member reference base type 'int' is not a structure or union}}
+}
+
+void prim() {
+  castSum(1, 2);
+  // expected-note@-1{{in instantiation of function template specialization}}
+
+  struct Number {
+int Value;
+constexpr Number operator+(Number Rhs) const { return {Rhs.Value + Value}; }
+  };
+
+  static_assert(castSum(Number{1}, Number{2}) == 3);
+}
Index: lib/Parse/ParseExpr.cpp
===
--- lib/Parse/ParseExpr.cpp
+++ lib/Parse/ParseExpr.cpp
@@ -779,6 +779,10 @@
   // We have parsed the cast-expression and no postfix-expr pieces are
   // following.
   return Res;
+case FoldExpr:
+  // We parsed fold-expre

[PATCH] D49868: [Sema] Fix a crash by completing a type before using it

2018-07-26 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington updated this revision to Diff 157575.
erik.pilkington added a comment.

Add the testcase @rjmccall requested.


https://reviews.llvm.org/D49868

Files:
  clang/lib/Sema/SemaInit.cpp
  clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp


Index: clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
===
--- clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
+++ clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
@@ -348,6 +348,31 @@
   };
 }
 
+namespace rdar41903969 {
+template  struct A {};
+template  struct B;
+template  struct C {
+  C(A&);
+  C(B&);
+};
+
+void foo(A &a, B &b) {
+  (void)C{b};
+  (void)C{a};
+}
+
+template struct X {
+  X(std::initializer_list) = delete;
+  X(const X&);
+};
+
+template  struct D : X {};
+
+void bar(D& d) {
+  (void)X{d};
+}
+}
+
 #else
 
 // expected-no-diagnostics
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -9130,6 +9130,7 @@
   Expr *E = ListInit->getInit(0);
   auto *RD = E->getType()->getAsCXXRecordDecl();
   if (!isa(E) && RD &&
+  isCompleteType(Kind.getLocation(), E->getType()) &&
   isOrIsDerivedFromSpecializationOf(RD, Template))
 TryListConstructors = false;
 }


Index: clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
===
--- clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
+++ clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
@@ -348,6 +348,31 @@
   };
 }
 
+namespace rdar41903969 {
+template  struct A {};
+template  struct B;
+template  struct C {
+  C(A&);
+  C(B&);
+};
+
+void foo(A &a, B &b) {
+  (void)C{b};
+  (void)C{a};
+}
+
+template struct X {
+  X(std::initializer_list) = delete;
+  X(const X&);
+};
+
+template  struct D : X {};
+
+void bar(D& d) {
+  (void)X{d};
+}
+}
+
 #else
 
 // expected-no-diagnostics
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -9130,6 +9130,7 @@
   Expr *E = ListInit->getInit(0);
   auto *RD = E->getType()->getAsCXXRecordDecl();
   if (!isa(E) && RD &&
+  isCompleteType(Kind.getLocation(), E->getType()) &&
   isOrIsDerivedFromSpecializationOf(RD, Template))
 TryListConstructors = false;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
emmettneyman updated this revision to Diff 157577.
emmettneyman added a comment.

Made some minor fixes


Repository:
  rC Clang

https://reviews.llvm.org/D49526

Files:
  clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
  clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
  clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp

Index: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
===
--- clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
+++ clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
@@ -7,33 +7,48 @@
 //
 //===--===//
 //
-// Implements HandleLLVM for use by the Clang fuzzers. Mimics the llc tool to
-// compile an LLVM IR file to X86_64 assembly.
+// Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
+// vectorizer optimization pass over the given IR code. Then mimics lli on both
+// versions to JIT the generated code and execute it. Currently, functions are 
+// executed on dummy inputs.
 //
 //===--===//
 
 #include "handle_llvm.h"
 
 #include "llvm/ADT/Triple.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/CodeGen/CommandFlags.inc"
 #include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/TargetPassConfig.h"
+#include "llvm/ExecutionEngine/JITEventListener.h"
+#include "llvm/ExecutionEngine/JITSymbol.h"
+#include "llvm/ExecutionEngine/MCJIT.h"
+#include "llvm/ExecutionEngine/ObjectCache.h"
+#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
+#include "llvm/ExecutionEngine/SectionMemoryManager.h"
+#include "llvm/IR/IRPrintingPasses.h"
 #include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/LegacyPassNameParser.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/Pass.h"
 #include "llvm/PassRegistry.h"
-#include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/TargetRegistry.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Target/TargetMachine.h"
-
-#include 
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Vectorize.h"
 
 using namespace llvm;
 
+// Helper function to parse command line args and find the optimization level
 static void getOptLevel(const std::vector &ExtraArgs,
   CodeGenOpt::Level &OLvl) {
   // Find the optimization level from the command line args
@@ -53,59 +68,111 @@
   }
 }
 
-void clang_fuzzer::HandleLLVM(const std::string &S,
-  const std::vector &ExtraArgs) {
-  // Parse ExtraArgs to set the optimization level
-  CodeGenOpt::Level OLvl;
-  getOptLevel(ExtraArgs, OLvl);
+void ErrorAndExit(std::string message) {
+  errs()<< "ERROR: " << message << "\n";
+  std::exit(1);
+}
 
-  // Set the Module to include the the IR code to be compiled
-  SMDiagnostic Err;
+// Helper function to add optimization passes to the TargetMachine at the 
+// specified optimization level, OptLevel
+static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
+  CodeGenOpt::Level OptLevel,
+  unsigned SizeLevel) {
+  // Create and initialize a PassManagerBuilder
+  PassManagerBuilder Builder;
+  Builder.OptLevel = OptLevel;
+  Builder.SizeLevel = SizeLevel;
+  Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
+  Builder.LoopVectorize = true;
+  Builder.populateModulePassManager(MPM);
+}
 
+// Mimics the opt tool to run an optimization pass over the provided IR
+std::string OptLLVM(const std::string &IR, CodeGenOpt::Level OLvl) {
+  // Create a module that will run the optimization passes
+  SMDiagnostic Err;
   LLVMContext Context;
-  std::unique_ptr M = parseIR(MemoryBufferRef(S, "IR"), Err, Context);
-  if (!M) {
-errs() << "error: could not parse IR!\n";
-std::exit(1);
-  }
+  std::unique_ptr M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
+  if (!M || verifyModule(*M, &errs()))
+ErrorAndExit("Could not parse IR");
 
-  // Create a new Target
-  std::string Error;
-  const Target *TheTarget = TargetRegistry::lookupTarget(
-  sys::getDefaultTargetTriple(), Error);
-  if (!TheTarget) {
-errs() << Error;
-std::exit(1);
-  }
+  setFunctionAttributes(getCPUStr(), getFeaturesStr(), *M);
+  
+  legacy::PassManager Passes;
+  Triple ModuleTriple(M->getTargetTriple());
+  
+  Passes.add(new TargetLibraryInfoWrapperPass(ModuleTriple));
+  Passes.add(createTargetTransformInfoWrapperPass(TargetIRAnalysis()));
+  Passes.add(createVerifierPass());
 
-  TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
-
-  // Create a new Machine
-  std::string CPUStr = get

[PATCH] D49838: [AST] Sink 'part of explicit cast' down into ImplicitCastExpr

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added inline comments.



Comment at: include/clang/AST/Expr.h:2928
 
+  bool getIsPartOfExplicitCast() const {
+return CastExprBits.PartOfExplicitCast;

rsmith wrote:
> Please also rename this to`isPartOfExplicitCast` as requested on IRC.
Right, sorry.



Comment at: lib/Sema/SemaCast.cpp:97
   while ((CE = dyn_cast(CE->getSubExpr(
-CE->setIsPartOfExplicitCast(true);
+dyn_cast(CE)->setIsPartOfExplicitCast(true);
 }

rsmith wrote:
> lebedev.ri wrote:
> > lebedev.ri wrote:
> > > erichkeane wrote:
> > > > I think I'd prefer just using a different variable in the 'while' loop 
> > > > to avoid the cast.  something like while((auto ICE =
> > > > 
> > > > That said, either way this isn't a dyn_cast, this would be just a cast 
> > > > (since we KNOW the type).
> > > I was trying to avoid having one extra variable, which may confuse things.
> > > Let's see maybe it's not that ugly..
> > Indeed, `cast<>` should be used.
> > But trying to avoid this cast at all results in uglier code, so let's not.
> > (I need to call `getSubExpr()` on this new `ImplicitCastExpr`, so i'd need 
> > to maintain two variables, etc...)
> Maybe something like:
> ```
> for (auto *Next = CE->getSubExpr(); auto *ICE = 
> dyn_cast(Next); Next = ICE->getSubExpr())
>   ICE->setIsPartOfExplicitCast(true);
> ```
> or just
> ```
> for (; auto *ICE = dyn_cast(CE->getSubExpr()); CE = ICE)
>   ICE->setIsPartOfExplicitCast(true);
> ```
Oh wow, one can define variables not just in the "init-statement", how did i 
not notice this earlier?!
That changes the picture indeed.


Repository:
  rC Clang

https://reviews.llvm.org/D49838



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


[PATCH] D49838: [AST] Sink 'part of explicit cast' down into ImplicitCastExpr

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri updated this revision to Diff 157576.
lebedev.ri marked 3 inline comments as done.
lebedev.ri added a comment.

Address @rsmith review notes.


Repository:
  rC Clang

https://reviews.llvm.org/D49838

Files:
  include/clang/AST/Expr.h
  include/clang/AST/Stmt.h
  lib/AST/ASTDumper.cpp
  lib/Sema/SemaCast.cpp
  lib/Serialization/ASTReaderStmt.cpp
  lib/Serialization/ASTWriterStmt.cpp

Index: lib/Serialization/ASTWriterStmt.cpp
===
--- lib/Serialization/ASTWriterStmt.cpp
+++ lib/Serialization/ASTWriterStmt.cpp
@@ -665,7 +665,6 @@
   Record.push_back(E->path_size());
   Record.AddStmt(E->getSubExpr());
   Record.push_back(E->getCastKind()); // FIXME: stable encoding
-  Record.push_back(E->getIsPartOfExplicitCast());
 
   for (CastExpr::path_iterator
  PI = E->path_begin(), PE = E->path_end(); PI != PE; ++PI)
@@ -714,6 +713,7 @@
 
 void ASTStmtWriter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
   VisitCastExpr(E);
+  Record.push_back(E->isPartOfExplicitCast());
 
   if (E->path_size() == 0)
 AbbrevToUse = Writer.getExprImplicitCastAbbrev();
Index: lib/Serialization/ASTReaderStmt.cpp
===
--- lib/Serialization/ASTReaderStmt.cpp
+++ lib/Serialization/ASTReaderStmt.cpp
@@ -723,7 +723,6 @@
   assert(NumBaseSpecs == E->path_size());
   E->setSubExpr(Record.readSubExpr());
   E->setCastKind((CastKind)Record.readInt());
-  E->setIsPartOfExplicitCast(Record.readInt());
   CastExpr::path_iterator BaseI = E->path_begin();
   while (NumBaseSpecs--) {
 auto *BaseSpec = new (Record.getContext()) CXXBaseSpecifier;
@@ -770,6 +769,7 @@
 
 void ASTStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
   VisitCastExpr(E);
+  E->setIsPartOfExplicitCast(Record.readInt());
 }
 
 void ASTStmtReader::VisitExplicitCastExpr(ExplicitCastExpr *E) {
Index: lib/Sema/SemaCast.cpp
===
--- lib/Sema/SemaCast.cpp
+++ lib/Sema/SemaCast.cpp
@@ -93,8 +93,8 @@
   // Walk down from the CE to the OrigSrcExpr, and mark all immediate
   // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
   // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
-  while ((CE = dyn_cast(CE->getSubExpr(
-CE->setIsPartOfExplicitCast(true);
+  for (; auto *ICE = dyn_cast(CE->getSubExpr()); CE = ICE)
+ICE->setIsPartOfExplicitCast(true);
 }
 
 /// Complete an apparently-successful cast operation that yields
Index: lib/AST/ASTDumper.cpp
===
--- lib/AST/ASTDumper.cpp
+++ lib/AST/ASTDumper.cpp
@@ -521,6 +521,7 @@
 // Exprs
 void VisitExpr(const Expr *Node);
 void VisitCastExpr(const CastExpr *Node);
+void VisitImplicitCastExpr(const ImplicitCastExpr *Node);
 void VisitDeclRefExpr(const DeclRefExpr *Node);
 void VisitPredefinedExpr(const PredefinedExpr *Node);
 void VisitCharacterLiteral(const CharacterLiteral *Node);
@@ -2117,8 +2118,11 @@
   }
   dumpBasePath(OS, Node);
   OS << ">";
+}
 
-  if (Node->getIsPartOfExplicitCast())
+void ASTDumper::VisitImplicitCastExpr(const ImplicitCastExpr *Node) {
+  VisitCastExpr(Node);
+  if (Node->isPartOfExplicitCast())
 OS << " part_of_explicit_cast";
 }
 
Index: include/clang/AST/Stmt.h
===
--- include/clang/AST/Stmt.h
+++ include/clang/AST/Stmt.h
@@ -198,11 +198,12 @@
 
   class CastExprBitfields {
 friend class CastExpr;
+friend class ImplicitCastExpr;
 
 unsigned : NumExprBits;
 
 unsigned Kind : 6;
-unsigned PartOfExplicitCast : 1;
+unsigned PartOfExplicitCast : 1; // Only set for ImplicitCastExpr.
 unsigned BasePathSize : 32 - 6 - 1 - NumExprBits;
   };
 
Index: include/clang/AST/Expr.h
===
--- include/clang/AST/Expr.h
+++ include/clang/AST/Expr.h
@@ -2829,20 +2829,14 @@
   /// Construct an empty cast.
   CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
 : Expr(SC, Empty) {
+CastExprBits.PartOfExplicitCast = false;
 setBasePathSize(BasePathSize);
   }
 
 public:
   CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
   void setCastKind(CastKind K) { CastExprBits.Kind = K; }
 
-  bool getIsPartOfExplicitCast() const {
-return CastExprBits.PartOfExplicitCast;
-  }
-  void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
-CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
-  }
-
   static const char *getCastKindName(CastKind CK);
   const char *getCastKindName() const { return getCastKindName(getCastKind()); }
 
@@ -2931,6 +2925,11 @@
 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
   }
 
+  bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
+  void setIsPartOfExplicitCast(bool PartOfExpl

[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse added inline comments.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:152
+  typedef void (*func)(int*, int*, int*, int);
+  func f = (func) EE->getPointerToFunction(EntryFunc); 
+

Can we use `reinterpret_cast` here?


Repository:
  rC Clang

https://reviews.llvm.org/D49526



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


[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse added inline comments.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:125
+  Context);
+  Module *M = Owner.get();
+  if (!M)

We should be able to get rid of this line now, and rename Owner again.


Repository:
  rC Clang

https://reviews.llvm.org/D49526



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


Re: r337470 - [Sema] Add a new warning, -Wmemset-transposed-args

2018-07-26 Thread Erik Pilkington via cfe-commits



On 7/26/18 1:38 PM, Richard Smith wrote:
On Thu, 26 Jul 2018 at 13:14, Erik Pilkington via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:




On 7/26/18 12:52 PM, Richard Smith wrote:

Other than the (fixed) ffmpeg false positive, I see this firing
in three places.

One of them is in the libc tests for memset and bzero, where the
0 argument is intentional.


I don't find this case very convincing, if you're literally the
one person that has to test memset then you should probably just
compile with -Wno-suspicious-memaccess.


I think you're missing the point. In our tests, the false positive 
rate for this was extremely high. If the warning should be turned off 
in two-thirds of the places where it appears, then it should not be on 
by default. That's why I was asking for evidence that it's actually 
got a much higher true-positive rate than we saw.



One of them is here:

https://github.com/apache/xerces-c/blob/trunk/src/xercesc/util/XMLUTF16Transcoder.cpp#L114
(note that this code is correct).
And one of them was a real bug where the second and third
arguments of memset were transposed.

That's an extremely low false positive rate, much lower than what
we'd expect for an enabled-by-default warning. I find this
extremely surprising; I would have expected the ratio of true--
to false-positives to be much much higher. But ultimately data
wins out over expectations.
How does our experience compare to other people's experiences?
Are our findings abnormal? (They may well be; our corpus is very
C++-heavy.) If this is indeed typical, we should reconsider
whether to have these warnings enabled by default, as they do not
meet our bar for false positives.


I tested this internally, and it found ~50 true-positives and only
one false-positive (similar to apache bug above, where someone was
memsetting to a sizeof exression). Given those numbers, my
position is to keep it on-by-default, but I'm open to hear more.
We might be able to make this warning even more conservative in
this case by checking if the sizeof expression is actually
computing a size that corresponds to the type of the third
argument. I think that would be a good tradeoff if it meant we
could keep this on by default.


50:1 sounds a lot more reasonable than what I was seeing (1:3). In the 
past we've said >99% true-positive was a good threshold for 
on-by-default warnings; your data is a plausible sample set from such 
a Bernoulli distribution (whereas mine is ... not so much -- but I 
think this is at least evidence that in my corpus, something else had 
already caught most of these bugs already; do we have a pre-existing 
ClangTidy check for this or similar? Does GCC warn on it?).


Yep, GCC has -Wmemset-transposed-args already, and there is also a 
clang-tidy check. If your codebase already has to pass through those 
tools then I agree thats probably the reason your seeing those numbers.


If we can improve the true-positive rate further, that'd be a 
nice-to-have, but given the sizes of our respective sample sets, I 
think we lack the data to know if we've really helped the 
true-positive rate very much.



On Mon, 23 Jul 2018 at 09:28, Erik Pilkington via cfe-commits
mailto:cfe-commits@lists.llvm.org>>
wrote:

Sure, that seems pretty reasonable. r337706. Thanks for the
suggestion!


On 7/21/18 1:40 PM, Arthur O'Dwyer wrote:

In this case Clang is complaining about

    memset(complicated-expr, 0, 0);

which means that transposing the last two arguments would
not "fix" anything. Clang ought to not complain in this case.
It doesn't have anything to do with coming from a macro;
it's just that /both/ arguments are zero.
(I would also expect that `memset(complicated-expr,
(unsigned char)fill, (size_t)0)` shouldn't warn, either. But
we had some disagreement that casts to `(unsigned char)`
resp. `(size_t)` should be the right way to shut up the
warning in the first place...)
Basically Clang should only be suggesting a swap (and thus
complaining at all) in the case that swapping the arguments
would actually improve the situation.

–Arthur

On Sat, Jul 21, 2018 at 1:33 PM, Nico Weber via cfe-commits
mailto:cfe-commits@lists.llvm.org>> wrote:

This has a false positive on ffmpeg:

../../third_party/ffmpeg/libavcodec/options.c:273:64:
error: 'size' argument to memset is '0'; did you mean to
transpose the last two arguments?
[-Werror,-Wmemset-transposed-args]
alloc_and_copy_or_fail(intra_matrix, 64 *
sizeof(int16_t), 0);

With:

#define alloc_and_copy_or_fail(obj, size, pad) \
    if (src->obj && size > 0) { \
        des

[PATCH] D49650: Targets/AMDGPU: Don't set fp32-denormals feature for r600

2018-07-26 Thread Jan Vesely via Phabricator via cfe-commits
jvesely added a comment.

In https://reviews.llvm.org/D49650#1176336, @arsenm wrote:

> In https://reviews.llvm.org/D49650#1175461, @jvesely wrote:
>
> > In https://reviews.llvm.org/D49650#1175438, @arsenm wrote:
> >
> > > According to cayman manual, these registers do exist so we should 
> > > probably just make the feature accepted on r600 as well
> >
> >
> > sure, that's the way it was before r335942. I assumed the removal was 
> > intentional.
>
>
> Probably accidental because nothing in r600 was actually using it


given the number of warnings it outputs, I find that unlikely.
@tstellar what was your intention? It's not like someone is going to work on 
EG/CM denormals any time soon.

I don't mind either way. I just want to avoid another round of bikeshedding.


Repository:
  rC Clang

https://reviews.llvm.org/D49650



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


Re: r337470 - [Sema] Add a new warning, -Wmemset-transposed-args

2018-07-26 Thread Richard Smith via cfe-commits
On Thu, 26 Jul 2018 at 13:22, Arthur O'Dwyer via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> On Thu, Jul 26, 2018 at 12:52 PM, Richard Smith 
> wrote:
>
>> Other than the (fixed) ffmpeg false positive, I see this firing in three
>> places.
>>
>> One of them is in the libc tests for memset and bzero, where the 0
>> argument is intentional.
>> One of them is here:
>> https://github.com/apache/xerces-c/blob/trunk/src/xercesc/util/XMLUTF16Transcoder.cpp#L114
>> (note that this code is correct).
>> And one of them was a real bug where the second and third arguments of
>> memset were transposed.
>>
>> That's an extremely low false positive rate, much lower than what we'd
>> expect for an enabled-by-default warning. I find this extremely surprising;
>> I would have expected the ratio of true-- to false-positives to be much
>> much higher. But ultimately data wins out over expectations.
>>
>> How does our experience compare to other people's experiences? Are our
>> findings abnormal? (They may well be; our corpus is very C++-heavy.) If
>> this is indeed typical, we should reconsider whether to have these warnings
>> enabled by default, as they do not meet our bar for false positives.
>>
>
> I am confused by the "low/high" and "meet/do not meet" in this comment.
>
> Is this warning currently enabled by default?
>

It's currently enabled by default.

  Is it currently enabled by -Wall?
>

It's not controlled by -Wall / -Wno-all.


> Are you saying that "2-in-3-firings false positive" is sufficiently high
> that this warning should be disabled by default?
>

Yes, absolutely, that's *way* too high a false-positive rate for an
enabled-by-default warning.


> Are you saying that "2-in-a-gazillion-lines false positive" is
> sufficiently low that this warning should be included in -Wall? Are you
> saying something else?
>

How often the warning fires in total is not especially important. What
matters is how much signal it provides that there is a problem in the code.


> My experience at Green Hills many years ago was that this warning caught a
> ton of real bugs; but I don't remember if it was "on by default" or in our
> equivalent of "-Wall" or what. I think it should be enabled by -Wall (or
> -Wmost), and have no opinion as to whether it should also be on-by-default.
>

As I said, my expectation is that this would be a good warning to have. But
data wins, and the data I had did not back up this expectation. Erik's
additional data helps a lot to justify this warning being enabled by
default.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r337470 - [Sema] Add a new warning, -Wmemset-transposed-args

2018-07-26 Thread Richard Smith via cfe-commits
On Thu, 26 Jul 2018 at 13:14, Erik Pilkington via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

>
>
> On 7/26/18 12:52 PM, Richard Smith wrote:
>
> Other than the (fixed) ffmpeg false positive, I see this firing in three
> places.
>
> One of them is in the libc tests for memset and bzero, where the 0
> argument is intentional.
>
>
> I don't find this case very convincing, if you're literally the one person
> that has to test memset then you should probably just compile with
> -Wno-suspicious-memaccess.
>

I think you're missing the point. In our tests, the false positive rate for
this was extremely high. If the warning should be turned off in two-thirds
of the places where it appears, then it should not be on by default. That's
why I was asking for evidence that it's actually got a much higher
true-positive rate than we saw.

> One of them is here:
> https://github.com/apache/xerces-c/blob/trunk/src/xercesc/util/XMLUTF16Transcoder.cpp#L114
> (note that this code is correct).
> And one of them was a real bug where the second and third arguments of
> memset were transposed.
>
> That's an extremely low false positive rate, much lower than what we'd
> expect for an enabled-by-default warning. I find this extremely surprising;
> I would have expected the ratio of true-- to false-positives to be much
> much higher. But ultimately data wins out over expectations.
> How does our experience compare to other people's experiences? Are our
> findings abnormal? (They may well be; our corpus is very C++-heavy.) If
> this is indeed typical, we should reconsider whether to have these warnings
> enabled by default, as they do not meet our bar for false positives.
>
>
> I tested this internally, and it found ~50 true-positives and only one
> false-positive (similar to apache bug above, where someone was memsetting
> to a sizeof exression). Given those numbers, my position is to keep it
> on-by-default, but I'm open to hear more. We might be able to make this
> warning even more conservative in this case by checking if the sizeof
> expression is actually computing a size that corresponds to the type of the
> third argument. I think that would be a good tradeoff if it meant we could
> keep this on by default.
>

50:1 sounds a lot more reasonable than what I was seeing (1:3). In the past
we've said >99% true-positive was a good threshold for on-by-default
warnings; your data is a plausible sample set from such a Bernoulli
distribution (whereas mine is ... not so much -- but I think this is at
least evidence that in my corpus, something else had already caught most of
these bugs already; do we have a pre-existing ClangTidy check for this or
similar? Does GCC warn on it?).

If we can improve the true-positive rate further, that'd be a nice-to-have,
but given the sizes of our respective sample sets, I think we lack the data
to know if we've really helped the true-positive rate very much.

> On Mon, 23 Jul 2018 at 09:28, Erik Pilkington via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Sure, that seems pretty reasonable. r337706. Thanks for the suggestion!
>>
>> On 7/21/18 1:40 PM, Arthur O'Dwyer wrote:
>>
>> In this case Clang is complaining about
>>
>> memset(complicated-expr, 0, 0);
>>
>> which means that transposing the last two arguments would not "fix"
>> anything. Clang ought to not complain in this case.
>> It doesn't have anything to do with coming from a macro; it's just that
>> *both* arguments are zero.
>> (I would also expect that `memset(complicated-expr, (unsigned char)fill,
>> (size_t)0)` shouldn't warn, either. But we had some disagreement that casts
>> to `(unsigned char)` resp. `(size_t)` should be the right way to shut up
>> the warning in the first place...)
>> Basically Clang should only be suggesting a swap (and thus complaining at
>> all) in the case that swapping the arguments would actually improve the
>> situation.
>>
>> –Arthur
>>
>> On Sat, Jul 21, 2018 at 1:33 PM, Nico Weber via cfe-commits <
>> cfe-commits@lists.llvm.org> wrote:
>>
>>> This has a false positive on ffmpeg:
>>>
>>> ../../third_party/ffmpeg/libavcodec/options.c:273:64: error: 'size'
>>> argument to memset is '0'; did you mean to transpose the last two
>>> arguments? [-Werror,-Wmemset-transposed-args]
>>> alloc_and_copy_or_fail(intra_matrix, 64 * sizeof(int16_t), 0);
>>>
>>> With:
>>>
>>> #define alloc_and_copy_or_fail(obj, size, pad) \
>>> if (src->obj && size > 0) { \
>>> dest->obj = av_malloc(size + pad); \
>>> if (!dest->obj) \
>>> goto fail; \
>>> memcpy(dest->obj, src->obj, size); \
>>> if (pad) \
>>> memset(((uint8_t *) dest->obj) + size, 0, pad); \
>>> }
>>>
>>> (
>>> https://cs.chromium.org/chromium/src/third_party/ffmpeg/libavcodec/options.c?q=alloc_and_copy_or_fail&sq=package:chromium&g=0&l=261
>>> ; https://bugs.chromium.org/p/chromium/issues/detail?id=866202)
>>>
>>> Maybe the warning shouldn't fire if the memset is from a macro?
>>>
>>> On Thu

[PATCH] D49871: Improve support of PDB as an external layout source

2018-07-26 Thread Aleksandr Urakov via Phabricator via cfe-commits
aleksandr.urakov added a comment.

Thank you!

Can you, please, commit this for me? I have no commit access.


Repository:
  rC Clang

https://reviews.llvm.org/D49871



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


[PATCH] D49873: [Docs] ReleasesNotes update / Static analyser

2018-07-26 Thread David CARLIER via Phabricator via cfe-commits
devnexen created this revision.
devnexen added a reviewer: pcc.
devnexen created this object with visibility "All Users".
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D49873

Files:
  docs/ReleaseNotes.rst


Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -262,7 +262,8 @@
 Static Analyzer
 ---
 
-- ...
+- The new `MmapWriteExec` checker had been introduced to detect attempts to 
map pages
+both writable and executable.
 
 ...
 


Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -262,7 +262,8 @@
 Static Analyzer
 ---
 
-- ...
+- The new `MmapWriteExec` checker had been introduced to detect attempts to map pages
+both writable and executable.
 
 ...
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D46190: For a used declaration, mark any associated usings as referenced.

2018-07-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: include/clang/Sema/Sema.h:4040-4041
   // explicit nested-name-specifier).
-  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
+  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse,
+ CXXScopeSpec *SS = nullptr, Expr *E = nullptr);
   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,

Pass in the FoundDecl instead of a scope specifier and an expression.



Comment at: lib/Sema/SemaDeclCXX.cpp:15520-15525
+  while ((NA = dyn_cast(ND)) && !NA->isReferenced()) {
+NA->setReferenced();
+ND = NA->getAliasedNamespace();
+if (auto *NNS = NA->getQualifier())
+  MarkNamespaceAliasReferenced(NNS->getAsNamespaceAlias());
+  }

This is not the right approach. You should not iteratively mark namespaces as 
referenced here. Instead, when we parse the first namespace alias declaration 
in the chain, *it* should mark the subsequent one referenced immediately. So:

```
namespace A { int n; }
namespace B = A; // this declaration marks A referenced
namespace C = B; // this declaration marks B referenced
int k = C::n; // parsing the nested-name-specifier of this expression marks C 
referenced
```



Comment at: lib/Sema/SemaDeclCXX.cpp:15531-15586
+void Sema::MarkUsingReferenced(NamedDecl *ND, SourceLocation Loc,
+   CXXScopeSpec *SS, Expr *E) {
+  // The declaration was not defined in a namespace.
+  auto *DC = ND->getDeclContext();
+  if (!DC->isNamespace())
+return;
+

You should not do any of this. You should keep track of how each name was 
actually originally found, and mark the FoundDecl as referenced. Do not attempt 
to redo the lookup like you do here. You will get it wrong, and in any case, 
redoing the lookup is wasteful.


https://reviews.llvm.org/D46190



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


[PATCH] D49148: [DEBUGINFO] Disable unsupported debug info options for NVPTX target.

2018-07-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev marked an inline comment as done.
ABataev added inline comments.



Comment at: lib/Driver/ToolChains/Clang.cpp:933-938
+  if (TC.supportsDebugInfoOption(A)) {
+Action();
+return true;
+  }
+  reportUnsupportedDebugInfoOption(A, Args, D, TC.getTriple());
+  return false;

echristo wrote:
> I'd probably simplify this as:
> 
> ```
> if (TC.supportsDebugInfoOption(A))
>   return true;
> reportUnsupportedDebugInfoOption(A, Args, D, TC.getTriple());
> return false;
> ```
> 
> And just leave the action part in the rest of the code.  I think that means 
> you could also leave the bool off.
> 
> As another optimization here you could, instead, just check all of the 
> arguments ahead of time by getting the full list of debug info and just 
> checking them all. That's probably not worth it though TBH.
>
Done, but I need boolean result in most cases.


Repository:
  rC Clang

https://reviews.llvm.org/D49148



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


[PATCH] D49770: [ARM64] [Windows] Follow MS X86_64 C++ ABI when passing structs

2018-07-26 Thread Sanjin Sijaric via Phabricator via cfe-commits
ssijaric updated this revision to Diff 157559.
ssijaric added a comment.

Last change before committing to address Reid's point of using 
CCK_MicrosoftWin64 for Windows on both X86_64 and ARM64.


Repository:
  rC Clang

https://reviews.llvm.org/D49770

Files:
  include/clang/Basic/TargetInfo.h
  lib/Basic/Targets/AArch64.cpp
  lib/Basic/Targets/AArch64.h
  lib/Basic/Targets/X86.h
  lib/CodeGen/MicrosoftCXXABI.cpp
  lib/Sema/SemaDeclCXX.cpp
  test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp

Index: test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp
===
--- test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp
+++ test/CodeGenCXX/microsoft-abi-sret-and-byval.cpp
@@ -2,6 +2,7 @@
 // RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple=i386-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WIN32 %s
 // RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple=thumb-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WOA %s
 // RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple=x86_64-pc-win32 -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WIN64 %s
+// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple=aarch64-windows-msvc -mconstructor-aliases -fno-rtti | FileCheck -check-prefix WOA64 %s
 
 struct Empty {};
 
@@ -163,6 +164,9 @@
 // WIN64: define dso_local void @"?small_arg_with_dtor@@YAXUSmallWithDtor@@@Z"(i32 %s.coerce) {{.*}} {
 // WIN64:   call void @"??1SmallWithDtor@@QEAA@XZ"
 // WIN64: }
+// WOA64: define dso_local void @"?small_arg_with_dtor@@YAXUSmallWithDtor@@@Z"(i64 %s.coerce) {{.*}} {
+// WOA64:   call void @"??1SmallWithDtor@@QEAA@XZ"
+// WOA64: }
 
 // FIXME: MSVC incompatible!
 // WOA: define dso_local arm_aapcs_vfpcc void @"?small_arg_with_dtor@@YAXUSmallWithDtor@@@Z"(%struct.SmallWithDtor* %s) {{.*}} {
@@ -227,12 +231,14 @@
 // LINUX-LABEL: define void @_Z22small_arg_with_vftable16SmallWithVftable(%struct.SmallWithVftable* %s)
 // WIN32: define dso_local void @"?small_arg_with_vftable@@YAXUSmallWithVftable@@@Z"(<{ %struct.SmallWithVftable }>* inalloca)
 // WIN64: define dso_local void @"?small_arg_with_vftable@@YAXUSmallWithVftable@@@Z"(%struct.SmallWithVftable* %s)
+// WOA64: define dso_local void @"?small_arg_with_vftable@@YAXUSmallWithVftable@@@Z"(%struct.SmallWithVftable* %s)
 
 void medium_arg_with_copy_ctor(MediumWithCopyCtor s) {}
 // LINUX-LABEL: define void @_Z25medium_arg_with_copy_ctor18MediumWithCopyCtor(%struct.MediumWithCopyCtor* %s)
 // WIN32: define dso_local void @"?medium_arg_with_copy_ctor@@YAXUMediumWithCopyCtor@@@Z"(<{ %struct.MediumWithCopyCtor }>* inalloca)
 // WIN64: define dso_local void @"?medium_arg_with_copy_ctor@@YAXUMediumWithCopyCtor@@@Z"(%struct.MediumWithCopyCtor* %s)
 // WOA: define dso_local arm_aapcs_vfpcc void @"?medium_arg_with_copy_ctor@@YAXUMediumWithCopyCtor@@@Z"(%struct.MediumWithCopyCtor* %s)
+// WOA64: define dso_local void @"?medium_arg_with_copy_ctor@@YAXUMediumWithCopyCtor@@@Z"(%struct.MediumWithCopyCtor* %s)
 
 void big_arg(Big s) {}
 // LINUX-LABEL: define void @_Z7big_arg3Big(%struct.Big* byval align 4 %s)
Index: lib/Sema/SemaDeclCXX.cpp
===
--- lib/Sema/SemaDeclCXX.cpp
+++ lib/Sema/SemaDeclCXX.cpp
@@ -5831,7 +5831,7 @@
 return !D->hasNonTrivialDestructorForCall() &&
!D->hasNonTrivialCopyConstructorForCall();
 
-  if (CCK == TargetInfo::CCK_MicrosoftX86_64) {
+  if (CCK == TargetInfo::CCK_MicrosoftWin64) {
 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
 bool DtorIsTrivialForCall = false;
 
Index: lib/CodeGen/MicrosoftCXXABI.cpp
===
--- lib/CodeGen/MicrosoftCXXABI.cpp
+++ lib/CodeGen/MicrosoftCXXABI.cpp
@@ -827,6 +827,7 @@
 return RAA_Default;
 
   case llvm::Triple::x86_64:
+  case llvm::Triple::aarch64:
 return !canCopyArgument(RD) ? RAA_Indirect : RAA_Default;
   }
 
Index: lib/Basic/Targets/X86.h
===
--- lib/Basic/Targets/X86.h
+++ lib/Basic/Targets/X86.h
@@ -752,7 +752,7 @@
 
   TargetInfo::CallingConvKind
   getCallingConvKind(bool ClangABICompat4) const override {
-return CCK_MicrosoftX86_64;
+return CCK_MicrosoftWin64;
   }
 };
 
Index: lib/Basic/Targets/AArch64.h
===
--- lib/Basic/Targets/AArch64.h
+++ lib/Basic/Targets/AArch64.h
@@ -126,6 +126,8 @@
   MacroBuilder &Builder) const;
   void getTargetDefines(const LangOptions &Opts,
 MacroBuilder &Builder) const override;
+  TargetInfo::CallingConvKind
+  getCallingConvKind(bool ClangABICompat4) const override;
 };
 
 // ARM64 MinGW target
Index: lib/Basic/Targets/AArch64.cpp
===
--- lib/Basic/Targets/AArch64.cpp
+++ lib/Basic/Targets/AArch64.cpp
@@ -533,6 +533,1

[PATCH] D49148: [DEBUGINFO] Disable unsupported debug info options for NVPTX target.

2018-07-26 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev updated this revision to Diff 157563.
ABataev added a comment.

Address ERic's comments.


Repository:
  rC Clang

https://reviews.llvm.org/D49148

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Driver/ToolChain.h
  lib/Driver/ToolChains/Clang.cpp
  lib/Driver/ToolChains/Cuda.cpp
  lib/Driver/ToolChains/Cuda.h
  test/Driver/cuda-dwarf-2.cu
  test/Driver/cuda-unsupported-debug-options.cu
  test/Driver/openmp-offload-gpu.c
  test/Driver/openmp-unsupported-debug-options.c

Index: test/Driver/openmp-unsupported-debug-options.c
===
--- /dev/null
+++ test/Driver/openmp-unsupported-debug-options.c
@@ -0,0 +1,21 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -g -gz 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf -fdebug-info-for-profiling 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf-2 -gsplit-dwarf 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf-3 -glldb 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf-4 -gcodeview 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -gdwarf-5 -gmodules 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -ggdb -gembed-source -gdwarf-5 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -ggdb1 -fdebug-macro 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -ggdb2 -ggnu-pubnames 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -ggdb3 -gdwarf-aranges 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -c %s -g -gcolumn-info -fdebug-types-section 2>&1 | FileCheck %s
+// CHECK: debug information option '{{-gz|-fdebug-info-for-profiling|-gsplit-dwarf|-glldb|-gcodeview|-gmodules|-gembed-source|-fdebug-macro|-ggnu-pubnames|-gdwarf-aranges|-fdebug-types-section}}' is not supported for target 'nvptx64-nvidia-cuda' [-Wunsupported-target-opt]
+// CHECK-NOT: debug information option '{{.*}}' is not supported for target 'x86
+// CHECK: "-triple" "nvptx64-nvidia-cuda"
+// CHECK-NOT: {{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}}
+// CHECK: "-triple" "x86_64
+// CHECK-SAME: {{-compress-debug|-fdebug-info-for-profiling|split-dwarf|lldb|codeview|module-format|embed-source|debug-info-macro|gnu-pubnames|generate-arange-section|generate-type-units}}
Index: test/Driver/openmp-offload-gpu.c
===
--- test/Driver/openmp-offload-gpu.c
+++ test/Driver/openmp-offload-gpu.c
@@ -182,6 +182,8 @@
 // RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -ggdb1 -O2 --cuda-noopt-device-debug 2>&1 \
 // RUN:   | FileCheck -check-prefix=NO_DEBUG -check-prefix=LINE_TABLE %s
 
+// LINE_TABLE-NOT: warning: debug
+// NO_DEBUG-NOT: warning: debug
 // NO_DEBUG: ptxas
 // LINE_TABLE: "-lineinfo"
 // NO_DEBUG-NOT: "-g"
@@ -203,6 +205,7 @@
 // RUN:   %clang -### -no-canonical-prefixes -fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -Xopenmp-target -march=sm_60 %s -ggdb3 -O2 --cuda-noopt-device-debug 2>&1 \
 // RUN:   | FileCheck -check-prefix=HAS_DEBUG %s
 
+// HAS_DEBUG-NOT: warning: debug
 // HAS_DEBUG: "-triple" "nvptx64-nvidia-cuda"
 // HAS_DEBUG-SAME: "-dwarf-version=2"
 // HAS_DEBUG-SAME: "-fopenmp-is-device"
Index: test/Driver/cuda-unsupported-debug-options.cu
===
--- /dev/null
+++ test/Driver/cuda-unsupported-debug-options.cu
@@ -0,0 +1,21 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang -### -target x86_64-linux-gnu -c %s -g -gz 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -c %s -gdwarf -fdebug-info-for-profiling 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -c %s -gdwarf-2 -gsplit-dwarf 2>&1 | FileCheck %s
+// RUN: %clang -### -target x86_64-linux-gnu -c %s -gdwarf-3 -glldb 2>&1 | FileCheck %s
+// RUN: %clang -### -targ

[PATCH] D49844: [AST] Add a isActuallyImplicitCast() helper to the CastExpr class.

2018-07-26 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri abandoned this revision.
lebedev.ri added a comment.

In https://reviews.llvm.org/D49844#1177273, @rsmith wrote:

> What I requested was that either we make `CastExpr::isPartOfExplicitCast()` 
> return `true` for `CastExpr`s that are not `ImplicitCastExpr`s, or that we 
> move `isPartOfExplicitCast` do the `ImplicitCastExpr` derived class. We don't 
> need to do both, and since we're doing the latter in 
> https://reviews.llvm.org/D49838, we don't need to do anything else. 
> (Essentially, my request was to fix the bug that 
> `CastExpr::isPartOfExplicitCast()` incorrectly returned `false` when called 
> on an explicit cast expression, and I don't mind which way we fix it.)


Ok, no problem at atll, so i have read too much into it :)
I will then simply inline this into the only caller.


Repository:
  rC Clang

https://reviews.llvm.org/D49844



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


[PATCH] D46190: For a used declaration, mark any associated usings as referenced.

2018-07-26 Thread Paul Robinson via Phabricator via cfe-commits
probinson accepted this revision.
probinson added a comment.

Although I am far from expert in how Clang manages declarations, AFAICT this 
does what @rsmith requested, so LGTM.


https://reviews.llvm.org/D46190



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


[PATCH] D48808: [CodeGen] Emit parallel_loop_access for each loop in the loop stack.

2018-07-26 Thread Michael Kruse via Phabricator via cfe-commits
Meinersbur added a comment.

ping


Repository:
  rC Clang

https://reviews.llvm.org/D48808



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


[PATCH] D49844: [AST] Add a isActuallyImplicitCast() helper to the CastExpr class.

2018-07-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith requested changes to this revision.
rsmith added a comment.
This revision now requires changes to proceed.

What I requested was that either we make `CastExpr::isPartOfExplicitCast()` 
return `true` for `CastExpr`s that are not `ImplicitCastExpr`s, or that we move 
`isPartOfExplicitCast` do the `ImplicitCastExpr` derived class. We don't need 
to do both, and since we're doing the latter in 
https://reviews.llvm.org/D49838, we don't need to do anything else. 
(Essentially, my request was to fix the bug that 
`CastExpr::isPartOfExplicitCast()` incorrectly returned `false` when called on 
an explicit cast expression, and I don't mind which way we fix it.)


Repository:
  rC Clang

https://reviews.llvm.org/D49844



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


Re: r337470 - [Sema] Add a new warning, -Wmemset-transposed-args

2018-07-26 Thread Arthur O'Dwyer via cfe-commits
On Thu, Jul 26, 2018 at 12:52 PM, Richard Smith 
wrote:

> Other than the (fixed) ffmpeg false positive, I see this firing in three
> places.
>
> One of them is in the libc tests for memset and bzero, where the 0
> argument is intentional.
> One of them is here: https://github.com/apache/xerces-c/blob/trunk/
> src/xercesc/util/XMLUTF16Transcoder.cpp#L114 (note that this code is
> correct).
> And one of them was a real bug where the second and third arguments of
> memset were transposed.
>
> That's an extremely low false positive rate, much lower than what we'd
> expect for an enabled-by-default warning. I find this extremely surprising;
> I would have expected the ratio of true-- to false-positives to be much
> much higher. But ultimately data wins out over expectations.
>
> How does our experience compare to other people's experiences? Are our
> findings abnormal? (They may well be; our corpus is very C++-heavy.) If
> this is indeed typical, we should reconsider whether to have these warnings
> enabled by default, as they do not meet our bar for false positives.
>

I am confused by the "low/high" and "meet/do not meet" in this comment.

Is this warning currently enabled by default?  Is it currently enabled by
-Wall?

Are you saying that "2-in-3-firings false positive" is sufficiently high
that this warning should be disabled by default? Are you saying that
"2-in-a-gazillion-lines false positive" is sufficiently low that this
warning should be included in -Wall? Are you saying something else?

My experience at Green Hills many years ago was that this warning caught a
ton of real bugs; but I don't remember if it was "on by default" or in our
equivalent of "-Wall" or what. I think it should be enabled by -Wall (or
-Wmost), and have no opinion as to whether it should also be on-by-default.

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


[PATCH] D49838: [AST] Sink 'part of explicit cast' down into ImplicitCastExpr

2018-07-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added inline comments.



Comment at: include/clang/AST/Expr.h:2928
 
+  bool getIsPartOfExplicitCast() const {
+return CastExprBits.PartOfExplicitCast;

Please also rename this to`isPartOfExplicitCast` as requested on IRC.



Comment at: include/clang/AST/Stmt.h:206
 unsigned Kind : 6;
-unsigned PartOfExplicitCast : 1;
+unsigned PartOfExplicitCast : 1; // Only representable for 
ImplicitCastExpr.
 unsigned BasePathSize : 32 - 6 - 1 - NumExprBits;

representable for -> set for



Comment at: lib/Sema/SemaCast.cpp:97
   while ((CE = dyn_cast(CE->getSubExpr(
-CE->setIsPartOfExplicitCast(true);
+dyn_cast(CE)->setIsPartOfExplicitCast(true);
 }

lebedev.ri wrote:
> lebedev.ri wrote:
> > erichkeane wrote:
> > > I think I'd prefer just using a different variable in the 'while' loop to 
> > > avoid the cast.  something like while((auto ICE =
> > > 
> > > That said, either way this isn't a dyn_cast, this would be just a cast 
> > > (since we KNOW the type).
> > I was trying to avoid having one extra variable, which may confuse things.
> > Let's see maybe it's not that ugly..
> Indeed, `cast<>` should be used.
> But trying to avoid this cast at all results in uglier code, so let's not.
> (I need to call `getSubExpr()` on this new `ImplicitCastExpr`, so i'd need to 
> maintain two variables, etc...)
Maybe something like:
```
for (auto *Next = CE->getSubExpr(); auto *ICE = 
dyn_cast(Next); Next = ICE->getSubExpr())
  ICE->setIsPartOfExplicitCast(true);
```
or just
```
for (; auto *ICE = dyn_cast(CE->getSubExpr()); CE = ICE)
  ICE->setIsPartOfExplicitCast(true);
```


Repository:
  rC Clang

https://reviews.llvm.org/D49838



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


Re: r337470 - [Sema] Add a new warning, -Wmemset-transposed-args

2018-07-26 Thread Erik Pilkington via cfe-commits



On 7/26/18 12:52 PM, Richard Smith wrote:
Other than the (fixed) ffmpeg false positive, I see this firing in 
three places.


One of them is in the libc tests for memset and bzero, where the 0 
argument is intentional.


I don't find this case very convincing, if you're literally the one 
person that has to test memset then you should probably just compile 
with -Wno-suspicious-memaccess.


One of them is here: 
https://github.com/apache/xerces-c/blob/trunk/src/xercesc/util/XMLUTF16Transcoder.cpp#L114 
(note that this code is correct).
And one of them was a real bug where the second and third arguments of 
memset were transposed.


That's an extremely low false positive rate, much lower than what we'd 
expect for an enabled-by-default warning. I find this extremely 
surprising; I would have expected the ratio of true-- to 
false-positives to be much much higher. But ultimately data wins out 
over expectations.
How does our experience compare to other people's experiences? Are our 
findings abnormal? (They may well be; our corpus is very C++-heavy.) 
If this is indeed typical, we should reconsider whether to have these 
warnings enabled by default, as they do not meet our bar for false 
positives.


I tested this internally, and it found ~50 true-positives and only one 
false-positive (similar to apache bug above, where someone was 
memsetting to a sizeof exression). Given those numbers, my position is 
to keep it on-by-default, but I'm open to hear more. We might be able to 
make this warning even more conservative in this case by checking if the 
sizeof expression is actually computing a size that corresponds to the 
type of the third argument. I think that would be a good tradeoff if it 
meant we could keep this on by default.


On Mon, 23 Jul 2018 at 09:28, Erik Pilkington via cfe-commits 
mailto:cfe-commits@lists.llvm.org>> wrote:


Sure, that seems pretty reasonable. r337706. Thanks for the
suggestion!


On 7/21/18 1:40 PM, Arthur O'Dwyer wrote:

In this case Clang is complaining about

    memset(complicated-expr, 0, 0);

which means that transposing the last two arguments would not
"fix" anything. Clang ought to not complain in this case.
It doesn't have anything to do with coming from a macro; it's
just that /both/ arguments are zero.
(I would also expect that `memset(complicated-expr, (unsigned
char)fill, (size_t)0)` shouldn't warn, either. But we had some
disagreement that casts to `(unsigned char)` resp. `(size_t)`
should be the right way to shut up the warning in the first place...)
Basically Clang should only be suggesting a swap (and thus
complaining at all) in the case that swapping the arguments would
actually improve the situation.

–Arthur

On Sat, Jul 21, 2018 at 1:33 PM, Nico Weber via cfe-commits
mailto:cfe-commits@lists.llvm.org>>
wrote:

This has a false positive on ffmpeg:

../../third_party/ffmpeg/libavcodec/options.c:273:64: error:
'size' argument to memset is '0'; did you mean to transpose
the last two arguments? [-Werror,-Wmemset-transposed-args]
alloc_and_copy_or_fail(intra_matrix, 64 * sizeof(int16_t), 0);

With:

#define alloc_and_copy_or_fail(obj, size, pad) \
    if (src->obj && size > 0) { \
        dest->obj = av_malloc(size + pad); \
        if (!dest->obj) \
            goto fail; \
        memcpy(dest->obj, src->obj, size); \
        if (pad) \
            memset(((uint8_t *) dest->obj) + size, 0, pad); \
    }


(https://cs.chromium.org/chromium/src/third_party/ffmpeg/libavcodec/options.c?q=alloc_and_copy_or_fail&sq=package:chromium&g=0&l=261
; https://bugs.chromium.org/p/chromium/issues/detail?id=866202)

Maybe the warning shouldn't fire if the memset is from a macro?

On Thu, Jul 19, 2018 at 12:51 PM Erik Pilkington via
cfe-commits mailto:cfe-commits@lists.llvm.org>> wrote:

Author: epilk
Date: Thu Jul 19 09:46:15 2018
New Revision: 337470

URL: http://llvm.org/viewvc/llvm-project?rev=337470&view=rev
Log:
[Sema] Add a new warning, -Wmemset-transposed-args

This diagnoses calls to memset that have the second and
third arguments
transposed, for example:

  memset(buf, sizeof(buf), 0);

This is done by checking if the third argument is a
literal 0, or if the second
is a sizeof expression (and the third isn't). The first
check is also done for
calls to bzero.

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

Added:
    cfe/trunk/test/Sema/transpose-memset.c
Modified:
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
 

[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
emmettneyman updated this revision to Diff 157553.
emmettneyman added a comment.

Changed int to CodeGenOpt::Level and fixed unique_ptr issue


Repository:
  rC Clang

https://reviews.llvm.org/D49526

Files:
  clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
  clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
  clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp

Index: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
===
--- clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
+++ clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
@@ -7,33 +7,48 @@
 //
 //===--===//
 //
-// Implements HandleLLVM for use by the Clang fuzzers. Mimics the llc tool to
-// compile an LLVM IR file to X86_64 assembly.
+// Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
+// vectorizer optimization pass over the given IR code. Then mimics lli on both
+// versions to JIT the generated code and execute it. Currently, functions are 
+// executed on dummy inputs.
 //
 //===--===//
 
 #include "handle_llvm.h"
 
 #include "llvm/ADT/Triple.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/CodeGen/CommandFlags.inc"
 #include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/TargetPassConfig.h"
+#include "llvm/ExecutionEngine/JITEventListener.h"
+#include "llvm/ExecutionEngine/JITSymbol.h"
+#include "llvm/ExecutionEngine/MCJIT.h"
+#include "llvm/ExecutionEngine/ObjectCache.h"
+#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
+#include "llvm/ExecutionEngine/SectionMemoryManager.h"
+#include "llvm/IR/IRPrintingPasses.h"
 #include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/LegacyPassNameParser.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/Pass.h"
 #include "llvm/PassRegistry.h"
-#include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/TargetRegistry.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Target/TargetMachine.h"
-
-#include 
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Vectorize.h"
 
 using namespace llvm;
 
+// Helper function to parse command line args and find the optimization level
 static void getOptLevel(const std::vector &ExtraArgs,
   CodeGenOpt::Level &OLvl) {
   // Find the optimization level from the command line args
@@ -53,59 +68,112 @@
   }
 }
 
-void clang_fuzzer::HandleLLVM(const std::string &S,
-  const std::vector &ExtraArgs) {
-  // Parse ExtraArgs to set the optimization level
-  CodeGenOpt::Level OLvl;
-  getOptLevel(ExtraArgs, OLvl);
+void ErrorAndExit(std::string message) {
+  errs()<< "ERROR: " << message << "\n";
+  std::exit(1);
+}
 
-  // Set the Module to include the the IR code to be compiled
-  SMDiagnostic Err;
+// Helper function to add optimization passes to the TargetMachine at the 
+// specified optimization level, OptLevel
+static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
+  CodeGenOpt::Level OptLevel,
+  unsigned SizeLevel) {
+  // Create and initialize a PassManagerBuilder
+  PassManagerBuilder Builder;
+  Builder.OptLevel = OptLevel;
+  Builder.SizeLevel = SizeLevel;
+  Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
+  Builder.LoopVectorize = true;
+  Builder.populateModulePassManager(MPM);
+}
 
+// Mimics the opt tool to run an optimization pass over the provided IR
+std::string OptLLVM(const std::string &IR, CodeGenOpt::Level OLvl) {
+  // Create a module that will run the optimization passes
+  SMDiagnostic Err;
   LLVMContext Context;
-  std::unique_ptr M = parseIR(MemoryBufferRef(S, "IR"), Err, Context);
-  if (!M) {
-errs() << "error: could not parse IR!\n";
-std::exit(1);
-  }
+  std::unique_ptr M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
+  if (!M || verifyModule(*M, &errs()))
+ErrorAndExit("Could not parse IR");
 
-  // Create a new Target
-  std::string Error;
-  const Target *TheTarget = TargetRegistry::lookupTarget(
-  sys::getDefaultTargetTriple(), Error);
-  if (!TheTarget) {
-errs() << Error;
-std::exit(1);
-  }
+  setFunctionAttributes(getCPUStr(), getFeaturesStr(), *M);
+  
+  legacy::PassManager Passes;
+  Triple ModuleTriple(M->getTargetTriple());
+  
+  Passes.add(new TargetLibraryInfoWrapperPass(ModuleTriple));
+  Passes.add(createTargetTransformInfoWrapperPass(TargetIRAnalysis()));
+  Passes.add(createVerifierPass());
 
-  TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
-
-  // Create a n

[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
emmettneyman added a comment.

In https://reviews.llvm.org/D49526#1177208, @morehouse wrote:

> Do we need to parse the arguments for opt-level, or can we just hardcode 
> `-O2` and remove the argument parsing code?


I have the argument parsing code since the original `clang-proto-fuzzer` code 
had it and @kcc mentioned we might want to change the command line arguments in 
the future.


Repository:
  rC Clang

https://reviews.llvm.org/D49526



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


[PATCH] D49871: Improve support of PDB as an external layout source

2018-07-26 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rC Clang

https://reviews.llvm.org/D49871



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


[PATCH] D49833: [clangd] Receive compilationDatabasePath in 'initialize' request

2018-07-26 Thread Marc-Andre Laperle via Phabricator via cfe-commits
malaperle added a comment.

In https://reviews.llvm.org/D49833#1176337, @ilya-biryukov wrote:

> Not strictly opposed to this change, but is there any reason why the clients 
> can't guarantee they'll send didChangeConfiguration right after clangd is 
> initialized?


LSP:

> Until the server has responded to the initialize request with an 
> InitializeResult, the client must not send any additional requests or 
> notifications to the server.

So the client is free to send "didOpen" or any request after the "initialize", 
which means we could end up parsing files with wrong commands before we get the 
first "didChangeConfiguration". In fact, in our indexing prototype we start 
indexing as soon as the "initialize" is processed and we do not know whether or 
not there will be a didChangeConfiguration soon after.
Setting the CDB path as part of the initialize seems more natural and less 
error-prone.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D49833



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


Re: r337470 - [Sema] Add a new warning, -Wmemset-transposed-args

2018-07-26 Thread Richard Smith via cfe-commits
Other than the (fixed) ffmpeg false positive, I see this firing in three
places.

One of them is in the libc tests for memset and bzero, where the 0 argument
is intentional.
One of them is here:
https://github.com/apache/xerces-c/blob/trunk/src/xercesc/util/XMLUTF16Transcoder.cpp#L114
(note that this code is correct).
And one of them was a real bug where the second and third arguments of
memset were transposed.

That's an extremely low false positive rate, much lower than what we'd
expect for an enabled-by-default warning. I find this extremely surprising;
I would have expected the ratio of true-- to false-positives to be much
much higher. But ultimately data wins out over expectations.

How does our experience compare to other people's experiences? Are our
findings abnormal? (They may well be; our corpus is very C++-heavy.) If
this is indeed typical, we should reconsider whether to have these warnings
enabled by default, as they do not meet our bar for false positives.

On Mon, 23 Jul 2018 at 09:28, Erik Pilkington via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Sure, that seems pretty reasonable. r337706. Thanks for the suggestion!
>
> On 7/21/18 1:40 PM, Arthur O'Dwyer wrote:
>
> In this case Clang is complaining about
>
> memset(complicated-expr, 0, 0);
>
> which means that transposing the last two arguments would not "fix"
> anything. Clang ought to not complain in this case.
> It doesn't have anything to do with coming from a macro; it's just that
> *both* arguments are zero.
> (I would also expect that `memset(complicated-expr, (unsigned char)fill,
> (size_t)0)` shouldn't warn, either. But we had some disagreement that casts
> to `(unsigned char)` resp. `(size_t)` should be the right way to shut up
> the warning in the first place...)
> Basically Clang should only be suggesting a swap (and thus complaining at
> all) in the case that swapping the arguments would actually improve the
> situation.
>
> –Arthur
>
> On Sat, Jul 21, 2018 at 1:33 PM, Nico Weber via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> This has a false positive on ffmpeg:
>>
>> ../../third_party/ffmpeg/libavcodec/options.c:273:64: error: 'size'
>> argument to memset is '0'; did you mean to transpose the last two
>> arguments? [-Werror,-Wmemset-transposed-args]
>> alloc_and_copy_or_fail(intra_matrix, 64 * sizeof(int16_t), 0);
>>
>> With:
>>
>> #define alloc_and_copy_or_fail(obj, size, pad) \
>> if (src->obj && size > 0) { \
>> dest->obj = av_malloc(size + pad); \
>> if (!dest->obj) \
>> goto fail; \
>> memcpy(dest->obj, src->obj, size); \
>> if (pad) \
>> memset(((uint8_t *) dest->obj) + size, 0, pad); \
>> }
>>
>> (
>> https://cs.chromium.org/chromium/src/third_party/ffmpeg/libavcodec/options.c?q=alloc_and_copy_or_fail&sq=package:chromium&g=0&l=261
>> ; https://bugs.chromium.org/p/chromium/issues/detail?id=866202)
>>
>> Maybe the warning shouldn't fire if the memset is from a macro?
>>
>> On Thu, Jul 19, 2018 at 12:51 PM Erik Pilkington via cfe-commits <
>> cfe-commits@lists.llvm.org> wrote:
>>
>>> Author: epilk
>>> Date: Thu Jul 19 09:46:15 2018
>>> New Revision: 337470
>>>
>>> URL: http://llvm.org/viewvc/llvm-project?rev=337470&view=rev
>>> Log:
>>> [Sema] Add a new warning, -Wmemset-transposed-args
>>>
>>> This diagnoses calls to memset that have the second and third arguments
>>> transposed, for example:
>>>
>>>   memset(buf, sizeof(buf), 0);
>>>
>>> This is done by checking if the third argument is a literal 0, or if the
>>> second
>>> is a sizeof expression (and the third isn't). The first check is also
>>> done for
>>> calls to bzero.
>>>
>>> Differential revision: https://reviews.llvm.org/D49112
>>>
>>> Added:
>>> cfe/trunk/test/Sema/transpose-memset.c
>>> Modified:
>>> cfe/trunk/include/clang/Basic/DiagnosticGroups.td
>>> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
>>> cfe/trunk/lib/Sema/SemaChecking.cpp
>>>
>>> Modified: cfe/trunk/include/clang/Basic/DiagnosticGroups.td
>>> URL:
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?rev=337470&r1=337469&r2=337470&view=diff
>>>
>>> ==
>>> --- cfe/trunk/include/clang/Basic/DiagnosticGroups.td (original)
>>> +++ cfe/trunk/include/clang/Basic/DiagnosticGroups.td Thu Jul 19
>>> 09:46:15 2018
>>> @@ -443,6 +443,13 @@ def : DiagGroup<"synth">;
>>>  def SizeofArrayArgument : DiagGroup<"sizeof-array-argument">;
>>>  def SizeofArrayDecay : DiagGroup<"sizeof-array-decay">;
>>>  def SizeofPointerMemaccess : DiagGroup<"sizeof-pointer-memaccess">;
>>> +def MemsetTransposedArgs : DiagGroup<"memset-transposed-args">;
>>> +def DynamicClassMemaccess : DiagGroup<"dynamic-class-memaccess">;
>>> +def NonTrivialMemaccess : DiagGroup<"nontrivial-memaccess">;
>>> +def SuspiciousBzero : DiagGroup<"suspicious-bzero">;
>>> +def SuspiciousMemaccess : DiagGroup<"suspicious-memaccess"

[PATCH] D49589: [UBSan] Strengthen pointer checks in 'new' expressions

2018-07-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/CodeGen/CGClass.cpp:2190
  This, Args, AggValueSlot::MayOverlap,
- E->getLocation());
+ E->getLocation(), true);
 }

Please include `/* */` comments to describe what `true` and `false` mean as 
arguments throughout this patch, just like the `/*Delegating*/` comment here.



Comment at: lib/CodeGen/CGValue.h:487
+  /// them.
+  bool CheckedFlag : 1;
+

Are those checks anything more than pointer alignment?  If so, please call this
(and all the methods for it) `SanitizerCheckedFlag`; otherwise, please just 
call it
`AlignmentCheckedFlag`.


Repository:
  rC Clang

https://reviews.llvm.org/D49589



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


[PATCH] D49868: [Sema] Fix a crash by completing a type before using it

2018-07-26 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

Could you include a test that satisfies the exception but requires a template 
to be instantiated to check that?  It's probably already tested elsewhere, but 
still.


Repository:
  rC Clang

https://reviews.llvm.org/D49868



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


[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Matt Morehouse via Phabricator via cfe-commits
morehouse added a comment.

Do we need to parse the arguments for opt-level, or can we just hardcode `-O2` 
and remove the argument parsing code?




Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:144
+   Context);
+  Module *M = Owner.get();
+  if (!M)

emmettneyman wrote:
> morehouse wrote:
> > Why not just rename `Owner` to `M` and remove this line?
> Reverted it back since the change caused the fuzzer to crash.
You will need to move any uses of `M` above the call to `std::move`, since that 
leaves `M` in an invalid state.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:90
+// Mimics the opt tool to run an optimization pass over the provided IR
+std::string OptLLVM(const std::string &IR, int OLvl) {
+  // Create a module that will run the optimization passes

Shouldn't `OLvl` be a `CodeGenOpt::Level`?


Repository:
  rC Clang

https://reviews.llvm.org/D49526



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


[PATCH] D49715: [analyzer] CallEvent: Add partially working methods for obtaining the callee stack frame.

2018-07-26 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ updated this revision to Diff 157550.
NoQ added a comment.

Add one more handy method, `getAdjustedParameterIndex()`, which helps using 
`getParameterLocation()`.


https://reviews.llvm.org/D49715

Files:
  include/clang/Analysis/ConstructionContext.h
  include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
  include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
  lib/StaticAnalyzer/Core/CallEvent.cpp

Index: lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- lib/StaticAnalyzer/Core/CallEvent.cpp
+++ lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -27,6 +27,7 @@
 #include "clang/AST/Type.h"
 #include "clang/Analysis/AnalysisDeclContext.h"
 #include "clang/Analysis/CFG.h"
+#include "clang/Analysis/CFGStmtMap.h"
 #include "clang/Analysis/ProgramPoint.h"
 #include "clang/CrossTU/CrossTranslationUnit.h"
 #include "clang/Basic/IdentifierTable.h"
@@ -166,6 +167,68 @@
   return CheckerContext::isCLibraryFunction(FD, FunctionName);
 }
 
+AnalysisDeclContext *CallEvent::getCalleeAnalysisDeclContext() const {
+  const Decl *D = getDecl();
+
+  // If the callee is completely unknown, we cannot construct the stack frame.
+  if (!D)
+return nullptr;
+
+  // FIXME: Skip virtual functions for now. There's no easy procedure to foresee
+  // the exact decl that should be used, especially when it's not a definition.
+  if (const Decl *RD = getRuntimeDefinition().getDecl())
+if (RD != D)
+  return nullptr;
+
+  return LCtx->getAnalysisDeclContext()->getManager()->getContext(D);
+}
+
+const StackFrameContext *CallEvent::getCalleeStackFrame() const {
+  AnalysisDeclContext *ADC = getCalleeAnalysisDeclContext();
+  if (!ADC)
+return nullptr;
+
+  const Expr *E = getOriginExpr();
+  if (!E)
+return nullptr;
+
+  // Recover CFG block via reverse lookup.
+  // TODO: If we were to keep CFG element information as part of the CallEvent
+  // instead of doing this reverse lookup, we would be able to build the stack
+  // frame for non-expression-based calls, and also we wouldn't need the reverse
+  // lookup.
+  CFGStmtMap *Map = LCtx->getAnalysisDeclContext()->getCFGStmtMap();
+  const CFGBlock *B = Map->getBlock(E);
+  assert(B);
+
+  // Also recover CFG index by scanning the CFG block.
+  unsigned Idx = 0, Sz = B->size();
+  for (; Idx < Sz; ++Idx)
+if (auto StmtElem = (*B)[Idx].getAs())
+  if (StmtElem->getStmt() == E)
+break;
+  assert(Idx < Sz);
+
+  return ADC->getManager()->getStackFrame(ADC, LCtx, E, B, Idx);
+}
+
+const VarRegion *CallEvent::getParameterLocation(unsigned Index) const {
+  const StackFrameContext *SFC = getCalleeStackFrame();
+  // We cannot construct a VarRegion without a stack frame.
+  if (!SFC)
+return nullptr;
+
+  const ParmVarDecl *PVD = parameters()[Index];
+  const VarRegion *VR =
+  State->getStateManager().getRegionManager().getVarRegion(PVD, SFC);
+
+  // This sanity check would fail if our parameter declaration doesn't
+  // correspond to the stack frame's function declaration.
+  assert(VR->getStackFrame() == SFC);
+
+  return VR;
+}
+
 /// Returns true if a type is a pointer-to-const or reference-to-const
 /// with no further indirection.
 static bool isPointerToConst(QualType Ty) {
Index: include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -580,7 +580,15 @@
  SVal LHS, SVal RHS, QualType T) {
 return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
   }
-  
+
+  /// By looking at a certain item that may be potentially part of an object's
+  /// ConstructionContext, retrieve such object's location. A particular
+  /// statement can be transparently passed as \p Item in most cases.
+  static Optional
+  getObjectUnderConstruction(ProgramStateRef State,
+ const ConstructionContextItem &Item,
+ const LocationContext *LC);
+
 protected:
   /// evalBind - Handle the semantics of binding a value to a specific location.
   ///  This method is used by evalStore, VisitDeclStmt, and others.
@@ -773,13 +781,6 @@
const ConstructionContextItem &Item,
const LocationContext *LC);
 
-  /// If the given statement corresponds to an object under construction,
-  /// being part of its construciton context, retrieve that object's location.
-  static Optional
-  getObjectUnderConstruction(ProgramStateRef State,
- const ConstructionContextItem &Item,
- const LocationContext *LC);
-
   /// If the given expression corresponds to a temporary that was used for
   /// passing into an elidable copy/move constructor and that constructor
   /// was actually elided, track that we also need to elide the destructor.
Index: include/c

[PATCH] D49871: Improve support of PDB as an external layout source

2018-07-26 Thread Aleksandr Urakov via Phabricator via cfe-commits
aleksandr.urakov created this revision.
aleksandr.urakov added reviewers: rsmith, zturner, rnk, mstorsjo, majnemer.
aleksandr.urakov added a project: clang.

This patch improves support of PDB as an external layout source in the next 
cases:

- Multiple non-virtual inheritance from packed base classes. When using 
external layout, there's no need to align `NonVirtualSize` of a base class. It 
may cause an overlapping when the next base classes will be layouted (but there 
is a slightly different case in the test because I can't find a way to specify 
a base offset);
- Support of nameless structs and unions. There is no info about nameless child 
structs and unions in Microsoft cl-emitted PDBs. Instead all its fields are 
just treated as outer structure's (union's) fields. This also causes a fields 
overlapping, and makes it possible for unions to have fields located at a 
non-zero offset.


Repository:
  rC Clang

https://reviews.llvm.org/D49871

Files:
  lib/AST/RecordLayoutBuilder.cpp
  test/CodeGenCXX/Inputs/override-layout-nameless-struct-union.layout
  test/CodeGenCXX/Inputs/override-layout-packed-base.layout
  test/CodeGenCXX/override-layout-nameless-struct-union.cpp
  test/CodeGenCXX/override-layout-packed-base.cpp

Index: test/CodeGenCXX/override-layout-packed-base.cpp
===
--- /dev/null
+++ test/CodeGenCXX/override-layout-packed-base.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -w -fdump-record-layouts-simple -foverride-record-layout=%S/Inputs/override-layout-packed-base.layout %s | FileCheck %s
+
+// CHECK: Type: class B<0>
+// CHECK:   FieldOffsets: [0, 32]
+
+// CHECK: Type: class B<1>
+// CHECK:   FieldOffsets: [0, 32]
+
+//#pragma pack(push, 1)
+template
+class B {
+  int _b1;
+  char _b2;
+};
+//#pragma pack(pop)
+
+// CHECK: Type: class C
+// CHECK:   FieldOffsets: [80]
+
+class C : B<0>, B<1> {
+  char _c;
+};
+
+void use_structs() {
+  C cs[sizeof(C)];
+}
Index: test/CodeGenCXX/override-layout-nameless-struct-union.cpp
===
--- /dev/null
+++ test/CodeGenCXX/override-layout-nameless-struct-union.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -w -fdump-record-layouts-simple -foverride-record-layout=%S/Inputs/override-layout-nameless-struct-union.layout %s | FileCheck %s
+
+// CHECK: Type: struct S
+// CHECK:   Size:64
+// CHECK:   Alignment:32
+// CHECK:   FieldOffsets: [0, 32, 32]
+struct S {
+  short _s;
+//union {
+int _su0;
+char _su1;
+//};
+};
+
+// CHECK: Type: union U
+// CHECK:   Size:96
+// CHECK:   Alignment:32
+// CHECK:   FieldOffsets: [0, 0, 32, 64, 68, 73]
+union U {
+  short _u;
+//struct {
+char _us0;
+int _us1;
+unsigned _us20 : 4;
+unsigned _us21 : 5;
+unsigned _us22 : 6;
+//};
+};
+
+void use_structs() {
+  S ss[sizeof(S)];
+  U us[sizeof(U)];
+}
Index: test/CodeGenCXX/Inputs/override-layout-packed-base.layout
===
--- /dev/null
+++ test/CodeGenCXX/Inputs/override-layout-packed-base.layout
@@ -0,0 +1,18 @@
+
+*** Dumping AST Record Layout
+Type: class B<0>
+
+Layout: 
+
+*** Dumping AST Record Layout
+Type: class B<1>
+
+Layout: 
+
+*** Dumping AST Record Layout
+Type: class C
+
+Layout: 
Index: test/CodeGenCXX/Inputs/override-layout-nameless-struct-union.layout
===
--- /dev/null
+++ test/CodeGenCXX/Inputs/override-layout-nameless-struct-union.layout
@@ -0,0 +1,16 @@
+
+*** Dumping AST Record Layout
+Type: struct S
+
+Layout: 
+
+*** Dumping AST Record Layout
+Type: union U
+
+Layout: 
Index: lib/AST/RecordLayoutBuilder.cpp
===
--- lib/AST/RecordLayoutBuilder.cpp
+++ lib/AST/RecordLayoutBuilder.cpp
@@ -2445,7 +2445,9 @@
   auto RoundingAlignment = Alignment;
   if (!MaxFieldAlignment.isZero())
 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
-  NonVirtualSize = Size = Size.alignTo(RoundingAlignment);
+  if (!UseExternalLayout)
+Size = Size.alignTo(RoundingAlignment);
+  NonVirtualSize = Size;
   RequiredAlignment = std::max(
   RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
   layoutVirtualBases(RD);
@@ -2646,21 +2648,16 @@
   LastFieldIsNonZeroWidthBitfield = false;
   ElementInfo Info = getAdjustedElementInfo(FD);
   Alignment = std::max(Alignment, Info.Alignment);
-  if (IsUnion) {
-placeFieldAtOffset(CharUnits::Zero());
-Size = std::max(Size, Info.Size);
-  } else {
-CharUnits FieldOffset;
-if (UseExternalLayout) {
-  FieldOffset =
-  Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
-  assert(FieldOffset >= Size && "field offset already allocated");
-} else {
-  FieldOffset = Size.alignTo(Info.Alignment);
-}
-placeFieldAtOffset(FieldOffset);
-Size = FieldOffset + Info.Size;
-  }
+  CharUnits FieldOffset;
+  if (Use

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

2018-07-26 Thread Simon Marchi via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC338057: [VirtualFileSystem] InMemoryFileSystem::status: 
Return a Status with the… (authored by simark, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D48903?vs=157467&id=157548#toc

Repository:
  rC Clang

https://reviews.llvm.org/D48903

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

Index: lib/Basic/FileManager.cpp
===
--- lib/Basic/FileManager.cpp
+++ lib/Basic/FileManager.cpp
@@ -315,9 +315,11 @@
   UFE.InPCH = Data.InPCH;
   UFE.File = std::move(F);
   UFE.IsValid = true;
-  if (UFE.File)
-if (auto RealPathName = UFE.File->getName())
-  UFE.RealPathName = *RealPathName;
+
+  SmallString<128> RealPathName;
+  if (!FS->getRealPath(InterndFileName, RealPathName))
+UFE.RealPathName = RealPathName.str();
+
   return &UFE;
 }
 
Index: lib/Basic/VirtualFileSystem.cpp
===
--- lib/Basic/VirtualFileSystem.cpp
+++ lib/Basic/VirtualFileSystem.cpp
@@ -474,12 +474,28 @@
   Status Stat;
   InMemoryNodeKind Kind;
 
+protected:
+  /// Return Stat.  This should only be used for internal/debugging use.  When
+  /// clients wants the Status of this node, they should use
+  /// \p getStatus(StringRef).
+  const Status &getStatus() const { return Stat; }
+
 public:
   InMemoryNode(Status Stat, InMemoryNodeKind Kind)
   : Stat(std::move(Stat)), Kind(Kind) {}
   virtual ~InMemoryNode() = default;
 
-  const Status &getStatus() const { return Stat; }
+  /// Return the \p Status for this node. \p RequestedName should be the name
+  /// through which the caller referred to this node. It will override
+  /// \p Status::Name in the return value, to mimic the behavior of \p RealFile.
+  Status getStatus(StringRef RequestedName) const {
+return Status::copyWithNewName(Stat, RequestedName);
+  }
+
+  /// Get the filename of this node (the name without the directory part).
+  StringRef getFileName() const {
+return llvm::sys::path::filename(Stat.getName());
+  }
   InMemoryNodeKind getKind() const { return Kind; }
   virtual std::string toString(unsigned Indent) const = 0;
 };
@@ -504,14 +520,21 @@
   }
 };
 
-/// Adapt a InMemoryFile for VFS' File interface.
+/// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
+/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
+/// \p RealFile.
 class InMemoryFileAdaptor : public File {
   InMemoryFile &Node;
+  /// The name to use when returning a Status for this file.
+  std::string RequestedName;
 
 public:
-  explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
+  explicit InMemoryFileAdaptor(InMemoryFile &Node, std::string RequestedName)
+  : Node(Node), RequestedName(std::move(RequestedName)) {}
 
-  llvm::ErrorOr status() override { return Node.getStatus(); }
+  llvm::ErrorOr status() override {
+return Node.getStatus(RequestedName);
+  }
 
   llvm::ErrorOr>
   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
@@ -711,7 +734,7 @@
 llvm::ErrorOr InMemoryFileSystem::status(const Twine &Path) {
   auto Node = lookupInMemoryNode(*this, Root.get(), Path);
   if (Node)
-return (*Node)->getStatus();
+return (*Node)->getStatus(Path.str());
   return Node.getError();
 }
 
@@ -724,7 +747,8 @@
   // When we have a file provide a heap-allocated wrapper for the memory buffer
   // to match the ownership semantics for File.
   if (auto *F = dyn_cast(*Node))
-return std::unique_ptr(new detail::InMemoryFileAdaptor(*F));
+return std::unique_ptr(
+new detail::InMemoryFileAdaptor(*F, Path.str()));
 
   // FIXME: errc::not_a_file?
   return make_error_code(llvm::errc::invalid_argument);
@@ -736,21 +760,33 @@
 class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
   detail::InMemoryDirectory::const_iterator I;
   detail::InMemoryDirectory::const_iterator E;
+  std::string RequestedDirName;
+
+  void setCurrentEntry() {
+if (I != E) {
+  SmallString<256> Path(RequestedDirName);
+  llvm::sys::path::append(Path, I->second->getFileName());
+  CurrentEntry = I->second->getStatus(Path);
+} else {
+  // When we're at the end, make CurrentEntry invalid and DirIterImpl will
+  // do the rest.
+  CurrentEntry = Status();
+}
+  }
 
 public:
   InMemoryDirIterator() = default;
 
-  explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
-  : I(Dir.begin()), E(Dir.end()) {
-if (I != E)
-  CurrentEntry = I->second->getStatus();
+  explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir,
+   std::string RequestedDirName)
+  : I(Dir.begin()), E(Dir.end()),
+RequestedDirName(std::move(RequestedDirName)) {
+setCurrentEntry();
   }
 
   std::error

r338057 - [VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the requested name

2018-07-26 Thread Simon Marchi via cfe-commits
Author: simark
Date: Thu Jul 26 11:55:02 2018
New Revision: 338057

URL: http://llvm.org/viewvc/llvm-project?rev=338057&view=rev
Log:
[VirtualFileSystem] InMemoryFileSystem::status: Return a Status with the 
requested name

Summary:

InMemoryFileSystem::status behaves differently than
RealFileSystem::status.  The Name contained in the Status returned by
RealFileSystem::status will be the path as requested by the caller,
whereas InMemoryFileSystem::status returns the normalized path.

For example, when requested the status for "../src/first.h",
RealFileSystem returns a Status with "../src/first.h" as the Name.
InMemoryFileSystem returns "/absolute/path/to/src/first.h".

The reason for this change is that I want to make a unit test in the
clangd testsuite (where we use an InMemoryFileSystem) to reproduce a
bug I get with the clangd program (where a RealFileSystem is used).
This difference in behavior "hides" the bug in the unit test version.

Reviewers: malaperle, ilya-biryukov, bkramer

Subscribers: cfe-commits, ioeric, ilya-biryukov, bkramer, hokein, omtcyfz

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

Modified:
cfe/trunk/lib/Basic/FileManager.cpp
cfe/trunk/lib/Basic/VirtualFileSystem.cpp
cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp
cfe/trunk/unittests/Driver/ToolChainTest.cpp

Modified: cfe/trunk/lib/Basic/FileManager.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/FileManager.cpp?rev=338057&r1=338056&r2=338057&view=diff
==
--- cfe/trunk/lib/Basic/FileManager.cpp (original)
+++ cfe/trunk/lib/Basic/FileManager.cpp Thu Jul 26 11:55:02 2018
@@ -315,9 +315,11 @@ const FileEntry *FileManager::getFile(St
   UFE.InPCH = Data.InPCH;
   UFE.File = std::move(F);
   UFE.IsValid = true;
-  if (UFE.File)
-if (auto RealPathName = UFE.File->getName())
-  UFE.RealPathName = *RealPathName;
+
+  SmallString<128> RealPathName;
+  if (!FS->getRealPath(InterndFileName, RealPathName))
+UFE.RealPathName = RealPathName.str();
+
   return &UFE;
 }
 

Modified: cfe/trunk/lib/Basic/VirtualFileSystem.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/VirtualFileSystem.cpp?rev=338057&r1=338056&r2=338057&view=diff
==
--- cfe/trunk/lib/Basic/VirtualFileSystem.cpp (original)
+++ cfe/trunk/lib/Basic/VirtualFileSystem.cpp Thu Jul 26 11:55:02 2018
@@ -474,12 +474,28 @@ class InMemoryNode {
   Status Stat;
   InMemoryNodeKind Kind;
 
+protected:
+  /// Return Stat.  This should only be used for internal/debugging use.  When
+  /// clients wants the Status of this node, they should use
+  /// \p getStatus(StringRef).
+  const Status &getStatus() const { return Stat; }
+
 public:
   InMemoryNode(Status Stat, InMemoryNodeKind Kind)
   : Stat(std::move(Stat)), Kind(Kind) {}
   virtual ~InMemoryNode() = default;
 
-  const Status &getStatus() const { return Stat; }
+  /// Return the \p Status for this node. \p RequestedName should be the name
+  /// through which the caller referred to this node. It will override
+  /// \p Status::Name in the return value, to mimic the behavior of \p 
RealFile.
+  Status getStatus(StringRef RequestedName) const {
+return Status::copyWithNewName(Stat, RequestedName);
+  }
+
+  /// Get the filename of this node (the name without the directory part).
+  StringRef getFileName() const {
+return llvm::sys::path::filename(Stat.getName());
+  }
   InMemoryNodeKind getKind() const { return Kind; }
   virtual std::string toString(unsigned Indent) const = 0;
 };
@@ -504,14 +520,21 @@ public:
   }
 };
 
-/// Adapt a InMemoryFile for VFS' File interface.
+/// Adapt a InMemoryFile for VFS' File interface.  The goal is to make
+/// \p InMemoryFileAdaptor mimic as much as possible the behavior of
+/// \p RealFile.
 class InMemoryFileAdaptor : public File {
   InMemoryFile &Node;
+  /// The name to use when returning a Status for this file.
+  std::string RequestedName;
 
 public:
-  explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
+  explicit InMemoryFileAdaptor(InMemoryFile &Node, std::string RequestedName)
+  : Node(Node), RequestedName(std::move(RequestedName)) {}
 
-  llvm::ErrorOr status() override { return Node.getStatus(); }
+  llvm::ErrorOr status() override {
+return Node.getStatus(RequestedName);
+  }
 
   llvm::ErrorOr>
   getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
@@ -711,7 +734,7 @@ lookupInMemoryNode(const InMemoryFileSys
 llvm::ErrorOr InMemoryFileSystem::status(const Twine &Path) {
   auto Node = lookupInMemoryNode(*this, Root.get(), Path);
   if (Node)
-return (*Node)->getStatus();
+return (*Node)->getStatus(Path.str());
   return Node.getError();
 }
 
@@ -724,7 +747,8 @@ InMemoryFileSystem::openFileForRead(cons
   // When we have a file provide a heap-allocated wrapper for the memory buffer
   // to match t

[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
emmettneyman updated this revision to Diff 157545.
emmettneyman added a comment.

Small change to fix line length


Repository:
  rC Clang

https://reviews.llvm.org/D49526

Files:
  clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
  clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
  clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp

Index: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
===
--- clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
+++ clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
@@ -7,33 +7,48 @@
 //
 //===--===//
 //
-// Implements HandleLLVM for use by the Clang fuzzers. Mimics the llc tool to
-// compile an LLVM IR file to X86_64 assembly.
+// Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
+// vectorizer optimization pass over the given IR code. Then mimics lli on both
+// versions to JIT the generated code and execute it. Currently, functions are 
+// executed on dummy inputs.
 //
 //===--===//
 
 #include "handle_llvm.h"
 
 #include "llvm/ADT/Triple.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/CodeGen/CommandFlags.inc"
 #include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/TargetPassConfig.h"
+#include "llvm/ExecutionEngine/JITEventListener.h"
+#include "llvm/ExecutionEngine/JITSymbol.h"
+#include "llvm/ExecutionEngine/MCJIT.h"
+#include "llvm/ExecutionEngine/ObjectCache.h"
+#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
+#include "llvm/ExecutionEngine/SectionMemoryManager.h"
+#include "llvm/IR/IRPrintingPasses.h"
 #include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/LegacyPassNameParser.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/Pass.h"
 #include "llvm/PassRegistry.h"
-#include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/TargetRegistry.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Target/TargetMachine.h"
-
-#include 
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Vectorize.h"
 
 using namespace llvm;
 
+// Helper function to parse command line args and find the optimization level
 static void getOptLevel(const std::vector &ExtraArgs,
   CodeGenOpt::Level &OLvl) {
   // Find the optimization level from the command line args
@@ -53,59 +68,111 @@
   }
 }
 
-void clang_fuzzer::HandleLLVM(const std::string &S,
-  const std::vector &ExtraArgs) {
-  // Parse ExtraArgs to set the optimization level
-  CodeGenOpt::Level OLvl;
-  getOptLevel(ExtraArgs, OLvl);
+void ErrorAndExit(std::string message) {
+  errs()<< "ERROR: " << message << "\n";
+  std::exit(1);
+}
 
-  // Set the Module to include the the IR code to be compiled
-  SMDiagnostic Err;
+// Helper function to add optimization passes to the TargetMachine at the 
+// specified optimization level, OptLevel
+static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
+  unsigned OptLevel, unsigned SizeLevel) {
+  // Create and initialize a PassManagerBuilder
+  PassManagerBuilder Builder;
+  Builder.OptLevel = OptLevel;
+  Builder.SizeLevel = SizeLevel;
+  Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
+  Builder.LoopVectorize = true;
+  Builder.populateModulePassManager(MPM);
+}
 
+// Mimics the opt tool to run an optimization pass over the provided IR
+std::string OptLLVM(const std::string &IR, int OLvl) {
+  // Create a module that will run the optimization passes
+  SMDiagnostic Err;
   LLVMContext Context;
-  std::unique_ptr M = parseIR(MemoryBufferRef(S, "IR"), Err, Context);
-  if (!M) {
-errs() << "error: could not parse IR!\n";
-std::exit(1);
-  }
+  std::unique_ptr M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
+  if (!M || verifyModule(*M, &errs()))
+ErrorAndExit("Could not parse IR");
 
-  // Create a new Target
-  std::string Error;
-  const Target *TheTarget = TargetRegistry::lookupTarget(
-  sys::getDefaultTargetTriple(), Error);
-  if (!TheTarget) {
-errs() << Error;
-std::exit(1);
-  }
+  setFunctionAttributes(getCPUStr(), getFeaturesStr(), *M);
+  
+  legacy::PassManager Passes;
+  Triple ModuleTriple(M->getTargetTriple());
+  
+  Passes.add(new TargetLibraryInfoWrapperPass(ModuleTriple));
+  Passes.add(createTargetTransformInfoWrapperPass(TargetIRAnalysis()));
+  Passes.add(createVerifierPass());
 
-  TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
-
-  // Create a new Machine
-  std::string CPUStr = getCPUStr();
-  std::string FeaturesStr = getFeatur

[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
emmettneyman added inline comments.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:144
+   Context);
+  Module *M = Owner.get();
+  if (!M)

morehouse wrote:
> Why not just rename `Owner` to `M` and remove this line?
Reverted it back since the change caused the fuzzer to crash.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:147
+  builder.setUseOrcMCJITReplacement(false);
+  builder.setMCJITMemoryManager(make_unique());
+  builder.setOptLevel(OLvl);

morehouse wrote:
> This uses `llvm:make_unique`, which was written when LLVM used C++11.  But 
> since LLVM now uses C++14, I think we should use `std::make_unique` instead.
We talked offline, but just to put it in writing: My current LLVM build uses 
C++11 so I'm keeping it `llvm::make_unique`.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:184
+  CodeGenOpt::Level OLvl;
+  getOptLevel(ExtraArgs, OLvl);
+  

morehouse wrote:
> We're allowing the JIT opt-level to be specified on the command line, but 
> we're hard-coding OptLevel=3 for the optimization passes.
> 
> Do we need to allow the opt-level to be specified on the command line?
Good point. Will change to make `OptLLVM()` use the same optimization level as 
the JIT Engine.


Repository:
  rC Clang

https://reviews.llvm.org/D49526



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


[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Emmett Neyman via Phabricator via cfe-commits
emmettneyman updated this revision to Diff 157544.
emmettneyman added a comment.

- Code style fixes
- Removed `FPasses`
- Allowed CL Args to specify opt level for `OptLLVM()`


Repository:
  rC Clang

https://reviews.llvm.org/D49526

Files:
  clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp
  clang/tools/clang-fuzzer/handle-llvm/CMakeLists.txt
  clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp

Index: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
===
--- clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
+++ clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
@@ -7,33 +7,48 @@
 //
 //===--===//
 //
-// Implements HandleLLVM for use by the Clang fuzzers. Mimics the llc tool to
-// compile an LLVM IR file to X86_64 assembly.
+// Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
+// vectorizer optimization pass over the given IR code. Then mimics lli on both
+// versions to JIT the generated code and execute it. Currently, functions are 
+// executed on dummy inputs.
 //
 //===--===//
 
 #include "handle_llvm.h"
 
 #include "llvm/ADT/Triple.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/TargetTransformInfo.h"
 #include "llvm/CodeGen/CommandFlags.inc"
 #include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/TargetPassConfig.h"
+#include "llvm/ExecutionEngine/JITEventListener.h"
+#include "llvm/ExecutionEngine/JITSymbol.h"
+#include "llvm/ExecutionEngine/MCJIT.h"
+#include "llvm/ExecutionEngine/ObjectCache.h"
+#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
+#include "llvm/ExecutionEngine/SectionMemoryManager.h"
+#include "llvm/IR/IRPrintingPasses.h"
 #include "llvm/IR/LegacyPassManager.h"
+#include "llvm/IR/LegacyPassNameParser.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Verifier.h"
 #include "llvm/IRReader/IRReader.h"
+#include "llvm/Pass.h"
 #include "llvm/PassRegistry.h"
-#include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/TargetRegistry.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Target/TargetMachine.h"
-
-#include 
+#include "llvm/Transforms/IPO/PassManagerBuilder.h"
+#include "llvm/Transforms/IPO.h"
+#include "llvm/Transforms/Vectorize.h"
 
 using namespace llvm;
 
+// Helper function to parse command line args and find the optimization level
 static void getOptLevel(const std::vector &ExtraArgs,
   CodeGenOpt::Level &OLvl) {
   // Find the optimization level from the command line args
@@ -53,59 +68,110 @@
   }
 }
 
-void clang_fuzzer::HandleLLVM(const std::string &S,
-  const std::vector &ExtraArgs) {
-  // Parse ExtraArgs to set the optimization level
-  CodeGenOpt::Level OLvl;
-  getOptLevel(ExtraArgs, OLvl);
+void ErrorAndExit(std::string message) {
+  errs()<< "ERROR: " << message << "\n";
+  std::exit(1);
+}
 
-  // Set the Module to include the the IR code to be compiled
-  SMDiagnostic Err;
+// Helper function to add optimization passes to the TargetMachine at the 
+// specified optimization level, OptLevel
+static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
+  unsigned OptLevel, unsigned SizeLevel) {
+  // Create and initialize a PassManagerBuilder
+  PassManagerBuilder Builder;
+  Builder.OptLevel = OptLevel;
+  Builder.SizeLevel = SizeLevel;
+  Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
+  Builder.LoopVectorize = true;
+  Builder.populateModulePassManager(MPM);
+}
 
+// Mimics the opt tool to run an optimization pass over the provided IR
+std::string OptLLVM(const std::string &IR, int OLvl) {
+  // Create a module that will run the optimization passes
+  SMDiagnostic Err;
   LLVMContext Context;
-  std::unique_ptr M = parseIR(MemoryBufferRef(S, "IR"), Err, Context);
-  if (!M) {
-errs() << "error: could not parse IR!\n";
-std::exit(1);
-  }
+  std::unique_ptr M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
+  if (!M || verifyModule(*M, &errs()))
+ErrorAndExit("Could not parse IR");
 
-  // Create a new Target
-  std::string Error;
-  const Target *TheTarget = TargetRegistry::lookupTarget(
-  sys::getDefaultTargetTriple(), Error);
-  if (!TheTarget) {
-errs() << Error;
-std::exit(1);
-  }
+  setFunctionAttributes(getCPUStr(), getFeaturesStr(), *M);
+  
+  legacy::PassManager Passes;
+  Triple ModuleTriple(M->getTargetTriple());
+  
+  Passes.add(new TargetLibraryInfoWrapperPass(ModuleTriple));
+  Passes.add(createTargetTransformInfoWrapperPass(TargetIRAnalysis()));
+  Passes.add(createVerifierPass());
 
-  TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
-
-  // Create a new Machine
-  std::strin

[PATCH] D49526: Updated llvm-proto-fuzzer to execute the compiled code

2018-07-26 Thread Peter Collingbourne via Phabricator via cfe-commits
pcc added inline comments.



Comment at: clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp:147
+  builder.setUseOrcMCJITReplacement(false);
+  builder.setMCJITMemoryManager(make_unique());
+  builder.setOptLevel(OLvl);

morehouse wrote:
> This uses `llvm:make_unique`, which was written when LLVM used C++11.  But 
> since LLVM now uses C++14, I think we should use `std::make_unique` instead.
LLVM doesn't use C++14 yet.


Repository:
  rC Clang

https://reviews.llvm.org/D49526



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


r338056 - Refactor checking of switch conditions and case values.

2018-07-26 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Thu Jul 26 11:41:30 2018
New Revision: 338056

URL: http://llvm.org/viewvc/llvm-project?rev=338056&view=rev
Log:
Refactor checking of switch conditions and case values.

Check each case value in turn while parsing it, performing the
conversion to the switch type within the context of the expression
itself. This will become necessary in order to properly handle cleanups
for temporaries created as part of the case label (in an upcoming
patch). For now it's just good hygiene.

This necessitates moving the checking for the switch condition itself to
earlier, so that the destination type is available when checking the
case labels.

As a nice side-effect, we get slightly improved diagnostic quality and
error recovery by separating the case expression checking from the case
statement checking and from tracking whether there are discarded case
labels.

Modified:
cfe/trunk/include/clang/Parse/Parser.h
cfe/trunk/include/clang/Sema/ScopeInfo.h
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Parse/ParseExpr.cpp
cfe/trunk/lib/Parse/ParseStmt.cpp
cfe/trunk/lib/Sema/SemaCodeComplete.cpp
cfe/trunk/lib/Sema/SemaStmt.cpp
cfe/trunk/lib/Sema/TreeTransform.h
cfe/trunk/test/Parser/switch-recovery.cpp
cfe/trunk/test/Sema/complex-int.c
cfe/trunk/test/Sema/switch.c
cfe/trunk/test/SemaCXX/i-c-e-cxx.cpp
cfe/trunk/test/SemaCXX/scope-check.cpp
cfe/trunk/test/SemaCXX/typo-correction.cpp

Modified: cfe/trunk/include/clang/Parse/Parser.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Parse/Parser.h?rev=338056&r1=338055&r2=338056&view=diff
==
--- cfe/trunk/include/clang/Parse/Parser.h (original)
+++ cfe/trunk/include/clang/Parse/Parser.h Thu Jul 26 11:41:30 2018
@@ -1578,6 +1578,7 @@ public:
   ExprResult ParseConstantExpressionInExprEvalContext(
   TypeCastState isTypeCast = NotTypeCast);
   ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
+  ExprResult ParseCaseExpression(SourceLocation CaseLoc);
   ExprResult ParseConstraintExpression();
   // Expr that doesn't include commas.
   ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);

Modified: cfe/trunk/include/clang/Sema/ScopeInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/ScopeInfo.h?rev=338056&r1=338055&r2=338056&view=diff
==
--- cfe/trunk/include/clang/Sema/ScopeInfo.h (original)
+++ cfe/trunk/include/clang/Sema/ScopeInfo.h Thu Jul 26 11:41:30 2018
@@ -175,9 +175,13 @@ public:
   /// Used to determine if errors occurred in this function or block.
   DiagnosticErrorTrap ErrorTrap;
 
+  /// A SwitchStmt, along with a flag indicating if its list of case statements
+  /// is incomplete (because we dropped an invalid one while parsing).
+  using SwitchInfo = llvm::PointerIntPair;
+
   /// SwitchStack - This is the current set of active switch statements in the
   /// block.
-  SmallVector SwitchStack;
+  SmallVector SwitchStack;
 
   /// The list of return statements that occur within the function or
   /// block, if there is any chance of applying the named return value

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=338056&r1=338055&r2=338056&view=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Thu Jul 26 11:41:30 2018
@@ -3727,9 +3727,10 @@ public:
SourceLocation EndLoc);
   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
   StmtResult ActOnForEachLValueExpr(Expr *E);
-  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
-   SourceLocation DotDotDotLoc, Expr *RHSVal,
-   SourceLocation ColonLoc);
+  ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
+  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
+   SourceLocation DotDotDotLoc, ExprResult RHS,
+   SourceLocation ColonLoc);
   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
 
   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,

Modified: cfe/trunk/lib/Parse/ParseExpr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseExpr.cpp?rev=338056&r1=338055&r2=338056&view=diff
==
--- cfe/trunk/lib/Parse/ParseExpr.cpp (original)
+++ cfe/trunk/lib/Parse/ParseExpr.cpp Thu Jul 26 11:41:30 2018
@@ -217,6 +217,14 @@ ExprResult Parser::ParseConstantExpressi
   return ParseConstantExpressionInExprEvalContext(isTypeCast);
 }
 
+ExprResult Parser::ParseCaseExpression(SourceLocation CaseLoc) {
+  EnterExpressionEvaluationCon

r338055 - [OPENMP, DOCS] Fixed typo, NFC.

2018-07-26 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Thu Jul 26 11:40:41 2018
New Revision: 338055

URL: http://llvm.org/viewvc/llvm-project?rev=338055&view=rev
Log:
[OPENMP, DOCS] Fixed typo, NFC.

Modified:
cfe/trunk/docs/ReleaseNotes.rst

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=338055&r1=338054&r2=338055&view=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Thu Jul 26 11:40:41 2018
@@ -226,7 +226,7 @@ OpenMP Support in Clang
   option will be forwarded to the respective OpenMP device offloading toolchain
   described by the triple. For example passing the compute capability to
   the OpenMP NVPTX offloading toolchain can be done as follows:
-  `-Xopenmp-target=nvptx62-nvidia-cuda -march=sm_60`. For the case when only 
one
+  `-Xopenmp-target=nvptx64-nvidia-cuda -march=sm_60`. For the case when only 
one
   target offload toolchain is specified under the `-fopenmp-targets=`
   option, then the triple can be skipped: `-Xopenmp-target -march=sm_60`.
 


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


[PATCH] D49715: [analyzer] CallEvent: Add partially working methods for obtaining the callee stack frame.

2018-07-26 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: lib/StaticAnalyzer/Core/CallEvent.cpp:197
+
+  // Recover CFG block via reverse lookup. Maybe it should just be a part of 
the
+  // CallEvent object? That would have been convenient.

george.karpenkov wrote:
> Can we remove "maybe" / "that would have been" comments?
Changed them into a TODO because they're rather important to keep. Like, that's 
a flaw in this code.


https://reviews.llvm.org/D49715



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


Re: [clang-tools-extra] r338017 - [clangd] Proof-of-concept query iterators for Dex symbol index

2018-07-26 Thread Kirill Bobyrev via cfe-commits
Hi Jeremy,

Thank you for reporting the issue and apologies for inconvenience. There
was another bug which caused buildbots crashes, I was looking into that
before so I missed this one.

I built Clang 3.6 and Clang 3.7 locally, simply wrapping everything into
std::move didn't resolve the issue, I reverted the changes (
https://reviews.llvm.org/rL338054) and will investigate.

Thank you for reaching out,
Kirill Bobyrev

On Thu, Jul 26, 2018 at 7:16 PM Jeremy Morse 
wrote:

> [Resending with cfe-commits@, whoops]
>
> Hi Kirill,
>
> We believe this patch might be breaking one of the buildbots:
>
>
> http://lab.llvm.org:8011/builders/clang-x86_64-linux-abi-test/builds/29719
>
> Which is complaining about the std::unique_ptr copy constructor being
> called in DexIndexTests.cpp. It seems likely that returning a unique_ptr:
>
> > std::unique_ptr
> > createAnd(std::vector> Children) {
> >   return llvm::make_unique(move(Children));
> > }
>
> And sites such as:
>
> >  auto AndEmpty = createAnd({create(L0)});
>
> Are triggering a bug in clang 3.7 and 3.8 where the move constructor isn't
> correctly inferred:
>
> https://godbolt.org/g/Aquug4
>
> Wrapping everything in std::move will likely fix that, those two versions
> of clang are still officially supported by LLVM/Clang.
>
> --
> Thanks,
> Jeremy
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r338054 - Revert Clangd Dex Iterators patch

2018-07-26 Thread Kirill Bobyrev via cfe-commits
Author: omtcyfz
Date: Thu Jul 26 11:25:48 2018
New Revision: 338054

URL: http://llvm.org/viewvc/llvm-project?rev=338054&view=rev
Log:
Revert Clangd Dex Iterators patch

This reverts two revisions:

* https://reviews.llvm.org/rL338017
* https://reviews.llvm.org/rL338028

They caused crash for Clang 3.6 & Clang 3.7 buildbots, it was
reported by Jeremy Morse.

Removed:
clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
clang-tools-extra/trunk/clangd/index/dex/Iterator.h
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/unittests/clangd/DexIndexTests.cpp

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=338054&r1=338053&r2=338054&view=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Thu Jul 26 11:25:48 2018
@@ -43,7 +43,6 @@ add_clang_library(clangDaemon
   index/SymbolCollector.cpp
   index/SymbolYAML.cpp
 
-  index/dex/Iterator.cpp
   index/dex/Trigram.cpp
 
   LINK_LIBS

Removed: clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp?rev=338053&view=auto
==
--- clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/dex/Iterator.cpp (removed)
@@ -1,244 +0,0 @@
-//===--- Iterator.cpp - Query Symbol Retrieval --*- C++ 
-*-===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===--===//
-
-#include "Iterator.h"
-#include 
-#include 
-#include 
-
-namespace clang {
-namespace clangd {
-namespace dex {
-
-namespace {
-
-/// Implements Iterator over a PostingList. DocumentIterator is the most basic
-/// iterator: it doesn't have any children (hence it is the leaf of iterator
-/// tree) and is simply a wrapper around PostingList::const_iterator.
-class DocumentIterator : public Iterator {
-public:
-  DocumentIterator(PostingListRef Documents)
-  : Documents(Documents), Index(std::begin(Documents)) {}
-
-  bool reachedEnd() const override { return Index == std::end(Documents); }
-
-  /// Advances cursor to the next item.
-  void advance() override {
-assert(!reachedEnd() && "DocumentIterator can't advance at the end.");
-++Index;
-  }
-
-  /// Applies binary search to advance cursor to the next item with DocID equal
-  /// or higher than the given one.
-  void advanceTo(DocID ID) override {
-assert(!reachedEnd() && "DocumentIterator can't advance at the end.");
-Index = std::lower_bound(Index, std::end(Documents), ID);
-  }
-
-  DocID peek() const override {
-assert(!reachedEnd() && "DocumentIterator can't call peek() at the end.");
-return *Index;
-  }
-
-  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
-OS << '[';
-auto Separator = "";
-for (const auto &ID : Documents) {
-  OS << Separator << ID;
-  Separator = ", ";
-}
-OS << ']';
-return OS;
-  }
-
-private:
-  PostingListRef Documents;
-  PostingListRef::const_iterator Index;
-};
-
-/// Implements Iterator over the intersection of other iterators.
-///
-/// AndIterator iterates through common items among all children. It becomes
-/// exhausted as soon as any child becomes exhausted. After each mutation, the
-/// iterator restores the invariant: all children must point to the same item.
-class AndIterator : public Iterator {
-public:
-  AndIterator(std::vector> AllChildren)
-  : Children(std::move(AllChildren)) {
-assert(!Children.empty() && "AndIterator should have at least one child.");
-// Establish invariants.
-sync();
-  }
-
-  bool reachedEnd() const override { return ReachedEnd; }
-
-  /// Advances all children to the next common item.
-  void advance() override {
-assert(!reachedEnd() && "AndIterator can't call advance() at the end.");
-Children.front()->advance();
-sync();
-  }
-
-  /// Advances all children to the next common item with DocumentID >= ID.
-  void advanceTo(DocID ID) override {
-assert(!reachedEnd() && "AndIterator can't call advanceTo() at the end.");
-Children.front()->advanceTo(ID);
-sync();
-  }
-
-  DocID peek() const override { return Children.front()->peek(); }
-
-  llvm::raw_ostream &dump(llvm::raw_ostream &OS) const override {
-OS << "(& ";
-auto Separator = "";
-for (const auto &Child : Children) {
-  OS << Separator << *Child;
-  Separator = " ";
-}
-OS << ')';
-return OS;
-  }
-
-private:
-  /// Restores class invariants: each child will point to the sam

Re: r338049 - [OPENMP] What's new for OpenMP in clang.

2018-07-26 Thread GMail via cfe-commits
Oh, yes, it is a typo, thanks for catching it!

-
Best regards,
Alexey Bataev

26.07.2018 13:59, Jonas Hahnfeld via cfe-commits пишет:
> Hi Alexey,
>
> On 2018-07-26 19:53, Alexey Bataev via cfe-commits wrote:
>> Author: abataev
>> Date: Thu Jul 26 10:53:45 2018
>> New Revision: 338049
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=338049&view=rev
>> Log:
>> [OPENMP] What's new for OpenMP in clang.
>>
>> Updated ReleaseNotes + Status of the OpenMP support in clang.
>>
>> Modified:
>>     cfe/trunk/docs/OpenMPSupport.rst
>>     cfe/trunk/docs/ReleaseNotes.rst
>>
>> Modified: cfe/trunk/docs/OpenMPSupport.rst
>> [...]
>>
>> Modified: cfe/trunk/docs/ReleaseNotes.rst
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=338049&r1=338048&r2=338049&view=diff
>>
>> ==
>>
>> --- cfe/trunk/docs/ReleaseNotes.rst (original)
>> +++ cfe/trunk/docs/ReleaseNotes.rst Thu Jul 26 10:53:45 2018
>> @@ -216,7 +216,21 @@ OpenCL C Language Changes in Clang
>>  OpenMP Support in Clang
>>  --
>>
>> -- ...
>> +- Clang gained basic support for OpenMP 4.5 offloading for NVPTX
>> target.
>> +   To compile your program for NVPTX target use the following options:
>> +   `-fopenmp -fopenmp-targets=nvptx64-nvidia-cuda` for 64 bit
>> platforms or
>> +   `-fopenmp -fopenmp-targets=nvptx-nvidia-cuda` for 32 bit platform.
>> +
>> +- Passing options to the OpenMP device offloading toolchain can be
>> done using
>> +  the `-Xopenmp-target= -opt=val` flag. In this way the
>> `-opt=val`
>> +  option will be forwarded to the respective OpenMP device
>> offloading toolchain
>> +  described by the triple. For example passing the compute
>> capability to
>> +  the OpenMP NVPTX offloading toolchain can be done as follows:
>> +  `-Xopenmp-target=nvptx62-nvidia-cuda -march=sm_60`.
>
> Is that a typo and should say "nvptx64"?
>



signature.asc
Description: OpenPGP digital signature
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49868: [Sema] Fix a crash by completing a type before using it

2018-07-26 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington created this revision.
erik.pilkington added reviewers: rsmith, rjmccall.
Herald added a subscriber: dexonsmith.

Only apply this exception on a type that we're able to check.

Thanks!
Erik


Repository:
  rC Clang

https://reviews.llvm.org/D49868

Files:
  clang/lib/Sema/SemaInit.cpp
  clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp


Index: clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
===
--- clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
+++ clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
@@ -348,6 +348,20 @@
   };
 }
 
+namespace rdar41903969 {
+template  struct A {};
+template  struct B;
+template  struct C {
+  C(A&);
+  C(B&);
+};
+
+void foo(A &a, B &b) {
+  (void)C{b};
+  (void)C{a};
+}
+}
+
 #else
 
 // expected-no-diagnostics
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -9130,6 +9130,7 @@
   Expr *E = ListInit->getInit(0);
   auto *RD = E->getType()->getAsCXXRecordDecl();
   if (!isa(E) && RD &&
+  isCompleteType(Kind.getLocation(), E->getType()) &&
   isOrIsDerivedFromSpecializationOf(RD, Template))
 TryListConstructors = false;
 }


Index: clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
===
--- clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
+++ clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
@@ -348,6 +348,20 @@
   };
 }
 
+namespace rdar41903969 {
+template  struct A {};
+template  struct B;
+template  struct C {
+  C(A&);
+  C(B&);
+};
+
+void foo(A &a, B &b) {
+  (void)C{b};
+  (void)C{a};
+}
+}
+
 #else
 
 // expected-no-diagnostics
Index: clang/lib/Sema/SemaInit.cpp
===
--- clang/lib/Sema/SemaInit.cpp
+++ clang/lib/Sema/SemaInit.cpp
@@ -9130,6 +9130,7 @@
   Expr *E = ListInit->getInit(0);
   auto *RD = E->getType()->getAsCXXRecordDecl();
   if (!isa(E) && RD &&
+  isCompleteType(Kind.getLocation(), E->getType()) &&
   isOrIsDerivedFromSpecializationOf(RD, Template))
 TryListConstructors = false;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D48862: [OpenEmbedded] Fix lib paths for OpenEmbedded targets

2018-07-26 Thread Mandeep Singh Grang via Phabricator via cfe-commits
mgrang added a comment.

@rsmith Could you please take a look at the updated patch? I would like to 
commit this. Thanks.


https://reviews.llvm.org/D48862



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


r338050 - [COFF, ARM64] Decide when to mark struct returns as SRet

2018-07-26 Thread Mandeep Singh Grang via cfe-commits
Author: mgrang
Date: Thu Jul 26 11:07:59 2018
New Revision: 338050

URL: http://llvm.org/viewvc/llvm-project?rev=338050&view=rev
Log:
[COFF, ARM64] Decide when to mark struct returns as SRet

Summary:
Refer the MS ARM64 ABI Convention for the behavior for struct returns:
https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions#return-values

Reviewers: mstorsjo, compnerd, rnk, javed.absar, yinma, efriedma

Reviewed By: rnk, efriedma

Subscribers: haripul, TomTan, yinma, efriedma, kristof.beyls, chrib, 
llvm-commits

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

Added:
cfe/trunk/test/CodeGen/arm64-microsoft-arguments.cpp
Modified:
cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp

Modified: cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h?rev=338050&r1=338049&r2=338050&view=diff
==
--- cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h (original)
+++ cfe/trunk/include/clang/CodeGen/CGFunctionInfo.h Thu Jul 26 11:07:59 2018
@@ -96,6 +96,7 @@ private:
   bool InReg : 1;   // isDirect() || isExtend() || isIndirect()
   bool CanBeFlattened: 1;   // isDirect()
   bool SignExt : 1; // isExtend()
+  bool SuppressSRet : 1;// isIndirect()
 
   bool canHavePaddingType() const {
 return isDirect() || isExtend() || isIndirect() || isExpand();
@@ -111,13 +112,14 @@ private:
   }
 
   ABIArgInfo(Kind K)
-  : TheKind(K), PaddingInReg(false), InReg(false) {
+  : TheKind(K), PaddingInReg(false), InReg(false), SuppressSRet(false) {
   }
 
 public:
   ABIArgInfo()
   : TypeData(nullptr), PaddingType(nullptr), DirectOffset(0),
-TheKind(Direct), PaddingInReg(false), InReg(false) {}
+TheKind(Direct), PaddingInReg(false), InReg(false),
+SuppressSRet(false) {}
 
   static ABIArgInfo getDirect(llvm::Type *T = nullptr, unsigned Offset = 0,
   llvm::Type *Padding = nullptr,
@@ -406,6 +408,16 @@ public:
 CanBeFlattened = Flatten;
   }
 
+  bool getSuppressSRet() const {
+assert(isIndirect() && "Invalid kind!");
+return SuppressSRet;
+  }
+
+  void setSuppressSRet(bool Suppress) {
+assert(isIndirect() && "Invalid kind!");
+SuppressSRet = Suppress;
+  }
+
   void dump() const;
 };
 

Modified: cfe/trunk/lib/CodeGen/CGCall.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CGCall.cpp?rev=338050&r1=338049&r2=338050&view=diff
==
--- cfe/trunk/lib/CodeGen/CGCall.cpp (original)
+++ cfe/trunk/lib/CodeGen/CGCall.cpp Thu Jul 26 11:07:59 2018
@@ -1988,7 +1988,8 @@ void CodeGenModule::ConstructAttributeLi
   // Attach attributes to sret.
   if (IRFunctionArgs.hasSRetArg()) {
 llvm::AttrBuilder SRETAttrs;
-SRETAttrs.addAttribute(llvm::Attribute::StructRet);
+if (!RetAI.getSuppressSRet())
+  SRETAttrs.addAttribute(llvm::Attribute::StructRet);
 hasUsedSRet = true;
 if (RetAI.getInReg())
   SRETAttrs.addAttribute(llvm::Attribute::InReg);

Modified: cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp?rev=338050&r1=338049&r2=338050&view=diff
==
--- cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp (original)
+++ cfe/trunk/lib/CodeGen/MicrosoftCXXABI.cpp Thu Jul 26 11:07:59 2018
@@ -1060,10 +1060,22 @@ bool MicrosoftCXXABI::classifyReturnType
 // the second parameter.
 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
 FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
+
+// aarch64-windows requires that instance methods use X1 for the return
+// address. So for aarch64-windows we do not mark the
+// return as SRet.
+FI.getReturnInfo().setSuppressSRet(CGM.getTarget().getTriple().getArch() ==
+   llvm::Triple::aarch64);
 return true;
   } else if (!RD->isPOD()) {
 // If it's a free function, non-POD types are returned indirectly.
 FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
+
+// aarch64-windows requires that non-POD, non-instance returns use X0 for
+// the return address. So for aarch64-windows we do not mark the return as
+// SRet.
+FI.getReturnInfo().setSuppressSRet(CGM.getTarget().getTriple().getArch() ==
+   llvm::Triple::aarch64);
 return true;
   }
 

Added: cfe/trunk/test/CodeGen/arm64-microsoft-arguments.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/arm64-microsoft-arguments.cpp?rev=338050&view=auto
==
--- cfe/trunk/test/Code

Re: r338049 - [OPENMP] What's new for OpenMP in clang.

2018-07-26 Thread Jonas Hahnfeld via cfe-commits

Hi Alexey,

On 2018-07-26 19:53, Alexey Bataev via cfe-commits wrote:

Author: abataev
Date: Thu Jul 26 10:53:45 2018
New Revision: 338049

URL: http://llvm.org/viewvc/llvm-project?rev=338049&view=rev
Log:
[OPENMP] What's new for OpenMP in clang.

Updated ReleaseNotes + Status of the OpenMP support in clang.

Modified:
cfe/trunk/docs/OpenMPSupport.rst
cfe/trunk/docs/ReleaseNotes.rst

Modified: cfe/trunk/docs/OpenMPSupport.rst
[...]

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL:
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=338049&r1=338048&r2=338049&view=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Thu Jul 26 10:53:45 2018
@@ -216,7 +216,21 @@ OpenCL C Language Changes in Clang
 OpenMP Support in Clang
 --

-- ...
+- Clang gained basic support for OpenMP 4.5 offloading for NVPTX 
target.

+   To compile your program for NVPTX target use the following options:
+   `-fopenmp -fopenmp-targets=nvptx64-nvidia-cuda` for 64 bit 
platforms or

+   `-fopenmp -fopenmp-targets=nvptx-nvidia-cuda` for 32 bit platform.
+
+- Passing options to the OpenMP device offloading toolchain can be 
done using
+  the `-Xopenmp-target= -opt=val` flag. In this way the 
`-opt=val`
+  option will be forwarded to the respective OpenMP device offloading 
toolchain
+  described by the triple. For example passing the compute capability 
to

+  the OpenMP NVPTX offloading toolchain can be done as follows:
+  `-Xopenmp-target=nvptx62-nvidia-cuda -march=sm_60`.


Is that a typo and should say "nvptx64"?
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D49848: Parse a possible trailing postfix expression suffix after a fold expression

2018-07-26 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

Shouldn't the caller of ParseParenExpression already be doing this?


Repository:
  rC Clang

https://reviews.llvm.org/D49848



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


r338049 - [OPENMP] What's new for OpenMP in clang.

2018-07-26 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Thu Jul 26 10:53:45 2018
New Revision: 338049

URL: http://llvm.org/viewvc/llvm-project?rev=338049&view=rev
Log:
[OPENMP] What's new for OpenMP in clang.

Updated ReleaseNotes + Status of the OpenMP support in clang.

Modified:
cfe/trunk/docs/OpenMPSupport.rst
cfe/trunk/docs/ReleaseNotes.rst

Modified: cfe/trunk/docs/OpenMPSupport.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/OpenMPSupport.rst?rev=338049&r1=338048&r2=338049&view=diff
==
--- cfe/trunk/docs/OpenMPSupport.rst (original)
+++ cfe/trunk/docs/OpenMPSupport.rst Thu Jul 26 10:53:45 2018
@@ -10,13 +10,15 @@
 .. role:: partial
 .. role:: good
 
+.. contents::
+   :local:
+
 ==
 OpenMP Support
 ==
 
-Clang fully supports OpenMP 3.1 + some elements of OpenMP 4.5. Clang supports 
offloading to X86_64, AArch64 and PPC64[LE] devices.
-Support for Cuda devices is not ready yet.
-The status of major OpenMP 4.5 features support in Clang.
+Clang fully supports OpenMP 4.5. Clang supports offloading to X86_64, AArch64,
+PPC64[LE] and has `basic support for Cuda devices`_.
 
 Standalone directives
 =
@@ -35,7 +37,7 @@ Standalone directives
 
 * #pragma omp target: :good:`Complete`.
 
-* #pragma omp declare target: :partial:`Partial`.  No full codegen support.
+* #pragma omp declare target: :good:`Complete`.
 
 * #pragma omp teams: :good:`Complete`.
 
@@ -64,5 +66,66 @@ Combined directives
 
 * #pragma omp target teams distribute parallel for [simd]: :good:`Complete`.
 
-Clang does not support any constructs/updates from upcoming OpenMP 5.0 except 
for `reduction`-based clauses in the `task` and `target`-based directives.
-In addition, the LLVM OpenMP runtime `libomp` supports the OpenMP Tools 
Interface (OMPT) on x86, x86_64, AArch64, and PPC64 on Linux, Windows, and mac 
OS.
+Clang does not support any constructs/updates from upcoming OpenMP 5.0 except
+for `reduction`-based clauses in the `task` and `target`-based directives.
+
+In addition, the LLVM OpenMP runtime `libomp` supports the OpenMP Tools
+Interface (OMPT) on x86, x86_64, AArch64, and PPC64 on Linux, Windows, and mac 
OS.
+ows, and mac OS.
+
+.. _basic support for Cuda devices:
+
+Cuda devices support
+
+
+Directives execution modes
+--
+
+Clang code generation for target regions supports two modes: the SPMD and
+non-SPMD modes. Clang chooses one of these two modes automatically based on the
+way directives and clauses on those directives are used. The SPMD mode uses a
+simplified set of runtime functions thus increasing performance at the cost of
+supporting some OpenMP features. The non-SPMD mode is the most generic mode and
+supports all currently available OpenMP features. The compiler will always
+attempt to use the SPMD mode wherever possible. SPMD mode will not be used if:
+
+   - The target region contains an `if()` clause that refers to a `parallel`
+ directive.
+
+   - The target region contains a `parallel` directive with a `num_threads()`
+ clause.
+
+   - The target region contains user code (other than OpenMP-specific
+ directives) in between the `target` and the `parallel` directives.
+
+Data-sharing modes
+--
+
+Clang supports two data-sharing models for Cuda devices: `Generic` and `Cuda`
+modes. The default mode is `Generic`. `Cuda` mode can give an additional
+performance and can be activated using the `-fopenmp-cuda-mode` flag. In
+`Generic` mode all local variables that can be shared in the parallel regions
+are stored in the global memory. In `Cuda` mode local variables are not shared
+between the threads and it is user responsibility to share the required data
+between the threads in the parallel regions.
+
+Features not supported or with limited support for Cuda devices
+---
+
+- Reductions across the teams are not supported yet.
+
+- Cancellation constructs are not supported.
+
+- Doacross loop nest is not supported.
+
+- User-defined reductions are supported only for trivial types.
+
+- Nested parallelism: inner parallel regions are executed sequentially.
+
+- Static linking of libraries containing device code is not supported yet.
+
+- Automatic translation of math functions in target regions to device-specific
+  math functions is not implemented yet.
+
+- Debug information for OpenMP target regions is not supported yet.
+

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=338049&r1=338048&r2=338049&view=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Thu Jul 26 10:53:45 2018
@@ -216,7 +216,21 @@ OpenCL C Language Changes in Clang
 OpenMP Support in Clang
 

  1   2   >