[PATCH] D73397: [Clang] Enable -fsanitize=leak on Fuchsia targets

2020-01-27 Thread Petr Hosek via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf4261e112129: [Clang] Enable -fsanitize=leak on Fuchsia 
targets (authored by mcgrathr, committed by phosek).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73397

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/Fuchsia.cpp
  
clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/aarch64-fuchsia/libclang_rt.lsan.a
  
clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/x86_64-fuchsia/libclang_rt.lsan.a
  clang/test/Driver/fuchsia.c

Index: clang/test/Driver/fuchsia.c
===
--- clang/test/Driver/fuchsia.c
+++ clang/test/Driver/fuchsia.c
@@ -174,6 +174,35 @@
 // CHECK-SCUDO-SHARED: "-fsanitize=safe-stack,scudo"
 // CHECK-SCUDO-SHARED: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}libclang_rt.scudo.so"
 
+// RUN: %clang %s -### --target=aarch64-fuchsia \
+// RUN: -fsanitize=leak 2>&1 \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: -fuse-ld=lld \
+// RUN: | FileCheck %s -check-prefix=CHECK-LSAN-AARCH64
+// CHECK-LSAN-AARCH64: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
+// CHECK-LSAN-AARCH64: "-fsanitize=leak,shadow-call-stack"
+// CHECK-LSAN-AARCH64: "-pie"
+// CHECK-LSAN-AARCH64: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aarch64-fuchsia{{/|}}libclang_rt.lsan.a"
+
+// RUN: %clang %s -### --target=x86_64-fuchsia \
+// RUN: -fsanitize=leak 2>&1 \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: -fuse-ld=lld \
+// RUN: | FileCheck %s -check-prefix=CHECK-LSAN-X86
+// CHECK-LSAN-X86: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
+// CHECK-LSAN-X86: "-fsanitize=leak,safe-stack"
+// CHECK-LSAN-X86: "-pie"
+// CHECK-LSAN-X86: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}x86_64-fuchsia{{/|}}libclang_rt.lsan.a"
+
+// RUN: %clang %s -### --target=aarch64-fuchsia \
+// RUN: -fsanitize=leak -fPIC -shared 2>&1 \
+// RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
+// RUN: -fuse-ld=lld \
+// RUN: | FileCheck %s -check-prefix=CHECK-LSAN-SHARED
+// CHECK-LSAN-SHARED: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
+// CHECK-LSAN-SHARED: "-fsanitize=leak,shadow-call-stack"
+// CHECK-LSAN-SHARED-NOT: "[[RESOURCE_DIR]]{{/|}}lib{{/|}}aarch64-fuchsia{{/|}}libclang_rt.lsan.a"
+
 // RUN: %clang %s -### --target=x86_64-fuchsia \
 // RUN: -fxray-instrument -fxray-modes=xray-basic \
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_per_target_subdir \
Index: clang/lib/Driver/ToolChains/Fuchsia.cpp
===
--- clang/lib/Driver/ToolChains/Fuchsia.cpp
+++ clang/lib/Driver/ToolChains/Fuchsia.cpp
@@ -340,6 +340,7 @@
   Res |= SanitizerKind::PointerSubtract;
   Res |= SanitizerKind::Fuzzer;
   Res |= SanitizerKind::FuzzerNoLink;
+  Res |= SanitizerKind::Leak;
   Res |= SanitizerKind::SafeStack;
   Res |= SanitizerKind::Scudo;
   return Res;
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -642,17 +642,21 @@
 StaticRuntimes.push_back("stats_client");
 
   // Collect static runtimes.
-  if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
-// Don't link static runtimes into DSOs or if -shared-libasan.
+  if (Args.hasArg(options::OPT_shared)) {
+// Don't link static runtimes into DSOs.
 return;
   }
-  if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
+
+  // Each static runtime that has a DSO counterpart above is excluded below,
+  // but runtimes that exist only as static are not affected by needsSharedRt.
+
+  if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
 StaticRuntimes.push_back("asan");
 if (SanArgs.linkCXXRuntimes())
   StaticRuntimes.push_back("asan_cxx");
   }
 
-  if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
+  if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
 StaticRuntimes.push_back("hwasan");
 if (SanArgs.linkCXXRuntimes())
   StaticRuntimes.push_back("hwasan_cxx");
@@ -671,7 +675,7 @@
 if (SanArgs.linkCXXRuntimes())
   StaticRuntimes.push_back("tsan_cxx");
   }
-  if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
+  if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
 if (SanArgs.requiresMinimalRuntime()) {
   StaticRuntimes.push_back("ubsan_minimal");
 } else {
@@ -684,18 +688,20 @@
 NonWholeStaticRuntimes.push_back("safestack");
 RequiredSymbols.push_back("__safestack_init");
   }
-  if (SanArgs.needsCfiRt() && SanArgs.

[PATCH] D73464: [clang] Add TagDecl AST matcher

2020-01-27 Thread Karasev Nikita via Phabricator via cfe-commits
f00kat updated this revision to Diff 240779.
f00kat added a comment.

1. Fix Registry.cpp
2. Generate AST Matchers doc


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73464

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

Index: clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -184,6 +184,13 @@
   EXPECT_TRUE(notMatches("enum X {};", Matcher));
 }
 
+TEST(TagDecl, MatchesTagDecls) {
+  EXPECT_TRUE(matches("struct X {};", tagDecl(hasName("X";
+  EXPECT_TRUE(matches("class C {};", tagDecl(hasName("C";
+  EXPECT_TRUE(matches("union U {};", tagDecl(hasName("U";
+  EXPECT_TRUE(matches("enum E {};", tagDecl(hasName("E";
+}
+
 TEST(Matcher, UnresolvedLookupExpr) {
   // FIXME: The test is known to be broken on Windows with delayed template
   // parsing.
Index: clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNarrowingTest.cpp
@@ -2504,6 +2504,13 @@
   EXPECT_TRUE(notMatches("enum X {};", enumDecl(isScoped(;
 }
 
+TEST(TagDeclKind, MatchesTagDeclKind) {
+  EXPECT_TRUE(matches("struct X {};", tagDecl(isStruct(;
+  EXPECT_TRUE(matches("class C {};", tagDecl(isClass(;
+  EXPECT_TRUE(matches("union U {};", tagDecl(isUnion(;
+  EXPECT_TRUE(matches("enum E {};", tagDecl(isEnum(;
+}
+
 TEST(HasTrailingReturn, MatchesTrailingReturn) {
   EXPECT_TRUE(matches("auto Y() -> int { return 0; }",
   functionDecl(hasTrailingReturn(;
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -492,6 +492,7 @@
   REGISTER_MATCHER(substTemplateTypeParmType);
   REGISTER_MATCHER(switchCase);
   REGISTER_MATCHER(switchStmt);
+  REGISTER_MATCHER(tagDecl);
   REGISTER_MATCHER(tagType);
   REGISTER_MATCHER(templateArgument);
   REGISTER_MATCHER(templateArgumentCountIs);
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -647,6 +647,7 @@
 const internal::VariadicDynCastAllOfMatcher enumDecl;
 const internal::VariadicDynCastAllOfMatcher
 enumConstantDecl;
+const internal::VariadicDynCastAllOfMatcher tagDecl;
 const internal::VariadicDynCastAllOfMatcher cxxMethodDecl;
 const internal::VariadicDynCastAllOfMatcher
 cxxConversionDecl;
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -1194,6 +1194,20 @@
 extern const internal::VariadicDynCastAllOfMatcher
 enumConstantDecl;
 
+/// Matches tag declarations.
+///
+/// Example matches X, Z, U, S, E
+/// \code
+///   class X;
+///   template class Z {};
+///   struct S {};
+///   union U {};
+///   enum E {
+/// A, B, C
+///   };
+/// \endcode
+extern const internal::VariadicDynCastAllOfMatcher tagDecl;
+
 /// Matches method declarations.
 ///
 /// Example matches y
@@ -4845,42 +4859,58 @@
   return InnerMatcher.matches(Node.getType(), Finder, Builder);
 }
 
-/// Matches RecordDecl object that are spelled with "struct."
+/// Matches TagDecl object that are spelled with "struct."
 ///
-/// Example matches S, but not C or U.
+/// Example matches S, but not C, U or E.
 /// \code
 ///   struct S {};
 ///   class C {};
 ///   union U {};
+///   enum E {};
 /// \endcode
-AST_MATCHER(RecordDecl, isStruct) {
+AST_MATCHER(TagDecl, isStruct) {
   return Node.isStruct();
 }
 
-/// Matches RecordDecl object that are spelled with "union."
+/// Matches TagDecl object that are spelled with "union."
 ///
-/// Example matches U, but not C or S.
+/// Example matches U, but not C, S or E.
 /// \code
 ///   struct S {};
 ///   class C {};
 ///   union U {};
+///   enum E {};
 /// \endcode
-AST_MATCHER(RecordDecl, isUnion) {
+AST_MATCHER(TagDecl, isUnion) {
   return Node.isUnion();
 }
 
-/// Matches RecordDecl object that are spelled with "class."
+/// Matches TagDecl object that are spelled with "class."
 ///
-/// Example matches C, but not S or U.
+/// Example matches C, but not S, U or E.
 /// \code
 ///   struct S {};
 ///   class C {};
 ///   union U {

[clang] f4261e1 - [Clang] Enable -fsanitize=leak on Fuchsia targets

2020-01-27 Thread Petr Hosek via cfe-commits

Author: Roland McGrath
Date: 2020-01-27T23:37:51-08:00
New Revision: f4261e1121293c1f5a3aba416668e6309099f9da

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

LOG: [Clang] Enable -fsanitize=leak on Fuchsia targets

This required some fixes to the generic code for two issues:

1. -fsanitize=safe-stack is default on x86_64-fuchsia and is *not* incompatible 
with -fsanitize=leak on Fuchisa
2. -fsanitize=leak and other static-only runtimes must not be omitted under 
-shared-libsan (which is the default on Fuchsia)

Patch By: mcgrathr

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

Added: 

clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/aarch64-fuchsia/libclang_rt.lsan.a

clang/test/Driver/Inputs/resource_dir_with_per_target_subdir/lib/x86_64-fuchsia/libclang_rt.lsan.a

Modified: 
clang/lib/Driver/SanitizerArgs.cpp
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Driver/ToolChains/Fuchsia.cpp
clang/test/Driver/fuchsia.c

Removed: 




diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index ac9a294ee3fa..c2fa514c44b4 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -412,9 +412,11 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
  SanitizerKind::Leak | SanitizerKind::Thread |
  SanitizerKind::Memory | SanitizerKind::KernelAddress),
   std::make_pair(SanitizerKind::SafeStack,
- SanitizerKind::Address | SanitizerKind::HWAddress |
- SanitizerKind::Leak | SanitizerKind::Thread |
- SanitizerKind::Memory | SanitizerKind::KernelAddress),
+ (TC.getTriple().isOSFuchsia() ? SanitizerMask()
+   : SanitizerKind::Leak) |
+ SanitizerKind::Address | SanitizerKind::HWAddress |
+ SanitizerKind::Thread | SanitizerKind::Memory |
+ SanitizerKind::KernelAddress),
   std::make_pair(SanitizerKind::KernelHWAddress,
  SanitizerKind::Address | SanitizerKind::HWAddress |
  SanitizerKind::Leak | SanitizerKind::Thread |
@@ -831,8 +833,9 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
   }
 
   if (AllAddedKinds & SanitizerKind::SafeStack) {
-// SafeStack runtime is built into the system on Fuchsia.
-SafeStackRuntime = !TC.getTriple().isOSFuchsia();
+// SafeStack runtime is built into the system on Android and Fuchsia.
+SafeStackRuntime =
+!TC.getTriple().isAndroid() && !TC.getTriple().isOSFuchsia();
   }
 
   LinkRuntimes =

diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 37ec73468570..4adccaaa4cb7 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -642,17 +642,21 @@ collectSanitizerRuntimes(const ToolChain &TC, const 
ArgList &Args,
 StaticRuntimes.push_back("stats_client");
 
   // Collect static runtimes.
-  if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
-// Don't link static runtimes into DSOs or if -shared-libasan.
+  if (Args.hasArg(options::OPT_shared)) {
+// Don't link static runtimes into DSOs.
 return;
   }
-  if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
+
+  // Each static runtime that has a DSO counterpart above is excluded below,
+  // but runtimes that exist only as static are not affected by needsSharedRt.
+
+  if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && 
SanArgs.linkRuntimes()) {
 StaticRuntimes.push_back("asan");
 if (SanArgs.linkCXXRuntimes())
   StaticRuntimes.push_back("asan_cxx");
   }
 
-  if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
+  if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && 
SanArgs.linkRuntimes()) {
 StaticRuntimes.push_back("hwasan");
 if (SanArgs.linkCXXRuntimes())
   StaticRuntimes.push_back("hwasan_cxx");
@@ -671,7 +675,7 @@ collectSanitizerRuntimes(const ToolChain &TC, const ArgList 
&Args,
 if (SanArgs.linkCXXRuntimes())
   StaticRuntimes.push_back("tsan_cxx");
   }
-  if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
+  if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && 
SanArgs.linkRuntimes()) {
 if (SanArgs.requiresMinimalRuntime()) {
   StaticRuntimes.push_back("ubsan_minimal");
 } else {
@@ -684,18 +688,20 @@ collectSanitizerRuntimes(const ToolChain &TC, const 
ArgList &Args,
 NonWholeStaticRuntimes.push_back("safestack");
 RequiredSymbols.push_back("__safestack_init");
   }
-  if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
-StaticRuntimes.p

[PATCH] D57265: [PM/CC1] Add -f[no-]split-cold-code CC1 options to toggle splitting

2020-01-27 Thread Puyan Lotfi via Phabricator via cfe-commits
plotfi added a comment.

Why hasn't this patch landed in llvm.org? I see it on the github apple/master 
but not on llvm.org master.


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

https://reviews.llvm.org/D57265



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


[PATCH] D72824: [X86] Add combination for fma and fneg on X86 under strict FP.

2020-01-27 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72824



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


[PATCH] D72820: [FPEnv] Add pragma FP_CONTRACT support under strict FP.

2020-01-27 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72820



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


[PATCH] D70172: [CUDA][HIP][OpenMP] Emit deferred diagnostics by a post-parsing AST travese

2020-01-27 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 240760.
yaxunl retitled this revision from "[CUDA][HIP] Fix assertion due to dtor check 
on windows" to "[CUDA][HIP][OpenMP] Emit deferred diagnostics by a post-parsing 
AST travese".
yaxunl edited the summary of this revision.
yaxunl added a comment.
Herald added a subscriber: guansong.
Herald added a reviewer: jdoerfert.

Remove the call graph and do a final AST traverse by John's comments.


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

https://reviews.llvm.org/D70172

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCUDA.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/declare_target_messages.cpp
  clang/test/OpenMP/nvptx_target_exceptions_messages.cpp
  clang/test/SemaCUDA/bad-calls-on-same-line.cu
  clang/test/SemaCUDA/call-device-fn-from-host.cu
  clang/test/SemaCUDA/call-host-fn-from-device.cu
  clang/test/SemaCUDA/openmp-target.cu
  clang/test/SemaCUDA/trace-through-global.cu

Index: clang/test/SemaCUDA/trace-through-global.cu
===
--- clang/test/SemaCUDA/trace-through-global.cu
+++ clang/test/SemaCUDA/trace-through-global.cu
@@ -38,7 +38,7 @@
   // Notice that these two diagnostics are different: Because the call to hd1
   // is not dependent on T, the call to hd1 comes from 'launch_kernel', while
   // the call to hd3, being dependent, comes from 'launch_kernel'.
-  hd1(); // expected-note {{called by 'launch_kernel'}}
+  hd1(); // expected-note {{called by 'launch_kernel'}}
   hd3(T()); // expected-note {{called by 'launch_kernel'}}
 }
 
Index: clang/test/SemaCUDA/openmp-target.cu
===
--- clang/test/SemaCUDA/openmp-target.cu
+++ clang/test/SemaCUDA/openmp-target.cu
@@ -16,9 +16,9 @@
 void bazzz() {bazz();}
 #pragma omp declare target to(bazzz) device_type(nohost)
 void any() {bazz();} // expected-error {{function with 'device_type(nohost)' is not available on host}}
-void host1() {bazz();}
+void host1() {bazz();} // expected-error {{function with 'device_type(nohost)' is not available on host}}
 #pragma omp declare target to(host1) device_type(host)
-void host2() {bazz();}
+void host2() {bazz();} // expected-error {{function with 'device_type(nohost)' is not available on host}}
 #pragma omp declare target to(host2)
 void device() {host1();}
 #pragma omp declare target to(device) device_type(nohost)
Index: clang/test/SemaCUDA/call-host-fn-from-device.cu
===
--- clang/test/SemaCUDA/call-host-fn-from-device.cu
+++ clang/test/SemaCUDA/call-host-fn-from-device.cu
@@ -56,14 +56,14 @@
 }
 
 template  __host__ __device__ void hd2() { host_fn(); }
-// expected-error@-1 2 {{reference to __host__ function 'host_fn' in __host__ __device__ function}}
+// expected-error@-1 {{reference to __host__ function 'host_fn' in __host__ __device__ function}}
 __global__ void kernel() { hd2(); }
 
 __host__ __device__ void hd() { host_fn(); }
 // expected-error@-1 {{reference to __host__ function 'host_fn' in __host__ __device__ function}}
 
 template  __host__ __device__ void hd3() { host_fn(); }
-// expected-error@-1 2 {{reference to __host__ function 'host_fn' in __host__ __device__ function}}
+// expected-error@-1 {{reference to __host__ function 'host_fn' in __host__ __device__ function}}
 __device__ void device_fn() { hd3(); }
 
 // No error because this is never instantiated.
Index: clang/test/SemaCUDA/call-device-fn-from-host.cu
===
--- clang/test/SemaCUDA/call-device-fn-from-host.cu
+++ clang/test/SemaCUDA/call-device-fn-from-host.cu
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 %s --std=c++11 -triple x86_64-unknown-linux -emit-llvm -o - \
 // RUN:   -verify -verify-ignore-unexpected=note
 // RUN: %clang_cc1 %s --std=c++11 -triple x86_64-unknown-linux -emit-llvm -o - \
-// RUN:   -verify -verify-ignore-unexpected=note -fopenmp
+// RUN:   -verify=expected,omp -verify-ignore-unexpected=note -fopenmp
 
 // Note: This test won't work with -fsyntax-only, because some of these errors
 // are emitted during codegen.
@@ -39,7 +39,7 @@
 }
 
 template  __host__ __device__ void hd2() { device_fn(); }
-// expected-error@-1 2 {{reference to __device__ function 'device_fn' in __host__ __device__ function}}
+// expected-error@-1 {{reference to __device__ function 'device_fn' in __host__ __device__ function}}
 void host_fn() { hd2(); }
 
 __host__ __device__ void hd() { device_fn(); }
Index: clang/test/SemaCUDA/bad-calls-on-same-line.cu
===
--- clang/test/SemaCUDA/bad-calls-on-same-line.cu
+++ clang/test/SemaCUDA/bad-calls-on-same-line.cu
@@ -33,8 +33,8 @@
 
 void host_fn() {
   hd();
-  hd();  // expected-note {{function template specialization 'hd'}}
+  hd();
 

[PATCH] D73521: [analyzer][WIP] add-new-checker.py: Introduction

2020-01-27 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso marked an inline comment as done.
Charusso added a comment.

This script dumps out a dummy checker which is the continuation of the Clang 
Tidy's 
https://github.com/llvm/llvm-project/blob/master/clang-tools-extra/clang-tidy/add_new_check.py

However, we could stick to the main-function-redeclaration-checker in a 2020 
fashion. As I see peoples starting their careers with Tidy, that is why this 
checker born, but please feel free to swap or modify. I think that is the 
easiest way to document changes in requirements of checker-writing. I also 
wanted to document common mistakes, like how to use a `Twine`, what is a 
`dyn_cast_or_null<>` vs. `cast<>`, make sure the `SVal` type is written out and 
it is not `const` or `const*`.


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

https://reviews.llvm.org/D73521



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


[PATCH] D73521: [analyzer][WIP] add-new-checker.py: Introduction

2020-01-27 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso updated this revision to Diff 240759.
Charusso added a comment.

- Make it runable. Whoops.


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

https://reviews.llvm.org/D73521

Files:
  clang/test/Analysis/add-new-checker/add-main-package.rst
  clang/test/Analysis/add-new-checker/add-main-package.td
  clang/test/Analysis/add-new-checker/add-multiple-packages.rst
  clang/test/Analysis/add-new-checker/add-multiple-packages.td
  clang/test/Analysis/add-new-checker/check-add-new-checker.py
  clang/test/Analysis/add-new-checker/checker-name.rst
  clang/test/Analysis/add-new-checker/checker-name.td
  clang/test/Analysis/add-new-checker/flow-package-exist-checker.rst
  clang/test/Analysis/add-new-checker/flow-package-exist-checker.td
  clang/test/Analysis/add-new-checker/flow-package-not-exist-layering.rst
  clang/test/Analysis/add-new-checker/flow-package-not-exist-layering.td
  clang/test/Analysis/add-new-checker/flow-package-not-exist.rst
  clang/test/Analysis/add-new-checker/flow-package-not-exist.td
  clang/test/Analysis/add-new-checker/lit.local.cfg.py
  clang/utils/analyzer/add-new-checker.py

Index: clang/utils/analyzer/add-new-checker.py
===
--- /dev/null
+++ clang/utils/analyzer/add-new-checker.py
@@ -0,0 +1,732 @@
+#!/usr/bin/env python
+#
+#===- add-new-checker.py - Creates a Static Analyzer checker --*- python -*-===#
+#
+# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+#
+#======#
+#
+# Example usage: python add-new-checker.py alpha.package.Foo
+#
+#======#
+
+import argparse
+import json
+import os
+import re
+import subprocess
+
+
+class Checker:
+def __init__(self, packages, name):
+self.packages = packages
+self.name = name
+
+def name(self):
+return self.name
+
+def packages(self):
+return self.packages
+
+def __str__(self):
+return '.'.join(self.packages) + '.' + self.name
+
+
+# Obtain the longest known package-chain of the 'packages' chain. For example
+# the checker creation of 'alpha.core.a.Checker' would return ['alpha', 'core'].
+def get_best_package_match(packages, known_packages):
+best_package_match = []
+for i in range(len(packages)):
+temp_packages = packages[:i + 1]
+package_name = '.'.join(temp_packages)
+if package_name in known_packages:
+best_package_match = temp_packages
+return best_package_match
+
+
+# Put every additional package and the checker into an increasing size jagged
+# array. For example the checker creation of 'core.a.Checker' would return
+# '[['core', 'a'], ['core', 'a', 'Checker']]'.
+def get_addition(packages, name, best_package_match):
+addition = []
+match_count = len(best_package_match)
+for i, package in enumerate(packages):
+if i < match_count:
+continue
+addition.append(best_package_match + packages[match_count : i + 1])
+addition.append(packages + [name])
+return addition
+
+
+def add_checkers_entry(clang_path, checker, args):
+checkers_include_path = os.path.join(clang_path, 
+'include', 'clang', 'StaticAnalyzer', 'Checkers')
+checkers_path = os.path.join(checkers_include_path, 'Checkers.td')
+if args.is_test:
+checkers_path = args.test_path
+if not checkers_path.endswith('.td.tmp'):
+return
+
+packages = checker.packages
+name = checker.name
+
+# Load the checkers' TableGen.
+# FIXME: Add path to 'llvm-tblgen'.
+data = None
+try:
+data = subprocess.check_output(['llvm-tblgen', '-dump-json',
+checkers_path,
+'-I=' + checkers_include_path])
+except subprocess.CalledProcessError as e:
+print('TableGen JSON dump failed:\n' + e.output.decode())
+
+data = json.loads(data)
+
+# Store the package names with their chained definition. For example the
+# package 'CoreAlpha' => 'alpha.core'.
+package_name_def_map = {}
+for package_def in data['!instanceof']['Package']:
+package = data[package_def]
+if package['ParentPackage']:
+chain = [package]
+while True:
+parent_package = chain[-1]['ParentPackage']
+if parent_package is None:
+break
+chain.append(data[parent_package['def']])
+
+dump = []
+for elem in reversed(chain):
+package_name = elem['PackageName']
+dump.append(package_name)
+package_name_def_map['.'.join(dump)] = package['!name']
+else:
+package_

[PATCH] D73520: [analyzer] BugReporterVisitors: Refactor and documentation

2020-01-27 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso marked 2 inline comments as done.
Charusso added inline comments.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h:195
+
+  static const char *getTag() { return "FindLastStore"; }
+

I have made every tag a small-string.



Comment at: 
clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h:203
+ID.AddBoolean(EnableNullFPSuppression);
+  }
 };

I have put every Profile into the header, so it is easier to see which members 
are not added to the Profile. I think the root cause of 
https://bugs.llvm.org/show_bug.cgi?id=42938 could be some issue with 
differentiating between visitors.


Repository:
  rC Clang

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

https://reviews.llvm.org/D73520



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


[PATCH] D73202: Make AST reading work better with LLVM_APPEND_VC_REV=NO

2020-01-27 Thread Nico Weber via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG49532137d087: Make AST reading work better with 
LLVM_APPEND_VC_REV=NO (authored by thakis).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73202

Files:
  clang/include/clang/Serialization/ASTBitCodes.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Modules/diagnostics.modulemap
  clang/test/Modules/exception-spec.cpp
  clang/test/Modules/merge-lifetime-extended-temporary.cpp
  clang/test/Modules/objc-method-redecl.m
  clang/test/Modules/using-decl-inheritance.cpp


Index: clang/test/Modules/using-decl-inheritance.cpp
===
--- clang/test/Modules/using-decl-inheritance.cpp
+++ clang/test/Modules/using-decl-inheritance.cpp
@@ -1,3 +1,4 @@
+// RUN: rm -rf %t
 // RUN: %clang_cc1 -x c++ -fmodules -fmodules-local-submodule-visibility 
-fmodules-cache-path=%t %s -verify
 // RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t %s -verify
 
Index: clang/test/Modules/objc-method-redecl.m
===
--- clang/test/Modules/objc-method-redecl.m
+++ clang/test/Modules/objc-method-redecl.m
@@ -1,3 +1,4 @@
+// RUN: rm -rf %t
 // RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -x objective-c-header 
-emit-pch %S/Inputs/objc-method-redecl.h -o %t.pch -Wno-objc-root-class
 // RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -x objective-c 
-include-pch %t.pch %s -verify -Wno-objc-root-class
 // expected-no-diagnostics
Index: clang/test/Modules/merge-lifetime-extended-temporary.cpp
===
--- clang/test/Modules/merge-lifetime-extended-temporary.cpp
+++ clang/test/Modules/merge-lifetime-extended-temporary.cpp
@@ -1,3 +1,4 @@
+// RUN: rm -rf %t
 // RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -x 
c++ -I%S/Inputs/merge-lifetime-extended-temporary -verify -std=c++11 %s 
-DORDER=1
 // RUN: %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -x 
c++ -I%S/Inputs/merge-lifetime-extended-temporary -verify -std=c++11 %s 
-DORDER=2
 
Index: clang/test/Modules/exception-spec.cpp
===
--- clang/test/Modules/exception-spec.cpp
+++ clang/test/Modules/exception-spec.cpp
@@ -1,3 +1,4 @@
+// RUN: rm -rf %t
 // RUN: %clang_cc1 -x c++ -std=c++17 -fmodules 
-fmodules-local-submodule-visibility -fmodules-cache-path=%t %s -verify
 
 // expected-no-diagnostics
Index: clang/test/Modules/diagnostics.modulemap
===
--- clang/test/Modules/diagnostics.modulemap
+++ clang/test/Modules/diagnostics.modulemap
@@ -1,3 +1,4 @@
+// RUN: rm -rf %t
 // RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t 
-fmodule-map-file=%S/Inputs/diagnostics-aux.modulemap -fmodule-map-file=%s 
-fsyntax-only -x c++ /dev/null 2>&1 | FileCheck %s --implicit-check-not error:
 
 // CHECK: In file included from {{.*}}diagnostics-aux.modulemap:3:
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -41,6 +41,7 @@
 #include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Sema/CodeCompleteOptions.h"
+#include "clang/Serialization/ASTBitCodes.h"
 #include "clang/Serialization/ModuleFileExtension.h"
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
 #include "llvm/ADT/APInt.h"
@@ -3635,6 +3636,11 @@
   // CityHash, but this will do for now.
   hash_code code = hash_value(getClangFullRepositoryVersion());
 
+  // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
+  // and getClangFullRepositoryVersion() doesn't include git revision.
+  code = hash_combine(code, serialization::VERSION_MAJOR,
+  serialization::VERSION_MINOR);
+
   // Extend the signature with the language options
 #define LANGOPT(Name, Bits, Default, Description) \
code = hash_combine(code, LangOpts->Name);
Index: clang/include/clang/Serialization/ASTBitCodes.h
===
--- clang/include/clang/Serialization/ASTBitCodes.h
+++ clang/include/clang/Serialization/ASTBitCodes.h
@@ -41,7 +41,7 @@
 /// Version 4 of AST files also requires that the version control branch 
and
 /// revision match exactly, since there is no backward compatibility of
 /// AST files at this time.
-const unsigned VERSION_MAJOR = 8;
+const unsigned VERSION_MAJOR = 9;
 
 /// AST file minor version number supported by this version of
 /// Clang.


Index: clang/test/Modules/using-decl-inheritance.cpp
==

[clang] 4953213 - Make AST reading work better with LLVM_APPEND_VC_REV=NO

2020-01-27 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2020-01-27T22:08:37-05:00
New Revision: 49532137d087d8053789d18540c5e7916b91ef30

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

LOG: Make AST reading work better with LLVM_APPEND_VC_REV=NO

With LLVM_APPEND_VC_REV=NO, Modules/merge-lifetime-extended-temporary.cpp
would fail if it ran before a0f50d731639350c7a7 (which changed
the serialization format) and then after, for these reasons:

1. With LLVM_APPEND_VC_REV=NO, the module hash before and after the
   change was the same.

2. Modules/merge-lifetime-extended-temporary.cpp is the only test
   we have that uses -fmodule-cache-path=%t that
   a) actually writes to the cache path
   b) doesn't do `rm -rf %t` at the top of the test

So the old run would write a module file, and then the new run would
try to load it, but the serialized format changed.

Do several things to fix this:

1. Include clang::serialization::VERSION_MAJOR/VERSION_MINOR in
   the module hash, so that when the AST format changes (...and
   we remember to bump these), we use a different module cache dir.
2. Bump VERSION_MAJOR, since a0f50d731639350c7a7 changed the
   on-disk format in a way that a gch file written before that change
   can't be read after that change.
3. Add `rm -rf %t` to all tests that pass -fmodule-cache-path=%t.
   This is unnecessary from a correctness PoV after 1 and 2,
   but makes it so that we don't amass many cache dirs over time.
   (Arguably, it also makes it so that the test suite doesn't catch
   when we change the serialization format but don't bump
   clang::serialization::VERSION_MAJOR/VERSION_MINOR; oh well.)

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

Added: 


Modified: 
clang/include/clang/Serialization/ASTBitCodes.h
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/Modules/diagnostics.modulemap
clang/test/Modules/exception-spec.cpp
clang/test/Modules/merge-lifetime-extended-temporary.cpp
clang/test/Modules/objc-method-redecl.m
clang/test/Modules/using-decl-inheritance.cpp

Removed: 




diff  --git a/clang/include/clang/Serialization/ASTBitCodes.h 
b/clang/include/clang/Serialization/ASTBitCodes.h
index 44a12c875da7..83af4d15e27b 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -41,7 +41,7 @@ namespace serialization {
 /// Version 4 of AST files also requires that the version control branch 
and
 /// revision match exactly, since there is no backward compatibility of
 /// AST files at this time.
-const unsigned VERSION_MAJOR = 8;
+const unsigned VERSION_MAJOR = 9;
 
 /// AST file minor version number supported by this version of
 /// Clang.

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index eb1c50f68a03..b3733a221090 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -41,6 +41,7 @@
 #include "clang/Lex/HeaderSearchOptions.h"
 #include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Sema/CodeCompleteOptions.h"
+#include "clang/Serialization/ASTBitCodes.h"
 #include "clang/Serialization/ModuleFileExtension.h"
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
 #include "llvm/ADT/APInt.h"
@@ -3635,6 +3636,11 @@ std::string CompilerInvocation::getModuleHash() const {
   // CityHash, but this will do for now.
   hash_code code = hash_value(getClangFullRepositoryVersion());
 
+  // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
+  // and getClangFullRepositoryVersion() doesn't include git revision.
+  code = hash_combine(code, serialization::VERSION_MAJOR,
+  serialization::VERSION_MINOR);
+
   // Extend the signature with the language options
 #define LANGOPT(Name, Bits, Default, Description) \
code = hash_combine(code, LangOpts->Name);

diff  --git a/clang/test/Modules/diagnostics.modulemap 
b/clang/test/Modules/diagnostics.modulemap
index 865892b53b28..01aa0b66a406 100644
--- a/clang/test/Modules/diagnostics.modulemap
+++ b/clang/test/Modules/diagnostics.modulemap
@@ -1,3 +1,4 @@
+// RUN: rm -rf %t
 // RUN: not %clang_cc1 -fmodules -fmodules-cache-path=%t 
-fmodule-map-file=%S/Inputs/diagnostics-aux.modulemap -fmodule-map-file=%s 
-fsyntax-only -x c++ /dev/null 2>&1 | FileCheck %s --implicit-check-not error:
 
 // CHECK: In file included from {{.*}}diagnostics-aux.modulemap:3:

diff  --git a/clang/test/Modules/exception-spec.cpp 
b/clang/test/Modules/exception-spec.cpp
index 083cd950f7c5..a1fcc2238ad3 100644
--- a/clang/test/Modules/exception-spec.cpp
+++ b/clang/test/Modules/exception-spec.cpp
@@ -1,3 +1,4 @@
+// RUN: rm -rf %t
 // RUN: %clang_cc1 -x c++ -std=c++17 -fmodules 
-fmodules-local-s

Re: [clang] af80b8c - PR44684: Look through parens and similar constructs when determining

2020-01-27 Thread Nico Weber via cfe-commits
This seems to break check-clang-tools on non-Linux:
http://45.33.8.238/mac/6529/step_8.txt
http://45.33.8.238/win/6770/step_8.txt

On Mon, Jan 27, 2020 at 9:21 PM Richard Smith via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

>
> Author: Richard Smith
> Date: 2020-01-27T18:20:57-08:00
> New Revision: af80b8ccc5772c14920d4554b7ca7e15f2fad1c4
>
> URL:
> https://github.com/llvm/llvm-project/commit/af80b8ccc5772c14920d4554b7ca7e15f2fad1c4
> DIFF:
> https://github.com/llvm/llvm-project/commit/af80b8ccc5772c14920d4554b7ca7e15f2fad1c4.diff
>
> LOG: PR44684: Look through parens and similar constructs when determining
> whether a call is to a builtin.
>
> We already had a general mechanism to do this but for some reason
> weren't using it. In passing, check for the other unary operators that
> can intervene in a reasonably-direct function call (we already handled
> '&' but missed '*' and '+').
>
> Added:
>
>
> Modified:
> clang/lib/AST/Expr.cpp
> clang/lib/AST/ExprConstant.cpp
> clang/test/Parser/builtin_classify_type.c
> clang/test/Sema/constant-builtins.c
>
> Removed:
>
>
>
>
> 
> diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
> index 20505b21b15c..c2f73c2dc9d5 100644
> --- a/clang/lib/AST/Expr.cpp
> +++ b/clang/lib/AST/Expr.cpp
> @@ -1443,19 +1443,28 @@ void CallExpr::updateDependenciesFromArg(Expr
> *Arg) {
>  Decl *Expr::getReferencedDeclOfCallee() {
>Expr *CEE = IgnoreParenImpCasts();
>
> -  while (SubstNonTypeTemplateParmExpr *NTTP
> -=
> dyn_cast(CEE)) {
> -CEE = NTTP->getReplacement()->IgnoreParenCasts();
> +  while (SubstNonTypeTemplateParmExpr *NTTP =
> + dyn_cast(CEE)) {
> +CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
>}
>
>// If we're calling a dereference, look at the pointer instead.
> -  if (BinaryOperator *BO = dyn_cast(CEE)) {
> -if (BO->isPtrMemOp())
> -  CEE = BO->getRHS()->IgnoreParenCasts();
> -  } else if (UnaryOperator *UO = dyn_cast(CEE)) {
> -if (UO->getOpcode() == UO_Deref)
> -  CEE = UO->getSubExpr()->IgnoreParenCasts();
> +  while (true) {
> +if (BinaryOperator *BO = dyn_cast(CEE)) {
> +  if (BO->isPtrMemOp()) {
> +CEE = BO->getRHS()->IgnoreParenImpCasts();
> +continue;
> +  }
> +} else if (UnaryOperator *UO = dyn_cast(CEE)) {
> +  if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
> +  UO->getOpcode() == UO_Plus) {
> +CEE = UO->getSubExpr()->IgnoreParenImpCasts();
> +continue;
> +  }
> +}
> +break;
>}
> +
>if (DeclRefExpr *DRE = dyn_cast(CEE))
>  return DRE->getDecl();
>if (MemberExpr *ME = dyn_cast(CEE))
> @@ -1466,28 +1475,11 @@ Decl *Expr::getReferencedDeclOfCallee() {
>return nullptr;
>  }
>
> -/// getBuiltinCallee - If this is a call to a builtin, return the builtin
> ID. If
> -/// not, return 0.
> +/// If this is a call to a builtin, return the builtin ID. If not, return
> 0.
>  unsigned CallExpr::getBuiltinCallee() const {
> -  // All simple function calls (e.g. func()) are implicitly cast to
> pointer to
> -  // function. As a result, we try and obtain the DeclRefExpr from the
> -  // ImplicitCastExpr.
> -  const ImplicitCastExpr *ICE = dyn_cast(getCallee());
> -  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(),
> (*func)()).
> -return 0;
> -
> -  const DeclRefExpr *DRE = dyn_cast(ICE->getSubExpr());
> -  if (!DRE)
> -return 0;
> -
> -  const FunctionDecl *FDecl = dyn_cast(DRE->getDecl());
> -  if (!FDecl)
> -return 0;
> -
> -  if (!FDecl->getIdentifier())
> -return 0;
> -
> -  return FDecl->getBuiltinID();
> +  auto *FDecl =
> +
> dyn_cast_or_null(getCallee()->getReferencedDeclOfCallee());
> +  return FDecl ? FDecl->getBuiltinID() : 0;
>  }
>
>  bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
>
> diff  --git a/clang/lib/AST/ExprConstant.cpp
> b/clang/lib/AST/ExprConstant.cpp
> index c79973507323..75554c4692e9 100644
> --- a/clang/lib/AST/ExprConstant.cpp
> +++ b/clang/lib/AST/ExprConstant.cpp
> @@ -10660,7 +10660,7 @@ static bool getBuiltinAlignArguments(const
> CallExpr *E, EvalInfo &Info,
>
>  bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
>  unsigned BuiltinOp) {
> -  switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
> +  switch (BuiltinOp) {
>default:
>  return ExprEvaluatorBaseTy::VisitCallExpr(E);
>
>
> diff  --git a/clang/test/Parser/builtin_classify_type.c
> b/clang/test/Parser/builtin_classify_type.c
> index 63fd8e28045a..94434e9f2ee4 100644
> --- a/clang/test/Parser/builtin_classify_type.c
> +++ b/clang/test/Parser/builtin_classify_type.c
> @@ -9,7 +9,7 @@ int main() {
>struct foo s;
>
>static int ary[__builtin_classify_type(a)];
> -  static int ary2[(__builtin_classify_type)(a)]; //
> expected-error{{variable length array decla

[PATCH] D73495: [CodeGen] Attach no-builtin attributes to function definitions with no Decl

2020-01-27 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:1917
 const auto *NBA = Fn->getAttr();
-bool HasWildcard = NBA && llvm::is_contained(NBA->builtinNames(), "*");
-if (getLangOpts().NoBuiltin || HasWildcard)
-  FuncAttrs.addAttribute("no-builtins");
-else {
-  auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
-SmallString<32> AttributeName;
-AttributeName += "no-builtin-";
-AttributeName += BuiltinName;
-FuncAttrs.addAttribute(AttributeName);
-  };
-  llvm::for_each(getLangOpts().NoBuiltinFuncs, AddNoBuiltinAttr);
-  if (NBA)
-llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
-}
+addNonCallSiteNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
   }

thegameg wrote:
> efriedma wrote:
> > What happens if we have a TargetDecl that isn't a FunctionDecl?  (I think 
> > this happens in some cases, but not completely sure which, exactly.)
> It looks like that can be triggered by indirect calls:
> 
> ```
> typedef void T(void);
> void test3(T f) {
>   f();
> }
> ```
> 
> Since this adds the attribute to definitions and not to call sites, we should 
> never need that.
> 
> This patch is for the case where `CreateGlobalInitOrDestructFunction` ends up 
> re-using the same function to attach the attributes.
> 
> I'll update the description to make it more clear.
Are you sure that's the only case where the TargetDecl isn't a FunctionDecl?  
I'm afraid there might be some weird case where the TargetDecl defines 
something like a function, but isn't technically a FunctionDecl. Maybe an ObjC 
method or something like that.  And then we end up in a situation where 
addNonCallSiteNoBuiltinAttributes is never called.


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

https://reviews.llvm.org/D73495



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


[PATCH] D73521: [analyzer][WIP] add-new-checker.py: Introduction

2020-01-27 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso created this revision.
Charusso added a reviewer: NoQ.
Charusso added a project: clang.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, xazax.hun.

This script could be used to generate a dummy Static Analyzer checker.
Example usage:
`python add-new-checker.py alpha.package.Foo`

It also helps to document checker-writing.


Repository:
  rC Clang

https://reviews.llvm.org/D73521

Files:
  clang/test/Analysis/add-new-checker/add-main-package.rst
  clang/test/Analysis/add-new-checker/add-main-package.td
  clang/test/Analysis/add-new-checker/add-multiple-packages.rst
  clang/test/Analysis/add-new-checker/add-multiple-packages.td
  clang/test/Analysis/add-new-checker/check-add-new-checker.py
  clang/test/Analysis/add-new-checker/checker-name.rst
  clang/test/Analysis/add-new-checker/checker-name.td
  clang/test/Analysis/add-new-checker/flow-package-exist-checker.rst
  clang/test/Analysis/add-new-checker/flow-package-exist-checker.td
  clang/test/Analysis/add-new-checker/flow-package-not-exist-layering.rst
  clang/test/Analysis/add-new-checker/flow-package-not-exist-layering.td
  clang/test/Analysis/add-new-checker/flow-package-not-exist.rst
  clang/test/Analysis/add-new-checker/flow-package-not-exist.td
  clang/test/Analysis/add-new-checker/lit.local.cfg.py
  clang/utils/analyzer/add-new-checker.py

Index: clang/utils/analyzer/add-new-checker.py
===
--- /dev/null
+++ clang/utils/analyzer/add-new-checker.py
@@ -0,0 +1,732 @@
+#!/usr/bin/env python
+#
+#===- add-new-checker.py - Creates a Static Analyzer checker --*- python -*-===#
+#
+# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+# See https://llvm.org/LICENSE.txt for license information.
+# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+#
+#======#
+#
+# Example usage: python3 add-new-checker.py alpha.package.Foo
+#
+#======#
+
+import argparse
+import json
+import os
+import re
+import subprocess
+
+
+class Checker:
+def __init__(self, packages, name):
+self.packages = packages
+self.name = name
+
+def name(self):
+return self.name
+
+def packages(self):
+return self.packages
+
+def __str__(self):
+return '.'.join(self.packages) + '.' + self.name
+
+
+# Obtain the longest known package-chain of the 'packages' chain. For example
+# the checker creation of 'alpha.core.a.Checker' would return ['alpha', 'core'].
+def get_best_package_match(packages, known_packages):
+best_package_match = []
+for i in range(len(packages)):
+temp_packages = packages[:i + 1]
+package_name = '.'.join(temp_packages)
+if package_name in known_packages:
+best_package_match = temp_packages
+return best_package_match
+
+
+# Put every additional package and the checker into an increasing size jagged
+# array. For example the checker creation of 'core.a.Checker' would return
+# '[['core', 'a'], ['core', 'a', 'Checker']]'.
+def get_addition(packages, name, best_package_match):
+addition = []
+match_count = len(best_package_match)
+for i, package in enumerate(packages):
+if i < match_count:
+continue
+addition.append(best_package_match + packages[match_count : i + 1])
+addition.append(packages + [name])
+return addition
+
+
+def add_checkers_entry(clang_path, checker, args):
+checkers_include_path = os.path.join(clang_path, 
+'include', 'clang', 'StaticAnalyzer', 'Checkers')
+checkers_path = os.path.join(checkers_include_path, 'Checkers.td')
+if args.is_test:
+checkers_path = args.test_path
+if not checkers_path.endswith('.td.tmp'):
+return
+
+packages = checker.packages
+name = checker.name
+
+# Load the checkers' TableGen.
+# FIXME: Add path to 'llvm-tblgen'.
+data = None
+try:
+data = subprocess.check_output(['llvm-tblgen', '-dump-json',
+checkers_path,
+'-I=' + checkers_include_path])
+except subprocess.CalledProcessError as e:
+print('TableGen JSON dump failed:\n' + e.output.decode())
+
+data = json.loads(data)
+
+# Store the package names with their chained definition. For example the
+# package 'CoreAlpha' => 'alpha.core'.
+package_name_def_map = {}
+for package_def in data['!instanceof']['Package']:
+package = data[package_def]
+if package['ParentPackage']:
+chain = [package]
+while True:
+parent_package = chain[-1]['ParentPackage']
+if parent_package is None:
+break
+chain.append(data[parent_package['def']

[PATCH] D73520: [analyzer] BugReporterVisitors: Refactor and documentation

2020-01-27 Thread Csaba Dabis via Phabricator via cfe-commits
Charusso created this revision.
Charusso added a reviewer: NoQ.
Charusso added a project: clang.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, xazax.hun.

-


Repository:
  rC Clang

https://reviews.llvm.org/D73520

Files:
  clang/include/clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h
  clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
  clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp

Index: clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
===
--- clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
+++ clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
@@ -14,6 +14,7 @@
 #include "clang/Basic/Version.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringMap.h"
@@ -205,8 +206,9 @@
 // FIXME: What should be reported here?
 break;
   case PathDiagnosticPiece::Event:
-return Piece.getTagStr() == "ConditionBRVisitor" ? Importance::Important
- : Importance::Essential;
+return Piece.getTag() == ConditionBRVisitor::getTag()
+   ? Importance::Important
+   : Importance::Essential;
   case PathDiagnosticPiece::ControlFlow:
 return Importance::Unimportant;
   }
Index: clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
===
--- clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -1,15 +1,10 @@
-//===- BugReporterVisitors.cpp - Helpers for reporting bugs ---===//
+//===- BugReporterVisitors.cpp - Bug explaining and suppression -*- C++ -*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
-//
-//  This file defines a set of BugReporter "visitors" which can be used to
-//  enhance the diagnostics reported for a bug.
-//
-//===--===//
 
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
 #include "clang/AST/ASTContext.h"
@@ -82,18 +77,6 @@
   return nullptr;
 }
 
-/// Given that expression S represents a pointer that would be dereferenced,
-/// try to find a sub-expression from which the pointer came from.
-/// This is used for tracking down origins of a null or undefined value:
-/// "this is null because that is null because that is null" etc.
-/// We wipe away field and element offsets because they merely add offsets.
-/// We also wipe away all casts except lvalue-to-rvalue casts, because the
-/// latter represent an actual pointer dereference; however, we remove
-/// the final lvalue-to-rvalue cast before returning from this function
-/// because it demonstrates more clearly from where the pointer rvalue was
-/// loaded. Examples:
-///   x->y.z  ==>  x (lvalue)
-///   foo()->y.z  ==>  foo() (rvalue)
 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   const auto *E = dyn_cast(S);
   if (!E)
@@ -362,21 +345,17 @@
 SM(MmrMgr.getContext().getSourceManager()),
 PP(MmrMgr.getContext().getPrintingPolicy()), TKind(TKind) {}
 
-  void Profile(llvm::FoldingSetNodeID &ID) const override {
-static int Tag = 0;
-ID.AddPointer(&Tag);
-ID.AddPointer(RegionOfInterest);
-  }
-
-  void *getTag() const {
-static int Tag = 0;
-return static_cast(&Tag);
-  }
-
   PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
BugReporterContext &BR,
PathSensitiveBugReport &R) override;
 
+  static const char *getTag() { return "NoStoreFunc"; }
+
+  void Profile(llvm::FoldingSetNodeID &ID) const override {
+ID.AddPointer(getTag());
+ID.AddPointer(RegionOfInterest);
+  }
+
 private:
   /// Attempts to find the region of interest in a given record decl,
   /// by either following the base classes or fields.
@@ -837,10 +816,7 @@
   R->getAs(), V));
   }
 
-  void* getTag() const {
-static int Tag = 0;
-return static_cast(&Tag);
-  }
+  static const char *getTag() { return "MacroNullRet"; }
 
   void Profile(llvm::FoldingSetNodeID &ID) const override {
 ID.AddPointer(getTag());
@@ -903,13 +879,10 @@
   : CalleeSFC(Frame), EnableNullFPSuppression(Suppressed),
 Options(Options), TKind(TKind) {}
 
-  static void *getTag() {
-static int Tag = 0;
-return static_cast(&Tag);
-  }
+  static const char *getTag() { return "Return"; }

[clang] af80b8c - PR44684: Look through parens and similar constructs when determining

2020-01-27 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2020-01-27T18:20:57-08:00
New Revision: af80b8ccc5772c14920d4554b7ca7e15f2fad1c4

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

LOG: PR44684: Look through parens and similar constructs when determining
whether a call is to a builtin.

We already had a general mechanism to do this but for some reason
weren't using it. In passing, check for the other unary operators that
can intervene in a reasonably-direct function call (we already handled
'&' but missed '*' and '+').

Added: 


Modified: 
clang/lib/AST/Expr.cpp
clang/lib/AST/ExprConstant.cpp
clang/test/Parser/builtin_classify_type.c
clang/test/Sema/constant-builtins.c

Removed: 




diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 20505b21b15c..c2f73c2dc9d5 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -1443,19 +1443,28 @@ void CallExpr::updateDependenciesFromArg(Expr *Arg) {
 Decl *Expr::getReferencedDeclOfCallee() {
   Expr *CEE = IgnoreParenImpCasts();
 
-  while (SubstNonTypeTemplateParmExpr *NTTP
-= dyn_cast(CEE)) 
{
-CEE = NTTP->getReplacement()->IgnoreParenCasts();
+  while (SubstNonTypeTemplateParmExpr *NTTP =
+ dyn_cast(CEE)) {
+CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
   }
 
   // If we're calling a dereference, look at the pointer instead.
-  if (BinaryOperator *BO = dyn_cast(CEE)) {
-if (BO->isPtrMemOp())
-  CEE = BO->getRHS()->IgnoreParenCasts();
-  } else if (UnaryOperator *UO = dyn_cast(CEE)) {
-if (UO->getOpcode() == UO_Deref)
-  CEE = UO->getSubExpr()->IgnoreParenCasts();
+  while (true) {
+if (BinaryOperator *BO = dyn_cast(CEE)) {
+  if (BO->isPtrMemOp()) {
+CEE = BO->getRHS()->IgnoreParenImpCasts();
+continue;
+  }
+} else if (UnaryOperator *UO = dyn_cast(CEE)) {
+  if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
+  UO->getOpcode() == UO_Plus) {
+CEE = UO->getSubExpr()->IgnoreParenImpCasts();
+continue;
+  }
+}
+break;
   }
+
   if (DeclRefExpr *DRE = dyn_cast(CEE))
 return DRE->getDecl();
   if (MemberExpr *ME = dyn_cast(CEE))
@@ -1466,28 +1475,11 @@ Decl *Expr::getReferencedDeclOfCallee() {
   return nullptr;
 }
 
-/// getBuiltinCallee - If this is a call to a builtin, return the builtin ID. 
If
-/// not, return 0.
+/// If this is a call to a builtin, return the builtin ID. If not, return 0.
 unsigned CallExpr::getBuiltinCallee() const {
-  // All simple function calls (e.g. func()) are implicitly cast to pointer to
-  // function. As a result, we try and obtain the DeclRefExpr from the
-  // ImplicitCastExpr.
-  const ImplicitCastExpr *ICE = dyn_cast(getCallee());
-  if (!ICE) // FIXME: deal with more complex calls (e.g. (func)(), (*func)()).
-return 0;
-
-  const DeclRefExpr *DRE = dyn_cast(ICE->getSubExpr());
-  if (!DRE)
-return 0;
-
-  const FunctionDecl *FDecl = dyn_cast(DRE->getDecl());
-  if (!FDecl)
-return 0;
-
-  if (!FDecl->getIdentifier())
-return 0;
-
-  return FDecl->getBuiltinID();
+  auto *FDecl =
+  dyn_cast_or_null(getCallee()->getReferencedDeclOfCallee());
+  return FDecl ? FDecl->getBuiltinID() : 0;
 }
 
 bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index c79973507323..75554c4692e9 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -10660,7 +10660,7 @@ static bool getBuiltinAlignArguments(const CallExpr *E, 
EvalInfo &Info,
 
 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
 unsigned BuiltinOp) {
-  switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
+  switch (BuiltinOp) {
   default:
 return ExprEvaluatorBaseTy::VisitCallExpr(E);
 

diff  --git a/clang/test/Parser/builtin_classify_type.c 
b/clang/test/Parser/builtin_classify_type.c
index 63fd8e28045a..94434e9f2ee4 100644
--- a/clang/test/Parser/builtin_classify_type.c
+++ b/clang/test/Parser/builtin_classify_type.c
@@ -9,7 +9,7 @@ int main() {
   struct foo s;
 
   static int ary[__builtin_classify_type(a)];
-  static int ary2[(__builtin_classify_type)(a)]; // expected-error{{variable 
length array declaration cannot have 'static' storage duration}}
+  static int ary2[(__builtin_classify_type)(a)];
   static int ary3[(*__builtin_classify_type)(a)]; // expected-error{{builtin 
functions must be directly called}}
 
   int result;

diff  --git a/clang/test/Sema/constant-builtins.c 
b/clang/test/Sema/constant-builtins.c
index c98f62dfc5a2..ae3b9135c965 100644
--- a/clang/test/Sema/constant-builtins.c
+++ b/clang/test/Sema/constant-builtins.c
@@ -25,4 +25,13 @@ short

[PATCH] D73513: [memtag] Plug in stack safety analysis.

2020-01-27 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

{icon check-circle color=green} Unit tests: pass. 62250 tests passed, 0 failed 
and 816 were skipped.

{icon times-circle color=red} clang-tidy: fail. clang-tidy found 0 errors and 1 
warnings 
.
 0 of them are added as review comments below (why? 
).

{icon times-circle color=red} clang-format: fail. Please format your changes 
with clang-format by running `git-clang-format HEAD^` or applying this patch 
.

Build artifacts 
: 
diff.json 
,
 clang-tidy.txt 
,
 clang-format.patch 
,
 CMakeCache.txt 
,
 console-log.txt 
,
 test-results.xml 


//Pre-merge checks is in beta. Report issue 
.
 Please join beta  or enable 
it for your project 
.//


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73513



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


[PATCH] D73513: [memtag] Plug in stack safety analysis.

2020-01-27 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

To explain some design decisions:

The analysis is added to the IR pipeline and not to the AArch64 codegen 
pipeline mainly because we plan to extend it with ThinLTO support in the 
future. To do that, module summary builder will need to depend on the 
(function-)local stack safety analysis pass, and the global analysis result 
will be provided by the combined summary reader, and all of that must happen in 
the target-independent IR pipeline.

Another reason is that the legacy pass manager, which is still used for 
codegen, is not good at mixing function and module analyses. AFAIK a module 
pass that depends on function analysis will always produce an on-the-fly pass 
manager which can not reuse earlier analysis results; and a function pass can 
not depend on a module analysis at all (at least I could not make it work).

For these two reasons I opted not to use analysis manager framework to pass the 
safety information to AArch64StackTaggingPass, and chose to use alloca metadata 
instead.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73513



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


[PATCH] D73513: [memtag] Plug in stack safety analysis.

2020-01-27 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis created this revision.
eugenis added reviewers: pcc, vitalybuka, ostannard.
Herald added subscribers: cfe-commits, hiraditya, kristof.beyls.
Herald added projects: clang, LLVM.

Run StackSafetyAnalysis at the end of the IR pipeline and annotate
proven safe allocas with !stack-safe metadata. Do not instrument such
allocas in the AArch64StackTagging pass.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D73513

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/test/Driver/memtag.c
  llvm/include/llvm/Analysis/StackSafetyAnalysis.h
  llvm/lib/Analysis/StackSafetyAnalysis.cpp
  llvm/lib/Target/AArch64/AArch64StackTagging.cpp
  llvm/test/CodeGen/AArch64/stack-tagging.ll

Index: llvm/test/CodeGen/AArch64/stack-tagging.ll
===
--- llvm/test/CodeGen/AArch64/stack-tagging.ll
+++ llvm/test/CodeGen/AArch64/stack-tagging.ll
@@ -33,6 +33,7 @@
   %x1 = alloca i32, align 4
   %x2 = alloca i8, align 4
   %x3 = alloca i32, i32 11, align 4
+  %x4 = alloca i32, align 4, !stack-safe !0
   call void @use32(i32* %x1)
   call void @use8(i8* %x2)
   call void @use32(i32* %x3)
@@ -49,6 +50,9 @@
 ; CHECK:  alloca { [11 x i32], [4 x i8] }, align 16
 ; CHECK:  call { [11 x i32], [4 x i8] }* @llvm.aarch64.tagp.{{.*}}({ [11 x i32], [4 x i8] }* {{.*}}, i64 2)
 ; CHECK:  call void @llvm.aarch64.settag(i8* {{.*}}, i64 48)
+; CHECK:  alloca i32, align 4
+; CHECK-NOT: @llvm.aarch64.tagp
+; CHECK-NOT: @llvm.aarch64.settag
 
 ; CHECK:  call void @use32(
 ; CHECK:  call void @use8(
@@ -185,3 +189,5 @@
 ; CHECK: call void @llvm.aarch64.settag(
 ; CHECK: call void @llvm.aarch64.settag(
 ; CHECK: ret void
+
+!0 = !{}
\ No newline at end of file
Index: llvm/lib/Target/AArch64/AArch64StackTagging.cpp
===
--- llvm/lib/Target/AArch64/AArch64StackTagging.cpp
+++ llvm/lib/Target/AArch64/AArch64StackTagging.cpp
@@ -400,7 +400,9 @@
   // dynamic alloca instrumentation for them as well.
   !AI.isUsedWithInAlloca() &&
   // swifterror allocas are register promoted by ISel
-  !AI.isSwiftError();
+  !AI.isSwiftError() &&
+  // safe allocas are not interesting
+  !AI.getMetadata("stack-safe");
   return IsInteresting;
 }
 
Index: llvm/lib/Analysis/StackSafetyAnalysis.cpp
===
--- llvm/lib/Analysis/StackSafetyAnalysis.cpp
+++ llvm/lib/Analysis/StackSafetyAnalysis.cpp
@@ -99,11 +99,11 @@
 }
 
 struct AllocaInfo {
-  const AllocaInst *AI = nullptr;
+  AllocaInst *AI = nullptr;
   uint64_t Size = 0;
   UseInfo Use;
 
-  AllocaInfo(unsigned PointerSize, const AllocaInst *AI, uint64_t Size)
+  AllocaInfo(unsigned PointerSize, AllocaInst *AI, uint64_t Size)
   : AI(AI), Size(Size), Use(PointerSize) {}
 
   StringRef getName() const { return AI->getName(); }
@@ -205,7 +205,7 @@
 namespace {
 
 class StackSafetyLocalAnalysis {
-  const Function &F;
+  Function &F;
   const DataLayout &DL;
   ScalarEvolution &SE;
   unsigned PointerSize = 0;
@@ -227,7 +227,7 @@
   }
 
 public:
-  StackSafetyLocalAnalysis(const Function &F, ScalarEvolution &SE)
+  StackSafetyLocalAnalysis(Function &F, ScalarEvolution &SE)
   : F(F), DL(F.getParent()->getDataLayout()), SE(SE),
 PointerSize(DL.getPointerSizeInBits()),
 UnknownRange(PointerSize, true) {}
@@ -653,17 +653,47 @@
   return PreservedAnalyses::all();
 }
 
+static bool SetStackSafetyMetadata(Module &M,
+   const StackSafetyGlobalInfo &SSGI) {
+  bool Changed = false;
+  unsigned Width = M.getDataLayout().getPointerSizeInBits();
+  for (auto &F : M.functions()) {
+if (F.isDeclaration() || F.hasOptNone())
+  continue;
+auto Iter = SSGI.find(&F);
+if (Iter == SSGI.end())
+  continue;
+StackSafetyInfo::FunctionInfo *Summary = Iter->second.getInfo();
+for (auto &AS : Summary->Allocas) {
+  ConstantRange AllocaRange{APInt(Width, 0), APInt(Width, AS.Size)};
+  if (AllocaRange.contains(AS.Use.Range)) {
+AS.AI->setMetadata(M.getMDKindID("stack-safe"),
+   MDNode::get(M.getContext(), None));
+Changed = true;
+  }
+}
+  }
+  return Changed;
+}
+
+PreservedAnalyses
+StackSafetyGlobalAnnotatorPass::run(Module &M, ModuleAnalysisManager &AM) {
+  auto &SSGI = AM.getResult(M);
+  (void)SetStackSafetyMetadata(M, SSGI);
+  return PreservedAnalyses::all();
+}
+
 char StackSafetyGlobalInfoWrapperPass::ID = 0;
 
-StackSafetyGlobalInfoWrapperPass::StackSafetyGlobalInfoWrapperPass()
-: ModulePass(ID) {
+StackSafetyGlobalInfoWrapperPass::StackSafetyGlobalInfoWrapperPass(bool SetMetadata)
+: ModulePass(ID), SetMetadata(SetMetadata) {
   initializeStackSafetyGlobalInfoWrapperPassPass(
   *PassRegistry::getPassRegistry());
 }
 
 void StackSafetyGlobalInfoWrapperPass::print(raw_ostream &O,
  const Module *M) const {
-  ::prin

[PATCH] D73495: [CodeGen] Attach no-builtin attributes to functions with no Decl

2020-01-27 Thread Francis Visoiu Mistrih via Phabricator via cfe-commits
thegameg marked an inline comment as done.
thegameg added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:1917
 const auto *NBA = Fn->getAttr();
-bool HasWildcard = NBA && llvm::is_contained(NBA->builtinNames(), "*");
-if (getLangOpts().NoBuiltin || HasWildcard)
-  FuncAttrs.addAttribute("no-builtins");
-else {
-  auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
-SmallString<32> AttributeName;
-AttributeName += "no-builtin-";
-AttributeName += BuiltinName;
-FuncAttrs.addAttribute(AttributeName);
-  };
-  llvm::for_each(getLangOpts().NoBuiltinFuncs, AddNoBuiltinAttr);
-  if (NBA)
-llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
-}
+addNonCallSiteNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
   }

efriedma wrote:
> What happens if we have a TargetDecl that isn't a FunctionDecl?  (I think 
> this happens in some cases, but not completely sure which, exactly.)
It looks like that can be triggered by indirect calls:

```
typedef void T(void);
void test3(T f) {
  f();
}
```

Since this adds the attribute to definitions and not to call sites, we should 
never need that.

This patch is for the case where `CreateGlobalInitOrDestructFunction` ends up 
re-using the same function to attach the attributes.

I'll update the description to make it more clear.


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

https://reviews.llvm.org/D73495



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


[PATCH] D71920: [AST] Refactor propagation of dependency bits. NFC

2020-01-27 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

I don't like the name `getDependencies`, because the function is not getting a 
list of dependencies, it's getting flags that indicate whether certain 
properties of the construct are dependent. Maybe `getDependence` or 
`getDependenceFlags` would be a better name? Likewise, instead of 
`addDependencies`, perhaps `addDependence`?




Comment at: clang/include/clang/AST/DependencyFlags.h:17-28
+enum class DependencyFlags : uint8_t {
+  Type = 1,
+  Value = 2,
+  Instantiation = 4,
+  UnexpandedPack = 8,
+
+  // Shorthands for commonly used combinations.

Hmm. We have a different set of propagated flags for types (dependent / 
instantiation dependent / unexpanded pack / variably-modified) and for (eg) 
template arguments and nested name specifiers (dependent / instantiation 
dependent / unexpanded pack). It would be nice to use the same machinery 
everywhere without introducing the possibility of meaningless states and giving 
the wrong names to some states.

I think we should aim for something more type-safe than this: use a different 
type for each different family of AST nodes, so we don't conflate "dependent" 
for template arguments with one or both of "type-dependent" and 
"value-dependent" for expressions, which mean different things.



Comment at: clang/include/clang/AST/DependencyFlags.h:32-59
+constexpr inline DependencyFlags operator~(DependencyFlags F) {
+  return static_cast(
+  ~static_cast(F) & static_cast(DependencyFlags::All));
+}
+
+constexpr inline DependencyFlags operator|(DependencyFlags L,
+   DependencyFlags R) {

You can use LLVM's `BitmaskEnum` mechanism in place of these operators. 
(`#include "clang/Basic/BitmaskEnum.h"` and add 
`LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/UnexpandedPack)` to the end of the 
enum.)



Comment at: clang/include/clang/AST/DependencyFlags.h:81-85
+inline DependencyFlags turnTypeToValueDependency(DependencyFlags F) {
+  if (!isTypeDependent(F))
+return F;
+  return (F & ~DependencyFlags::Type) | DependencyFlags::Value;
+}

This whole function should be equivalent to just `F & ~DependencyFlags::Type`. 
Any type-dependent expression must also be value-dependent, so you should never 
need to set the `::Value` bit. Perhaps we could assert this somewhere.



Comment at: clang/lib/AST/NestedNameSpecifier.cpp:221
   if (Base.getType()->isDependentType())
-return true;
+return DependencyFlags::Type;
 

This is wrong: `super` should be instantiation-dependent whenever `Specifier` 
names a dependent type. Please add a FIXME.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71920



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


[PATCH] D72527: [clang-tidy] adjust scripts to subsubsections in Release Notes

2020-01-27 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

As I wrote, I don't have GitHub commit access, so I need help with commit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72527



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


[PATCH] D73231: [CUDA] Assume the latest known CUDA version if we've found an unknown one.

2020-01-27 Thread Artem Belevich via Phabricator via cfe-commits
tra updated this revision to Diff 240731.
tra edited the summary of this revision.
tra added a comment.

Use std::string instead of Twine which can't be stored.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73231

Files:
  clang/include/clang/Basic/Cuda.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/lib/Basic/Cuda.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Headers/__clang_cuda_runtime_wrapper.h
  clang/test/Driver/Inputs/CUDA-unknown/usr/local/cuda/bin/.keep
  clang/test/Driver/Inputs/CUDA-unknown/usr/local/cuda/include/.keep
  clang/test/Driver/Inputs/CUDA-unknown/usr/local/cuda/lib/.keep
  clang/test/Driver/Inputs/CUDA-unknown/usr/local/cuda/lib64/.keep
  
clang/test/Driver/Inputs/CUDA-unknown/usr/local/cuda/nvvm/libdevice/libdevice.10.bc
  clang/test/Driver/Inputs/CUDA-unknown/usr/local/cuda/version.txt
  clang/test/Driver/cuda-version-check.cu

Index: clang/test/Driver/cuda-version-check.cu
===
--- clang/test/Driver/cuda-version-check.cu
+++ clang/test/Driver/cuda-version-check.cu
@@ -8,6 +8,8 @@
 // RUN:FileCheck %s --check-prefix=OK
 // RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA_80/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=OK
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA-unknown/usr/local/cuda 2>&1 %s | \
+// RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION
 
 // The installation at Inputs/CUDA is CUDA 7.0, which doesn't support sm_60.
 // RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA/usr/local/cuda 2>&1 %s | \
@@ -58,3 +60,5 @@
 
 // ERR_SM61: error: GPU arch sm_61 {{.*}}
 // ERR_SM61-NOT: error: GPU arch sm_61
+
+// UNKNOWN_VERSION: Unknown CUDA version 999.999. Assuming the latest supported version
Index: clang/test/Driver/Inputs/CUDA-unknown/usr/local/cuda/version.txt
===
--- /dev/null
+++ clang/test/Driver/Inputs/CUDA-unknown/usr/local/cuda/version.txt
@@ -0,0 +1 @@
+CUDA Version 999.999.999
Index: clang/lib/Headers/__clang_cuda_runtime_wrapper.h
===
--- clang/lib/Headers/__clang_cuda_runtime_wrapper.h
+++ clang/lib/Headers/__clang_cuda_runtime_wrapper.h
@@ -48,7 +48,7 @@
 #include "cuda.h"
 #if !defined(CUDA_VERSION)
 #error "cuda.h did not define CUDA_VERSION"
-#elif CUDA_VERSION < 7000 || CUDA_VERSION > 10010
+#elif CUDA_VERSION < 7000
 #error "Unsupported CUDA version!"
 #endif
 
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -33,37 +33,24 @@
 
 // Parses the contents of version.txt in an CUDA installation.  It should
 // contain one line of the from e.g. "CUDA Version 7.5.2".
-static CudaVersion ParseCudaVersionFile(llvm::StringRef V) {
+static CudaVersion ParseCudaVersionFile(const Driver &D, llvm::StringRef V) {
   if (!V.startswith("CUDA Version "))
 return CudaVersion::UNKNOWN;
   V = V.substr(strlen("CUDA Version "));
-  int Major = -1, Minor = -1;
-  auto First = V.split('.');
-  auto Second = First.second.split('.');
-  if (First.first.getAsInteger(10, Major) ||
-  Second.first.getAsInteger(10, Minor))
+  SmallVector VersionParts;
+  V.split(VersionParts, '.');
+  if (VersionParts.size() < 2)
 return CudaVersion::UNKNOWN;
+  std::string MajorMinor = join_items(".", VersionParts[0], VersionParts[1]);
+  CudaVersion Version = CudaStringToVersion(MajorMinor);
+  if (Version != CudaVersion::UNKNOWN)
+return Version;
 
-  if (Major == 7 && Minor == 0) {
-// This doesn't appear to ever happen -- version.txt doesn't exist in the
-// CUDA 7 installs I've seen.  But no harm in checking.
-return CudaVersion::CUDA_70;
-  }
-  if (Major == 7 && Minor == 5)
-return CudaVersion::CUDA_75;
-  if (Major == 8 && Minor == 0)
-return CudaVersion::CUDA_80;
-  if (Major == 9 && Minor == 0)
-return CudaVersion::CUDA_90;
-  if (Major == 9 && Minor == 1)
-return CudaVersion::CUDA_91;
-  if (Major == 9 && Minor == 2)
-return CudaVersion::CUDA_92;
-  if (Major == 10 && Minor == 0)
-return CudaVersion::CUDA_100;
-  if (Major == 10 && Minor == 1)
-return CudaVersion::CUDA_101;
-  return CudaVersion::UNKNOWN;
+  // Issue a warning and assume that the version we've found is compatible with
+  // the latest version we support.
+  D.Diag(diag::warn_drv_unknown_cuda_version)
+  << MajorMinor << CudaVersionToString(CudaVersion::LATEST);
+  return CudaVersion::LATEST;
 }
 
 CudaInstallationDetector::CudaInstallationDetector(
@@ -161,7 +148,7 @@
   // version.txt isn't present.
   Versio

[PATCH] D72527: [clang-tidy] adjust scripts to subsubsections in Release Notes

2020-01-27 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh accepted this revision.
alexfh added a comment.
This revision is now accepted and ready to land.

In D72527#1843427 , @Eugene.Zelenko 
wrote:

> Just ping.


Are you waiting for other reviewers or for me to "Accept Revision"? If the 
latter, "stamped", but I've already said that the patch LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72527



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


[PATCH] D73441: [clang-tidy] Fix bugprone-use-after-move when move is in noexcept operator

2020-01-27 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6874dfce3aef: [clang-tidy] Fix bugprone-use-after-move when 
move is in noexcept operator (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73441

Files:
  clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
@@ -1270,4 +1270,32 @@
 C c;
   }
 };
+} // namespace PR33020
+
+namespace UnevalContext {
+struct Foo {};
+void noExcept() {
+  Foo Bar;
+  (void) noexcept(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
 }
+void sizeOf() {
+  Foo Bar;
+  (void)sizeof(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
+}
+void alignOf() {
+  Foo Bar;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu-alignof-expression"
+  (void)alignof(Foo{std::move(Bar)});
+#pragma clang diagnostic pop
+  Foo Other{std::move(Bar)};
+}
+void typeId() {
+  Foo Bar;
+  // error: you need to include  before using the 'typeid' operator
+  // (void) typeid(Foo{std::move(Bar)}).name();
+  Foo Other{std::move(Bar)};
+}
+} // namespace UnevalContext
Index: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -8,6 +8,10 @@
 
 #include "UseAfterMoveCheck.h"
 
+#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Lex/Lexer.h"
 
@@ -23,6 +27,23 @@
 
 namespace {
 
+AST_MATCHER(Expr, hasUnevaluatedContext) {
+  if (isa(Node) || isa(Node))
+return true;
+  if (const auto *UnaryExpr = dyn_cast(&Node)) {
+switch (UnaryExpr->getKind()) {
+case UETT_SizeOf:
+case UETT_AlignOf:
+  return true;
+default:
+  return false;
+}
+  }
+  if (const auto *TypeIDExpr = dyn_cast(&Node))
+return !TypeIDExpr->isPotentiallyEvaluated();
+  return false;
+}
+
 /// Contains information about a use-after-move.
 struct UseAfterMove {
   // The DeclRefExpr that constituted the use of the object.
@@ -77,7 +98,8 @@
 static StatementMatcher inDecltypeOrTemplateArg() {
   return anyOf(hasAncestor(typeLoc()),
hasAncestor(declRefExpr(
-   
to(functionDecl(ast_matchers::isTemplateInstantiation());
+   to(functionDecl(ast_matchers::isTemplateInstantiation(),
+   hasAncestor(expr(hasUnevaluatedContext(;
 }
 
 UseAfterMoveFinder::UseAfterMoveFinder(ASTContext *TheContext)


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
@@ -1270,4 +1270,32 @@
 C c;
   }
 };
+} // namespace PR33020
+
+namespace UnevalContext {
+struct Foo {};
+void noExcept() {
+  Foo Bar;
+  (void) noexcept(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
 }
+void sizeOf() {
+  Foo Bar;
+  (void)sizeof(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
+}
+void alignOf() {
+  Foo Bar;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu-alignof-expression"
+  (void)alignof(Foo{std::move(Bar)});
+#pragma clang diagnostic pop
+  Foo Other{std::move(Bar)};
+}
+void typeId() {
+  Foo Bar;
+  // error: you need to include  before using the 'typeid' operator
+  // (void) typeid(Foo{std::move(Bar)}).name();
+  Foo Other{std::move(Bar)};
+}
+} // namespace UnevalContext
Index: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -8,6 +8,10 @@
 
 #include "UseAfterMoveCheck.h"
 
+#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Lex/Lexer.h"
 
@@ -23,6 +27,23 @@
 
 namespace {
 
+AST_MATCHER(Expr, hasUnevaluatedContext) {
+  if (isa(Node) || isa(Node))
+return true;
+  if (const auto *UnaryExpr = dyn_cast(&Node)) {
+switch (UnaryExpr->getKind()) {
+case UETT_SizeOf:
+case UETT_AlignOf:
+  return true;
+default:
+  return false;
+}
+  }
+  if 

[clang-tools-extra] 6874dfc - [clang-tidy] Fix bugprone-use-after-move when move is in noexcept operator

2020-01-27 Thread via cfe-commits

Author: Nathan
Date: 2020-01-28T00:39:07Z
New Revision: 6874dfce3aef4a0d85fc9d45f4c9c3d90cfcbf6e

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

LOG: [clang-tidy] Fix bugprone-use-after-move when move is in noexcept operator

Summary: Fixes [[ https://bugs.llvm.org/show_bug.cgi?id=44667 | noexcept 
operator misinterpreted as being evaluated ]].

Reviewers: aaron.ballman, alexfh, JonasToth, hokein, gribozavr2

Reviewed By: gribozavr2

Subscribers: merge_guards_bot, Quuxplusone, xazax.hun, cfe-commits

Tags: #clang, #clang-tools-extra

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
index 2a5c5fa414d2..6c855440aa55 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -8,6 +8,10 @@
 
 #include "UseAfterMoveCheck.h"
 
+#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Lex/Lexer.h"
 
@@ -23,6 +27,23 @@ namespace bugprone {
 
 namespace {
 
+AST_MATCHER(Expr, hasUnevaluatedContext) {
+  if (isa(Node) || isa(Node))
+return true;
+  if (const auto *UnaryExpr = dyn_cast(&Node)) {
+switch (UnaryExpr->getKind()) {
+case UETT_SizeOf:
+case UETT_AlignOf:
+  return true;
+default:
+  return false;
+}
+  }
+  if (const auto *TypeIDExpr = dyn_cast(&Node))
+return !TypeIDExpr->isPotentiallyEvaluated();
+  return false;
+}
+
 /// Contains information about a use-after-move.
 struct UseAfterMove {
   // The DeclRefExpr that constituted the use of the object.
@@ -77,7 +98,8 @@ class UseAfterMoveFinder {
 static StatementMatcher inDecltypeOrTemplateArg() {
   return anyOf(hasAncestor(typeLoc()),
hasAncestor(declRefExpr(
-   
to(functionDecl(ast_matchers::isTemplateInstantiation());
+   to(functionDecl(ast_matchers::isTemplateInstantiation(),
+   hasAncestor(expr(hasUnevaluatedContext(;
 }
 
 UseAfterMoveFinder::UseAfterMoveFinder(ASTContext *TheContext)

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
index a28c901308cc..8a69ca42a072 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
@@ -1270,4 +1270,32 @@ class C : T, B {
 C c;
   }
 };
+} // namespace PR33020
+
+namespace UnevalContext {
+struct Foo {};
+void noExcept() {
+  Foo Bar;
+  (void) noexcept(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
 }
+void sizeOf() {
+  Foo Bar;
+  (void)sizeof(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
+}
+void alignOf() {
+  Foo Bar;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu-alignof-expression"
+  (void)alignof(Foo{std::move(Bar)});
+#pragma clang diagnostic pop
+  Foo Other{std::move(Bar)};
+}
+void typeId() {
+  Foo Bar;
+  // error: you need to include  before using the 'typeid' operator
+  // (void) typeid(Foo{std::move(Bar)}).name();
+  Foo Other{std::move(Bar)};
+}
+} // namespace UnevalContext



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


[PATCH] D73441: [clang-tidy] Fix bugprone-use-after-move when move is in noexcept operator

2020-01-27 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

{icon check-circle color=green} Unit tests: pass. 62249 tests passed, 0 failed 
and 816 were skipped.

{icon check-circle color=green} clang-tidy: pass.

{icon check-circle color=green} clang-format: pass.

Build artifacts 
: 
diff.json 
,
 clang-tidy.txt 
,
 clang-format.patch 
,
 CMakeCache.txt 
,
 console-log.txt 
,
 test-results.xml 


//Pre-merge checks is in beta. Report issue 
.
 Please join beta  or enable 
it for your project 
.//


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73441



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


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

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 240720.
void added a comment.

Merge "__has_extension" patch into this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69876

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/AST/Stmt.h
  clang/include/clang/Basic/Features.def
  clang/lib/AST/Stmt.cpp
  clang/lib/Analysis/UninitializedValues.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Parse/ParseStmtAsm.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  clang/test/Analysis/uninit-asm-goto.cpp
  clang/test/CodeGen/asm-goto.c
  clang/test/Parser/asm-goto.c
  clang/test/Parser/asm-goto.cpp
  clang/test/Sema/asm-goto.cpp

Index: clang/test/Sema/asm-goto.cpp
===
--- clang/test/Sema/asm-goto.cpp
+++ clang/test/Sema/asm-goto.cpp
@@ -1,38 +1,38 @@
 // RUN: %clang_cc1 %s -triple i386-pc-linux-gnu -verify -fsyntax-only
 // RUN: %clang_cc1 %s -triple x86_64-pc-linux-gnu -verify -fsyntax-only
 
-struct NonTrivial {
-  ~NonTrivial();
+struct S {
+  ~S();
   int f(int);
 private:
   int k;
 };
-void JumpDiagnostics(int n) {
+void test1(int n) {
 // expected-error@+1 {{cannot jump from this goto statement to its label}}
   goto DirectJump;
 // expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
-  NonTrivial tnp1;
+  S s1;
 
 DirectJump:
 // expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
   asm goto("jmp %l0;" Later);
 // expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
-  NonTrivial tnp2;
+  S s2;
 // expected-note@+1 {{possible target of asm goto statement}}
 Later:
   return;
 }
 
-struct S { ~S(); };
-void foo(int a) {
+struct T { ~T(); };
+void test2(int a) {
   if (a) {
 FOO:
 // expected-note@+2 {{jump exits scope of variable with non-trivial destructor}}
 // expected-note@+1 {{jump exits scope of variable with non-trivial destructor}}
-S s;
+T t;
 void *p = &&BAR;
 // expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
-  asm goto("jmp %l0;" BAR);
+asm goto("jmp %l0;" BAR);
 // expected-error@+1 {{cannot jump from this indirect goto statement to one of its possible targets}}
 goto *p;
 p = &&FOO;
@@ -45,9 +45,7 @@
   return;
 }
 
-
-//Asm goto:
-int test16(int n)
+int test3(int n)
 {
   // expected-error@+2 {{cannot jump from this asm goto statement to one of its possible targets}}
   // expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
Index: clang/test/Parser/asm-goto.cpp
===
--- clang/test/Parser/asm-goto.cpp
+++ clang/test/Parser/asm-goto.cpp
@@ -1,14 +1,54 @@
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -fsyntax-only -verify -std=c++11 %s
 // RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fsyntax-only -verify -std=c++11 %s
 
-int zoo ()
-{
+int a, b, c, d, e, f, g, h, i, j, k, l;
+
+void test1(void) {
+  __asm__ volatile goto (""
+:: [a] "r" (a), [b] "r" (b), [c] "r" (c), [d] "r" (d),
+   [e] "r" (e), [f] "r" (f), [g] "r" (g), [h] "r" (h),
+   [i] "r" (i), [j] "r" (j), [k] "r" (k), [l] "r" (l)
+::lab1,lab2);
+lab1: return;
+lab2: return;
+}
+
+void test2(void) {
+  __asm__ volatile goto (""
+:: [a] "r,m" (a), [b] "r,m" (b), [c] "r,m" (c), [d] "r,m" (d),
+   [e] "r,m" (e), [f] "r,m" (f), [g] "r,m" (g), [h] "r,m" (h),
+   [i] "r,m" (i), [j] "r,m" (j), [k] "r,m" (k), [l] "r,m" (l)
+:: lab);
+  lab: return;
+}
+
+int test3(int x) {
+  __asm__ volatile goto ("decl %0; jnz %l[a]"
+ : "=r" (x) : "m" (x) : "memory" : a);
+a:
+  return -x;
+}
+
+int test4(int x) {
+  int y;
+  if (x > 42)
+__asm__ volatile goto ("decl %0; jnz %l[a]"
+   : "=r" (x), "=r" (y) : "m" (x) : "memory" : a);
+  else
+__asm__ volatile goto ("decl %0; jnz %l[b]"
+   : "=r" (x), "=r" (y) : "m" (x) : "memory" : b);
+  x = y + 42;
+a:
+  return -x;
+b:
+  return +x;
+}
+
+int test5(void) {
   int x,cond,*e;
   // expected-error@+1 {{expected ')'}}
   asm ("mov %[e], %[e]" : : [e] "rm" (*e)::a)
-  // expected-error@+1  {{'asm goto' cannot have output constraints}}
-  asm goto ("decl %0; jnz %l[a]" :"=r"(x): "m"(x) : "memory" : a);
-  // expected-error@+1 {{expected identifie}}
+  // expected-error@+1 {{expected identifier}}
   asm goto ("decl %0;" :: "m"(x) : "memory" : );
   // expected-error@+1  {{expected ':'}}
   asm goto ("decl %0;" :: "m"(x) : "memory" );
@@ -26,28 +66,24 @@
   return 0;
 }
 
-
-int a, b, c, d, e, f, g, h, i, j, k, l;
-
-void
-fgoto1 (void)
-{
-  __asm__ volatile goto (""
-:: [a] "r" (a), [b] "r" (b), [c] "r" (c), [d] "r" (d),
-   [e] "r" (e), [f] "r" (f), [g] "r" (g), [h] "r" (h),
-   [i] "r" (i), 

[PATCH] D73413: [clang-tidy] Add check to detect external definitions with no header declaration

2020-01-27 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

In D73413#1843368 , @njames93 wrote:

> In D73413#1843103 , @alexfh wrote:
>
> > How is this different from `-Wmissing-prototypes`?
>
>
> This checks variables too, and it looks for a prototype specifically in the 
> header files. missing-prototypes just ensures there is a prototype of a 
> function before its defined. It also checks based on linkage of the 
> function/variable


I observed a lot of cases when people cheated GCC  `-Wmissing-prototypes` by 
adding prototypes in source file instead of header.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73413



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


[PATCH] D72527: [clang-tidy] adjust scripts to subsubsections in Release Notes

2020-01-27 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added a comment.

Just ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72527



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


[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void abandoned this revision.
void added a comment.

I'm going to merge this into D69876  as it's 
closely related.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319



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


[PATCH] D72876: Create a clang-tidy check to warn when -dealloc is implemented inside an ObjC class category.

2020-01-27 Thread Michael Wyman via Phabricator via cfe-commits
mwyman added a comment.

Updated the diff based on review feedback.




Comment at: clang-tools-extra/clang-tidy/objc/DeallocInCategoriesCheck.cpp:21
+  Finder->addMatcher(
+  objcMethodDecl(hasName("dealloc"), 
hasDeclContext(objcCategoryImplDecl()))
+  .bind("dealloc"),

stephanemoore wrote:
> stephanemoore wrote:
> > Add `isInstanceMethod()` within the `objcMethodDecl`?
> Technically, isn't `-dealloc` specific to certain classes, e.g., 
> [`NSObject`](https://developer.apple.com/documentation/objectivec/nsobject/1571947-dealloc?language=objc))
>  and 
> [NSProxy](https://developer.apple.com/documentation/foundation/nsproxy/1589830-dealloc?language=objc)?
>  If that is true, we should technically check that the category is on a class 
> that is or is derived from a relevant class like `NSObject` or `NSProxy`.
Technically true, but given the prevalence of extant ObjC documentation talking 
about the -dealloc method in terms of deallocation, it seems highly unlikely 
any non-NSObject/NSProxy-rooted class hierarchies are going to use -dealloc in 
any other context, and want to allow implementations in a category.



Comment at: clang-tools-extra/clang-tidy/objc/DeallocInCategoriesCheck.h:24
+/// 
http://clang.llvm.org/extra/clang-tidy/checks/objc-dealloc-in-categories.html
+class DeallocInCategoriesCheck : public ClangTidyCheck {
+public:

stephanemoore wrote:
> What do you think of the name `DeallocInCategoryCheck`?
Much better.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72876



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


[PATCH] D73441: [clang-tidy] Fix bugprone-use-after-move when move is in noexcept operator

2020-01-27 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 240718.
njames93 added a comment.

- Remove artifacts of old dependent review


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73441

Files:
  clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
@@ -1270,4 +1270,32 @@
 C c;
   }
 };
+} // namespace PR33020
+
+namespace UnevalContext {
+struct Foo {};
+void noExcept() {
+  Foo Bar;
+  (void) noexcept(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
 }
+void sizeOf() {
+  Foo Bar;
+  (void)sizeof(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
+}
+void alignOf() {
+  Foo Bar;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu-alignof-expression"
+  (void)alignof(Foo{std::move(Bar)});
+#pragma clang diagnostic pop
+  Foo Other{std::move(Bar)};
+}
+void typeId() {
+  Foo Bar;
+  // error: you need to include  before using the 'typeid' operator
+  // (void) typeid(Foo{std::move(Bar)}).name();
+  Foo Other{std::move(Bar)};
+}
+} // namespace UnevalContext
Index: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -8,6 +8,10 @@
 
 #include "UseAfterMoveCheck.h"
 
+#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Lex/Lexer.h"
 
@@ -23,6 +27,23 @@
 
 namespace {
 
+AST_MATCHER(Expr, hasUnevaluatedContext) {
+  if (isa(Node) || isa(Node))
+return true;
+  if (const auto *UnaryExpr = dyn_cast(&Node)) {
+switch (UnaryExpr->getKind()) {
+case UETT_SizeOf:
+case UETT_AlignOf:
+  return true;
+default:
+  return false;
+}
+  }
+  if (const auto *TypeIDExpr = dyn_cast(&Node))
+return !TypeIDExpr->isPotentiallyEvaluated();
+  return false;
+}
+
 /// Contains information about a use-after-move.
 struct UseAfterMove {
   // The DeclRefExpr that constituted the use of the object.
@@ -77,7 +98,8 @@
 static StatementMatcher inDecltypeOrTemplateArg() {
   return anyOf(hasAncestor(typeLoc()),
hasAncestor(declRefExpr(
-   
to(functionDecl(ast_matchers::isTemplateInstantiation());
+   to(functionDecl(ast_matchers::isTemplateInstantiation(),
+   hasAncestor(expr(hasUnevaluatedContext(;
 }
 
 UseAfterMoveFinder::UseAfterMoveFinder(ASTContext *TheContext)


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-use-after-move.cpp
@@ -1270,4 +1270,32 @@
 C c;
   }
 };
+} // namespace PR33020
+
+namespace UnevalContext {
+struct Foo {};
+void noExcept() {
+  Foo Bar;
+  (void) noexcept(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
 }
+void sizeOf() {
+  Foo Bar;
+  (void)sizeof(Foo{std::move(Bar)});
+  Foo Other{std::move(Bar)};
+}
+void alignOf() {
+  Foo Bar;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wgnu-alignof-expression"
+  (void)alignof(Foo{std::move(Bar)});
+#pragma clang diagnostic pop
+  Foo Other{std::move(Bar)};
+}
+void typeId() {
+  Foo Bar;
+  // error: you need to include  before using the 'typeid' operator
+  // (void) typeid(Foo{std::move(Bar)}).name();
+  Foo Other{std::move(Bar)};
+}
+} // namespace UnevalContext
Index: clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp
@@ -8,6 +8,10 @@
 
 #include "UseAfterMoveCheck.h"
 
+#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Lex/Lexer.h"
 
@@ -23,6 +27,23 @@
 
 namespace {
 
+AST_MATCHER(Expr, hasUnevaluatedContext) {
+  if (isa(Node) || isa(Node))
+return true;
+  if (const auto *UnaryExpr = dyn_cast(&Node)) {
+switch (UnaryExpr->getKind()) {
+case UETT_SizeOf:
+case UETT_AlignOf:
+  return true;
+default:
+  return false;
+}
+  }
+  if (const auto *TypeIDExpr = dyn_cast(&Node))
+return !TypeIDExpr->isPotentiallyEvaluate

[PATCH] D73493: [AArch64][SVE] Add SVE2 intrinsics for uniform DSP operations

2020-01-27 Thread Eli Friedman via Phabricator via cfe-commits
efriedma accepted this revision.
efriedma added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73493



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


[PATCH] D72876: Create a clang-tidy check to warn when -dealloc is implemented inside an ObjC class category.

2020-01-27 Thread Michael Wyman via Phabricator via cfe-commits
mwyman updated this revision to Diff 240716.
mwyman marked 7 inline comments as done.
mwyman added a comment.

Addresses reviewer feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72876

Files:
  clang-tools-extra/clang-tidy/objc/CMakeLists.txt
  clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.cpp
  clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.h
  clang-tools-extra/clang-tidy/objc/ObjCTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/objc-dealloc-in-category.rst
  clang-tools-extra/test/clang-tidy/checkers/objc-dealloc-in-category.m

Index: clang-tools-extra/test/clang-tidy/checkers/objc-dealloc-in-category.m
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/objc-dealloc-in-category.m
@@ -0,0 +1,47 @@
+// RUN: %check_clang_tidy %s objc-dealloc-in-category %t
+
+@interface NSObject
+// Used to quash warning about missing base class.
+- (void)dealloc;
+@end
+
+@interface Foo : NSObject
+@end
+
+@implementation Foo
+- (void)dealloc {
+  // No warning should be generated here.
+}
+@end
+
+@interface Bar : NSObject
+@end
+
+@interface Bar (Category)
+@end
+
+@implementation Bar (Category)
++ (void)dealloc {
+  // Should not trigger on class methods.
+}
+
+- (void)dealloc {
+  // CHECK-MESSAGES: :[[@LINE-1]]:1: warning: method -dealloc should not be implemented in a category [objc-dealloc-in-category]
+}
+@end
+
+@interface Baz : NSObject
+@end
+
+@implementation Baz
+- (void)dealloc {
+  // Should not trigger on implementation in the class itself, even with
+  // it declared in the category (below).
+}
+@end
+
+@interface Baz (Category)
+// A declaration in a category @interface does not by itself provide an
+// overriding implementation, and should not generate a warning.
+- (void)dealloc;
+@end
Index: clang-tools-extra/docs/clang-tidy/checks/objc-dealloc-in-category.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/objc-dealloc-in-category.rst
@@ -0,0 +1,13 @@
+.. title:: clang-tidy - objc-dealloc-in-category
+
+objc-dealloc-in-category
+
+
+Finds implementations of ``-dealloc`` in Objective-C categories. The category
+implementation will override any dealloc in the class implementation,
+potentially causing issues.
+
+Classes implement ``-dealloc`` to perform important actions just before an
+object is deallocated, but if a category on the class implements ``-dealloc``
+it will override the class's implementation and those important actions may
+not be handled by the overriding ``-dealloc``.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -232,6 +232,7 @@
`mpi-buffer-deref `_, "Yes"
`mpi-type-mismatch `_, "Yes"
`objc-avoid-nserror-init `_,
+   `objc-dealloc-in-category `_,
`objc-forbidden-subclassing `_,
`objc-missing-hash `_,
`objc-property-declaration `_, "Yes"
@@ -280,7 +281,7 @@
`readability-redundant-member-init `_, "Yes"
`readability-redundant-preprocessor `_,
`readability-redundant-smartptr-get `_, "Yes"
-   `readability-redundant-string-cstr `_,
+   `readability-redundant-string-cstr `_, "Yes"
`readability-redundant-string-init `_, "Yes"
`readability-simplify-boolean-expr `_, "Yes"
`readability-simplify-subscript-expr `_, "Yes"
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -81,13 +81,18 @@
   ` check.
 
   Checks for usages of identifiers reserved for use by the implementation.
-  
+
 - New :doc:`cert-oop57-cpp
   ` check.
-  
+
   Flags use of the `C` standard library functions ``memset``, ``memcpy`` and
   ``memcmp`` and similar derivatives on non-trivial types.
 
+- New :doc:`objc-dealloc-in-category
+  ` check.
+
+  Finds implementations of -dealloc in Objective-C categories.
+
 New aliases
 ^^^
 
@@ -106,8 +111,8 @@
 
 - Improved :doc:`readability-redundant-string-init
   ` check now supports a
-  `StringNames` option enabling its application to custom string classes. The 
-  check now detects in class initializers and constructor initializers which 
+  `StringNames` option enabling its application to custom string classes. The
+  check now detects in class initializers and constructor initializers which
   are deemed to be redundant.
 
 Renamed checks
Index: clang-tools-extra/clang-tidy/objc/ObjCTidyModule.cpp
===
--- clang-tools-extra/clang-t

[PATCH] D73202: Make AST reading work better with LLVM_APPEND_VC_REV=NO

2020-01-27 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


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

https://reviews.llvm.org/D73202



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


[PATCH] D73413: [clang-tidy] Add check to detect external definitions with no header declaration

2020-01-27 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D73413#1843103 , @alexfh wrote:

> How is this different from `-Wmissing-prototypes`?


This checks variables too, and it looks for a prototype specifically in the 
header files. missing-prototypes just ensures there is a prototype of a 
function before its defined. It also checks based on linkage of the 
function/variable


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73413



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


[PATCH] D72448: [clang-tidy] readability-redundant-string-init now flags redundant initialisation in Field Decls and Constructor Initialisers

2020-01-27 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7c90666d2c3c: [clang-tidy] readability-redundant-string-init 
now flags redundant… (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72448

Files:
  clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-init.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-init.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-init.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-init.cpp
@@ -34,6 +34,12 @@
   std::string d(R"()");
   // CHECK-MESSAGES: [[@LINE-1]]:15: warning: redundant string initialization
   // CHECK-FIXES: std::string d;
+  std::string e{""};
+  // CHECK-MESSAGES: [[@LINE-1]]:15: warning: redundant string initialization
+  // CHECK-FIXES: std::string e;
+  std::string f = {""};
+  // CHECK-MESSAGES: [[@LINE-1]]:15: warning: redundant string initialization
+  // CHECK-FIXES: std::string f;
 
   std::string u = "u";
   std::string w("w");
@@ -227,3 +233,53 @@
   other::wstring e = L"";
   other::wstring f(L"");
 }
+
+class Foo {
+  std::string A = "";
+  // CHECK-MESSAGES: [[@LINE-1]]:15: warning: redundant string initialization
+  // CHECK-FIXES:  std::string A;
+  std::string B;
+  std::string C;
+  std::string D;
+  std::string E = "NotEmpty";
+
+public:
+  // Check redundant constructor where Field has a redundant initializer.
+  Foo() : A("") {}
+  // CHECK-MESSAGES: [[@LINE-1]]:11: warning: redundant string initialization
+  // CHECK-FIXES:  Foo()  {}
+
+  // Check redundant constructor where Field has no initializer.
+  Foo(char) : B("") {}
+  // CHECK-MESSAGES: [[@LINE-1]]:15: warning: redundant string initialization
+  // CHECK-FIXES:  Foo(char)  {}
+
+  // Check redundant constructor where Field has a valid initializer.
+  Foo(long) : E("") {}
+  // CHECK-MESSAGES: [[@LINE-1]]:15: warning: redundant string initialization
+  // CHECK-FIXES:  Foo(long) : E() {}
+
+  // Check how it handles removing 1 initializer, and defaulting the other.
+  Foo(int) : B(""), E("") {}
+  // CHECK-MESSAGES: [[@LINE-1]]:14: warning: redundant string initialization
+  // CHECK-MESSAGES: [[@LINE-2]]:21: warning: redundant string initialization
+  // CHECK-FIXES:  Foo(int) :  E() {}
+
+  Foo(short) : B{""} {}
+  // CHECK-MESSAGES: [[@LINE-1]]:16: warning: redundant string initialization
+  // CHECK-FIXES:  Foo(short)  {}
+
+  Foo(float) : A{""}, B{""} {}
+  // CHECK-MESSAGES: [[@LINE-1]]:16: warning: redundant string initialization
+  // CHECK-MESSAGES: [[@LINE-2]]:23: warning: redundant string initialization
+  // CHECK-FIXES:  Foo(float)  {}
+
+
+  // Check how it handles removing some redundant initializers while leaving
+  // valid initializers intact.
+  Foo(std::string Arg) : A(Arg), B(""), C("NonEmpty"), D(R"()"), E("") {}
+  // CHECK-MESSAGES: [[@LINE-1]]:34: warning: redundant string initialization
+  // CHECK-MESSAGES: [[@LINE-2]]:56: warning: redundant string initialization
+  // CHECK-MESSAGES: [[@LINE-3]]:66: warning: redundant string initialization
+  // CHECK-FIXES:  Foo(std::string Arg) : A(Arg),  C("NonEmpty"),  E() {}
+};
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -104,6 +104,11 @@
 Changes in existing checks
 ^^
 
+- Improved :doc:`readability-redundant-string-init
+  ` check now supports a
+  `StringNames` option enabling its application to custom string classes. The 
+  check now detects in class initializers and constructor initializers which 
+  are deemed to be redundant.
 
 Renamed checks
 ^^
Index: clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
@@ -20,6 +20,46 @@
 
 const char DefaultStringNames[] = "::std::basic_string";
 
+static ast_matchers::internal::Matcher
+hasAnyNameStdString(std::vector Names) {
+  return ast_matchers::internal::Matcher(
+  new ast_matchers::internal::HasNameMatcher(std::move(Names)));
+}
+
+static std::vector
+removeNamespaces(const std::vector &Names) {
+  std::vector Result;
+  Result.reserve(Names.size());
+  for (const std::string &Name : Names) {
+std::string::size_type ColonPos = Name.rfind(':');
+Result.push_back(
+Name.substr(ColonPos == std::string::npos ? 0 : ColonPos + 1));
+  }
+  return Result;
+}
+
+static const CXX

[clang-tools-extra] 7c90666 - [clang-tidy] readability-redundant-string-init now flags redundant initialisation in Field Decls and Constructor Initialisers

2020-01-27 Thread via cfe-commits

Author: Nathan
Date: 2020-01-27T23:51:45Z
New Revision: 7c90666d2c3cfb5a519275d89195be317e7cc0ab

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

LOG: [clang-tidy] readability-redundant-string-init now flags redundant 
initialisation in Field Decls and Constructor Initialisers

Summary:
The original behaviour of this check only looked at VarDecls with strings that 
had an empty string initializer. This has been improved to check for FieldDecls 
with an in class initializer as well as constructor initializers.

Addresses [[ https://bugs.llvm.org/show_bug.cgi?id=44474 | clang-tidy 
"modernize-use-default-member-init"/"readability-redundant-string-init" and 
redundant initializer of std::string ]]

Reviewers: aaron.ballman, alexfh, hokein

Reviewed By: aaron.ballman

Subscribers: merge_guards_bot, mgorny, Eugene.Zelenko, xazax.hun, cfe-commits

Tags: #clang, #clang-tools-extra

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/readability-redundant-string-init.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
index 6bf0edb7231f..866bb79829d8 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp
@@ -20,6 +20,46 @@ namespace readability {
 
 const char DefaultStringNames[] = "::std::basic_string";
 
+static ast_matchers::internal::Matcher
+hasAnyNameStdString(std::vector Names) {
+  return ast_matchers::internal::Matcher(
+  new ast_matchers::internal::HasNameMatcher(std::move(Names)));
+}
+
+static std::vector
+removeNamespaces(const std::vector &Names) {
+  std::vector Result;
+  Result.reserve(Names.size());
+  for (const std::string &Name : Names) {
+std::string::size_type ColonPos = Name.rfind(':');
+Result.push_back(
+Name.substr(ColonPos == std::string::npos ? 0 : ColonPos + 1));
+  }
+  return Result;
+}
+
+static const CXXConstructExpr *
+getConstructExpr(const CXXCtorInitializer &CtorInit) {
+  const Expr *InitExpr = CtorInit.getInit();
+  if (const auto *CleanUpExpr = dyn_cast(InitExpr))
+InitExpr = CleanUpExpr->getSubExpr();
+  return dyn_cast(InitExpr);
+}
+
+static llvm::Optional
+getConstructExprArgRange(const CXXConstructExpr &Construct) {
+  SourceLocation B, E;
+  for (const Expr *Arg : Construct.arguments()) {
+if (B.isInvalid())
+  B = Arg->getBeginLoc();
+if (Arg->getEndLoc().isValid())
+  E = Arg->getEndLoc();
+  }
+  if (B.isInvalid() || E.isInvalid())
+return llvm::None;
+  return SourceRange(B, E);
+}
+
 RedundantStringInitCheck::RedundantStringInitCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
@@ -33,18 +73,9 @@ void 
RedundantStringInitCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 void RedundantStringInitCheck::registerMatchers(MatchFinder *Finder) {
   if (!getLangOpts().CPlusPlus)
 return;
-  const auto hasStringTypeName = hasAnyName(
-  SmallVector(StringNames.begin(), StringNames.end()));
-
-  // Version of StringNames with namespaces removed
-  std::vector stringNamesNoNamespace;
-  for (const std::string &name : StringNames) {
-std::string::size_type colonPos = name.rfind(':');
-stringNamesNoNamespace.push_back(
-name.substr(colonPos == std::string::npos ? 0 : colonPos + 1));
-  }
-  const auto hasStringCtorName = hasAnyName(SmallVector(
-  stringNamesNoNamespace.begin(), stringNamesNoNamespace.end()));
+  const auto hasStringTypeName = hasAnyNameStdString(StringNames);
+  const auto hasStringCtorName =
+  hasAnyNameStdString(removeNamespaces(StringNames));
 
   // Match string constructor.
   const auto StringConstructorExpr = expr(
@@ -65,29 +96,76 @@ void RedundantStringInitCheck::registerMatchers(MatchFinder 
*Finder) {
   cxxConstructExpr(StringConstructorExpr,
hasArgument(0, ignoringImplicit(EmptyStringCtorExpr)));
 
+  const auto StringType = hasType(hasUnqualifiedDesugaredType(
+  recordType(hasDeclaration(cxxRecordDecl(hasStringTypeName);
+  const auto EmptyStringInit = expr(ignoringImplicit(
+  anyOf(EmptyStringCtorExpr, EmptyStringCtorExprWithTemporaries)));
+
   // Match a variable declaration with an empty string literal as initializer.
   // Examples:
   // string foo = "";
   // string bar("");
   Finder->addMatcher(
   namedDecl(
-  varDecl(
-  hasType(hasUnqualifiedDesugar

[PATCH] D73098: [clang-tidy] readability-identifier-naming disregards parameters restrictions on main like functions

2020-01-27 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc3d20fd47200: [clang-tidy] readability-identifier-naming 
disregards parameters restrictions… (authored by njames93).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73098

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp
@@ -0,0 +1,88 @@
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- \
+// RUN:   -config='{CheckOptions: [ \
+// RUN: {key: readability-identifier-naming.ParameterCase, value: CamelCase}, \
+// RUN: {key: readability-identifier-naming.IgnoreMainLikeFunctions, value: 1} \
+// RUN:  ]}'
+
+int mainLike(int argc, char **argv);
+int mainLike(int argc, char **argv, const char **env);
+int mainLike(int argc, const char **argv);
+int mainLike(int argc, const char **argv, const char **env);
+int mainLike(int argc, char *argv[]);
+int mainLike(int argc, const char *argv[]);
+int mainLike(int argc, char *argv[], char *env[]);
+int mainLike(int argc, const char *argv[], const char *env[]);
+void notMain(int argc, char **argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:31: warning: invalid case style for parameter 'argv'
+void notMain(int argc, char **argv, char **env);
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:31: warning: invalid case style for parameter 'argv'
+// CHECK-MESSAGES: :[[@LINE-3]]:44: warning: invalid case style for parameter 'env'
+int notMain(int argc, char **argv, char **env, int Extra);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:30: warning: invalid case style for parameter 'argv'
+// CHECK-MESSAGES: :[[@LINE-3]]:43: warning: invalid case style for parameter 'env'
+int notMain(int argc, char **argv, int Extra);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:30: warning: invalid case style for parameter 'argv'
+int notMain(int argc, char *argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:29: warning: invalid case style for parameter 'argv'
+int notMain(unsigned argc, char **argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:22: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:35: warning: invalid case style for parameter 'argv'
+int notMain(long argc, char *argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:30: warning: invalid case style for parameter 'argv'
+int notMain(int argc, char16_t **argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:34: warning: invalid case style for parameter 'argv'
+int notMain(int argc, char argv[]);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:28: warning: invalid case style for parameter 'argv'
+typedef char myFunChar;
+typedef int myFunInt;
+typedef char **myFunCharPtr;
+typedef long myFunLong;
+myFunInt mainLikeTypedef(myFunInt argc, myFunChar **argv);
+int mainLikeTypedef(int argc, myFunCharPtr argv);
+int notMainTypedef(myFunLong argc, char **argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:30: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:43: warning: invalid case style for parameter 'argv'
+
+// Don't flag as name contains the word main
+int myMainFunction(int argc, char *argv[]);
+
+// This is fine, named with wmain and has wchar ptr.
+int wmainLike(int argc, wchar_t *argv[]);
+
+// Flag this as has signature of main, but named as wmain.
+int wmainLike(int argc, char *argv[]);
+// CHECK-MESSAGES: :[[@LINE-1]]:19: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:31: warning: invalid case style for parameter 'argv'
+
+struct Foo {
+  Foo(int argc, char *argv[]) {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: invalid case style for parameter 'argc'
+  // CHECK-MESSAGES: :[[@LINE-2]]:23: warning: invalid case style for parameter 'argv'
+
+  int mainPub(int argc, char *argv[]);
+  static int mainPubStatic(int argc, char *argv[]);
+
+protected:
+  int mainProt(

[clang-tools-extra] c3d20fd - [clang-tidy] readability-identifier-naming disregards parameters restrictions on main like functions

2020-01-27 Thread via cfe-commits

Author: Nathan
Date: 2020-01-27T23:47:51Z
New Revision: c3d20fd472000c7abdc2c9cad051a2ab339709d9

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

LOG: [clang-tidy] readability-identifier-naming disregards parameters 
restrictions on main like functions

Summary:
Typically most main functions have the signature:
```
int main(int argc, char *argv[])
```
To stick with convention when renaming parameters we should ignore the `argc` 
and `argv` names even if the parameter style says they should be renamed. This 
patch addresses this by checking all ParmVarDecls if they form part of a 
function with a signature that matches main `int name(int argc, char * argv[], 
(optional char *env[]))`

Reviewers: aaron.ballman, JonasToth, alexfh, hokein

Reviewed By: aaron.ballman

Subscribers: Mordante, merge_guards_bot, xazax.hun, kristof.beyls, cfe-commits

Tags: #clang, #clang-tools-extra

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp

Modified: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index 6a39ece09777..119502e91ffe 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -8,15 +8,13 @@
 
 #include "IdentifierNamingCheck.h"
 
-#include "../utils/ASTUtils.h"
-#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/AST/CXXInheritance.h"
-#include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/Regex.h"
 
 #define DEBUG_TYPE "clang-tidy"
 
@@ -126,7 +124,9 @@ class IdentifierNamingCheckPPCallbacks : public PPCallbacks 
{
 
 IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
  ClangTidyContext *Context)
-: RenamerClangTidyCheck(Name, Context) {
+: RenamerClangTidyCheck(Name, Context),
+  IgnoreFailedSplit(Options.get("IgnoreFailedSplit", 0)),
+  IgnoreMainLikeFunctions(Options.get("IgnoreMainLikeFunctions", 0)) {
   auto const fromString = [](StringRef Str) {
 return llvm::StringSwitch>(Str)
 .Case("aNy_CasE", CT_AnyCase)
@@ -151,8 +151,6 @@ IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
   NamingStyles.push_back(llvm::None);
 }
   }
-
-  IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
 }
 
 IdentifierNamingCheck::~IdentifierNamingCheck() = default;
@@ -193,6 +191,7 @@ void 
IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   }
 
   Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
+  Options.store(Opts, "IgnoreMainLikeFunctions", IgnoreMainLikeFunctions);
 }
 
 static bool matchesStyle(StringRef Name,
@@ -324,6 +323,67 @@ static std::string fixupWithCase(StringRef Name,
   return Fixup;
 }
 
+static bool isParamInMainLikeFunction(const ParmVarDecl &ParmDecl,
+  bool IncludeMainLike) {
+  const auto *FDecl =
+  dyn_cast_or_null(ParmDecl.getParentFunctionOrMethod());
+  if (!FDecl)
+return false;
+  if (FDecl->isMain())
+return true;
+  if (!IncludeMainLike)
+return false;
+  if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
+return false;
+  enum MainType { None, Main, WMain };
+  auto IsCharPtrPtr = [](QualType QType) -> MainType {
+if (QType.isNull())
+  return None;
+if (QType = QType->getPointeeType(), QType.isNull())
+  return None;
+if (QType = QType->getPointeeType(), QType.isNull())
+  return None;
+if (QType->isCharType())
+  return Main;
+if (QType->isWideCharType())
+  return WMain;
+return None;
+  };
+  auto IsIntType = [](QualType QType) {
+if (QType.isNull())
+  return false;
+if (const auto *Builtin =
+dyn_cast(QType->getUnqualifiedDesugaredType())) {
+  return Builtin->getKind() == BuiltinType::Int;
+}
+return false;
+  };
+  if (!IsIntType(FDecl->getReturnType()))
+return false;
+  if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)
+return false;
+  if (!IsIntType(FDecl->parameters()[0]->getType()))
+return false;
+  MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType());
+  if (Type == None)
+return false;
+  if (FD

[PATCH] D73098: [clang-tidy] readability-identifier-naming disregards parameters restrictions on main like functions

2020-01-27 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 240706.
njames93 added a comment.

Fix diff, ready to recommit


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

https://reviews.llvm.org/D73098

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp
@@ -0,0 +1,88 @@
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- \
+// RUN:   -config='{CheckOptions: [ \
+// RUN: {key: readability-identifier-naming.ParameterCase, value: CamelCase}, \
+// RUN: {key: readability-identifier-naming.IgnoreMainLikeFunctions, value: 1} \
+// RUN:  ]}'
+
+int mainLike(int argc, char **argv);
+int mainLike(int argc, char **argv, const char **env);
+int mainLike(int argc, const char **argv);
+int mainLike(int argc, const char **argv, const char **env);
+int mainLike(int argc, char *argv[]);
+int mainLike(int argc, const char *argv[]);
+int mainLike(int argc, char *argv[], char *env[]);
+int mainLike(int argc, const char *argv[], const char *env[]);
+void notMain(int argc, char **argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:31: warning: invalid case style for parameter 'argv'
+void notMain(int argc, char **argv, char **env);
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:31: warning: invalid case style for parameter 'argv'
+// CHECK-MESSAGES: :[[@LINE-3]]:44: warning: invalid case style for parameter 'env'
+int notMain(int argc, char **argv, char **env, int Extra);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:30: warning: invalid case style for parameter 'argv'
+// CHECK-MESSAGES: :[[@LINE-3]]:43: warning: invalid case style for parameter 'env'
+int notMain(int argc, char **argv, int Extra);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:30: warning: invalid case style for parameter 'argv'
+int notMain(int argc, char *argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:29: warning: invalid case style for parameter 'argv'
+int notMain(unsigned argc, char **argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:22: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:35: warning: invalid case style for parameter 'argv'
+int notMain(long argc, char *argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:30: warning: invalid case style for parameter 'argv'
+int notMain(int argc, char16_t **argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:34: warning: invalid case style for parameter 'argv'
+int notMain(int argc, char argv[]);
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:28: warning: invalid case style for parameter 'argv'
+typedef char myFunChar;
+typedef int myFunInt;
+typedef char **myFunCharPtr;
+typedef long myFunLong;
+myFunInt mainLikeTypedef(myFunInt argc, myFunChar **argv);
+int mainLikeTypedef(int argc, myFunCharPtr argv);
+int notMainTypedef(myFunLong argc, char **argv);
+// CHECK-MESSAGES: :[[@LINE-1]]:30: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:43: warning: invalid case style for parameter 'argv'
+
+// Don't flag as name contains the word main
+int myMainFunction(int argc, char *argv[]);
+
+// This is fine, named with wmain and has wchar ptr.
+int wmainLike(int argc, wchar_t *argv[]);
+
+// Flag this as has signature of main, but named as wmain.
+int wmainLike(int argc, char *argv[]);
+// CHECK-MESSAGES: :[[@LINE-1]]:19: warning: invalid case style for parameter 'argc'
+// CHECK-MESSAGES: :[[@LINE-2]]:31: warning: invalid case style for parameter 'argv'
+
+struct Foo {
+  Foo(int argc, char *argv[]) {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: invalid case style for parameter 'argc'
+  // CHECK-MESSAGES: :[[@LINE-2]]:23: warning: invalid case style for parameter 'argv'
+
+  int mainPub(int argc, char *argv[]);
+  static int mainPubStatic(int argc, char *argv[]);
+
+protected:
+  int mainProt(int argc, char *argv[]);
+  // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: invalid case style for parameter 'argc'
+  // CHECK-MESSAGES: :[[@LINE-2]]

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

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void added a comment.

In D69876#1843199 , @MaskRay wrote:

> Does this depend on D69868 ?


Yes. I added it as a parent.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69876



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


[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void marked an inline comment as done.
void added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:1273
+  int y;
+  asm goto("# %0 %1 %2" : "=r"(y) : "r"(x) : : err);
+  return y;

MaskRay wrote:
> Is the canonical spelling `%l2`?
Nice catch! I patched it in D69876.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319



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


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

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 240692.
void added a comment.

Fix extension example, found by eagle-eye @maskray!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69876

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/AST/Stmt.h
  clang/lib/AST/Stmt.cpp
  clang/lib/Analysis/UninitializedValues.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/Parse/ParseStmtAsm.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  clang/test/Analysis/uninit-asm-goto.cpp
  clang/test/CodeGen/asm-goto.c
  clang/test/Parser/asm-goto.c
  clang/test/Parser/asm-goto.cpp
  clang/test/Sema/asm-goto.cpp

Index: clang/test/Sema/asm-goto.cpp
===
--- clang/test/Sema/asm-goto.cpp
+++ clang/test/Sema/asm-goto.cpp
@@ -1,38 +1,38 @@
 // RUN: %clang_cc1 %s -triple i386-pc-linux-gnu -verify -fsyntax-only
 // RUN: %clang_cc1 %s -triple x86_64-pc-linux-gnu -verify -fsyntax-only
 
-struct NonTrivial {
-  ~NonTrivial();
+struct S {
+  ~S();
   int f(int);
 private:
   int k;
 };
-void JumpDiagnostics(int n) {
+void test1(int n) {
 // expected-error@+1 {{cannot jump from this goto statement to its label}}
   goto DirectJump;
 // expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
-  NonTrivial tnp1;
+  S s1;
 
 DirectJump:
 // expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
   asm goto("jmp %l0;" Later);
 // expected-note@+1 {{jump bypasses variable with a non-trivial destructor}}
-  NonTrivial tnp2;
+  S s2;
 // expected-note@+1 {{possible target of asm goto statement}}
 Later:
   return;
 }
 
-struct S { ~S(); };
-void foo(int a) {
+struct T { ~T(); };
+void test2(int a) {
   if (a) {
 FOO:
 // expected-note@+2 {{jump exits scope of variable with non-trivial destructor}}
 // expected-note@+1 {{jump exits scope of variable with non-trivial destructor}}
-S s;
+T t;
 void *p = &&BAR;
 // expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
-  asm goto("jmp %l0;" BAR);
+asm goto("jmp %l0;" BAR);
 // expected-error@+1 {{cannot jump from this indirect goto statement to one of its possible targets}}
 goto *p;
 p = &&FOO;
@@ -45,9 +45,7 @@
   return;
 }
 
-
-//Asm goto:
-int test16(int n)
+int test3(int n)
 {
   // expected-error@+2 {{cannot jump from this asm goto statement to one of its possible targets}}
   // expected-error@+1 {{cannot jump from this asm goto statement to one of its possible targets}}
Index: clang/test/Parser/asm-goto.cpp
===
--- clang/test/Parser/asm-goto.cpp
+++ clang/test/Parser/asm-goto.cpp
@@ -1,14 +1,54 @@
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -fsyntax-only -verify -std=c++11 %s
 // RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fsyntax-only -verify -std=c++11 %s
 
-int zoo ()
-{
+int a, b, c, d, e, f, g, h, i, j, k, l;
+
+void test1(void) {
+  __asm__ volatile goto (""
+:: [a] "r" (a), [b] "r" (b), [c] "r" (c), [d] "r" (d),
+   [e] "r" (e), [f] "r" (f), [g] "r" (g), [h] "r" (h),
+   [i] "r" (i), [j] "r" (j), [k] "r" (k), [l] "r" (l)
+::lab1,lab2);
+lab1: return;
+lab2: return;
+}
+
+void test2(void) {
+  __asm__ volatile goto (""
+:: [a] "r,m" (a), [b] "r,m" (b), [c] "r,m" (c), [d] "r,m" (d),
+   [e] "r,m" (e), [f] "r,m" (f), [g] "r,m" (g), [h] "r,m" (h),
+   [i] "r,m" (i), [j] "r,m" (j), [k] "r,m" (k), [l] "r,m" (l)
+:: lab);
+  lab: return;
+}
+
+int test3(int x) {
+  __asm__ volatile goto ("decl %0; jnz %l[a]"
+ : "=r" (x) : "m" (x) : "memory" : a);
+a:
+  return -x;
+}
+
+int test4(int x) {
+  int y;
+  if (x > 42)
+__asm__ volatile goto ("decl %0; jnz %l[a]"
+   : "=r" (x), "=r" (y) : "m" (x) : "memory" : a);
+  else
+__asm__ volatile goto ("decl %0; jnz %l[b]"
+   : "=r" (x), "=r" (y) : "m" (x) : "memory" : b);
+  x = y + 42;
+a:
+  return -x;
+b:
+  return +x;
+}
+
+int test5(void) {
   int x,cond,*e;
   // expected-error@+1 {{expected ')'}}
   asm ("mov %[e], %[e]" : : [e] "rm" (*e)::a)
-  // expected-error@+1  {{'asm goto' cannot have output constraints}}
-  asm goto ("decl %0; jnz %l[a]" :"=r"(x): "m"(x) : "memory" : a);
-  // expected-error@+1 {{expected identifie}}
+  // expected-error@+1 {{expected identifier}}
   asm goto ("decl %0;" :: "m"(x) : "memory" : );
   // expected-error@+1  {{expected ':'}}
   asm goto ("decl %0;" :: "m"(x) : "memory" );
@@ -26,28 +66,24 @@
   return 0;
 }
 
-
-int a, b, c, d, e, f, g, h, i, j, k, l;
-
-void
-fgoto1 (void)
-{
-  __asm__ volatile goto (""
-:: [a] "r" (a), [b] "r" (b), [c] "r" (c), [d] "r" (d),
-   [e] "r" (e), [f] "r" (f), [g] "r" (g), [h] "r" (h),
-   [i] "r" (i), [j] "r" (j), [k] "r" (k), [l] "r" (l

[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void marked an inline comment as done.
void added a comment.

In D73319#1843129 , @nickdesaulniers 
wrote:

> In D73319#1842951 , @void wrote:
>
> > In D73319#1842900 , 
> > @nickdesaulniers wrote:
> >
> > > Great idea; thanks for the patch! Needs documentation. :)
> >
> >
> > I can't find a place for documentation of extensions, at least not the 
> > names of extensions like `gnu_asm`.
>
>
> How about 
> https://clang.llvm.org/docs/LanguageExtensions.html#checks-for-standard-language-features
>  ? Then we can add both `gnu_asm` and `gnu_asm_goto_with_outputs`.


That looks like it's features specific to various versions of C/C++. There were 
other examples like https://clang.llvm.org/docs/LanguageExtensions.html#blocks.




Comment at: clang/test/Parser/asm-goto.c:9
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
 

nickdesaulniers wrote:
> ah, sorry, maybe a test that makes use of `asm goto` + output constraints? 
> Maybe if you base your patch on top of the others in the series that 
> implement the feature?
There's one below in `zoo`. The order of these patches is a bit wonky because 
the front-end patch, which has more tests for AGWO, should go in before this 
one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319



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


[PATCH] D72282: [clang-tidy] Add `bugprone-unintended-adl`

2020-01-27 Thread Logan Smith via Phabricator via cfe-commits
logan-5 updated this revision to Diff 240691.
logan-5 added a comment.

Rebased with trunk. Updated whitelist to include more standard designated 
customization points .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72282

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UnintendedADLCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UnintendedADLCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone-unintended-adl.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-unintended-adl-generic-lambdas.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-unintended-adl-operators.cpp
  clang-tools-extra/test/clang-tidy/checkers/bugprone-unintended-adl.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-unintended-adl.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-unintended-adl.cpp
@@ -0,0 +1,213 @@
+// RUN: %check_clang_tidy %s bugprone-unintended-adl %t
+
+namespace aspace {
+struct A {};
+void func(const A &);
+} // namespace aspace
+
+namespace bspace {
+void func(int);
+void test() {
+  aspace::A a;
+  func(5);
+  func(a);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expression calls 'aspace::func' through ADL [bugprone-unintended-adl]
+}
+} // namespace bspace
+
+namespace ops {
+
+struct Stream {
+} stream;
+Stream &operator<<(Stream &s, int) {
+  return s;
+}
+Stream &operator<<(Stream &s, aspace::A) {
+  return s;
+}
+template 
+IStream &operator>>(IStream &s, int) {
+  return s;
+}
+template 
+IStream &operator>>(IStream &s, aspace::A) {
+  return s;
+}
+void smooth_operator(Stream);
+
+} // namespace ops
+
+void ops_test() {
+  ops::stream << 5;
+  // no warning
+  operator<<(ops::stream, 5);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expression calls 'ops::operator<<' through ADL [bugprone-unintended-adl]
+  ops::stream << aspace::A();
+  // no warning
+  operator<<(ops::stream, aspace::A());
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expression calls 'ops::operator<<' through ADL [bugprone-unintended-adl]
+
+  ops::stream >> aspace::A();
+  // no warning
+  operator>>(ops::stream, aspace::A());
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expression calls 'ops::operator>>' through ADL [bugprone-unintended-adl]
+
+  smooth_operator(ops::stream);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expression calls 'ops::smooth_operator' through ADL [bugprone-unintended-adl]
+}
+
+namespace std {
+// return types don't matter, returning 'void' everywhere for simplicity
+
+template 
+void swap(T &a, T &b);
+template 
+void make_error_code(T);
+template 
+void make_error_condition(T);
+template 
+void data(T);
+template 
+void begin(T);
+template 
+void end(T);
+template 
+void rbegin(T);
+template 
+void rend(T);
+template 
+void crbegin(T);
+template 
+void crend(T);
+template 
+void size(T);
+template 
+void ssize(T);
+template 
+void empty(T);
+
+template 
+void move(T &&);
+template 
+void forward(T &&);
+
+struct byte {};
+
+} // namespace std
+namespace ns {
+
+struct Swappable {};
+
+// whitelisted
+void swap(Swappable &a, Swappable &b);
+void make_error_code(Swappable);
+void make_error_condition(Swappable);
+void data(Swappable);
+void begin(Swappable);
+void end(Swappable);
+void rbegin(Swappable);
+void rend(Swappable);
+void crbegin(Swappable);
+void crend(Swappable);
+void size(Swappable);
+void ssize(Swappable);
+void empty(Swappable);
+
+// non-whitelisted
+void move(Swappable);
+void ref(Swappable);
+
+struct Swappable2 {};
+
+} // namespace ns
+struct {
+  template 
+  void operator()(T &&);
+} ref;
+
+void test2() {
+  // TODO add granularity for detecting functions that may always be called unqualified,
+  // versus those that can only be called through the 'using' 'two-step'
+  using namespace std;
+  ns::Swappable a, b;
+  swap(a, b);
+  make_error_code(a);
+  make_error_condition(a);
+  data(a);
+  begin(a);
+  end(a);
+  rbegin(a);
+  rend(a);
+  crbegin(a);
+  crend(a);
+  size(a);
+  ssize(a);
+  empty(a);
+
+  move(a);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expression calls 'ns::move' through ADL [bugprone-unintended-adl]
+}
+
+template 
+void foo(T t) {
+  using namespace std;
+  swap(t, t);
+  make_error_code(t);
+  make_error_condition(t);
+  data(t);
+  begin(t);
+  end(t);
+  rbegin(t);
+  rend(t);
+  crbegin(t);
+  crend(t);
+  size(t);
+  ssize(t);
+  empty(t);
+
+  move(t);
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: expression calls 'ns::move' through ADL [bugprone-unintended-adl]
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: with argument type 'struct ns::Swappable'
+  // CHECK-MESSAGES: [[@LINE-3]]:3: warning: unqualified call to 'move' may be res

[PATCH] D72675: [Clang][Driver] Fix -ffast-math/-ffp-contract interaction

2020-01-27 Thread Warren Ristow via Phabricator via cfe-commits
wristow marked 4 inline comments as done.
wristow added inline comments.



Comment at: clang/test/Driver/fast-math.c:196
+// RUN: %clang -### -ffast-math -ffp-contract=fast -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-UNSAFE-MATH %s
+//

wristow wrote:
> andrew.w.kaylor wrote:
> > What about "-ffp-contract=off -ffast-math"? The way the code is written 
> > that will override the -ffp-contract option. That's probably what we want, 
> > though it might be nice to have a warning.
> Yes, currently `-fffast-math` will override that earlier `-ffp-contract=off` 
> settings.  It's unclear to me whether we're ultimately intending for that to 
> be the behavior (because GCC doesn't do that, as @uweigand noted).  I guess 
> this is another reason to hold off for a bit, until we figure out the wider 
> spec.
Added more tests that illustrate this behavior of "-ffp-contract=off/on 
-ffast-math" overriding and enabling FMA.  (I haven't added a warning.  Holding 
off until we decide on other questions discussed in this review.)


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

https://reviews.llvm.org/D72675



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


[PATCH] D72675: [Clang][Driver] Fix -ffast-math/-ffp-contract interaction

2020-01-27 Thread Warren Ristow via Phabricator via cfe-commits
wristow updated this revision to Diff 240689.
wristow added a comment.

Used the clearer '!off && !on' (rather than '!(off || on)') in the checks.

Added more tests that note the current situation that `-ffast-math` enables 
FMA. overriding an earlier switch that had disabled it (included a "TODO" 
comment in these tests, since it isn't clear if that behavior is what we will 
ultimately stick with).


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

https://reviews.llvm.org/D72675

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/fast-math.c


Index: clang/test/Driver/fast-math.c
===
--- clang/test/Driver/fast-math.c
+++ clang/test/Driver/fast-math.c
@@ -180,6 +180,40 @@
 // CHECK-FAST-MATH: "-ffast-math"
 // CHECK-FAST-MATH: "-ffinite-math-only"
 //
+// -ffp-contract=off and -ffp-contract=on must disable the fast-math umbrella,
+// and the unsafe-fp-math umbrella (-ffp-contract=fast leaves them enabled).
+// Note that there is some uncertainty as to whether we want the fast-math
+// umbrella to enable FMA, but it is clear that irrespective of whether FMA
+// is enabled by fast-math, it should be disabled with a later switch.
+// RUN: %clang -### -ffast-math -ffp-contract=off -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-FAST-MATH %s
+// RUN: %clang -### -ffast-math -ffp-contract=off -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s
+// RUN: %clang -### -ffast-math -ffp-contract=on -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-FAST-MATH %s
+// RUN: %clang -### -ffast-math -ffp-contract=on -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-NO-UNSAFE-MATH %s
+// RUN: %clang -### -ffast-math -ffp-contract=fast -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FAST-MATH %s
+// RUN: %clang -### -ffast-math -ffp-contract=fast -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-UNSAFE-MATH %s
+//
+// The current behavior is that the umbrella aspect of -ffast-math enables FMA.
+// As noted above, there is some uncertainty on whether this is the desired
+// behavior.  For now, we verify that the umbrella aspect does kick in to
+// enable -ffp-contract=fast mode, overriding an earlier setting that had
+// disabled FMA.
+// TODO: Decide on whether -ffast-math should enable FMA.
+// RUN: %clang -### -ffp-contract=off -ffast-math -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FP-CONTRACT-FAST %s
+// RUN: %clang -### -ffp-contract=off -ffast-math -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FP-CONTRACT-FAST %s
+// RUN: %clang -### -ffp-contract=on -ffast-math -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FP-CONTRACT-FAST %s
+// RUN: %clang -### -ffp-contract=on -ffast-math -c %s 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-FP-CONTRACT-FAST %s
+// CHECK-FP-CONTRACT-FAST: "-ffp-contract=fast"
+//
 // RUN: %clang -### -ffast-math -fno-fast-math -c %s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NO-FAST-MATH %s
 // RUN: %clang -### -ffast-math -fno-finite-math-only -c %s 2>&1 \
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -2785,8 +2785,11 @@
   if (MathErrno)
 CmdArgs.push_back("-fmath-errno");
 
+  // If -ffp-contract=off/on has been specified on the command line, then we
+  // must suppress the emission of -ffast-math and -menable-unsafe-fp-math to
+  // cc1.
   if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
-  !TrappingMath)
+  !TrappingMath && !FPContract.equals("off") && !FPContract.equals("on"))
 CmdArgs.push_back("-menable-unsafe-fp-math");
 
   if (!SignedZeros)
@@ -2831,12 +2834,17 @@
 
   ParseMRecip(D, Args, CmdArgs);
 
-  // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for 
the
-  // individual features enabled by -ffast-math instead of the option itself as
-  // that's consistent with gcc's behaviour.
+  // -ffast-math acts as an "umbrella", enabling a variety of individual
+  // floating-point transformations.  We check if the appropriate set of those
+  // transformations are enabled, and if they are, we pass that umbrella switch
+  // to cc1.  This also interacts with another "umbrella" switch, -ffp-model.
+  // We handle -ffp-contract somewhat specially here, to produce a warning in
+  // situations where -ffp-model=fast is overridden by the setting of
+  // -ffp-contract.
   if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
   ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
-CmdArgs.push_back("-ffast-math");
+if (!FPContract.equals("off") && !FPContract.equals("on"))
+  CmdArgs.push_back("-ffast-math");
 if (FPModel.equals("fast")) {
   if (FPContract.equals("fast"))
 // All set, do nothing.


Index: clang/test/Dr

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

2020-01-27 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

Does this depend on D69868 ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69876



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


[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:1273
+  int y;
+  asm goto("# %0 %1 %2" : "=r"(y) : "r"(x) : : err);
+  return y;

Is the canonical spelling `%l2`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319



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


[PATCH] D73500: [driver] Add a -builtininc flag that lets Darwin driver include Clang builtin headers even with -nostdinc

2020-01-27 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith requested changes to this revision.
dexonsmith added inline comments.
This revision now requires changes to proceed.



Comment at: clang/include/clang/Driver/Options.td:503-504
 def bind__at__load : Flag<["-"], "bind_at_load">;
+def builtininc : Flag<["-"], "builtininc">,
+  HelpText<"Enable builtin #include directories even when -nostdinc is used">;
 def bundle__loader : Separate<["-"], "bundle_loader">;

I think `-ibuiltininc` might be better, since we already have lots of options 
that start with `-i` related to include paths.  Please also clarify in the 
HelpText that this overrules `-nostdinc` even if `-nostdinc` comes later.



Comment at: clang/lib/Driver/ToolChains/Darwin.cpp:1883-1888
   // Add the Clang builtin headers (/include)
-  if (!NoStdInc && !NoBuiltinInc) {
+  if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
 SmallString<128> P(D.ResourceDir);
 llvm::sys::path::append(P, "include");
 addSystemInclude(DriverArgs, CC1Args, P);
   }

It's probably better to let `-ibuiltininc` and `-nobuiltininc` cancel each 
other out, via a "last one wins" rule.  If you agree, consider documenting the 
behaviour also in the HelpText.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73500



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


[PATCH] D69585: PerformPendingInstatiations() already in the PCH

2020-01-27 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: clang/lib/Sema/Sema.cpp:985-986
+
+// FIXME: Instantiating implicit templates already in the PCH breaks some
+// OpenMP-specific code paths, see https://reviews.llvm.org/D69585 .
+if(LangOpts.PCHInstantiateTemplates && !LangOpts.OpenMP) {

llunak wrote:
> rnk wrote:
> > This really deserves to be debugged before we land it.
> I debugged this more than 2 months ago, that's why the OpenMP code owner is 
> added as a reviewer.  The initial diff (that I have no idea how to display 
> here) included a suggested fix and the description said this was a WIP and 
> included my findings about it. As far as I can tell the only effect that had 
> was that this patch was sitting here all the time without a single reaction, 
> so if nobody OpenMP related cares then I do not either.
> 
> 
So the original comment said "breaks some Open-MP specific code paths" - what 
kind of breakage occurs? (& I take it with the patch in its current form that 
breakage is present in the patch (as opposed to the previous version that 
conditionalized this feature so it didn't happen when OpenMP was enabled)?)



Comment at: clang/test/PCH/specialization-after-instantiation.cpp:2
+// Test this without pch.
+// RUN: %clang_cc1 -fsyntax-only -verify -DBODY %s
+

Does this need testing without PCH here? Presumably that's already been tested 
elsewhere for some time now?


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

https://reviews.llvm.org/D69585



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


[PATCH] D73464: [clang] Add TagDecl AST matcher

2020-01-27 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

A drive-by comment.




Comment at: clang/lib/ASTMatchers/Dynamic/Registry.cpp:212
+  REGISTER_MATCHER(tagDecl);
+  REGISTER_MATCHER(tagType);
   REGISTER_MATCHER(enumConstantDecl);

There's already `tagType` registration on the line 497. And yes, should the 
list be sorted, that would be obvious.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73464



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


[PATCH] D72811: [WIP][OPENMP5.0] allow lvalue for motion clause

2020-01-27 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

In D72811#1843066 , @cchen wrote:

> In D72811#1839561 , @ABataev wrote:
>
> > In D72811#1839538 , @cchen wrote:
> >
> > > In D72811#1837392 , @jdoerfert 
> > > wrote:
> > >
> > > > Thanks for working on this! While you are at it, `*this` is probably 
> > > > one of the most important ones to test and support.
> > >
> > >
> > > Can anyone tell me how to get `ValueDecl` from `CXXThisExpr`? I cannot 
> > > find any method return decl in 
> > > https://clang.llvm.org/doxygen/classclang_1_1CXXThisExpr.html#details.
> > >  Thanks!
> >
> >
> > CXXThisExpr is an expression without associated declaration.
>
>
> Then which kind of thing should I sent to `CurComponents` if we do not have 
> associated declaration for CXXThisExpr? We can't just send nullptr, right?


Check how compiler handles mapping of `this[0:1]`, which is the same as `*this`.




Comment at: clang/lib/Sema/SemaOpenMP.cpp:16007
+if (!RE->IgnoreParenImpCasts()->isLValue() &&
+(MLValue != clang::Expr::isModifiableLvalueResult::MLV_LValueCast)) {
   SemaRef.Diag(ELoc,

cchen wrote:
> ABataev wrote:
> > Why `MLV_LValueCast` must be allowed here?
> I'm doing this since `isLValue` return false for either C style casting CXX 
> style casting and `MLV_LValueCast` can categorize these two  as 
> `MLV_LValueCast`.
Are they the lvalues according to the standard? If not, no need for this 
analysis.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72811



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


[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

In D73319#1842951 , @void wrote:

> In D73319#1842900 , @nickdesaulniers 
> wrote:
>
> > Great idea; thanks for the patch! Needs documentation. :)
>
>
> I can't find a place for documentation of extensions, at least not the names 
> of extensions like `gnu_asm`.


How about 
https://clang.llvm.org/docs/LanguageExtensions.html#checks-for-standard-language-features
 ? Then we can add both `gnu_asm` and `gnu_asm_goto_with_outputs`.




Comment at: clang/test/Parser/asm-goto.c:9
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
 

ah, sorry, maybe a test that makes use of `asm goto` + output constraints? 
Maybe if you base your patch on top of the others in the series that implement 
the feature?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319



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


[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 240681.
void added a comment.

Add description of "gnu_asm_goto_with_outputs" to the language extensions doc.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/Basic/Features.def
  clang/test/Parser/asm-goto.c


Index: clang/test/Parser/asm-goto.c
===
--- clang/test/Parser/asm-goto.c
+++ clang/test/Parser/asm-goto.c
@@ -4,6 +4,9 @@
 #if !__has_extension(gnu_asm)
 #error Extension 'gnu_asm' should be available by default
 #endif
+#if !__has_extension(gnu_asm_goto_with_outputs)
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
 
 
 int a, b, c, d, e, f, g, h, i, j, k, l;
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -252,6 +252,7 @@
 EXTENSION(pragma_clang_attribute_namespaces, true)
 EXTENSION(pragma_clang_attribute_external_declaration, true)
 EXTENSION(gnu_asm, LangOpts.GNUAsm)
+EXTENSION(gnu_asm_goto_with_outputs, LangOpts.GNUAsm)
 
 #undef EXTENSION
 #undef FEATURE
Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -1255,6 +1255,34 @@
 
 Query for this feature with ``__has_extension(blocks)``.
 
+ASM Goto with Output Constraints
+
+
+In addition to the functionality provided by `GCC's extended
+assembly``_, clang
+supports output constraints with the `goto` form.
+
+The goto form of GCC's extended assembly allows the programmer to branch to a C
+label from within an inline assembly block. Clang extends this behavior by
+allowing the programmer to use output constriants:
+
+.. code-block:: c++
+
+  int foo(int x) {
+  int y;
+  asm goto("# %0 %1 %2" : "=r"(y) : "r"(x) : : err);
+  return y;
+err:
+  return -1;
+  }
+
+It's important to note that outputs are valid only on the "fallthrough" branch.
+Using outputs on an indirect branch may result in undefined behavior. For
+example, in the function above, use of the value assigned to `y` in the `err`
+block is undefined behavior.
+
+Query for this feature with ``__has_extension(gnu_asm_goto_with_outputs)``.
+
 Objective-C Features
 
 


Index: clang/test/Parser/asm-goto.c
===
--- clang/test/Parser/asm-goto.c
+++ clang/test/Parser/asm-goto.c
@@ -4,6 +4,9 @@
 #if !__has_extension(gnu_asm)
 #error Extension 'gnu_asm' should be available by default
 #endif
+#if !__has_extension(gnu_asm_goto_with_outputs)
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
 
 
 int a, b, c, d, e, f, g, h, i, j, k, l;
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -252,6 +252,7 @@
 EXTENSION(pragma_clang_attribute_namespaces, true)
 EXTENSION(pragma_clang_attribute_external_declaration, true)
 EXTENSION(gnu_asm, LangOpts.GNUAsm)
+EXTENSION(gnu_asm_goto_with_outputs, LangOpts.GNUAsm)
 
 #undef EXTENSION
 #undef FEATURE
Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -1255,6 +1255,34 @@
 
 Query for this feature with ``__has_extension(blocks)``.
 
+ASM Goto with Output Constraints
+
+
+In addition to the functionality provided by `GCC's extended
+assembly``_, clang
+supports output constraints with the `goto` form.
+
+The goto form of GCC's extended assembly allows the programmer to branch to a C
+label from within an inline assembly block. Clang extends this behavior by
+allowing the programmer to use output constriants:
+
+.. code-block:: c++
+
+  int foo(int x) {
+  int y;
+  asm goto("# %0 %1 %2" : "=r"(y) : "r"(x) : : err);
+  return y;
+err:
+  return -1;
+  }
+
+It's important to note that outputs are valid only on the "fallthrough" branch.
+Using outputs on an indirect branch may result in undefined behavior. For
+example, in the function above, use of the value assigned to `y` in the `err`
+block is undefined behavior.
+
+Query for this feature with ``__has_extension(gnu_asm_goto_with_outputs)``.
+
 Objective-C Features
 
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo

[PATCH] D71524: [analyzer] Support tainted objects in GenericTaintChecker

2020-01-27 Thread Borsik Gábor via Phabricator via cfe-commits
boga95 added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71524



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


[PATCH] D73413: [clang-tidy] Add check to detect external definitions with no header declaration

2020-01-27 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

How is this different from `-Wmissing-prototypes`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73413



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


[PATCH] D73408: [Clang][Bundler] Add 'exclude' flag to target objects sections

2020-01-27 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev updated this revision to Diff 240676.
sdmitriev added a comment.

Addressed review comments.


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

https://reviews.llvm.org/D73408

Files:
  clang/test/Driver/clang-offload-bundler.c
  clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp

Index: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
===
--- clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
+++ clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
@@ -30,6 +30,7 @@
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
@@ -463,6 +464,15 @@
 if (NumberOfProcessedInputs != NumberOfInputs)
   return Error::success();
 
+// We will use llvm-objcopy to add target objects sections to the output
+// fat object. These sections should have 'exclude' flag set which tells
+// link editor to remove them from linker inputs when linking executable or
+// shared library. llvm-objcopy currently does not support adding new
+// section and changing flags for the added section in one invocation, and
+// because of that we have to run it two times. First run adds sections and
+// the second changes flags.
+// TODO: change it to one run once llvm-objcopy starts supporting that.
+
 // Find llvm-objcopy in order to create the bundle binary.
 ErrorOr Objcopy = sys::findProgramByName(
 "llvm-objcopy", sys::path::parent_path(BundlerExecutable));
@@ -476,7 +486,15 @@
 // to pass down to llvm-objcopy.
 OS.close();
 
-// Compose command line for the objcopy tool.
+// Create an intermediate temporary file to save object after the first
+// llvm-objcopy run.
+SmallString<128u> IntermediateObj;
+if (std::error_code EC = sys::fs::createTemporaryFile(
+"clang-offload-bundler", "tmp", IntermediateObj))
+  return createFileError(IntermediateObj, EC);
+FileRemover IntermediateObjRemover(IntermediateObj);
+
+// Compose llvm-objcopy command line for add target objects' sections.
 BumpPtrAllocator Alloc;
 StringSaver SS{Alloc};
 SmallVector ObjcopyArgs{"llvm-objcopy"};
@@ -485,25 +503,44 @@
 OFFLOAD_BUNDLER_MAGIC_STR + TargetNames[I] +
 "=" + InputFileNames[I]));
 ObjcopyArgs.push_back(InputFileNames[HostInputIndex]);
+ObjcopyArgs.push_back(IntermediateObj);
+
+if (Error Err = executeObjcopy(*Objcopy, ObjcopyArgs))
+  return Err;
+
+// And run llvm-objcopy for the second time to update section flags.
+ObjcopyArgs.resize(1);
+for (unsigned I = 0; I < NumberOfInputs; ++I)
+  ObjcopyArgs.push_back(SS.save(Twine("--set-section-flags=") +
+OFFLOAD_BUNDLER_MAGIC_STR + TargetNames[I] +
+"=readonly,exclude"));
+ObjcopyArgs.push_back(IntermediateObj);
 ObjcopyArgs.push_back(OutputFileNames.front());
 
-// If the user asked for the commands to be printed out, we do that instead
-// of executing it.
+if (Error Err = executeObjcopy(*Objcopy, ObjcopyArgs))
+  return Err;
+
+return Error::success();
+  }
+
+  Error WriteBundle(raw_fd_ostream &OS, MemoryBuffer &Input) final {
+return Error::success();
+  }
+
+private:
+  static Error executeObjcopy(StringRef Objcopy, ArrayRef Args) {
+// If the user asked for the commands to be printed out, we do that
+// instead of executing it.
 if (PrintExternalCommands) {
-  errs() << "\"" << *Objcopy << "\"";
-  for (StringRef Arg : drop_begin(ObjcopyArgs, 1))
+  errs() << "\"" << Objcopy << "\"";
+  for (StringRef Arg : drop_begin(Args, 1))
 errs() << " \"" << Arg << "\"";
   errs() << "\n";
 } else {
-  if (sys::ExecuteAndWait(*Objcopy, ObjcopyArgs))
+  if (sys::ExecuteAndWait(Objcopy, Args))
 return createStringError(inconvertibleErrorCode(),
  "'llvm-objcopy' tool failed");
 }
-
-return Error::success();
-  }
-
-  Error WriteBundle(raw_fd_ostream &OS, MemoryBuffer &Input) final {
 return Error::success();
   }
 };
Index: clang/test/Driver/clang-offload-bundler.c
===
--- clang/test/Driver/clang-offload-bundler.c
+++ clang/test/Driver/clang-offload-bundler.c
@@ -253,7 +253,8 @@
 
 // RUN: clang-offload-bundler -type=o -targets=host-%itanium_abi_triple,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu -inputs=%t.o,%t.tgt1,%t.tgt2 -outputs=%t.bundle3.o -### 2>&1 \
 // RUN: | FileCheck %s -DHOST=%itanium_abi_triple -DINOBJ1=%t.o -DINOBJ2=%t.tgt1 -DINOBJ3=%t.tgt2 -DOUTOBJ=%t.bundle3.o --check-prefix CK-OBJ-CMD
-//

[PATCH] D73376: [analyzer] Add FuchsiaLockChecker and C11LockChecker

2020-01-27 Thread Gábor Horváth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf4c26d993bdc: [analyzer] Add FuchsiaLockChecker and 
C11LockChecker (authored by xazax.hun).

Changed prior to commit:
  https://reviews.llvm.org/D73376?vs=240650&id=240678#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73376

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
  clang/test/Analysis/c11lock.c
  clang/test/Analysis/fuchsia_lock.c

Index: clang/test/Analysis/fuchsia_lock.c
===
--- /dev/null
+++ clang/test/Analysis/fuchsia_lock.c
@@ -0,0 +1,104 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=fuchsia.Lock -verify %s
+
+typedef int spin_lock_t;
+typedef int zx_status_t;
+typedef int zx_time_t;
+
+void spin_lock(spin_lock_t *lock);
+int spin_trylock(spin_lock_t *lock);
+void spin_unlock(spin_lock_t *lock);
+void spin_lock_init(spin_lock_t *lock);
+
+void spin_lock_save(spin_lock_t *lock, void *statep,
+int flags);
+void spin_unlock_restore(spin_lock_t *lock, void *old_state,
+ int flags);
+
+spin_lock_t mtx1;
+spin_lock_t mtx2;
+
+void bad1(void)
+{
+	spin_lock(&mtx1);	// no-warning
+	spin_lock(&mtx1);	// expected-warning{{This lock has already been acquired}}
+}
+
+void bad2(void) {
+  spin_lock(&mtx1);
+  spin_unlock(&mtx1);
+  spin_unlock(&mtx1); // expected-warning {{This lock has already been unlocked}}
+}
+
+void bad3() {
+  spin_lock_init(&mtx1);
+  if (spin_trylock(&mtx1) != 0)
+spin_unlock(&mtx1); // expected-warning {{This lock has already been unlocked}}
+}
+
+void bad4(void) {
+  spin_lock(&mtx1);
+  spin_lock(&mtx2);
+  spin_unlock(&mtx1); // expected-warning {{This was not the most recently acquired lock. Possible lock order reversal}}
+  spin_unlock(&mtx2);
+}
+
+void good() {
+  spin_lock_t mtx;
+  spin_lock_init(&mtx);
+  spin_lock_save(&mtx, 0, 0);
+  spin_unlock_restore(&mtx, 0, 0);
+}
+
+void good2() {
+  spin_lock_t mtx;
+  spin_lock_init(&mtx);
+  if (spin_trylock(&mtx) == 0)
+spin_unlock(&mtx);
+}
+
+typedef int sync_mutex_t;
+void sync_mutex_lock(sync_mutex_t* mutex);
+void sync_mutex_lock_with_waiter(sync_mutex_t* mutex);
+zx_status_t sync_mutex_timedlock(sync_mutex_t* mutex, zx_time_t deadline);
+zx_status_t sync_mutex_trylock(sync_mutex_t* mutex);
+void sync_mutex_unlock(sync_mutex_t* mutex);
+
+sync_mutex_t smtx1;
+sync_mutex_t smtx2;
+
+void bad11(void)
+{
+	sync_mutex_lock(&smtx1);	// no-warning
+	sync_mutex_lock(&smtx1);	// expected-warning{{This lock has already been acquired}}
+}
+
+void bad12(void) {
+  sync_mutex_lock_with_waiter(&smtx1);
+  sync_mutex_unlock(&smtx1);
+  sync_mutex_unlock(&smtx1); // expected-warning {{This lock has already been unlocked}}
+}
+
+void bad13() {
+  sync_mutex_unlock(&smtx1);
+  if (sync_mutex_trylock(&smtx1) != 0)
+sync_mutex_unlock(&smtx1); // expected-warning {{This lock has already been unlocked}}
+}
+
+void bad14(void) {
+  sync_mutex_lock(&smtx1);
+  sync_mutex_lock(&smtx2);
+  sync_mutex_unlock(&smtx1); // expected-warning {{This was not the most recently acquired lock. Possible lock order reversal}}
+  sync_mutex_unlock(&smtx2);
+}
+
+void good11() {
+  sync_mutex_t mtx;
+  if (sync_mutex_trylock(&mtx) == 0)
+sync_mutex_unlock(&mtx);
+}
+
+void good12() {
+  sync_mutex_t mtx;
+  if (sync_mutex_timedlock(&mtx, 0) == 0)
+sync_mutex_unlock(&mtx);
+}
Index: clang/test/Analysis/c11lock.c
===
--- /dev/null
+++ clang/test/Analysis/c11lock.c
@@ -0,0 +1,90 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.core.C11Lock -verify %s
+
+typedef int mtx_t;
+struct timespec;
+
+enum {
+  // FIXME: The value if this enum is implementation defined. While all the
+  // implementations I am aware of using 0, the right solution would be to
+  // look this value up in the AST (and disable the check if it is not found).
+  thrd_success = 0,
+  thrd_error = 2
+};
+
+int mtx_init(mtx_t *mutex, int type);
+int mtx_lock(mtx_t *mutex);
+int mtx_timedlock(mtx_t *mutex,
+  const struct timespec *time_point);
+int mtx_trylock(mtx_t *mutex);
+int mtx_unlock(mtx_t *mutex);
+int mtx_destroy(mtx_t *mutex);
+
+mtx_t mtx1;
+mtx_t mtx2;
+
+void bad1(void)
+{
+  mtx_lock(&mtx1);	// no-warning
+  mtx_lock(&mtx1);	// expected-warning{{This lock has already been acquired}}
+}
+
+void bad2(void) {
+  mtx_t mtx;
+  mtx_init(&mtx, 0);
+  mtx_lock(&mtx);
+} // TODO: Warn for missing unlock?
+
+void bad3(void) {
+  mtx_t mtx;
+  mtx_init(&mtx, 0);
+} // TODO: Warn for missing destroy?
+
+void bad4(void) {
+  mtx_t mtx;
+  mtx_init(&mtx, 0);
+  mtx_lock(&mtx);
+  mtx_unlock(&mtx);
+} // TODO: warn for missing destroy?
+
+void bad5(void) {
+  mtx_lock(&mtx1);
+  mtx_unlock(&mtx1);
+  mtx_unlock(&mtx1); // expect

[clang] f4c26d9 - [analyzer] Add FuchsiaLockChecker and C11LockChecker

2020-01-27 Thread Gabor Horvath via cfe-commits

Author: Gabor Horvath
Date: 2020-01-27T13:55:56-08:00
New Revision: f4c26d993bdcb8e5250d774c0d2a6d91fee5ca00

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

LOG: [analyzer] Add FuchsiaLockChecker and C11LockChecker

These are mostly trivial additions as both of them are reusing existing
PThreadLockChecker logic. I only needed to add the list of functions to
check and do some plumbing to make sure that we display the right
checker name in the diagnostic.

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

Added: 
clang/test/Analysis/c11lock.c
clang/test/Analysis/fuchsia_lock.c

Modified: 
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index fc1529f2ea1c..83d78e4f8994 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -227,6 +227,16 @@ def StackAddrAsyncEscapeChecker : 
Checker<"StackAddressAsyncEscape">,
   Dependencies<[StackAddrEscapeBase]>,
   Documentation;
 
+def PthreadLockBase : Checker<"PthreadLockBase">,
+  HelpText<"Helper registering multiple checks.">,
+  Documentation,
+  Hidden;
+
+def C11LockChecker : Checker<"C11Lock">,
+  HelpText<"Simple lock -> unlock checker">,
+  Dependencies<[PthreadLockBase]>,
+  Documentation;
+
 } // end "alpha.core"
 
 
//===--===//
@@ -431,6 +441,7 @@ def ChrootChecker : Checker<"Chroot">,
 
 def PthreadLockChecker : Checker<"PthreadLock">,
   HelpText<"Simple lock -> unlock checker">,
+  Dependencies<[PthreadLockBase]>,
   Documentation;
 
 def StreamChecker : Checker<"Stream">,
@@ -1442,5 +1453,10 @@ def FuchsiaHandleChecker : Checker<"HandleChecker">,
   HelpText<"A Checker that detect leaks related to Fuchsia handles">,
   Documentation;
 
+def FuchsiaLockChecker : Checker<"Lock">,
+  HelpText<"Check for the correct usage of locking APIs.">,
+  Dependencies<[PthreadLockBase]>,
+  Documentation;
+
 } // end fuchsia
 

diff  --git a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
index ed0fc0f98c2c..d3470dad0a43 100644
--- a/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
@@ -6,8 +6,12 @@
 //
 
//===--===//
 //
-// This defines PthreadLockChecker, a simple lock -> unlock checker.
-// Also handles XNU locks, which behave similarly enough to share code.
+// This file defines:
+//  * PthreadLockChecker, a simple lock -> unlock checker.
+//Which also checks for XNU locks, which behave similarly enough to share
+//code.
+//  * FuchsiaLocksChecker, which is also rather similar.
+//  * C11LockChecker which also closely follows Pthread semantics.
 //
 
//===--===//
 
@@ -15,8 +19,8 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 
 using namespace clang;
 using namespace ento;
@@ -46,9 +50,7 @@ struct LockState {
 return LockState(UnlockedAndPossiblyDestroyed);
   }
 
-  bool operator==(const LockState &X) const {
-return K == X.K;
-  }
+  bool operator==(const LockState &X) const { return K == X.K; }
 
   bool isLocked() const { return K == Locked; }
   bool isUnlocked() const { return K == Unlocked; }
@@ -60,98 +62,149 @@ struct LockState {
 return K == UnlockedAndPossiblyDestroyed;
   }
 
-  void Profile(llvm::FoldingSetNodeID &ID) const {
-ID.AddInteger(K);
-  }
+  void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); }
 };
 
-class PthreadLockChecker
-: public Checker {
-  BugType BT_doublelock{this, "Double locking", "Lock checker"},
-  BT_doubleunlock{this, "Double unlocking", "Lock checker"},
-  BT_destroylock{this, "Use destroyed lock", "Lock checker"},
-  BT_initlock{this, "Init invalid lock", "Lock checker"},
-  BT_lor{this, "Lock order reversal", "Lock checker"};
-
-  enum LockingSemantics {
-NotApplicable = 0,
-PthreadSemantics,
-XNUSemantics
+class PthreadLockChecker : public Checker {
+public:
+  enum LockingSemantics { NotApplicable = 0, PthreadSemantics, XNUSemantics };
+  enum CheckerKi

[PATCH] D72811: [WIP][OPENMP5.0] allow lvalue for motion clause

2020-01-27 Thread Chi Chun Chen via Phabricator via cfe-commits
cchen marked an inline comment as done.
cchen added a comment.

In D72811#1839561 , @ABataev wrote:

> In D72811#1839538 , @cchen wrote:
>
> > In D72811#1837392 , @jdoerfert 
> > wrote:
> >
> > > Thanks for working on this! While you are at it, `*this` is probably one 
> > > of the most important ones to test and support.
> >
> >
> > Can anyone tell me how to get `ValueDecl` from `CXXThisExpr`? I cannot find 
> > any method return decl in 
> > https://clang.llvm.org/doxygen/classclang_1_1CXXThisExpr.html#details.
> >  Thanks!
>
>
> CXXThisExpr is an expression without associated declaration.


Then which kind of thing should I sent to `CurComponents` if we do not have 
associated declaration for CXXThisExpr? We can't just send nullptr, right?




Comment at: clang/lib/Sema/SemaOpenMP.cpp:16007
+if (!RE->IgnoreParenImpCasts()->isLValue() &&
+(MLValue != clang::Expr::isModifiableLvalueResult::MLV_LValueCast)) {
   SemaRef.Diag(ELoc,

ABataev wrote:
> Why `MLV_LValueCast` must be allowed here?
I'm doing this since `isLValue` return false for either C style casting CXX 
style casting and `MLV_LValueCast` can categorize these two  as 
`MLV_LValueCast`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72811



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


[PATCH] D72448: [clang-tidy] readability-redundant-string-init now flags redundant initialisation in Field Decls and Constructor Initialisers

2020-01-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman marked 2 inline comments as done.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!




Comment at: 
clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp:58
+  }
+  if (B.isInvalid() || E.isInvalid())
+return llvm::None;

njames93 wrote:
> aaron.ballman wrote:
> > Should we be worried about macros here?
> > 
> > It looks a bit like we're ignoring macros entirely for this check, so maybe 
> > that can be done as a separate patch instead. The situation I am worried 
> > about is:
> > ```
> > #if SOMETHING
> > #define INIT ""
> > #else
> > #define INIT "haha"
> > #endif
> > 
> > std::string S = INIT;
> > ```
> I feel that everything in this check needs to check macros, but that's 
> probably a follow up patch
Okay, separate patch it is.



Comment at: 
clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp:110
   namedDecl(
-  varDecl(
-  hasType(hasUnqualifiedDesugaredType(recordType(
-  hasDeclaration(cxxRecordDecl(hasStringTypeName),
-  hasInitializer(expr(ignoringImplicit(anyOf(
-  EmptyStringCtorExpr, EmptyStringCtorExprWithTemporaries)
-  .bind("vardecl"),
+  varDecl(StringType, hasInitializer(EmptyStringInit)).bind("vardecl"),
   unless(parmVarDecl())),

njames93 wrote:
> aaron.ballman wrote:
> > Should this also match on something like `std::string foo{};` as a 
> > redundant init? Similar question for the other cases. (Could be done in a 
> > follow-up patch if desired.)
> Probably should, however this is not what this patch is about
Okay, I'm fine with that as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72448



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


[PATCH] D73408: [Clang][Bundler] Add 'exclude' flag to target objects sections

2020-01-27 Thread Sergey Dmitriev via Phabricator via cfe-commits
sdmitriev added inline comments.



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:467-475
+// We will use llvm-objcopy to add target objects’ sections to the output
+// fat object. These sections should have ‘exclude’ flag set which tells
+// link editor to remove them from linker inputs when linking executable or
+// shared library. llvm-objcopy currently does not support adding new
+// section and changing flags for the added section in one invocation, and
+// because of that we have to run it two times. First run adds sections and
+// the second changes flags. TODO: change it to one run once llvm-objcopy

ABataev wrote:
> 1. Extra spaces in the comment.
> 2. TODO better to have on a separate line.
> 3. Maybe it is better to postpone it until llvm-objcopy can do this in one 
> run?
1. Will fix.
2. Ok.
3. I do not think that anybody is working on that problem now, so it is not 
clear how much time that will take. Also merging two llvm-objcopy invocations 
into one will be a simple NFC change, so I think this should not block this 
patch.



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:527
+
+// And run llvm-objcopy fro the second time to update section flags.
+ObjcopyArgs.resize(1);

ABataev wrote:
> from
This was supposed to be 'for'.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73408



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


[PATCH] D73495: [CodeGen] Attach no-builtin attributes to functions with no Decl

2020-01-27 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:1917
 const auto *NBA = Fn->getAttr();
-bool HasWildcard = NBA && llvm::is_contained(NBA->builtinNames(), "*");
-if (getLangOpts().NoBuiltin || HasWildcard)
-  FuncAttrs.addAttribute("no-builtins");
-else {
-  auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
-SmallString<32> AttributeName;
-AttributeName += "no-builtin-";
-AttributeName += BuiltinName;
-FuncAttrs.addAttribute(AttributeName);
-  };
-  llvm::for_each(getLangOpts().NoBuiltinFuncs, AddNoBuiltinAttr);
-  if (NBA)
-llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
-}
+addNonCallSiteNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
   }

What happens if we have a TargetDecl that isn't a FunctionDecl?  (I think this 
happens in some cases, but not completely sure which, exactly.)


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

https://reviews.llvm.org/D73495



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


[PATCH] D73434: [Sema] Remove a -Wrange warning from -Wall

2020-01-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73434



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


[PATCH] D73500: [driver] Add a -builtininc flag that lets Darwin driver include Clang builtin headers even with -nostdinc

2020-01-27 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman created this revision.
arphaman added a reviewer: dexonsmith.
Herald added subscribers: ributzka, jkorous.
Herald added a project: clang.

Some projects use -nostdinc, but need to access some intrinsics files when 
building specific files. The new `-builtininc` flag lets them use this flag 
when compiling these files to ensure they can access Clang's builtin headers.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D73500

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Darwin.cpp
  clang/test/Driver/darwin-header-search-system.cpp


Index: clang/test/Driver/darwin-header-search-system.cpp
===
--- clang/test/Driver/darwin-header-search-system.cpp
+++ clang/test/Driver/darwin-header-search-system.cpp
@@ -101,3 +101,31 @@
 // CHECK-NOSYSROOT: "-internal-isystem" "/usr/local/include"
 // CHECK-NOSYSROOT: "-internal-isystem" "[[RESOURCE]]/include"
 // CHECK-NOSYSROOT: "-internal-externc-isystem" "/usr/include"
+
+// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
+// RUN: -target x86_64-apple-darwin \
+// RUN: -ccc-install-dir 
%S/Inputs/basic_darwin_toolchain_no_libcxx/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: -isysroot %S/Inputs/basic_darwin_sdk_usr_and_usr_local \
+// RUN: -nostdinc -builtininc \
+// RUN:   | FileCheck -DSYSROOT=%S/Inputs/basic_darwin_sdk_usr_and_usr_local \
+// RUN:   -DRESOURCE=%S/Inputs/resource_dir \
+// RUN:   --check-prefix=CHECK-NOSTDINC-BUILTINC %s
+// CHECK-NOSTDINC-BUILTINC: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-NOSTDINC-BUILTINC-NOT: "-internal-isystem" 
"[[SYSROOT]]/usr/local/include"
+// CHECK-NOSTDINC-BUILTINC: "-internal-isystem" "[[RESOURCE]]/include"
+// CHECK-NOSTDINC-BUILTINC-NOT: "-internal-externc-isystem" 
"[[SYSROOT]]/usr/include"
+
+// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
+// RUN: -target x86_64-apple-darwin \
+// RUN: -ccc-install-dir 
%S/Inputs/basic_darwin_toolchain_no_libcxx/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: -isysroot %S/Inputs/basic_darwin_sdk_usr_and_usr_local \
+// RUN: -nostdinc -builtininc -nobuiltininc \
+// RUN:   | FileCheck -DSYSROOT=%S/Inputs/basic_darwin_sdk_usr_and_usr_local \
+// RUN:   -DRESOURCE=%S/Inputs/resource_dir \
+// RUN:   --check-prefix=CHECK-NOSTDINC-NO-BUILTINC %s
+// CHECK-NOSTDINC-NO-BUILTINC: "{{[^"]*}}clang{{[^"]*}}" "-cc1"
+// CHECK-NOSTDINC-NO-BUILTINC-NOT: "-internal-isystem" 
"[[SYSROOT]]/usr/local/include"
+// CHECK-NOSTDINC-NO-BUILTINC-NOT: "-internal-isystem" "[[RESOURCE]]/include"
+// CHECK-NOSTDINC-NO-BUILTINC-NOT: "-internal-externc-isystem" 
"[[SYSROOT]]/usr/include"
Index: clang/lib/Driver/ToolChains/Darwin.cpp
===
--- clang/lib/Driver/ToolChains/Darwin.cpp
+++ clang/lib/Driver/ToolChains/Darwin.cpp
@@ -1871,6 +1871,7 @@
   bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
   bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
   bool NoBuiltinInc = DriverArgs.hasArg(options::OPT_nobuiltininc);
+  bool ForceBuiltinInc = DriverArgs.hasArg(options::OPT_builtininc);
 
   // Add /usr/local/include
   if (!NoStdInc && !NoStdlibInc) {
@@ -1880,7 +1881,7 @@
   }
 
   // Add the Clang builtin headers (/include)
-  if (!NoStdInc && !NoBuiltinInc) {
+  if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
 SmallString<128> P(D.ResourceDir);
 llvm::sys::path::append(P, "include");
 addSystemInclude(DriverArgs, CC1Args, P);
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -500,6 +500,8 @@
 def a : Joined<["-"], "a">;
 def autocomplete : Joined<["--"], "autocomplete=">;
 def bind__at__load : Flag<["-"], "bind_at_load">;
+def builtininc : Flag<["-"], "builtininc">,
+  HelpText<"Enable builtin #include directories even when -nostdinc is used">;
 def bundle__loader : Separate<["-"], "bundle_loader">;
 def bundle : Flag<["-"], "bundle">;
 def b : JoinedOrSeparate<["-"], "b">, Flags<[Unsupported]>;


Index: clang/test/Driver/darwin-header-search-system.cpp
===
--- clang/test/Driver/darwin-header-search-system.cpp
+++ clang/test/Driver/darwin-header-search-system.cpp
@@ -101,3 +101,31 @@
 // CHECK-NOSYSROOT: "-internal-isystem" "/usr/local/include"
 // CHECK-NOSYSROOT: "-internal-isystem" "[[RESOURCE]]/include"
 // CHECK-NOSYSROOT: "-internal-externc-isystem" "/usr/include"
+
+// RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \
+// RUN: -target x86_64-apple-darwin \
+// RUN: -ccc-install-dir %S/Inputs/basic_darwin_toolchain_no_libcxx/usr/bin \
+// RUN: -resource-dir=%S/Inputs/resource_dir \
+// RUN: 

[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 240663.
void marked 2 inline comments as done.
void added a comment.

Move extension test to exsiting test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319

Files:
  clang/include/clang/Basic/Features.def
  clang/test/Parser/asm-goto.c


Index: clang/test/Parser/asm-goto.c
===
--- clang/test/Parser/asm-goto.c
+++ clang/test/Parser/asm-goto.c
@@ -4,6 +4,9 @@
 #if !__has_extension(gnu_asm)
 #error Extension 'gnu_asm' should be available by default
 #endif
+#if !__has_extension(gnu_asm_goto_with_outputs)
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
 
 
 int a, b, c, d, e, f, g, h, i, j, k, l;
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -252,6 +252,7 @@
 EXTENSION(pragma_clang_attribute_namespaces, true)
 EXTENSION(pragma_clang_attribute_external_declaration, true)
 EXTENSION(gnu_asm, LangOpts.GNUAsm)
+EXTENSION(gnu_asm_goto_with_outputs, LangOpts.GNUAsm)
 
 #undef EXTENSION
 #undef FEATURE


Index: clang/test/Parser/asm-goto.c
===
--- clang/test/Parser/asm-goto.c
+++ clang/test/Parser/asm-goto.c
@@ -4,6 +4,9 @@
 #if !__has_extension(gnu_asm)
 #error Extension 'gnu_asm' should be available by default
 #endif
+#if !__has_extension(gnu_asm_goto_with_outputs)
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
 
 
 int a, b, c, d, e, f, g, h, i, j, k, l;
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -252,6 +252,7 @@
 EXTENSION(pragma_clang_attribute_namespaces, true)
 EXTENSION(pragma_clang_attribute_external_declaration, true)
 EXTENSION(gnu_asm, LangOpts.GNUAsm)
+EXTENSION(gnu_asm_goto_with_outputs, LangOpts.GNUAsm)
 
 #undef EXTENSION
 #undef FEATURE
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void added a comment.

In D73319#1842900 , @nickdesaulniers 
wrote:

> Great idea; thanks for the patch! Needs documentation. :)


I can't find a place for documentation of extensions, at least not the names of 
extensions like `gnu_asm`.




Comment at: clang/test/Parser/asm-goto-with-outputs.c:7
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
+

nickdesaulniers wrote:
> probably don't need a bunch of test cases, just the check for the 
> preprocessor define?  In that case, why don't you just add the above to an 
> existing asm goto test?
Sure. done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319



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


[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

Great idea; thanks for the patch! Needs documentation. :)




Comment at: clang/test/Parser/asm-goto-with-outputs.c:7
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
+

probably don't need a bunch of test cases, just the check for the preprocessor 
define?  In that case, why don't you just add the above to an existing asm goto 
test?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319



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


[PATCH] D73319: Add extension 'gnu_asm_goto_with_outputs'

2020-01-27 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 240657.
void added a comment.

Use GNU asm predicate for the "asm goto with outputs" extension.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73319

Files:
  clang/include/clang/Basic/Features.def
  clang/test/Parser/asm-goto-with-outputs.c


Index: clang/test/Parser/asm-goto-with-outputs.c
===
--- /dev/null
+++ clang/test/Parser/asm-goto-with-outputs.c
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -triple i386-pc-linux-gnu -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+#if !__has_extension(gnu_asm_goto_with_outputs)
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
+
+int test1(int cond) {
+  asm volatile goto("testl %0, %0; jne %l2;" : "=r"(cond) : "r"(cond) :: 
label_true, loop);
+  asm volatile goto("testl %0, %0; jne %l3;" : "=r"(cond) : "r"(cond) :: 
label_true, loop);
+  return 0;
+loop:
+  return 0;
+label_true:
+  return 1;
+}
+
+int test2(int out1, int out2) {
+  asm volatile goto("testl %0, %0; jne %l3;" : "=r"(out1), "=r"(out2) : 
"r"(out1) :: label_true, loop);
+  asm volatile goto("testl %0, %0; jne %l4;" : "=r"(out1), "=r"(out2) : 
"r"(out1) :: label_true, loop);
+  return 0;
+loop:
+  return 0;
+label_true:
+  return 1;
+}
+
+int test3(int out1, int out2) {
+  if (out1 < out2)
+asm volatile goto("jne %l3" : "+S"(out1), "+D"(out2) : "r"(out1) :: 
label_true, loop);
+  else
+asm volatile goto("jne %l5" : "+S"(out1), "+D"(out2) : "r"(out1), 
"r"(out2) :: label_true, loop);
+  return out1 + out2;
+loop:
+  return -1;
+label_true:
+  return -2;
+}
+
+int test4(int addr, int size, int limit) {
+  asm goto(
+  "add %1,%0 ; "
+  "jc %l[t_err] ; "
+  "cmp %2,%0 ; "
+  "ja %l[t_err] ; "
+  : "+r" (addr)
+  : "g" (size), "g" (limit)
+  : : t_err);
+  return 0;
+t_err:
+  return 1;
+}
+
+int test5(int out1) {
+  int out2 = 42;
+  asm volatile goto("testl %0, %0; testl %1, %1; jne %l2" : "+S"(out2) : 
"r"(out1) :: label_true, landing);
+landing:
+  return out1 + out2;
+label_true:
+  return -2;
+}
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -252,6 +252,7 @@
 EXTENSION(pragma_clang_attribute_namespaces, true)
 EXTENSION(pragma_clang_attribute_external_declaration, true)
 EXTENSION(gnu_asm, LangOpts.GNUAsm)
+EXTENSION(gnu_asm_goto_with_outputs, LangOpts.GNUAsm)
 
 #undef EXTENSION
 #undef FEATURE


Index: clang/test/Parser/asm-goto-with-outputs.c
===
--- /dev/null
+++ clang/test/Parser/asm-goto-with-outputs.c
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -triple i386-pc-linux-gnu -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+#if !__has_extension(gnu_asm_goto_with_outputs)
+#error Extension 'gnu_asm_goto_with_outputs' should be available by default
+#endif
+
+int test1(int cond) {
+  asm volatile goto("testl %0, %0; jne %l2;" : "=r"(cond) : "r"(cond) :: label_true, loop);
+  asm volatile goto("testl %0, %0; jne %l3;" : "=r"(cond) : "r"(cond) :: label_true, loop);
+  return 0;
+loop:
+  return 0;
+label_true:
+  return 1;
+}
+
+int test2(int out1, int out2) {
+  asm volatile goto("testl %0, %0; jne %l3;" : "=r"(out1), "=r"(out2) : "r"(out1) :: label_true, loop);
+  asm volatile goto("testl %0, %0; jne %l4;" : "=r"(out1), "=r"(out2) : "r"(out1) :: label_true, loop);
+  return 0;
+loop:
+  return 0;
+label_true:
+  return 1;
+}
+
+int test3(int out1, int out2) {
+  if (out1 < out2)
+asm volatile goto("jne %l3" : "+S"(out1), "+D"(out2) : "r"(out1) :: label_true, loop);
+  else
+asm volatile goto("jne %l5" : "+S"(out1), "+D"(out2) : "r"(out1), "r"(out2) :: label_true, loop);
+  return out1 + out2;
+loop:
+  return -1;
+label_true:
+  return -2;
+}
+
+int test4(int addr, int size, int limit) {
+  asm goto(
+  "add %1,%0 ; "
+  "jc %l[t_err] ; "
+  "cmp %2,%0 ; "
+  "ja %l[t_err] ; "
+  : "+r" (addr)
+  : "g" (size), "g" (limit)
+  : : t_err);
+  return 0;
+t_err:
+  return 1;
+}
+
+int test5(int out1) {
+  int out2 = 42;
+  asm volatile goto("testl %0, %0; testl %1, %1; jne %l2" : "+S"(out2) : "r"(out1) :: label_true, landing);
+landing:
+  return out1 + out2;
+label_true:
+  return -2;
+}
Index: clang/include/clang/Basic/Features.def
===
--- clang/include/clang/Basic/Features.def
+++ clang/include/clang/Basic/Features.def
@@ -252,6 +252,7 @@
 EXTENSION(pragma_clang_attribute_namespaces, true)
 EXTENSION(pragma_clang_attribute_external_declaration, true)
 EXTENSION(gnu_asm, LangOpts.GNUAsm)
+EXTENSI

[PATCH] D73261: [dwarf5] Support DebugInfo for constexpr for C++ variables and functions

2020-01-27 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.

In D73261#1838683 , @probinson wrote:

> In D73261#1838552 , @djtodoro wrote:
>
> > > Is it necessary to use DIFlags? I am willing to do that but generally, it 
> > > is not welcomed because we have a limited number of DIFlags and most of 
> > > them are currently in use.
> >
> > Are there any flags within `DIFlags` that could be applied only to 
> > functions? If so, we should move them in to the `DISPFlags` in order to 
> > make some space within the `DIFlags`.
>
>
> There might be.  The trick is backward compatibility of bitcode.  It looks 
> like Virtual is already replicated to DISPFlags, but wasn't removed from 
> DIFlags.  Other candidates for migration to DISPFlags: Explicit, Prototyped, 
> NoReturn, Thunk, AllCallsDescribed, maybe NonTrivial.
>  Their exact semantics and how they're used would have to be verified.
>
> @dblaikie @aprantl  thoughts on this?
>
> huh. DIFlag bit 21 has no symbol; it used to be DIFlagMainSubprogram but we 
> did not put in a Reserved or Deprecated name for it.  That should be fixed.
>
> > In addition, does it make sense to making something like `DIVarFlags`? And 
> > move the flags applying only to variables.
>
> We might have some like that.  BitField and StaticMember, just based on the 
> names.
>
> Note that moving flags around is tricky and requires extreme care to ensure 
> full backward compatibility.  Moving flags would have to be its own patch and 
> this one would depend on it.


One clean way of doing this is to reserve one previously unused bit in DIFlags 
or DISPFlags to indicate that these flags were moved over and teach 
MetadataLoader to decode the old and new format accordingly. In that case we'd 
want a spearate patch that just moves the flag, though, all flags should be 
moved in the same patch.


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

https://reviews.llvm.org/D73261



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


[PATCH] D73376: [analyzer] Add FuchsiaLockChecker and C11LockChecker

2020-01-27 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.
This revision is now accepted and ready to land.

LGTM!~


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

https://reviews.llvm.org/D73376



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


[clang] e6d2583 - [OPENMP50]Track changes of lastprivate conditional in parallel-based

2020-01-27 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2020-01-27T14:53:25-05:00
New Revision: e6d2583e45ef3af7646d4a58bada2e639121

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

LOG: [OPENMP50]Track changes of lastprivate conditional in parallel-based
regions with reductions, lastprivates or linears clauses.

If the lastprivate conditional variable is updated in inner parallel
region with reduction, lastprivate or linear clause, the value must be
considred as a candidate for lastprivate conditional. Also, tracking in
inner parallel regions is not required.

Added: 
clang/test/OpenMP/parallel_for_lastprivate_conditional.cpp

Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
clang/lib/CodeGen/CGStmtOpenMP.cpp
clang/test/OpenMP/for_lastprivate_codegen.cpp
clang/test/OpenMP/sections_lastprivate_codegen.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 896cf378c16b..aecf150401bb 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -11357,25 +11357,7 @@ 
CGOpenMPRuntime::LastprivateConditionalRAII::LastprivateConditionalRAII(
 }
   }
   Data.IVLVal = IVLVal;
-  // In simd only mode or for simd directives no need to generate threadprivate
-  // references for the loop iteration counter, we can use the original one
-  // since outlining cannot happen in simd regions.
-  if (CGF.getLangOpts().OpenMPSimd ||
-  isOpenMPSimdDirective(S.getDirectiveKind())) {
-Data.UseOriginalIV = true;
-return;
-  }
-  PresumedLoc PLoc =
-  CGM.getContext().getSourceManager().getPresumedLoc(S.getBeginLoc());
-  assert(PLoc.isValid() && "Source location is expected to be always valid.");
-
-  llvm::sys::fs::UniqueID ID;
-  if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
-CGM.getDiags().Report(diag::err_cannot_open_file)
-<< PLoc.getFilename() << EC.message();
-  Data.IVName = CGM.getOpenMPRuntime().getName(
-  {"pl_cond", llvm::utostr(ID.getDevice()), llvm::utostr(ID.getFile()),
-   llvm::utostr(PLoc.getLine()), llvm::utostr(PLoc.getColumn()), "iv"});
+  Data.CGF = &CGF;
 }
 
 CGOpenMPRuntime::LastprivateConditionalRAII::~LastprivateConditionalRAII() {
@@ -11384,27 +11366,6 @@ 
CGOpenMPRuntime::LastprivateConditionalRAII::~LastprivateConditionalRAII() {
   CGM.getOpenMPRuntime().LastprivateConditionalStack.pop_back();
 }
 
-void CGOpenMPRuntime::initLastprivateConditionalCounter(
-CodeGenFunction &CGF, const OMPExecutableDirective &S) {
-  if (CGM.getLangOpts().OpenMPSimd ||
-  !llvm::any_of(S.getClausesOfKind(),
-[](const OMPLastprivateClause *C) {
-  return C->getKind() == OMPC_LASTPRIVATE_conditional;
-}))
-return;
-  const CGOpenMPRuntime::LastprivateConditionalData &Data =
-  LastprivateConditionalStack.back();
-  if (Data.UseOriginalIV)
-return;
-  // Global loop counter. Required to handle inner parallel-for regions.
-  // global_iv = iv;
-  Address GlobIVAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
-  CGF, Data.IVLVal.getType(), Data.IVName);
-  LValue GlobIVLVal = CGF.MakeAddrLValue(GlobIVAddr, Data.IVLVal.getType());
-  llvm::Value *IVVal = CGF.EmitLoadOfScalar(Data.IVLVal, S.getBeginLoc());
-  CGF.EmitStoreOfScalar(IVVal, GlobIVLVal);
-}
-
 namespace {
 /// Checks if the lastprivate conditional variable is referenced in LHS.
 class LastprivateConditionalRefChecker final
@@ -11415,9 +11376,7 @@ class LastprivateConditionalRefChecker final
   const Decl *FoundD = nullptr;
   StringRef UniqueDeclName;
   LValue IVLVal;
-  StringRef IVName;
   SourceLocation Loc;
-  bool UseOriginalIV = false;
 
 public:
   bool VisitDeclRefExpr(const DeclRefExpr *E) {
@@ -11430,8 +11389,6 @@ class LastprivateConditionalRefChecker final
   FoundD = E->getDecl()->getCanonicalDecl();
   UniqueDeclName = It->getSecond();
   IVLVal = D.IVLVal;
-  IVName = D.IVName;
-  UseOriginalIV = D.UseOriginalIV;
   break;
 }
 return FoundE == E;
@@ -11448,8 +11405,6 @@ class LastprivateConditionalRefChecker final
   FoundD = E->getMemberDecl()->getCanonicalDecl();
   UniqueDeclName = It->getSecond();
   IVLVal = D.IVLVal;
-  IVName = D.IVName;
-  UseOriginalIV = D.UseOriginalIV;
   break;
 }
 return FoundE == E;
@@ -11470,17 +11425,17 @@ class LastprivateConditionalRefChecker final
   CodeGenFunction &CGF,
   ArrayRef LPM)
   : CGF(CGF), LPM(LPM) {}
-  std::tuple
+  std::tuple
   getFoundData() const {
-return std::make_tuple(FoundE, FoundD, UniqueDeclName, IVLVal, IVName,
-   UseOriginalIV);
+return std::make_tuple(FoundE, Fo

[PATCH] D73408: [Clang][Bundler] Add 'exclude' flag to target objects sections

2020-01-27 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:467-475
+// We will use llvm-objcopy to add target objects’ sections to the output
+// fat object. These sections should have ‘exclude’ flag set which tells
+// link editor to remove them from linker inputs when linking executable or
+// shared library. llvm-objcopy currently does not support adding new
+// section and changing flags for the added section in one invocation, and
+// because of that we have to run it two times. First run adds sections and
+// the second changes flags. TODO: change it to one run once llvm-objcopy

1. Extra spaces in the comment.
2. TODO better to have on a separate line.
3. Maybe it is better to postpone it until llvm-objcopy can do this in one run?



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:508
+
+auto ExecuteObjcopy = [&Objcopy](ArrayRef ObjcopyArgs) -> Error 
{
+  // If the user asked for the commands to be printed out, we do that

Better to make it a function



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:527
+
+// And run llvm-objcopy fro the second time to update section flags.
+ObjcopyArgs.resize(1);

from


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73408



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


[PATCH] D73376: [analyzer] Add FuchsiaLockChecker and C11LockChecker

2020-01-27 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun updated this revision to Diff 240650.
xazax.hun added a comment.

- Add a FIXME.


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

https://reviews.llvm.org/D73376

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/PthreadLockChecker.cpp
  clang/test/Analysis/c11lock.c
  clang/test/Analysis/fuchsia_lock.c

Index: clang/test/Analysis/fuchsia_lock.c
===
--- /dev/null
+++ clang/test/Analysis/fuchsia_lock.c
@@ -0,0 +1,104 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=fuchsia.Lock -verify %s
+
+typedef int spin_lock_t;
+typedef int zx_status_t;
+typedef int zx_time_t;
+
+void spin_lock(spin_lock_t *lock);
+int spin_trylock(spin_lock_t *lock);
+void spin_unlock(spin_lock_t *lock);
+void spin_lock_init(spin_lock_t *lock);
+
+void spin_lock_save(spin_lock_t *lock, void *statep,
+int flags);
+void spin_unlock_restore(spin_lock_t *lock, void *old_state,
+ int flags);
+
+spin_lock_t mtx1;
+spin_lock_t mtx2;
+
+void bad1(void)
+{
+	spin_lock(&mtx1);	// no-warning
+	spin_lock(&mtx1);	// expected-warning{{This lock has already been acquired}}
+}
+
+void bad2(void) {
+  spin_lock(&mtx1);
+  spin_unlock(&mtx1);
+  spin_unlock(&mtx1); // expected-warning {{This lock has already been unlocked}}
+}
+
+void bad3() {
+  spin_lock_init(&mtx1);
+  if (spin_trylock(&mtx1) != 0)
+spin_unlock(&mtx1); // expected-warning {{This lock has already been unlocked}}
+}
+
+void bad4(void) {
+  spin_lock(&mtx1);
+  spin_lock(&mtx2);
+  spin_unlock(&mtx1); // expected-warning {{This was not the most recently acquired lock. Possible lock order reversal}}
+  spin_unlock(&mtx2);
+}
+
+void good() {
+  spin_lock_t mtx;
+  spin_lock_init(&mtx);
+  spin_lock_save(&mtx, 0, 0);
+  spin_unlock_restore(&mtx, 0, 0);
+}
+
+void good2() {
+  spin_lock_t mtx;
+  spin_lock_init(&mtx);
+  if (spin_trylock(&mtx) == 0)
+spin_unlock(&mtx);
+}
+
+typedef int sync_mutex_t;
+void sync_mutex_lock(sync_mutex_t* mutex);
+void sync_mutex_lock_with_waiter(sync_mutex_t* mutex);
+zx_status_t sync_mutex_timedlock(sync_mutex_t* mutex, zx_time_t deadline);
+zx_status_t sync_mutex_trylock(sync_mutex_t* mutex);
+void sync_mutex_unlock(sync_mutex_t* mutex);
+
+sync_mutex_t smtx1;
+sync_mutex_t smtx2;
+
+void bad11(void)
+{
+	sync_mutex_lock(&smtx1);	// no-warning
+	sync_mutex_lock(&smtx1);	// expected-warning{{This lock has already been acquired}}
+}
+
+void bad12(void) {
+  sync_mutex_lock_with_waiter(&smtx1);
+  sync_mutex_unlock(&smtx1);
+  sync_mutex_unlock(&smtx1); // expected-warning {{This lock has already been unlocked}}
+}
+
+void bad13() {
+  sync_mutex_unlock(&smtx1);
+  if (sync_mutex_trylock(&smtx1) != 0)
+sync_mutex_unlock(&smtx1); // expected-warning {{This lock has already been unlocked}}
+}
+
+void bad14(void) {
+  sync_mutex_lock(&smtx1);
+  sync_mutex_lock(&smtx2);
+  sync_mutex_unlock(&smtx1); // expected-warning {{This was not the most recently acquired lock. Possible lock order reversal}}
+  sync_mutex_unlock(&smtx2);
+}
+
+void good11() {
+  sync_mutex_t mtx;
+  if (sync_mutex_trylock(&mtx) == 0)
+sync_mutex_unlock(&mtx);
+}
+
+void good12() {
+  sync_mutex_t mtx;
+  if (sync_mutex_timedlock(&mtx, 0) == 0)
+sync_mutex_unlock(&mtx);
+}
Index: clang/test/Analysis/c11lock.c
===
--- /dev/null
+++ clang/test/Analysis/c11lock.c
@@ -0,0 +1,90 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.core.C11Lock -verify %s
+
+typedef int mtx_t;
+struct timespec;
+
+enum {
+  // FIXME: The value if this enum is implementation defined. While all the
+  // implementations I am aware of using 0, the right solution would be to
+  // look this value up in the AST (and disable the check if it is not found).
+  thrd_success = 0,
+  thrd_error = 2
+};
+
+int mtx_init(mtx_t *mutex, int type);
+int mtx_lock(mtx_t *mutex);
+int mtx_timedlock(mtx_t *mutex,
+  const struct timespec *time_point);
+int mtx_trylock(mtx_t *mutex);
+int mtx_unlock(mtx_t *mutex);
+int mtx_destroy(mtx_t *mutex);
+
+mtx_t mtx1;
+mtx_t mtx2;
+
+void bad1(void)
+{
+  mtx_lock(&mtx1);	// no-warning
+  mtx_lock(&mtx1);	// expected-warning{{This lock has already been acquired}}
+}
+
+void bad2(void) {
+  mtx_t mtx;
+  mtx_init(&mtx, 0);
+  mtx_lock(&mtx);
+} // TODO: Warn for missing unlock?
+
+void bad3(void) {
+  mtx_t mtx;
+  mtx_init(&mtx, 0);
+} // TODO: Warn for missing destroy?
+
+void bad4(void) {
+  mtx_t mtx;
+  mtx_init(&mtx, 0);
+  mtx_lock(&mtx);
+  mtx_unlock(&mtx);
+} // TODO: warn for missing destroy?
+
+void bad5(void) {
+  mtx_lock(&mtx1);
+  mtx_unlock(&mtx1);
+  mtx_unlock(&mtx1); // expected-warning {{This lock has already been unlocked}}
+}
+
+void bad6() {
+  mtx_init(&mtx1, 0);
+  if (mtx_trylock(&mtx1) != thrd_success)
+mtx_unlock(&mtx1); // expected-warning {{This lock has already been unlocke

[PATCH] D72841: [RFC] Add support for pragma float_control, to control precision and exception behavior at the source level

2020-01-27 Thread Andy Kaylor via Phabricator via cfe-commits
andrew.w.kaylor added a comment.

It's not clear to me from reading this how the "precise" control is going to 
work with relation to the fast math flags. I don't think MSVC allows the 
granularity of control over these flags that we have in clang, so maybe they 
don't have this problem.

Consider this code: https://godbolt.org/z/mHiLCm

With the options "-ffp-model=precise -fno-honor-infinities -fno-honor-nans" the 
math operations here are generated with the "nnan ninf contract" flags. That's 
correct. What will happen when I use the pragma to turn precise off? Does it 
enable all fast math flags? Will the subsequent "pop" leave the "ninf nnan" 
fast math flags enabled?

As I said, I don't think you can get into this situation with MSVC. I believe 
that icc will go into full fast math mode with the "precise, off, push" pragma 
but will go back to "nnan ninf contract" mode with the pop. At least, that's 
what the design docs say. I haven't looked at the code to verify this. It seems 
like the correct behavior in any case. I think the clang FPOptions needs 
individual entries for all of the fast math flags to handle this case.




Comment at: clang/docs/LanguageExtensions.rst:3042
+by the pragma behaves as though the command-line option ``ffp-model=precise``
+is enabled.  That is, fast-math is disabled and fp-contract=on (fused
+multiple add) is enabled.

Re  "fp-contraction=on": I agree that this is what it should do, but I don't 
think that's what fp-model=precise currently does. I think it's setting 
fp-contraction=fast.



Comment at: clang/docs/LanguageExtensions.rst:3043
+is enabled.  That is, fast-math is disabled and fp-contract=on (fused
+multiple add) is enabled.
+

s/multiple/multiply



Comment at: clang/docs/LanguageExtensions.rst:3050
+
+The full syntax this pragma supports is ``float_control(except|precise, 
on|off, [push])`` and ``float_control(push|pop)``.  The ``push`` and ``pop`` 
forms can only occur at file scope.
+

Looks like you need a line break here.



Comment at: clang/docs/LanguageExtensions.rst:3050
+
+The full syntax this pragma supports is ``float_control(except|precise, 
on|off, [push])`` and ``float_control(push|pop)``.  The ``push`` and ``pop`` 
forms can only occur at file scope.
+

andrew.w.kaylor wrote:
> Looks like you need a line break here.
Are the precise and except stacks independent?



Comment at: clang/include/clang/Basic/DiagnosticParseKinds.td:1112
   InGroup;
 // - #pragma fp_contract
+def err_pragma_file_or_compound_scope : Error<

This comment is wrong after your change.



Comment at: clang/include/clang/Basic/DiagnosticParseKinds.td:1135
+def err_pragma_float_control_malformed : Error<
+  "pragma float_control is malformed; it requires one or two comma-separated "
+  "arguments">;

This isn't quite accurate. The pop case has no comma-separated arguments. It 
might be better to print the full syntax here if that's feasible.



Comment at: clang/include/clang/Basic/LangOptions.h:363
+exceptions(LangOptions::FPE_Ignore),
+fp_precise(false)
 {}

It seems like fp_precise describes too many things to be a single option. Even 
within this set of options it overlaps with fp_contract.



Comment at: clang/test/CodeGen/fp-floatcontrol-stack.cpp:124
+#if DEFAULT
+//CHECK-DDEFAULT: fmul float
+//CHECK-DDEFAULT: fadd float

Are there also fast-math flags set here? If not, why not?



Comment at: clang/test/CodeGen/fp-floatcontrol-stack.cpp:2
+// RUN: %clang_cc1 -DDEFAULT=1 -emit-llvm -o - %s | FileCheck 
--check-prefix=CHECK-DDEFAULT %s
+// RUN: %clang_cc1 -DEBSTRICT=1 -ffp-exception-behavior=strict -emit-llvm -o - 
%s | FileCheck --check-prefix=CHECK-DEBSTRICT %s
+

Can you add run lines for -ffast-math and (separately) "-fno-honor-nans 
-fno-honor-infinities"?



Comment at: clang/test/CodeGen/fp-floatcontrol-stack.cpp:17
+// for exception behavior and rounding mode.
+//CHECK-DEBSTRICT: 
llvm.experimental.constrained.fmul{{.*}}tonearest{{.*}}strict
+#endif

There should be a constrained fadd here also, right?



Comment at: clang/test/CodeGen/fp-floatcontrol-stack.cpp:52
+#if EBSTRICT
+//CHECK-DEBSTRICT: 
llvm.experimental.constrained.fmul{{.*}}tonearest{{.*}}ignore
+#endif

Why is the constrained intrinsic generated in this case? If we've got both 
constraints set to the defaults at the file scope I would have expected that to 
turn off the constrained mode.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72841



___
cfe-commits mailing list
cfe-commit

[clang-tools-extra] c72a6ac - Revert "[clang-tidy] readability-identifier-naming disregards parameters restrictions on main like functions"

2020-01-27 Thread Shoaib Meenai via cfe-commits

Author: Shoaib Meenai
Date: 2020-01-27T11:50:25-08:00
New Revision: c72a6ac4b630d2344dbea44a7d75fa61795dcd76

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

LOG: Revert "[clang-tidy] readability-identifier-naming disregards parameters 
restrictions on main like functions"

This reverts commit 27e3671ff49b72640f89c34a415412e400503442.

This was an accidental push, and the author requested a revert on IRC as
their local branch is in a bad state.

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst

clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-member-decl-usage.cpp

Removed: 

clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp



diff  --git 
a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index 119502e91ffe..6a39ece09777 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -8,13 +8,15 @@
 
 #include "IdentifierNamingCheck.h"
 
+#include "../utils/ASTUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/AST/CXXInheritance.h"
+#include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Format.h"
-#include "llvm/Support/Regex.h"
 
 #define DEBUG_TYPE "clang-tidy"
 
@@ -124,9 +126,7 @@ class IdentifierNamingCheckPPCallbacks : public PPCallbacks 
{
 
 IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
  ClangTidyContext *Context)
-: RenamerClangTidyCheck(Name, Context),
-  IgnoreFailedSplit(Options.get("IgnoreFailedSplit", 0)),
-  IgnoreMainLikeFunctions(Options.get("IgnoreMainLikeFunctions", 0)) {
+: RenamerClangTidyCheck(Name, Context) {
   auto const fromString = [](StringRef Str) {
 return llvm::StringSwitch>(Str)
 .Case("aNy_CasE", CT_AnyCase)
@@ -151,6 +151,8 @@ IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
   NamingStyles.push_back(llvm::None);
 }
   }
+
+  IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
 }
 
 IdentifierNamingCheck::~IdentifierNamingCheck() = default;
@@ -191,7 +193,6 @@ void 
IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   }
 
   Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
-  Options.store(Opts, "IgnoreMainLikeFunctions", IgnoreMainLikeFunctions);
 }
 
 static bool matchesStyle(StringRef Name,
@@ -323,67 +324,6 @@ static std::string fixupWithCase(StringRef Name,
   return Fixup;
 }
 
-static bool isParamInMainLikeFunction(const ParmVarDecl &ParmDecl,
-  bool IncludeMainLike) {
-  const auto *FDecl =
-  dyn_cast_or_null(ParmDecl.getParentFunctionOrMethod());
-  if (!FDecl)
-return false;
-  if (FDecl->isMain())
-return true;
-  if (!IncludeMainLike)
-return false;
-  if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
-return false;
-  enum MainType { None, Main, WMain };
-  auto IsCharPtrPtr = [](QualType QType) -> MainType {
-if (QType.isNull())
-  return None;
-if (QType = QType->getPointeeType(), QType.isNull())
-  return None;
-if (QType = QType->getPointeeType(), QType.isNull())
-  return None;
-if (QType->isCharType())
-  return Main;
-if (QType->isWideCharType())
-  return WMain;
-return None;
-  };
-  auto IsIntType = [](QualType QType) {
-if (QType.isNull())
-  return false;
-if (const auto *Builtin =
-dyn_cast(QType->getUnqualifiedDesugaredType())) {
-  return Builtin->getKind() == BuiltinType::Int;
-}
-return false;
-  };
-  if (!IsIntType(FDecl->getReturnType()))
-return false;
-  if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)
-return false;
-  if (!IsIntType(FDecl->parameters()[0]->getType()))
-return false;
-  MainType Type = IsCharPtrPtr(FDecl->parameters()[1]->getType());
-  if (Type == None)
-return false;
-  if (FDecl->getNumParams() == 3 &&
-  IsCharPtrPtr(FDecl->parameters()[2]->getType()) != Type)
-return false;
-
-  if (Type == Main) {
-static llvm::Regex Matcher(
-"(^[Mm]ain([_A-Z]|$))|([a-z0-9_]Main([_A-Z]|$))|(_main(_|$))");
-assert(Matcher.isValid() && "Invalid M

[PATCH] D73098: [clang-tidy] readability-identifier-naming disregards parameters restrictions on main like functions

2020-01-27 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

May need to roll this back, I think as i had this on the same local branch as 
D73052  I have brought both of them in at once


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73098



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


[PATCH] D73376: [analyzer] Add FuchsiaLockChecker and C11LockChecker

2020-01-27 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added inline comments.



Comment at: clang/test/Analysis/c11lock.c:7
+enum {
+  thrd_success = 0,
+  thrd_error = 2

xazax.hun wrote:
> Strictly speaking, this is implementation defined. But the C11 
> implementations I am aware of are following this trend (`thrd_success == 0`). 
> E.g. if the implementation is using pthreads as a backend it is unlikely for 
> this to be any other value.
Yeah, this is most likely fine but we should add a FIXME just in case. We could 
most likely uncover the exact constant easily by simply matching the AST (and 
abort all checking if the constant isn't found in the AST).


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

https://reviews.llvm.org/D73376



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


[PATCH] D73261: [dwarf5] Support DebugInfo for constexpr for C++ variables and functions

2020-01-27 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

General question: What purpose do you (or anyone else - @probinson, @aprantl) 
have for this attribute? I'd like to encourage the idea that we don't need to 
implement every feature DWARF provides if there's no planned use for it - 
things can/should be implemented as-motivated so we don't end up with weird 
features/implementations/etc that are essentially untested/unused.




Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:3406
   getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
-  TParamsArray.get(), getFunctionDeclaration(FD));
+  false, TParamsArray.get(), getFunctionDeclaration(FD));
   const FunctionDecl *CanonDecl = FD->getCanonicalDecl();

Any reason isConstexpr shouldn't be specified here too?



Comment at: clang/test/CodeGenCXX/constExpr.cpp:9
+// CHECK: DIGlobalVariable(name: "bar", {{.*}} constExpr: true)
+// CHECK: DISubprogram(name: "main", {{.*}} constExpr: false{{.*}}
+// CHECK: DILocalVariable(name: "baz", {{.*}} constExpr: true)

do these {{.*}} on the end of the lines provide any particular value? 


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

https://reviews.llvm.org/D73261



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


[clang] 2d0b29e - [clang] Fix covered default in switch

2020-01-27 Thread Jinsong Ji via cfe-commits

Author: Jinsong Ji
Date: 2020-01-27T19:28:11Z
New Revision: 2d0b29e0de5b2fd7cc05e8a341db3bf460e18d46

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

LOG: [clang] Fix covered default in switch

clang/lib/Format/TokenAnnotator.cpp:3162:7:
error: default label in switch which covers all enumeration values
[-Werror,-Wcovered-switch-default]
  default:
  ^
1 error generated.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 8f9a29ab2f29..c4798f65592a 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3159,8 +3159,6 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine 
&Line,
 // functions.
 return (Left.NestingLevel == 0 && Line.Level == 0) &&
!Left.Children.empty();
-  default:
-break;
   }
 }
 



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


[PATCH] D73261: [dwarf5] Support DebugInfo for constexpr for C++ variables and functions

2020-01-27 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

In D73261#1838683 , @probinson wrote:

> In D73261#1838552 , @djtodoro wrote:
>
> > > Is it necessary to use DIFlags? I am willing to do that but generally, it 
> > > is not welcomed because we have a limited number of DIFlags and most of 
> > > them are currently in use.
> >
> > Are there any flags within `DIFlags` that could be applied only to 
> > functions? If so, we should move them in to the `DISPFlags` in order to 
> > make some space within the `DIFlags`.
>
>
> There might be.  The trick is backward compatibility of bitcode.  It looks 
> like Virtual is already replicated to DISPFlags, but wasn't removed from 
> DIFlags.  Other candidates for migration to DISPFlags: Explicit, Prototyped, 
> NoReturn, Thunk, AllCallsDescribed, maybe NonTrivial.
>  Their exact semantics and how they're used would have to be verified.
>
> @dblaikie @aprantl  thoughts on this?


Don't have strong feelings/knowledge here (Apple folks have more vested 
interested in the IR backwards compatibility issues). We can rev the Debug Info 
Version metadata to allow us to recycle those bits rather than leaving them 
dead/reserved/deprecated. Once we actually need bits, I expect we should do 
that - but sounds like we're not there quite yet.

> huh. DIFlag bit 21 has no symbol; it used to be DIFlagMainSubprogram but we 
> did not put in a Reserved or Deprecated name for it.  That should be fixed.
> 
>> In addition, does it make sense to making something like `DIVarFlags`? And 
>> move the flags applying only to variables.
> 
> We might have some like that.  BitField and StaticMember, just based on the 
> names.
> 
> Note that moving flags around is tricky and requires extreme care to ensure 
> full backward compatibility.  Moving flags would have to be its own patch and 
> this one would depend on it.




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

https://reviews.llvm.org/D73261



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


[PATCH] D73098: [clang-tidy] readability-identifier-naming disregards parameters restrictions on main like functions

2020-01-27 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG27e3671ff49b: [clang-tidy] readability-identifier-naming 
disregards parameters restrictions… (authored by njames93).

Changed prior to commit:
  https://reviews.llvm.org/D73098?vs=240400&id=240647#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73098

Files:
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
  clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
  clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-member-decl-usage.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-member-decl-usage.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-member-decl-usage.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-member-decl-usage.cpp
@@ -1,7 +1,8 @@
 // RUN: %check_clang_tidy %s readability-identifier-naming %t -- \
 // RUN:   -config='{CheckOptions: [ \
 // RUN: {key: readability-identifier-naming.MemberCase, value: CamelCase}, \
-// RUN: {key: readability-identifier-naming.ParameterCase, value: CamelCase} \
+// RUN: {key: readability-identifier-naming.ParameterCase, value: CamelCase}, \
+// RUN: {key: readability-identifier-naming.MethodCase, value: camelBack} \
 // RUN:  ]}' -- -fno-delayed-template-parsing
 
 int set_up(int);
@@ -83,12 +84,12 @@
 }; //NOLINT
 }; // namespace std
 
-class Foo { 
+class Foo {
   std::vector &stack;
   // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: invalid case style for member 'stack' [readability-identifier-naming]
 public:
   Foo(std::vector &stack)
-  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: invalid case style for parameter 'stack' [readability-identifier-naming]
+  // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: invalid case style for parameter 'stack' [readability-identifier-naming]
   // CHECK-FIXES: {{^}}  Foo(std::vector &Stack)
   : stack(stack) {
 // CHECK-FIXES: {{^}}  : Stack(Stack) {
@@ -134,4 +135,94 @@
 void foo() {
   Container container;
 }
-}; // namespace CtorInits
+} // namespace CtorInits
+
+namespace resolved_dependance {
+template 
+struct A0 {
+  int value;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for member 'value'
+  A0 &operator=(const A0 &Other) {
+value = Other.value;   // A0
+this->value = Other.value; // A0
+// CHECK-FIXES:  {{^}}Value = Other.Value;   // A0
+// CHECK-FIXES-NEXT: {{^}}this->Value = Other.Value; // A0
+return *this;
+  }
+  void outOfLineReset();
+};
+
+template 
+void A0::outOfLineReset() {
+  this->value -= value; // A0
+  // CHECK-FIXES: {{^}}  this->Value -= Value; // A0
+}
+
+template 
+struct A1 {
+  int value; // A1
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for member 'value'
+  // CHECK-FIXES: {{^}}  int Value; // A1
+  int GetValue() const { return value; } // A1
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for method 'GetValue'
+  // CHECK-FIXES {{^}}  int getValue() const { return Value; } // A1
+  void SetValue(int Value) { this->value = Value; } // A1
+  // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: invalid case style for method 'SetValue'
+  // CHECK-FIXES {{^}}  void setValue(int Value) { this->Value = Value; } // A1
+  A1 &operator=(const A1 &Other) {
+this->SetValue(Other.GetValue()); // A1
+this->value = Other.value;// A1
+// CHECK-FIXES:  {{^}}this->setValue(Other.getValue()); // A1
+// CHECK-FIXES-NEXT: {{^}}this->Value = Other.Value;// A1
+return *this;
+  }
+  void outOfLineReset();
+};
+
+template 
+void A1::outOfLineReset() {
+  this->value -= value; // A1
+  // CHECK-FIXES: {{^}}  this->Value -= Value; // A1
+}
+
+template 
+struct A2 {
+  int value; // A2
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: invalid case style for member 'value'
+  // CHECK-FIXES: {{^}}  int Value; // A2
+  A2 &operator=(const A2 &Other) {
+value = Other.value;   // A2
+this->value = Other.value; // A2
+// CHECK-FIXES:  {{^}}Value = Other.Value;   // A2
+// CHECK-FIXES-NEXT: {{^}}this->Value = Other.Value; // A2
+return *this;
+  }
+};
+
+// create some instances to check it works when instantiated.
+A1 AInt{};
+A1 BInt = (AInt.outOfLineReset(), AInt);
+A1 AUnsigned{};
+A1 BUnsigned = AUnsigned;
+} // namespace resolved_dependance
+
+namespace unresolved_dependance {
+template 
+struct DependentBase {
+  int depValue;
+  // CHECK-MESSA

[PATCH] D73439: [ASTMatchers] Add cxxNoexceptExpr AST matcher

2020-01-27 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

{icon check-circle color=green} Unit tests: pass. 62196 tests passed, 0 failed 
and 815 were skipped.

{icon check-circle color=green} clang-tidy: pass.

{icon check-circle color=green} clang-format: pass.

Build artifacts 
: 
diff.json 
,
 clang-tidy.txt 
,
 clang-format.patch 
,
 CMakeCache.txt 
,
 console-log.txt 
,
 test-results.xml 


//Pre-merge checks is in beta. Report issue 
.
 Please join beta  or enable 
it for your project 
.//


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73439



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


[PATCH] D73462: [dwarf-5] Support DebugInfo for Defaulted parameters for C++ templates

2020-01-27 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added inline comments.



Comment at: llvm/include/llvm/IR/DebugInfoMetadata.h:2155
   friend class MDNode;
+  bool isDefault;
 

What about default arguments for non-type template parameters? ("template" etc... )



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73462



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


[clang-tools-extra] 27e3671 - [clang-tidy] readability-identifier-naming disregards parameters restrictions on main like functions

2020-01-27 Thread via cfe-commits

Author: Nathan
Date: 2020-01-27T19:23:21Z
New Revision: 27e3671ff49b72640f89c34a415412e400503442

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

LOG: [clang-tidy] readability-identifier-naming disregards parameters 
restrictions on main like functions

Summary:
Typically most main functions have the signature:
```
int main(int argc, char *argv[])
```
To stick with convention when renaming parameters we should ignore the `argc` 
and `argv` names even if the parameter style says they should be renamed. This 
patch addresses this by checking all ParmVarDecls if they form part of a 
function with a signature that matches main `int name(int argc, char * argv[], 
(optional char *env[]))`

Reviewers: aaron.ballman, JonasToth, alexfh, hokein

Reviewed By: aaron.ballman

Subscribers: Mordante, merge_guards_bot, xazax.hun, kristof.beyls, cfe-commits

Tags: #clang, #clang-tools-extra

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-main-like.cpp

Modified: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h
clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/readability-identifier-naming.rst

clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-member-decl-usage.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index 6a39ece09777..119502e91ffe 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -8,15 +8,13 @@
 
 #include "IdentifierNamingCheck.h"
 
-#include "../utils/ASTUtils.h"
-#include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/AST/CXXInheritance.h"
-#include "clang/Frontend/CompilerInstance.h"
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Format.h"
+#include "llvm/Support/Regex.h"
 
 #define DEBUG_TYPE "clang-tidy"
 
@@ -126,7 +124,9 @@ class IdentifierNamingCheckPPCallbacks : public PPCallbacks 
{
 
 IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
  ClangTidyContext *Context)
-: RenamerClangTidyCheck(Name, Context) {
+: RenamerClangTidyCheck(Name, Context),
+  IgnoreFailedSplit(Options.get("IgnoreFailedSplit", 0)),
+  IgnoreMainLikeFunctions(Options.get("IgnoreMainLikeFunctions", 0)) {
   auto const fromString = [](StringRef Str) {
 return llvm::StringSwitch>(Str)
 .Case("aNy_CasE", CT_AnyCase)
@@ -151,8 +151,6 @@ IdentifierNamingCheck::IdentifierNamingCheck(StringRef Name,
   NamingStyles.push_back(llvm::None);
 }
   }
-
-  IgnoreFailedSplit = Options.get("IgnoreFailedSplit", 0);
 }
 
 IdentifierNamingCheck::~IdentifierNamingCheck() = default;
@@ -193,6 +191,7 @@ void 
IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   }
 
   Options.store(Opts, "IgnoreFailedSplit", IgnoreFailedSplit);
+  Options.store(Opts, "IgnoreMainLikeFunctions", IgnoreMainLikeFunctions);
 }
 
 static bool matchesStyle(StringRef Name,
@@ -324,6 +323,67 @@ static std::string fixupWithCase(StringRef Name,
   return Fixup;
 }
 
+static bool isParamInMainLikeFunction(const ParmVarDecl &ParmDecl,
+  bool IncludeMainLike) {
+  const auto *FDecl =
+  dyn_cast_or_null(ParmDecl.getParentFunctionOrMethod());
+  if (!FDecl)
+return false;
+  if (FDecl->isMain())
+return true;
+  if (!IncludeMainLike)
+return false;
+  if (FDecl->getAccess() != AS_public && FDecl->getAccess() != AS_none)
+return false;
+  enum MainType { None, Main, WMain };
+  auto IsCharPtrPtr = [](QualType QType) -> MainType {
+if (QType.isNull())
+  return None;
+if (QType = QType->getPointeeType(), QType.isNull())
+  return None;
+if (QType = QType->getPointeeType(), QType.isNull())
+  return None;
+if (QType->isCharType())
+  return Main;
+if (QType->isWideCharType())
+  return WMain;
+return None;
+  };
+  auto IsIntType = [](QualType QType) {
+if (QType.isNull())
+  return false;
+if (const auto *Builtin =
+dyn_cast(QType->getUnqualifiedDesugaredType())) {
+  return Builtin->getKind() == BuiltinType::Int;
+}
+return false;
+  };
+  if (!IsIntType(FDecl->getReturnType()))
+return false;
+  if (FDecl->getNumParams() < 2 || FDecl->getNumParams() > 3)

[PATCH] D73453: Preserve -nostdinc and --sysroot when calling query driver

2020-01-27 Thread Tobias Pisani via Phabricator via cfe-commits
topisani updated this revision to Diff 240643.
topisani marked an inline comment as done.
topisani added a comment.

Addressed CR comments

I'm sure about the tests, I basically just added to the one test that already 
exists that it passes one of each "type" of preservable argument.


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

https://reviews.llvm.org/D73453

Files:
  clang-tools-extra/clangd/QueryDriverDatabase.cpp
  clang-tools-extra/clangd/test/system-include-extractor.test

Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -7,6 +7,9 @@
 # %temp_dir%/my/dir2 as include search paths.
 # RUN: echo '#!/bin/bash' >> %t.dir/my_driver.sh
 # RUN: echo '[ "$0" = "%t.dir/my_driver.sh" ] || exit' >> %t.dir/my_driver.sh
+# RUN: echo '[[ " $* " =~ " -nostdinc " ]] || exit' >> %t.dir/my_driver.sh
+# RUN: echo '[[ " $* " =~ " --sysroot /my/sysroot/path " ]] || exit' >> %t.dir/my_driver.sh
+# RUN: echo '[[ " $* " =~ " -isysroot=/isysroot " ]] || exit' >> %t.dir/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/my_driver.sh
 # RUN: echo 'echo -e "#include <...> search starts here:\r" >&2' >> %t.dir/my_driver.sh
 # RUN: echo 'echo %t.dir/my/dir/ >&2' >> %t.dir/my_driver.sh
@@ -22,7 +25,7 @@
 
 # Generate a compile_commands.json that will query the mock driver we've
 # created. Which should add a.h and b.h into include search path.
-# RUN: echo '[{"directory": "%/t.dir", "command": "%/t.dir/my_driver.sh the-file.cpp", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
+# RUN: echo '[{"directory": "%/t.dir", "command": "%/t.dir/my_driver.sh the-file.cpp -nostdinc --sysroot /my/sysroot/path -isysroot=/isysroot", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
 
 # RUN: sed -e "s|INPUT_DIR|%/t.dir|g" %s > %t.test.1
 # On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
Index: clang-tools-extra/clangd/QueryDriverDatabase.cpp
===
--- clang-tools-extra/clangd/QueryDriverDatabase.cpp
+++ clang-tools-extra/clangd/QueryDriverDatabase.cpp
@@ -85,9 +85,10 @@
   return SystemIncludes;
 }
 
-std::vector extractSystemIncludes(PathRef Driver,
-   llvm::StringRef Lang,
-   llvm::Regex &QueryDriverRegex) {
+std::vector
+extractSystemIncludes(PathRef Driver, llvm::StringRef Lang,
+  llvm::ArrayRef CommandLine,
+  llvm::Regex &QueryDriverRegex) {
   trace::Span Tracer("Extract system includes");
   SPAN_ATTACH(Tracer, "driver", Driver);
   SPAN_ATTACH(Tracer, "lang", Lang);
@@ -120,14 +121,37 @@
   llvm::Optional Redirects[] = {
   {""}, {""}, llvm::StringRef(StdErrPath)};
 
-  // Should we also preserve flags like "-sysroot", "-nostdinc" ?
-  const llvm::StringRef Args[] = {Driver, "-E", "-x", Lang, "-", "-v"};
+  llvm::SmallVector Args = {Driver, "-E", "-x",
+ Lang,   "-",  "-v"};
+
+  // These flags will be preserved
+  const llvm::StringRef FlagsToPreserve[] = {
+  "-nostdinc", "--no-standard-includes", "-nostdinc++", "-nobuiltininc"};
+  // This and the following argument will be preserved
+  const llvm::StringRef ArgsToPreserve[] = {"--sysroot", "-isysroot"};
+  // Flags starting with these strings will be preserved
+  const llvm::StringRef FlagPrefixesToPreserve[] = {"--sysroot=", "-isysroot="};
+
+  for (size_t I = 0, E = CommandLine.size(); I < E; ++I) {
+llvm::StringRef Arg = CommandLine[I];
+if (llvm::any_of(FlagsToPreserve, [&Arg](auto &&S) { return S == Arg; })) {
+  Args.push_back(Arg);
+} else if (llvm::any_of(ArgsToPreserve,
+[&Arg](auto &&S) { return S == Arg; }) &&
+   I + 1 < E) {
+  Args.push_back(Arg);
+  Args.push_back(CommandLine[I + 1]);
+} else if (llvm::any_of(FlagPrefixesToPreserve,
+[&Arg](auto &&S) { return Arg.startswith(S); })) {
+  Args.push_back(Arg);
+}
+  }
 
   if (int RC = llvm::sys::ExecuteAndWait(Driver, Args, /*Env=*/llvm::None,
  Redirects)) {
 elog("System include extraction: driver execution failed with return code: "
- "{0}",
- llvm::to_string(RC));
+ "{0}. Args: ['{1}']",
+ llvm::to_string(RC), llvm::join(Args, "', '"));
 return {};
   }
 
@@ -247,8 +271,8 @@
   if (It != DriverToIncludesCache.end())
 SystemIncludes = It->second;
   else
-DriverToIncludesCache[Key] = SystemIncludes =
-extractSystemIncludes(Key.first, Key.second, QueryDriverRegex);
+DriverToIncludesCache[Key] = SystemIncludes = extractSystemIncludes(
+Key.first, Key.

[PATCH] D73062: [analyzer] Simplify BoolAssignmentChecker

2020-01-27 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG88c7b1642079: [analyzer] Simplify BoolAssignmentChecker 
(authored by Mikhail Gadelha ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73062

Files:
  clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp

Index: clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
@@ -70,8 +70,8 @@
   // Get the value of the right-hand side.  We only care about values
   // that are defined (UnknownVals and UndefinedVals are handled by other
   // checkers).
-  Optional DV = val.getAs();
-  if (!DV)
+  Optional NV = val.getAs();
+  if (!NV)
 return;
 
   // Check if the assigned value meets our criteria for correctness.  It must
@@ -79,78 +79,17 @@
   // the value is possibly < 0 (for a negative value) or greater than 1.
   ProgramStateRef state = C.getState();
   SValBuilder &svalBuilder = C.getSValBuilder();
+  BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
   ConstraintManager &CM = C.getConstraintManager();
 
-  // First, ensure that the value is >= 0.
-  DefinedSVal zeroVal = svalBuilder.makeIntVal(0, valTy);
-  SVal greaterThanOrEqualToZeroVal =
-svalBuilder.evalBinOp(state, BO_GE, *DV, zeroVal,
-  svalBuilder.getConditionType());
+  llvm::APSInt Zero = BVF.getValue(0, valTy);
+  llvm::APSInt One = BVF.getValue(1, valTy);
 
-  Optional greaterThanEqualToZero =
-  greaterThanOrEqualToZeroVal.getAs();
+  ProgramStateRef StIn, StOut;
+  std::tie(StIn, StOut) = CM.assumeInclusiveRangeDual(state, *NV, Zero, One);
 
-  if (!greaterThanEqualToZero) {
-// The SValBuilder cannot construct a valid SVal for this condition.
-// This means we cannot properly reason about it.
-return;
-  }
-
-  ProgramStateRef stateLT, stateGE;
-  std::tie(stateGE, stateLT) = CM.assumeDual(state, *greaterThanEqualToZero);
-
-  // Is it possible for the value to be less than zero?
-  if (stateLT) {
-// It is possible for the value to be less than zero.  We only
-// want to emit a warning, however, if that value is fully constrained.
-// If it it possible for the value to be >= 0, then essentially the
-// value is underconstrained and there is nothing left to be done.
-if (!stateGE)
-  emitReport(stateLT, C);
-
-// In either case, we are done.
-return;
-  }
-
-  // If we reach here, it must be the case that the value is constrained
-  // to only be >= 0.
-  assert(stateGE == state);
-
-  // At this point we know that the value is >= 0.
-  // Now check to ensure that the value is <= 1.
-  DefinedSVal OneVal = svalBuilder.makeIntVal(1, valTy);
-  SVal lessThanEqToOneVal =
-svalBuilder.evalBinOp(state, BO_LE, *DV, OneVal,
-  svalBuilder.getConditionType());
-
-  Optional lessThanEqToOne =
-  lessThanEqToOneVal.getAs();
-
-  if (!lessThanEqToOne) {
-// The SValBuilder cannot construct a valid SVal for this condition.
-// This means we cannot properly reason about it.
-return;
-  }
-
-  ProgramStateRef stateGT, stateLE;
-  std::tie(stateLE, stateGT) = CM.assumeDual(state, *lessThanEqToOne);
-
-  // Is it possible for the value to be greater than one?
-  if (stateGT) {
-// It is possible for the value to be greater than one.  We only
-// want to emit a warning, however, if that value is fully constrained.
-// If it is possible for the value to be <= 1, then essentially the
-// value is underconstrained and there is nothing left to be done.
-if (!stateLE)
-  emitReport(stateGT, C);
-
-// In either case, we are done.
-return;
-  }
-
-  // If we reach here, it must be the case that the value is constrained
-  // to only be <= 1.
-  assert(stateLE == state);
+  if (!StIn)
+emitReport(StOut, C);
 }
 
 void ento::registerBoolAssignmentChecker(CheckerManager &mgr) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D73457: [Clang] Warn about 'z' printf modifier in old MSVC.

2020-01-27 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.
This revision is now accepted and ready to land.

LGTM!

In D73457#1842605 , @amccarth wrote:

> In D73457#1842493 , @simon_tatham 
> wrote:
>
> > Removed the special case for `MSCompatibilityVersion == 0`. If the default 
> > compatibility setting needs to be changed, that's a separate piece of work 
> > and should be done by someone who understands more than I do about all 
> > those failing tests :-) The new version of this patch just uses the 
> > existing default.
>
>
> +1.  The issue of how the default version gets set is a separate issue.  I 
> think it's best to keep this patch decoupled from that.


Definitely agreed! I just didn't want to do duplicate work if there was a bug 
elsewhere that would impact how we proceed here.

>> With the typical command line I use with the `clang-cl` driver, a specific 
>> version has been set anyway by the time cc1 is running. So probably I 
>> shouldn't have been worrying in the first place about what happens if there 
>> isn't one set.
> 
> The default you found for MSVC15 is the last result default.  (Though I would 
> have expected that to be MSVC17 by now.)  I believe the driver will actually 
> try to figure out the most recent version of MSVC installed on the machine 
> (assuming it's Windows), and use that.  Only if it can't find one, will it 
> use that default.
> 
> As I recall, this is because clang will still (by default) use the MS runtime 
> libraries for Windows builds, in which case it's important for the 
> compatibility version to match the one for the libraries that are going to be 
> used.  I think we can/should reconsider this when clang-cl starts using 
> different run-time libraries for Windows builds.

Ah, thank you for that context!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73457



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


[PATCH] D73495: [CodeGen] Attach no-builtin attributes to functions with no Decl

2020-01-27 Thread Francis Visoiu Mistrih via Phabricator via cfe-commits
thegameg created this revision.
thegameg added reviewers: gchatelet, tejohnson, aaron.ballman, efriedma.
thegameg added a project: clang.

When using -fno-builtin[-], we don't attach the IR attributes to 
functions with no Decl.

This results in projects using -fno-builtin or -ffreestanding to start seeing 
symbols like _memset_pattern16.

The fix changes the behavior to always add the attribute if LangOptions 
requests it.


https://reviews.llvm.org/D73495

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/test/CodeGenCXX/global-init.cpp

Index: clang/test/CodeGenCXX/global-init.cpp
===
--- clang/test/CodeGenCXX/global-init.cpp
+++ clang/test/CodeGenCXX/global-init.cpp
@@ -2,6 +2,8 @@
 // RUN: %clang_cc1 -triple=x86_64-apple-darwin10 -emit-llvm %s -o - |FileCheck -check-prefix CHECK-NOEXC %s
 // RUN: %clang_cc1 -triple=x86_64-apple-darwin10 -emit-llvm -mframe-pointer=non-leaf %s -o - \
 // RUN:   | FileCheck -check-prefix CHECK-FP %s
+// RUN: %clang_cc1 -triple=x86_64-apple-darwin10 -emit-llvm %s -o - -fno-builtin \
+// RUN:   | FileCheck -check-prefix CHECK-NOBUILTIN %s
 
 struct A {
   A();
@@ -202,9 +204,12 @@
 
 // rdar://problem/8090834: this should be nounwind
 // CHECK-NOEXC: define internal void @_GLOBAL__sub_I_global_init.cpp() [[NUW:#[0-9]+]] section "__TEXT,__StaticInit,regular,pure_instructions" {
-
 // CHECK-NOEXC: attributes [[NUW]] = { noinline nounwind{{.*}} }
 
+// Make sure we mark global initializers with the no-builtins attribute.
+// CHECK-NOBUILTIN: define internal void @_GLOBAL__sub_I_global_init.cpp() [[NUW:#[0-9]+]] section "__TEXT,__StaticInit,regular,pure_instructions" {
+// CHECK-NOBUILTIN: attributes [[NUW]] = { noinline nounwind{{.*}}"no-builtins"{{.*}} }
+
 // PR21811: attach the appropriate attribute to the global init function
 // CHECK-FP: define internal void @_GLOBAL__sub_I_global_init.cpp() [[NUX:#[0-9]+]] section "__TEXT,__StaticInit,regular,pure_instructions" {
 // CHECK-FP: attributes [[NUX]] = { noinline nounwind {{.*}}"frame-pointer"="non-leaf"{{.*}} }
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -1832,6 +1832,43 @@
   F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
 }
 
+static void
+addNonCallSiteNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
+  const LangOptions &LangOpts,
+  const NoBuiltinAttr *NBA = nullptr) {
+  auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
+SmallString<32> AttributeName;
+AttributeName += "no-builtin-";
+AttributeName += BuiltinName;
+FuncAttrs.addAttribute(AttributeName);
+  };
+
+  // First, handle the language options passed through -fno-builtin[-]
+  if (LangOpts.NoBuiltin) {
+// -fno-builtin disables them all.
+FuncAttrs.addAttribute("no-builtins");
+return;
+  }
+
+  // Then, add attributes for builtins specified through -fno-builtin-.
+  llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
+
+  // Now, let's check the __attribute__((no_builtin("...")) attribute added to
+  // the source.
+  if (!NBA)
+return;
+
+  // If there is a wildcard in the builtin names specified through the
+  // attribute, disable them all.
+  if (llvm::is_contained(NBA->builtinNames(), "*")) {
+FuncAttrs.addAttribute("no-builtins");
+return;
+  }
+
+  // And last, add the rest of the builtin names.
+  llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
+}
+
 void CodeGenModule::ConstructAttributeList(
 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo,
 llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) {
@@ -1877,20 +1914,7 @@
   FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
 
 const auto *NBA = Fn->getAttr();
-bool HasWildcard = NBA && llvm::is_contained(NBA->builtinNames(), "*");
-if (getLangOpts().NoBuiltin || HasWildcard)
-  FuncAttrs.addAttribute("no-builtins");
-else {
-  auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
-SmallString<32> AttributeName;
-AttributeName += "no-builtin-";
-AttributeName += BuiltinName;
-FuncAttrs.addAttribute(AttributeName);
-  };
-  llvm::for_each(getLangOpts().NoBuiltinFuncs, AddNoBuiltinAttr);
-  if (NBA)
-llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
-}
+addNonCallSiteNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
   }
 }
 
@@ -1923,6 +1947,10 @@
   FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
  NumElemsParam);
 }
+  } else {
+// If there is no TargetDecl, we still want to attach the attributes to
+// functions that are compiler-generated, like static initializers.
+add

[clang] 88c7b16 - [analyzer] Simplify BoolAssignmentChecker

2020-01-27 Thread Mikhail Gadelha via cfe-commits

Author: Mikhail Gadelha
Date: 2020-01-27T14:51:35-04:00
New Revision: 88c7b1642079439a73b4d7a6e57e67347f574a15

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

LOG: [analyzer] Simplify BoolAssignmentChecker

Summary:
Instead of checking the range manually, changed the checker to use 
assumeInclusiveRangeDual instead.

This patch was part of D28955.

Reviewers: NoQ

Reviewed By: NoQ

Subscribers: ddcc, xazax.hun, baloghadamsoftware, szepet, a.sidorin, Szelethus, 
donat.nagy, dkrupp, Charusso, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
index 1423b9c39b26..a64b1213ba29 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BoolAssignmentChecker.cpp
@@ -70,8 +70,8 @@ void BoolAssignmentChecker::checkBind(SVal loc, SVal val, 
const Stmt *S,
   // Get the value of the right-hand side.  We only care about values
   // that are defined (UnknownVals and UndefinedVals are handled by other
   // checkers).
-  Optional DV = val.getAs();
-  if (!DV)
+  Optional NV = val.getAs();
+  if (!NV)
 return;
 
   // Check if the assigned value meets our criteria for correctness.  It must
@@ -79,78 +79,17 @@ void BoolAssignmentChecker::checkBind(SVal loc, SVal val, 
const Stmt *S,
   // the value is possibly < 0 (for a negative value) or greater than 1.
   ProgramStateRef state = C.getState();
   SValBuilder &svalBuilder = C.getSValBuilder();
+  BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
   ConstraintManager &CM = C.getConstraintManager();
 
-  // First, ensure that the value is >= 0.
-  DefinedSVal zeroVal = svalBuilder.makeIntVal(0, valTy);
-  SVal greaterThanOrEqualToZeroVal =
-svalBuilder.evalBinOp(state, BO_GE, *DV, zeroVal,
-  svalBuilder.getConditionType());
+  llvm::APSInt Zero = BVF.getValue(0, valTy);
+  llvm::APSInt One = BVF.getValue(1, valTy);
 
-  Optional greaterThanEqualToZero =
-  greaterThanOrEqualToZeroVal.getAs();
+  ProgramStateRef StIn, StOut;
+  std::tie(StIn, StOut) = CM.assumeInclusiveRangeDual(state, *NV, Zero, One);
 
-  if (!greaterThanEqualToZero) {
-// The SValBuilder cannot construct a valid SVal for this condition.
-// This means we cannot properly reason about it.
-return;
-  }
-
-  ProgramStateRef stateLT, stateGE;
-  std::tie(stateGE, stateLT) = CM.assumeDual(state, *greaterThanEqualToZero);
-
-  // Is it possible for the value to be less than zero?
-  if (stateLT) {
-// It is possible for the value to be less than zero.  We only
-// want to emit a warning, however, if that value is fully constrained.
-// If it it possible for the value to be >= 0, then essentially the
-// value is underconstrained and there is nothing left to be done.
-if (!stateGE)
-  emitReport(stateLT, C);
-
-// In either case, we are done.
-return;
-  }
-
-  // If we reach here, it must be the case that the value is constrained
-  // to only be >= 0.
-  assert(stateGE == state);
-
-  // At this point we know that the value is >= 0.
-  // Now check to ensure that the value is <= 1.
-  DefinedSVal OneVal = svalBuilder.makeIntVal(1, valTy);
-  SVal lessThanEqToOneVal =
-svalBuilder.evalBinOp(state, BO_LE, *DV, OneVal,
-  svalBuilder.getConditionType());
-
-  Optional lessThanEqToOne =
-  lessThanEqToOneVal.getAs();
-
-  if (!lessThanEqToOne) {
-// The SValBuilder cannot construct a valid SVal for this condition.
-// This means we cannot properly reason about it.
-return;
-  }
-
-  ProgramStateRef stateGT, stateLE;
-  std::tie(stateLE, stateGT) = CM.assumeDual(state, *lessThanEqToOne);
-
-  // Is it possible for the value to be greater than one?
-  if (stateGT) {
-// It is possible for the value to be greater than one.  We only
-// want to emit a warning, however, if that value is fully constrained.
-// If it is possible for the value to be <= 1, then essentially the
-// value is underconstrained and there is nothing left to be done.
-if (!stateLE)
-  emitReport(stateGT, C);
-
-// In either case, we are done.
-return;
-  }
-
-  // If we reach here, it must be the case that the value is constrained
-  // to only be <= 1.
-  assert(stateLE == state);
+  if (!StIn)
+emitReport(StOut, C);
 }
 
 void ento::registerBoolAssignmentChecker(CheckerManager &mgr) {



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

[PATCH] D73439: [ASTMatchers] Add cxxNoexceptExpr AST matcher

2020-01-27 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 240640.
njames93 added a comment.

- Tweak documentation


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73439

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

Index: clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
===
--- clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
+++ clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp
@@ -679,6 +679,16 @@
   cxxDeleteExpr()));
 }
 
+TEST(Matcher, NoexceptExpression) {
+  StatementMatcher NoExcept = cxxNoexceptExpr();
+  EXPECT_TRUE(matches("void foo(); bool bar = noexcept(foo());", NoExcept));
+  EXPECT_TRUE(
+  matches("void foo() noexcept; bool bar = noexcept(foo());", NoExcept));
+  EXPECT_TRUE(notMatches("void foo() noexcept;", NoExcept));
+  EXPECT_TRUE(notMatches("void foo() noexcept(1+1);", NoExcept));
+  EXPECT_TRUE(matches("void foo() noexcept(noexcept(1+1));", NoExcept));
+}
+
 TEST(Matcher, DefaultArgument) {
   StatementMatcher Arg = cxxDefaultArgExpr();
 
Index: clang/lib/Analysis/ExprMutationAnalyzer.cpp
===
--- clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -43,9 +43,6 @@
   return Node.isPotentiallyEvaluated();
 }
 
-const ast_matchers::internal::VariadicDynCastAllOfMatcher
-cxxNoexceptExpr;
-
 const ast_matchers::internal::VariadicDynCastAllOfMatcher
 genericSelectionExpr;
Index: clang/lib/ASTMatchers/Dynamic/Registry.cpp
===
--- clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -183,6 +183,7 @@
   REGISTER_MATCHER(cxxMemberCallExpr);
   REGISTER_MATCHER(cxxMethodDecl);
   REGISTER_MATCHER(cxxNewExpr);
+  REGISTER_MATCHER(cxxNoexceptExpr);
   REGISTER_MATCHER(cxxNullPtrLiteralExpr);
   REGISTER_MATCHER(cxxOperatorCallExpr);
   REGISTER_MATCHER(cxxRecordDecl);
Index: clang/lib/ASTMatchers/ASTMatchersInternal.cpp
===
--- clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -730,6 +730,8 @@
 materializeTemporaryExpr;
 const internal::VariadicDynCastAllOfMatcher cxxNewExpr;
 const internal::VariadicDynCastAllOfMatcher cxxDeleteExpr;
+const internal::VariadicDynCastAllOfMatcher
+cxxNoexceptExpr;
 const internal::VariadicDynCastAllOfMatcher
 arraySubscriptExpr;
 const internal::VariadicDynCastAllOfMatcher
Index: clang/include/clang/ASTMatchers/ASTMatchers.h
===
--- clang/include/clang/ASTMatchers/ASTMatchers.h
+++ clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -1824,6 +1824,22 @@
 extern const internal::VariadicDynCastAllOfMatcher
 cxxDeleteExpr;
 
+/// Matches noexcept expressions.
+///
+/// Given
+/// \code
+///   bool a() noexcept;
+///   bool b() noexcept(true);
+///   bool c() noexcept(false);
+///   bool d() noexcept(noexcept(a()));
+///   bool e = noexcept(b()) || noexcept(c());
+/// \endcode
+/// cxxNoexceptExpr()
+///   matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
+///   doesn't match the noexcept specifier in the declarations a, b, c or d.
+extern const internal::VariadicDynCastAllOfMatcher
+cxxNoexceptExpr;
+
 /// Matches array subscript expressions.
 ///
 /// Given
Index: clang/docs/LibASTMatchersReference.html
===
--- clang/docs/LibASTMatchersReference.html
+++ clang/docs/LibASTMatchersReference.html
@@ -1003,6 +1003,21 @@
 
 
 
+MatcherStmt>cxxNoexceptExprMatcherCXXNoexceptExpr>...
+Matches noexcept expressions.
+
+Given
+  bool a() noexcept;
+  bool b() noexcept(true);
+  bool c() noexcept(false);
+  bool d() noexcept(noexcept(a()));
+  bool e = noexcept(b()) || noexcept(c());
+cxxNoexceptExpr()
+  matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
+  doesn't match the noexcept specifier in the declarations a, b, c or d.
+
+
+
 MatcherStmt>cxxNullPtrLiteralExprMatcherCXXNullPtrLiteralExpr>...
 Matches nullptr literal.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D72841: [RFC] Add support for pragma float_control, to control precision and exception behavior at the source level

2020-01-27 Thread Melanie Blower via Phabricator via cfe-commits
mibintc updated this revision to Diff 240638.
mibintc added a comment.

rebase per @sepavloff request


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72841

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Basic/PragmaKinds.h
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CodeGen/fp-floatcontrol-class.cpp
  clang/test/CodeGen/fp-floatcontrol-pragma.cpp
  clang/test/CodeGen/fp-floatcontrol-stack.cpp
  clang/test/Parser/fp-floatcontrol-syntax.cpp
  llvm/include/llvm/IR/IRBuilder.h

Index: llvm/include/llvm/IR/IRBuilder.h
===
--- llvm/include/llvm/IR/IRBuilder.h
+++ llvm/include/llvm/IR/IRBuilder.h
@@ -299,10 +299,16 @@
 IRBuilderBase &Builder;
 FastMathFlags FMF;
 MDNode *FPMathTag;
+bool IsFPConstrained;
+fp::ExceptionBehavior DefaultConstrainedExcept;
+fp::RoundingMode DefaultConstrainedRounding;
 
   public:
 FastMathFlagGuard(IRBuilderBase &B)
-: Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
+: Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag),
+  IsFPConstrained(B.IsFPConstrained),
+  DefaultConstrainedExcept(B.DefaultConstrainedExcept),
+  DefaultConstrainedRounding(B.DefaultConstrainedRounding) {}
 
 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
 FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
@@ -310,6 +316,9 @@
 ~FastMathFlagGuard() {
   Builder.FMF = FMF;
   Builder.DefaultFPMathTag = FPMathTag;
+  Builder.IsFPConstrained = IsFPConstrained;
+  Builder.DefaultConstrainedExcept = DefaultConstrainedExcept;
+  Builder.DefaultConstrainedRounding = DefaultConstrainedRounding;
 }
   };
 
Index: clang/test/Parser/fp-floatcontrol-syntax.cpp
===
--- /dev/null
+++ clang/test/Parser/fp-floatcontrol-syntax.cpp
@@ -0,0 +1,25 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -DCHECK_ERROR %s
+// XFAIL: *
+
+float function_scope(float a) {
+  return a;
+}
+
+// There seems to be a bug in Actions.CurContext->isTranslationUnit()
+// unless this dummy class is used. FIXME Fix the issue then remove this
+// workaround.
+#define TU_WORKAROUND
+#ifdef TU_WORKAROUND
+class ResetTUScope;
+#endif
+#ifdef CHECK_ERROR
+#  pragma float_control(push)
+#  pragma float_control(pop)
+#  pragma float_control(precise,on,push)
+void check_stack() {
+#pragma float_control(push) // expected-error {{can only appear at file scope}}
+#pragma float_control(pop) // expected-error {{can only appear at file scope}}
+#pragma float_control(precise,on,push) // expected-error {{can only appear at file scope}}
+  return;
+}
+#endif
Index: clang/test/CodeGen/fp-floatcontrol-stack.cpp
===
--- /dev/null
+++ clang/test/CodeGen/fp-floatcontrol-stack.cpp
@@ -0,0 +1,171 @@
+// RUN: %clang_cc1 -DDEFAULT=1 -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-DDEFAULT %s
+// RUN: %clang_cc1 -DEBSTRICT=1 -ffp-exception-behavior=strict -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-DEBSTRICT %s
+
+#define FUN(n) (float z) { return n * z + n; }
+
+float fun_default FUN(1)
+//CHECK-LABEL: define {{.*}} @_Z11fun_defaultf{{.*}}
+#if DEFAULT
+//CHECK-DDEFAULT: fmul float
+//CHECK-DDEFAULT: fadd float
+#endif
+#if EBSTRICT
+// Note that backend wants constrained intrinsics used "everywhere"
+// if they have been requested on the command line, so fp operations
+// will be built with constrained intrinsics and default settings
+// for exception behavior and rounding mode.
+//CHECK-DEBSTRICT: llvm.experimental.constrained.fmul{{.*}}tonearest{{.*}}strict
+#endif
+class ResetScope;
+
+#pragma float_control(except, on, push)
+float exc_on FUN(2)
+//CHECK-LABEL: define {{.*}} @_Z6exc_onf{{.*}}
+#if DEFAULT
+//CHECK-DDEFAULT: llvm.experimental.constrained.fmul{{.*}}
+#endif
+#if EBSTRICT
+//CHECK-DEBSTRICT: llvm.experimental.constrained.fmul{{.*}}tonearest{{.*}}strict
+#endif
+
+class ResetScope;
+#pragma float_control(pop)
+float exc_pop FUN(5)
+//CHECK-LABEL: define {{.*}} @_Z7exc_popf{{.*}}
+#if DEFAULT
+//CHECK-DDEFAULT: fmul float
+//CHECK-DDEFAULT: fadd float
+#endif
+#if EBSTRICT
+//CHECK-DEBSTRICT: llvm.experimental.constrained.fmul{{.*}}tonearest{{.*}}strict
+#endif
+
+class ResetScope;
+#pragma float_control(except, off)
+float exc_off FUN(5

[PATCH] D73457: [Clang] Warn about 'z' printf modifier in old MSVC.

2020-01-27 Thread Adrian McCarthy via Phabricator via cfe-commits
amccarth added a comment.

In D73457#1842493 , @simon_tatham 
wrote:

> Removed the special case for `MSCompatibilityVersion == 0`. If the default 
> compatibility setting needs to be changed, that's a separate piece of work 
> and should be done by someone who understands more than I do about all those 
> failing tests :-) The new version of this patch just uses the existing 
> default.


+1.  The issue of how the default version gets set is a separate issue.  I 
think it's best to keep this patch decoupled from that.

> With the typical command line I use with the `clang-cl` driver, a specific 
> version has been set anyway by the time cc1 is running. So probably I 
> shouldn't have been worrying in the first place about what happens if there 
> isn't one set.

The default you found for MSVC15 is the last result default.  (Though I would 
have expected that to be MSVC17 by now.)  I believe the driver will actually 
try to figure out the most recent version of MSVC installed on the machine 
(assuming it's Windows), and use that.  Only if it can't find one, will it use 
that default.

As I recall, this is because clang will still (by default) use the MS runtime 
libraries for Windows builds, in which case it's important for the 
compatibility version to match the one for the libraries that are going to be 
used.  I think we can/should reconsider this when clang-cl starts using 
different run-time libraries for Windows builds.

I'm not officially a reviewer on this patch, but LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73457



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


[PATCH] D73462: [dwarf-5] Support DebugInfo for Defaulted parameters for C++ templates

2020-01-27 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.
Herald added a subscriber: ormris.

Can you add a bitcode roundtrip test to test/Assembler?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73462



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


[PATCH] D73413: [clang-tidy] Add check to detect external definitions with no header declaration

2020-01-27 Thread pre-merge checks [bot] via Phabricator via cfe-commits
merge_guards_bot added a comment.

{icon check-circle color=green} Unit tests: pass. 62197 tests passed, 0 failed 
and 815 were skipped.

{icon times-circle color=red} clang-tidy: fail. clang-tidy found 0 errors and 1 
warnings 
.
 0 of them are added as review comments below (why? 
).

{icon check-circle color=green} clang-format: pass.

Build artifacts 
: 
diff.json 
,
 clang-tidy.txt 
,
 clang-format.patch 
,
 CMakeCache.txt 
,
 console-log.txt 
,
 test-results.xml 


//Pre-merge checks is in beta. Report issue 
.
 Please join beta  or enable 
it for your project 
.//


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73413



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


[PATCH] D73151: [analyzer] Fix handle leak false positive when the handle dies too early

2020-01-27 Thread Gábor Horváth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc98d98ba9b0f: [analyzer] Fix handle leak false positive when 
the handle dies too early (authored by xazax.hun).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D73151

Files:
  clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
  clang/test/Analysis/fuchsia_handle.cpp


Index: clang/test/Analysis/fuchsia_handle.cpp
===
--- clang/test/Analysis/fuchsia_handle.cpp
+++ clang/test/Analysis/fuchsia_handle.cpp
@@ -66,6 +66,26 @@
 zx_handle_close(sa);
 }
 
+void handleDieBeforeErrorSymbol01() {
+  zx_handle_t sa, sb;
+  zx_status_t status = zx_channel_create(0, &sa, &sb);
+  if (status < 0)
+return;
+  __builtin_trap();
+}
+
+void handleDieBeforeErrorSymbol02() {
+  zx_handle_t sa, sb;
+  zx_status_t status = zx_channel_create(0, &sa, &sb);
+  // expected-note@-1 {{Handle allocated through 2nd parameter}}
+  if (status == 0) { // expected-note {{Assuming 'status' is equal to 0}}
+ // expected-note@-1 {{Taking true branch}}
+return; // expected-warning {{Potential leak of handle}}
+// expected-note@-1 {{Potential leak of handle}}
+  }
+  __builtin_trap();
+}
+
 void checkNoCrash01() {
   zx_handle_t sa, sb;
   zx_channel_create(0, &sa, &sb);
Index: clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
@@ -149,6 +149,10 @@
   CASE(Kind::Released)
   CASE(Kind::Escaped)
 }
+if (ErrorSym) {
+  OS << " ErrorSym: ";
+  ErrorSym->dumpToStream(OS);
+}
   }
 
   LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
@@ -401,7 +405,13 @@
   SmallVector LeakedSyms;
   HStateMapTy TrackedHandles = State->get();
   for (auto &CurItem : TrackedHandles) {
-if (!SymReaper.isDead(CurItem.first))
+SymbolRef ErrorSym = CurItem.second.getErrorSym();
+// Keeping zombie handle symbols. In case the error symbol is dying later
+// than the handle symbol we might produce spurious leak warnings (in case
+// we find out later from the status code that the handle allocation failed
+// in the first place).
+if (!SymReaper.isDead(CurItem.first) ||
+(ErrorSym && !SymReaper.isDead(ErrorSym)))
   continue;
 if (CurItem.second.isAllocated() || CurItem.second.maybeAllocated())
   LeakedSyms.push_back(CurItem.first);


Index: clang/test/Analysis/fuchsia_handle.cpp
===
--- clang/test/Analysis/fuchsia_handle.cpp
+++ clang/test/Analysis/fuchsia_handle.cpp
@@ -66,6 +66,26 @@
 zx_handle_close(sa);
 }
 
+void handleDieBeforeErrorSymbol01() {
+  zx_handle_t sa, sb;
+  zx_status_t status = zx_channel_create(0, &sa, &sb);
+  if (status < 0)
+return;
+  __builtin_trap();
+}
+
+void handleDieBeforeErrorSymbol02() {
+  zx_handle_t sa, sb;
+  zx_status_t status = zx_channel_create(0, &sa, &sb);
+  // expected-note@-1 {{Handle allocated through 2nd parameter}}
+  if (status == 0) { // expected-note {{Assuming 'status' is equal to 0}}
+ // expected-note@-1 {{Taking true branch}}
+return; // expected-warning {{Potential leak of handle}}
+// expected-note@-1 {{Potential leak of handle}}
+  }
+  __builtin_trap();
+}
+
 void checkNoCrash01() {
   zx_handle_t sa, sb;
   zx_channel_create(0, &sa, &sb);
Index: clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/FuchsiaHandleChecker.cpp
@@ -149,6 +149,10 @@
   CASE(Kind::Released)
   CASE(Kind::Escaped)
 }
+if (ErrorSym) {
+  OS << " ErrorSym: ";
+  ErrorSym->dumpToStream(OS);
+}
   }
 
   LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
@@ -401,7 +405,13 @@
   SmallVector LeakedSyms;
   HStateMapTy TrackedHandles = State->get();
   for (auto &CurItem : TrackedHandles) {
-if (!SymReaper.isDead(CurItem.first))
+SymbolRef ErrorSym = CurItem.second.getErrorSym();
+// Keeping zombie handle symbols. In case the error symbol is dying later
+// than the handle symbol we might produce spurious leak warnings (in case
+// we find out later from the status code that the handle allocation failed
+// in the first place).
+if (!SymReaper.isDead(CurItem.first) ||
+(ErrorSym && !SymReaper.isDead(ErrorSym)))
   continue;
 if (CurItem.second.isAllocated() || CurItem.second.maybeAllocated())
   LeakedSyms.push_back(CurItem.first);
___
cfe-commits mailing list
cfe-commits@li

  1   2   3   >