[PATCH] D37925: Allow specifying sanitizers in blacklists

2017-09-21 Thread Dean Michael Berris via Phabricator via cfe-commits
dberris added inline comments.



Comment at: lib/Basic/XRayLists.cpp:29
   // whether it's treated as a "never" instrument function.
-  if (AlwaysInstrument->inSection("fun", FunctionName, "arg1"))
+  if (AlwaysInstrument->inSection("xray_always_instrument", "fun", 
FunctionName,
+  "arg1"))

vlad.tsyrklevich wrote:
> eugenis wrote:
> > It feels redundant to have AlwaysInstrument and NeverInstrument lists, and 
> > then the same distinction in section names. Maybe sections could be named 
> > "xray" in  both cases? Or, better, the lists could be merged into a single 
> > list with always and never sections? There is also an issue of backward 
> > compatibility. Anyway, that's for xray devs to decide. @dberris 
> I chose this approach for backwards compatibility, but I'd defer to what 
> @dberris thinks is best.
Sorry for being late here.

I'm fine with keeping this as-is, then merging the lists into a single one. At 
the time this was designed/implemented, I hadn't thought about whether we could 
have used a single list. At the time it made sense to separate the always/never 
lists and applied in a set order (always wins over never).

If this is all-new functionality anyway, I'd think using "xray" as the section 
header and then using per-entry "always" and "never" identifiers/sections make 
sense.

If you leave a TODO here (and/or file a bug on XRay) I can do the migration to 
a single list later. I'm fine with how this is set as-is.


https://reviews.llvm.org/D37925



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


[PATCH] D37263: [clang-format] Ignore case and stable sort using-declarations

2017-09-21 Thread Krasimir Georgiev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL313963: [clang-format] Ignore case and stable sort 
using-declarations (authored by krasimir).

Repository:
  rL LLVM

https://reviews.llvm.org/D37263

Files:
  cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
  cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp

Index: cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
===
--- cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
+++ cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
@@ -34,7 +34,7 @@
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration ) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 
@@ -78,7 +78,8 @@
 const SourceManager , tooling::Replacements *Fixes) {
   SmallVector SortedUsingDeclarations(
   UsingDeclarations->begin(), UsingDeclarations->end());
-  std::sort(SortedUsingDeclarations.begin(), SortedUsingDeclarations.end());
+  std::stable_sort(SortedUsingDeclarations.begin(),
+   SortedUsingDeclarations.end());
   for (size_t I = 0, E = UsingDeclarations->size(); I < E; ++I) {
 if ((*UsingDeclarations)[I].Line == SortedUsingDeclarations[I].Line)
   continue;
Index: cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
===
--- cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
+++ cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
@@ -86,6 +86,77 @@
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using A;",
+sortUsingDeclarations("using a;\n"
+  "using A;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
+TEST_F(UsingDeclarationsSorterTest, SortsStably) {
+  EXPECT_EQ("using a;\n"
+"using a;\n"
+"using A;\n"
+"using a;\n"
+"using A;\n"
+"using a;\n"
+"using A;\n"
+"using a;\n"
+"using B;\n"
+"using b;\n"
+"using b;\n"
+"using B;\n"
+"using b;\n"
+"using b;\n"
+"using b;\n"
+"using B;\n"
+"using b;",
+sortUsingDeclarations("using a;\n"
+  "using B;\n"
+  "using a;\n"
+  "using b;\n"
+  "using A;\n"
+  "using a;\n"
+  "using b;\n"
+  "using B;\n"
+  "using b;\n"
+  "using A;\n"
+  "using a;\n"
+  "using b;\n"
+  "using b;\n"
+  "using B;\n"
+  "using b;\n"
+  "using A;\n"
+  "using a;"));
+}
+
 TEST_F(UsingDeclarationsSorterTest, SortsMultipleTopLevelDeclarations) {
   EXPECT_EQ("using a;\n"
 "using b;\n"
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r313963 - [clang-format] Ignore case and stable sort using-declarations

2017-09-21 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Sep 21 21:48:17 2017
New Revision: 313963

URL: http://llvm.org/viewvc/llvm-project?rev=313963=rev
Log:
[clang-format] Ignore case and stable sort using-declarations

Summary:
This ignores case while sorting using-declarations, fixing a case where `_` 
would appear between lowercase and uppercase characters.
It also applies stable sort, so that replacements for the exact same using 
declarations are not generated.

Reviewers: klimek, alexfh

Reviewed By: alexfh

Subscribers: cfe-commits

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

Modified:
cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp

Modified: cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp?rev=313963=313962=313963=diff
==
--- cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp (original)
+++ cfe/trunk/lib/Format/UsingDeclarationsSorter.cpp Thu Sep 21 21:48:17 2017
@@ -34,7 +34,7 @@ struct UsingDeclaration {
   : Line(Line), Label(Label) {}
 
   bool operator<(const UsingDeclaration ) const {
-return Label < Other.Label;
+return StringRef(Label).compare_lower(Other.Label) < 0;
   }
 };
 
@@ -78,7 +78,8 @@ void endUsingDeclarationBlock(
 const SourceManager , tooling::Replacements *Fixes) {
   SmallVector SortedUsingDeclarations(
   UsingDeclarations->begin(), UsingDeclarations->end());
-  std::sort(SortedUsingDeclarations.begin(), SortedUsingDeclarations.end());
+  std::stable_sort(SortedUsingDeclarations.begin(),
+   SortedUsingDeclarations.end());
   for (size_t I = 0, E = UsingDeclarations->size(); I < E; ++I) {
 if ((*UsingDeclarations)[I].Line == SortedUsingDeclarations[I].Line)
   continue;

Modified: cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp?rev=313963=313962=313963=diff
==
--- cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp (original)
+++ cfe/trunk/unittests/Format/UsingDeclarationsSorterTest.cpp Thu Sep 21 
21:48:17 2017
@@ -86,6 +86,77 @@ TEST_F(UsingDeclarationsSorterTest, Swap
   "using a, b;"));
 }
 
+TEST_F(UsingDeclarationsSorterTest, SortsCaseInsensitively) {
+  EXPECT_EQ("using A;\n"
+"using a;",
+sortUsingDeclarations("using A;\n"
+  "using a;"));
+  EXPECT_EQ("using a;\n"
+"using A;",
+sortUsingDeclarations("using a;\n"
+  "using A;"));
+  EXPECT_EQ("using a;\n"
+"using B;",
+sortUsingDeclarations("using B;\n"
+  "using a;"));
+  EXPECT_EQ("using _;\n"
+"using a;",
+sortUsingDeclarations("using a;\n"
+  "using _;"));
+  EXPECT_EQ("using a::_;\n"
+"using a::a;",
+sortUsingDeclarations("using a::a;\n"
+  "using a::_;"));
+
+  EXPECT_EQ("using ::testing::_;\n"
+"using ::testing::Aardvark;\n"
+"using ::testing::apple::Honeycrisp;\n"
+"using ::testing::Xylophone;\n"
+"using ::testing::zebra::Stripes;",
+sortUsingDeclarations("using ::testing::Aardvark;\n"
+  "using ::testing::Xylophone;\n"
+  "using ::testing::_;\n"
+  "using ::testing::apple::Honeycrisp;\n"
+  "using ::testing::zebra::Stripes;"));
+}
+
+TEST_F(UsingDeclarationsSorterTest, SortsStably) {
+  EXPECT_EQ("using a;\n"
+"using a;\n"
+"using A;\n"
+"using a;\n"
+"using A;\n"
+"using a;\n"
+"using A;\n"
+"using a;\n"
+"using B;\n"
+"using b;\n"
+"using b;\n"
+"using B;\n"
+"using b;\n"
+"using b;\n"
+"using b;\n"
+"using B;\n"
+"using b;",
+sortUsingDeclarations("using a;\n"
+  "using B;\n"
+  "using a;\n"
+  "using b;\n"
+  "using A;\n"
+  "using a;\n"
+  "using b;\n"
+  "using B;\n"
+  "using b;\n"
+  "using A;\n"
+  "using a;\n"
+  "using b;\n"
+  "using b;\n"
+

r313957 - Closure types have no name (and can't have a typedef name for linkage

2017-09-21 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Thu Sep 21 21:33:20 2017
New Revision: 313957

URL: http://llvm.org/viewvc/llvm-project?rev=313957=rev
Log:
Closure types have no name (and can't have a typedef name for linkage
purposes), so they never formally have linkage.

Modified:
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/test/CXX/basic/basic.link/p8.cpp

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=313957=313956=313957=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Thu Sep 21 21:33:20 2017
@@ -1104,24 +1104,25 @@ LinkageInfo LinkageComputer::getLVForClo
   else
 Owner = cast(ContextDecl);
 
-  // FIXME: If there is no owner, the closure should have no linkage.
   if (!Owner)
-return LinkageInfo::external();
+return LinkageInfo::none();
 
   // If the owner has a deduced type, we need to skip querying the linkage and
   // visibility of that type, because it might involve this closure type.  The
   // only effect of this is that we might give a lambda VisibleNoLinkage rather
   // than NoLinkage when we don't strictly need to, which is benign.
   auto *VD = dyn_cast(Owner);
-  LinkageInfo OwnerLinkage =
+  LinkageInfo OwnerLV =
   VD && VD->getType()->getContainedDeducedType()
   ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
   : getLVForDecl(Owner, computation);
 
-  // FIXME: This is wrong. A lambda never formally has linkage; if this
-  // calculation determines a lambda has external linkage, it should be
-  // downgraded to VisibleNoLinkage.
-  return OwnerLinkage;
+  // A lambda never formally has linkage. But if the owner is externally
+  // visible, then the lambda is too. We apply the same rules to blocks.
+  if (!isExternallyVisible(OwnerLV.getLinkage()))
+return LinkageInfo::none();
+  return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
+ OwnerLV.isVisibilityExplicit());
 }
 
 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,

Modified: cfe/trunk/test/CXX/basic/basic.link/p8.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/basic/basic.link/p8.cpp?rev=313957=313956=313957=diff
==
--- cfe/trunk/test/CXX/basic/basic.link/p8.cpp (original)
+++ cfe/trunk/test/CXX/basic/basic.link/p8.cpp Thu Sep 21 21:33:20 2017
@@ -14,7 +14,7 @@ typedef decltype(f()) NoLinkage3;
 inline auto g() { return [] {}; }
 typedef decltype(g()) VisibleNoLinkage1;
 inline auto y = [] {};
-typedef decltype(x) VisibleNoLinkage2;
+typedef decltype(y) VisibleNoLinkage2;
 inline auto h() { struct {} x; return x; }
 typedef decltype(h()) VisibleNoLinkage3;
 
@@ -42,19 +42,12 @@ void use_no_linkage() {
   no_linkage3(); // expected-note {{used here}}
 }
 
-// FIXME: This should emit an extension warning. It does not because we
-// incorrectly give the lambda external linkage.
-extern VisibleNoLinkage1 visible_no_linkage1();
-
-// FIXME: We should accept this as an extension. We don't because we
-// incorrectly give the lambda no linkage instead of "VisibleNoLinkage".
-extern VisibleNoLinkage2 visible_no_linkage2(); // expected-error {{used but 
not defined}}
-
-// This case is correctly accepted as an extension.
+extern VisibleNoLinkage1 visible_no_linkage1(); // expected-warning {{ISO C++ 
requires a definition}}
+extern VisibleNoLinkage2 visible_no_linkage2(); // expected-warning {{ISO C++ 
requires a definition}}
 extern VisibleNoLinkage3 visible_no_linkage3(); // expected-warning {{ISO C++ 
requires a definition}}
 
 void use_visible_no_linkage() {
-  visible_no_linkage1();
+  visible_no_linkage1(); // expected-note {{used here}}
   visible_no_linkage2(); // expected-note {{used here}}
   visible_no_linkage3(); // expected-note {{used here}}
 }


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


[clang-tools-extra] r313962 - [clang-tidy] Fix example in documentation, NFC

2017-09-21 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Sep 21 21:37:56 2017
New Revision: 313962

URL: http://llvm.org/viewvc/llvm-project?rev=313962=rev
Log:
[clang-tidy] Fix example in documentation, NFC

Summary: A fix in documentation.

Reviewers: bkramer

Reviewed By: bkramer

Subscribers: JDevlieghere, xazax.hun

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

Modified:

clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-replace-random-shuffle.rst

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-replace-random-shuffle.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-replace-random-shuffle.rst?rev=313962=313961=313962=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-replace-random-shuffle.rst
 (original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-replace-random-shuffle.rst
 Thu Sep 21 21:37:56 2017
@@ -15,7 +15,7 @@ Below are two examples of what kind of o
   std::random_shuffle(vec.begin(), vec.end());
 
   // Second example
-  std::random_shuffle(vec.begin(), vec.end(), randomFun);
+  std::random_shuffle(vec.begin(), vec.end(), randomFunc);
 
 Both of these examples will be replaced with:
 


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


r313955 - Give external linkage and mangling to lambdas inside inline variables and variable templates.

2017-09-21 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Thu Sep 21 21:25:05 2017
New Revision: 313955

URL: http://llvm.org/viewvc/llvm-project?rev=313955=rev
Log:
Give external linkage and mangling to lambdas inside inline variables and 
variable templates.

This implements the proposed approach in 
https://github.com/itanium-cxx-abi/cxx-abi/issues/33

This reinstates r313827, reverted in r313856, with a fix for the 'out-of-bounds
enumeration value' ubsan error in that change.

Modified:
cfe/trunk/lib/AST/Decl.cpp
cfe/trunk/lib/AST/ItaniumMangle.cpp
cfe/trunk/lib/AST/Linkage.h
cfe/trunk/lib/Parse/ParseDecl.cpp
cfe/trunk/lib/Sema/SemaDeclCXX.cpp
cfe/trunk/lib/Sema/SemaLambda.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/test/CodeGenCXX/mangle-lambdas.cpp
cfe/trunk/test/SemaCXX/vartemplate-lambda.cpp
cfe/trunk/test/SemaTemplate/instantiate-static-var.cpp

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=313955=313954=313955=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Thu Sep 21 21:25:05 2017
@@ -554,7 +554,8 @@ static LinkageInfo getExternalLinkageFor
 
 LinkageInfo
 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
-LVComputationKind computation) {
+LVComputationKind computation,
+bool IgnoreVarTypeLinkage) {
   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
  "Not a name having namespace scope");
   ASTContext  = D->getASTContext();
@@ -611,7 +612,7 @@ LinkageComputer::getLVForNamespaceScopeD
 //   - a data member of an anonymous union.
 const VarDecl *VD = IFD->getVarDecl();
 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
-return getLVForNamespaceScopeDecl(VD, computation);
+return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
   }
   assert(!isa(D) && "Didn't expect a FieldDecl!");
 
@@ -700,7 +701,8 @@ LinkageComputer::getLVForNamespaceScopeD
 //
 // Note that we don't want to make the variable non-external
 // because of this, but unique-external linkage suits us.
-if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
+if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
+!IgnoreVarTypeLinkage) {
   LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
   if (!isExternallyVisible(TypeLV.getLinkage()))
 return LinkageInfo::uniqueExternal();
@@ -740,15 +742,9 @@ LinkageComputer::getLVForNamespaceScopeD
 // unique-external linkage, it's not legally usable from outside
 // this translation unit.  However, we should use the C linkage
 // rules instead for extern "C" declarations.
-if (Context.getLangOpts().CPlusPlus &&
-!Function->isInExternCContext()) {
-  // Only look at the type-as-written. If this function has an auto-deduced
-  // return type, we can't compute the linkage of that type because it 
could
-  // require looking at the linkage of this function, and we don't need 
this
-  // for correctness because the type is not part of the function's
-  // signature.
-  // FIXME: This is a hack. We should be able to solve this circularity 
and 
-  // the one in getLVForClassMember for Functions some other way.
+if (Context.getLangOpts().CPlusPlus && !Function->isInExternCContext()) {
+  // Only look at the type-as-written. Otherwise, deducing the return type
+  // of a function could change its linkage.
   QualType TypeAsWritten = Function->getType();
   if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
 TypeAsWritten = TSI->getType();
@@ -831,7 +827,8 @@ LinkageComputer::getLVForNamespaceScopeD
 
 LinkageInfo
 LinkageComputer::getLVForClassMember(const NamedDecl *D,
- LVComputationKind computation) {
+ LVComputationKind computation,
+ bool IgnoreVarTypeLinkage) {
   // Only certain class members have linkage.  Note that fields don't
   // really have linkage, but it's convenient to say they do for the
   // purposes of calculating linkage of pointer-to-data-member
@@ -889,22 +886,14 @@ LinkageComputer::getLVForClassMember(con
   const NamedDecl *explicitSpecSuppressor = nullptr;
 
   if (const auto *MD = dyn_cast(D)) {
-// If the type of the function uses a type that has non-externally-visible
-// linkage, it's not legally usable from outside this translation unit.
-// But only look at the type-as-written. If this function has an
-// auto-deduced return type, we can't compute the linkage of that type
-// because it could require looking at the linkage of this function, and we
-

r313954 - Driver: remove support for libstdc++ from CrossWindows

2017-09-21 Thread Saleem Abdulrasool via cfe-commits
Author: compnerd
Date: Thu Sep 21 21:01:12 2017
New Revision: 313954

URL: http://llvm.org/viewvc/llvm-project?rev=313954=rev
Log:
Driver: remove support for libstdc++ from CrossWindows

This code path is entirely untested and not really maintained.  The
expected use here is with libc++ only.

Modified:
cfe/trunk/lib/Driver/ToolChains/CrossWindows.cpp
cfe/trunk/test/Driver/windows-cross.c

Modified: cfe/trunk/lib/Driver/ToolChains/CrossWindows.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/CrossWindows.cpp?rev=313954=313953=313954=diff
==
--- cfe/trunk/lib/Driver/ToolChains/CrossWindows.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/CrossWindows.cpp Thu Sep 21 21:01:12 2017
@@ -207,16 +207,7 @@ void tools::CrossWindows::Linker::Constr
 CrossWindowsToolChain::CrossWindowsToolChain(const Driver ,
  const llvm::Triple ,
  const llvm::opt::ArgList )
-: Generic_GCC(D, T, Args) {
-  if (D.CCCIsCXX() && GetCXXStdlibType(Args) == ToolChain::CST_Libstdcxx) {
-const std::string  = D.SysRoot;
-
-// libstdc++ resides in /usr/lib, but depends on libgcc which is placed in
-// /usr/lib/gcc.
-getFilePaths().push_back(SysRoot + "/usr/lib");
-getFilePaths().push_back(SysRoot + "/usr/lib/gcc");
-  }
-}
+: Generic_GCC(D, T, Args) {}
 
 bool CrossWindowsToolChain::IsUnwindTablesDefault(const ArgList ) const {
   // FIXME: all non-x86 targets need unwind tables, however, LLVM currently 
does
@@ -265,43 +256,21 @@ AddClangSystemIncludeArgs(const llvm::op
 void CrossWindowsToolChain::
 AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList ,
  llvm::opt::ArgStringList ) const {
-  const llvm::Triple  = getTriple();
   const std::string  = getDriver().SysRoot;
 
   if (DriverArgs.hasArg(options::OPT_nostdinc) ||
   DriverArgs.hasArg(options::OPT_nostdincxx))
 return;
 
-  switch (GetCXXStdlibType(DriverArgs)) {
-  case ToolChain::CST_Libcxx:
+  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx)
 addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include/c++/v1");
-break;
-
-  case ToolChain::CST_Libstdcxx:
-addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include/c++");
-addSystemInclude(DriverArgs, CC1Args,
- SysRoot + "/usr/include/c++/" + Triple.str());
-addSystemInclude(DriverArgs, CC1Args,
- SysRoot + "/usr/include/c++/backwards");
-  }
 }
 
 void CrossWindowsToolChain::
 AddCXXStdlibLibArgs(const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ) const {
-  switch (GetCXXStdlibType(DriverArgs)) {
-  case ToolChain::CST_Libcxx:
+  if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx)
 CC1Args.push_back("-lc++");
-break;
-  case ToolChain::CST_Libstdcxx:
-CC1Args.push_back("-lstdc++");
-CC1Args.push_back("-lmingw32");
-CC1Args.push_back("-lmingwex");
-CC1Args.push_back("-lgcc");
-CC1Args.push_back("-lmoldname");
-CC1Args.push_back("-lmingw32");
-break;
-  }
 }
 
 clang::SanitizerMask CrossWindowsToolChain::getSupportedSanitizers() const {

Modified: cfe/trunk/test/Driver/windows-cross.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/windows-cross.c?rev=313954=313953=313954=diff
==
--- cfe/trunk/test/Driver/windows-cross.c (original)
+++ cfe/trunk/test/Driver/windows-cross.c Thu Sep 21 21:01:12 2017
@@ -1,8 +1,3 @@
-// RUN: %clang -### --driver-mode=g++ -target armv7-windows-itanium --sysroot 
%S/Inputs/Windows/ARM/8.1 -B %S/Inputs/Windows/ARM/8.1/usr/bin -fuse-ld=ld 
-stdlib=libstdc++ -rtlib=platform -o /dev/null %s 2>&1 \
-// RUN:   | FileCheck %s --check-prefix CHECK-BASIC-LIBSTDCXX
-
-// CHECK-BASIC-LIBSTDCXX: armv7-windows-itanium-ld" 
"--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-Bdynamic" "--entry" 
"mainCRTStartup" "--allow-multiple-definition" "-o" "{{[^"]*}}" 
"-L{{.*}}/Inputs/Windows/ARM/8.1/usr/lib" 
"-L{{.*}}/Inputs/Windows/ARM/8.1/usr/lib/gcc" "{{.*}}.o" "-lstdc++" "-lmingw32" 
"-lmingwex" "-lgcc" "-lmoldname" "-lmingw32" "-lmsvcrt" "-lgcc_s" "-lgcc"
-
 // RUN: %clang -### -target armv7-windows-itanium --sysroot 
%S/Inputs/Windows/ARM/8.1 -B %S/Inputs/Windows/ARM/8.1/usr/bin -fuse-ld=ld 
-stdlib=libstdc++ -rtlib=compiler-rt -o /dev/null %s 2>&1 \
 // RUN:   | FileCheck %s --check-prefix CHECK-BASIC-LIBCXX
 
@@ -38,11 +33,6 @@
 
 // CHECK-STANDALONE: armv7-windows-itanium-ld" 
"--sysroot={{.*}}/Inputs/Windows/ARM/8.1" "-m" "thumb2pe" "-shared" "-Bdynamic" 
"--enable-auto-image-base" "--entry" "_DllMainCRTStartup" 
"--allow-multiple-definition" "-o" "shared.dll" "--out-implib" "shared.lib" 
"{{.*}}.o"
 
-// RUN: %clang -### -target armv7-windows-itanium --sysroot 
%S/Inputs/Windows/ARM/8.1 -B 

[PATCH] D38126: Make TBAA information to be part of LValueBaseInfo

2017-09-21 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added subscribers: cfe-commits, efriedma.
efriedma added a comment.

Please make sure to add the mailing list as a subscriber when you post a patch. 
 (I haven't looked at the patch yet.)


https://reviews.llvm.org/D38126



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


r313953 - Clean up some mistreatment of enumerations.

2017-09-21 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Thu Sep 21 19:22:32 2017
New Revision: 313953

URL: http://llvm.org/viewvc/llvm-project?rev=313953=rev
Log:
Clean up some mistreatment of enumerations.

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

Modified: cfe/trunk/include/clang/AST/Decl.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Decl.h?rev=313953=313952=313953=diff
==
--- cfe/trunk/include/clang/AST/Decl.h (original)
+++ cfe/trunk/include/clang/AST/Decl.h Thu Sep 21 19:22:32 2017
@@ -349,7 +349,14 @@ public:
 
   /// Kinds of explicit visibility.
   enum ExplicitVisibilityKind {
+/// Do an LV computation for, ultimately, a type.
+/// Visibility may be restricted by type visibility settings and
+/// the visibility of template arguments.
 VisibilityForType,
+
+/// Do an LV computation for, ultimately, a non-type declaration.
+/// Visibility may be restricted by value visibility settings and
+/// the visibility of template arguments.
 VisibilityForValue
   };
 

Modified: cfe/trunk/lib/AST/Decl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/Decl.cpp?rev=313953=313952=313953=diff
==
--- cfe/trunk/lib/AST/Decl.cpp (original)
+++ cfe/trunk/lib/AST/Decl.cpp Thu Sep 21 19:22:32 2017
@@ -103,28 +103,22 @@ TranslationUnitDecl::TranslationUnitDecl
 /// Does this computation kind permit us to consider additional
 /// visibility settings from attributes and the like?
 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
-  return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
+  return computation.IgnoreExplicitVisibility;
 }
 
 /// Given an LVComputationKind, return one of the same type/value sort
 /// that records that it already has explicit visibility.
 static LVComputationKind
-withExplicitVisibilityAlready(LVComputationKind oldKind) {
-  LVComputationKind newKind =
-static_cast(unsigned(oldKind) |
-   IgnoreExplicitVisibilityBit);
-  assert(oldKind != LVForType  || newKind == LVForExplicitType);
-  assert(oldKind != LVForValue || newKind == LVForExplicitValue);
-  assert(oldKind != LVForExplicitType  || newKind == LVForExplicitType);
-  assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
-  return newKind;
+withExplicitVisibilityAlready(LVComputationKind Kind) {
+  Kind.IgnoreExplicitVisibility = true;
+  return Kind;
 }
 
 static Optional getExplicitVisibility(const NamedDecl *D,
   LVComputationKind kind) {
-  assert(!hasExplicitVisibilityAlready(kind) &&
+  assert(!kind.IgnoreExplicitVisibility &&
  "asking for explicit visibility when we shouldn't be");
-  return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
+  return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
 }
 
 /// Is the given declaration a "type" or a "value" for the purposes of
@@ -190,7 +184,7 @@ static Optional getVisibilit
 
 LinkageInfo LinkageComputer::getLVForType(const Type ,
   LVComputationKind computation) {
-  if (computation == LVForLinkageOnly)
+  if (computation.IgnoreAllVisibility)
 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
   return getTypeLinkageAndVisibility();
 }
@@ -359,21 +353,11 @@ void LinkageComputer::mergeTemplateLV(
 /// that would match the given rules?
 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
  LVComputationKind computation) {
-  switch (computation) {
-  case LVForType:
-  case LVForExplicitType:
-if (D->hasAttr())
-  return true;
-// fallthrough
-  case LVForValue:
-  case LVForExplicitValue:
-if (D->hasAttr())
-  return true;
+  if (computation.IgnoreAllVisibility)
 return false;
-  case LVForLinkageOnly:
-return false;
-  }
-  llvm_unreachable("bad visibility computation kind");
+
+  return (computation.isTypeVisibility() && D->hasAttr()) 
||
+ D->hasAttr();
 }
 
 /// Should we consider visibility associated with the template
@@ -675,13 +659,10 @@ LinkageComputer::getLVForNamespaceScopeD
 // Add in global settings if the above didn't give us direct visibility.
 if (!LV.isVisibilityExplicit()) {
   // Use global type/value visibility as appropriate.
-  Visibility globalVisibility;
-  if (computation == LVForValue) {
-globalVisibility = Context.getLangOpts().getValueVisibilityMode();
-  } else {
-assert(computation == LVForType);
-globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
-  }
+  Visibility globalVisibility =
+  computation.isValueVisibility()
+  ? Context.getLangOpts().getValueVisibilityMode()
+ 

[PATCH] D38081: Set completion priority of destructors and operators to CCP_Unlikely.

2017-09-21 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Friendly ping. Any suggestions for other reviewers are also very welcome.


https://reviews.llvm.org/D38081



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


[PATCH] D37150: [clangd] Command line arg to specify compile_commands.json path

2017-09-21 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Could you please run `clang-format` on every submission?




Comment at: clangd/GlobalCompilationDatabase.cpp:98
+  {
+CompileCommandsDir = "/";  
+return tryLoadDatabaseFromPath(CompileCommandsDir.getValue());  

Is this some kind of accidental change? Why do we need to assign `"/"` to 
`CompileCommandsDir`?



Comment at: clangd/tool/ClangdMain.cpp:20
 #include 
+#include 
 

We certainly don't need that include.



Comment at: clangd/tool/ClangdMain.cpp:79
+CompileCommandsDirPath = llvm::None;
+  else
+  {

This should be something like:

```
  if (CompileCommandsDir.empty()) {
//...
CompileCommandsDirPath = llvm::None;
  } else if (!is_absolute(...)) {
//
CompileCommandsDirPath = llvm::None;
  } else if (!exists(...)) {
// 
CompileCommandsDirPath = llvm::None;
  } else {
CompileCommandsDirPath = CompileCommandsDir;
  }
```



  - It will have less nesting, therefore making code more readable.
  - It will fix an error in the current implementation. (Currently, `exists` 
check will run on an empty string if `-compile-commands-dir` is not an absolute 
path).




https://reviews.llvm.org/D37150



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


[PATCH] D36150: [clangd] LSP extension to switch between source/header file

2017-09-21 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov accepted this revision.
ilya-biryukov added a comment.

Looks good modulo a few NITS.
Let me know if you need help landing this.




Comment at: unittests/clangd/ClangdTests.cpp:910
+  auto FooH = getVirtualTestFilePath("foo.h");
+  auto invalid = getVirtualTestFilePath("main.cpp");
+

Code style: local variables are `UpperCamelCase`



Comment at: unittests/clangd/ClangdTests.cpp:916
+
+  llvm::Optional pathResult = Server.switchSourceHeader(FooCpp);
+  EXPECT_TRUE(pathResult.hasValue());

Code style: local variables are `UpperCamelCase`



Comment at: unittests/clangd/ClangdTests.cpp:967
+
+  // Test if asking for a corresponding file that doesn't exist returns an 
empty string.
+  pathResult = Server.switchSourceHeader(invalid);

The text is over the line limit.
Could you please `clang-format` every submission?


https://reviews.llvm.org/D36150



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


r313952 - Add test cases that weren't committed in r313945.

2017-09-21 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Thu Sep 21 18:54:36 2017
New Revision: 313952

URL: http://llvm.org/viewvc/llvm-project?rev=313952=rev
Log:
Add test cases that weren't committed in r313945.

Added:
cfe/trunk/test/CodeGenCXX/noescape.cpp
cfe/trunk/test/CodeGenObjC/noescape.m
cfe/trunk/test/Sema/noescape.c
cfe/trunk/test/SemaObjCXX/noescape.mm

Added: cfe/trunk/test/CodeGenCXX/noescape.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenCXX/noescape.cpp?rev=313952=auto
==
--- cfe/trunk/test/CodeGenCXX/noescape.cpp (added)
+++ cfe/trunk/test/CodeGenCXX/noescape.cpp Thu Sep 21 18:54:36 2017
@@ -0,0 +1,67 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm -o - %s | 
FileCheck %s
+
+struct S {
+  int a[4];
+  S(int *, int * __attribute__((noescape)));
+  S =(int * __attribute__((noescape)));
+  void m0(int *, int * __attribute__((noescape)));
+  virtual void vm1(int *, int * __attribute__((noescape)));
+};
+
+// CHECK: define void @_ZN1SC2EPiS0_(%struct.S* {{.*}}, {{.*}}, {{.*}} 
nocapture)
+// CHECK: define void @_ZN1SC1EPiS0_(%struct.S* {{.*}}, {{.*}}, {{.*}} 
nocapture) {{.*}} {
+// CHECK: call void @_ZN1SC2EPiS0_(%struct.S* {{.*}}, {{.*}}, {{.*}} nocapture 
{{.*}})
+
+S::S(int *, int * __attribute__((noescape))) {}
+
+// CHECK: define {{.*}} %struct.S* @_ZN1SaSEPi(%struct.S* {{.*}}, {{.*}} 
nocapture)
+S ::operator=(int * __attribute__((noescape))) { return *this; }
+
+// CHECK: define void @_ZN1S2m0EPiS0_(%struct.S* {{.*}}, {{.*}} nocapture)
+void S::m0(int *, int * __attribute__((noescape))) {}
+
+// CHECK: define void @_ZN1S3vm1EPiS0_(%struct.S* {{.*}}, {{.*}} nocapture)
+void S::vm1(int *, int * __attribute__((noescape))) {}
+
+// CHECK-LABEL: define void @_Z5test0P1SPiS1_(
+// CHECK: call void @_ZN1SC1EPiS0_(%struct.S* {{.*}}, {{.*}}, {{.*}} nocapture 
{{.*}})
+// CHECK: call {{.*}} %struct.S* @_ZN1SaSEPi(%struct.S* {{.*}}, {{.*}} 
nocapture {{.*}})
+// CHECK: call void @_ZN1S2m0EPiS0_(%struct.S* {{.*}}, {{.*}}, {{.*}} 
nocapture {{.*}})
+// CHECK: call void {{.*}}(%struct.S* {{.*}}, {{.*}}, {{.*}} nocapture {{.*}})
+void test0(S *s, int *p0, int *p1) {
+  S t(p0, p1);
+  t = p1;
+  s->m0(p0, p1);
+  s->vm1(p0, p1);
+}
+
+namespace std {
+  typedef decltype(sizeof(0)) size_t;
+}
+
+// CHECK: define {{.*}} @_ZnwmPv({{.*}}, {{.*}} nocapture {{.*}})
+void *operator new(std::size_t, void * __attribute__((noescape)) p) {
+  return p;
+}
+
+// CHECK-LABEL: define i8* @_Z5test1Pv(
+// CHECK : %call = call {{.*}} @_ZnwmPv({{.*}}, {{.*}} nocapture {{.*}})
+void *test1(void *p0) {
+  return ::operator new(16, p0);
+}
+
+// CHECK-LABEL: define void @_Z5test2PiS_(
+// CHECK: call void @"_ZZ5test2PiS_ENK3$_0clES_S_"({{.*}}, {{.*}}, {{.*}} 
nocapture {{.*}})
+// CHECK: define internal void @"_ZZ5test2PiS_ENK3$_0clES_S_"({{.*}}, {{.*}}, 
{{.*}} nocapture)
+void test2(int *p0, int *p1) {
+  auto t = [](int *, int * __attribute__((noescape))){};
+  t(p0, p1);
+}
+
+// CHECK-LABEL: define void @_Z5test3PFvU8noescapePiES_(
+// CHECK: call void {{.*}}(i32* nocapture {{.*}})
+typedef void (*NoEscapeFunc)(__attribute__((noescape)) int *);
+
+void test3(NoEscapeFunc f, int *p) {
+  f(p);
+}

Added: cfe/trunk/test/CodeGenObjC/noescape.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGenObjC/noescape.m?rev=313952=auto
==
--- cfe/trunk/test/CodeGenObjC/noescape.m (added)
+++ cfe/trunk/test/CodeGenObjC/noescape.m Thu Sep 21 18:54:36 2017
@@ -0,0 +1,71 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -fblocks -emit-llvm -o - %s | 
FileCheck %s
+
+typedef void (^BlockTy)(void);
+
+union U {
+  int *i;
+  long long *ll;
+} __attribute__((transparent_union));
+
+void noescapeFunc0(id, __attribute__((noescape)) BlockTy);
+void noescapeFunc1(__attribute__((noescape)) int *);
+void noescapeFunc2(__attribute__((noescape)) id);
+void noescapeFunc3(__attribute__((noescape)) union U);
+
+// CHECK-LABEL: define void @test0(
+// CHECK: call void @noescapeFunc0({{.*}}, {{.*}} nocapture {{.*}})
+// CHECK: declare void @noescapeFunc0(i8*, {{.*}} nocapture)
+void test0(BlockTy b) {
+  noescapeFunc0(0, b);
+}
+
+// CHECK-LABEL: define void @test1(
+// CHECK: call void @noescapeFunc1({{.*}} nocapture {{.*}})
+// CHECK: declare void @noescapeFunc1({{.*}} nocapture)
+void test1(int *i) {
+  noescapeFunc1(i);
+}
+
+// CHECK-LABEL: define void @test2(
+// CHECK: call void @noescapeFunc2({{.*}} nocapture {{.*}})
+// CHECK: declare void @noescapeFunc2({{.*}} nocapture)
+void test2(id i) {
+  noescapeFunc2(i);
+}
+
+// CHECK-LABEL: define void @test3(
+// CHECK: call void @noescapeFunc3({{.*}} nocapture {{.*}})
+// CHECK: declare void @noescapeFunc3({{.*}} nocapture)
+void test3(union U u) {
+  noescapeFunc3(u);
+}
+
+// CHECK: define internal void @"\01-[C0 m0:]"({{.*}}, {{.*}}, {{.*}} 
nocapture {{.*}})
+
+// CHECK-LABEL: define void @test4(

r313950 - [Analyzer] Static analyzer script for updating reference results

2017-09-21 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep 21 18:43:12 2017
New Revision: 313950

URL: http://llvm.org/viewvc/llvm-project?rev=313950=rev
Log:
[Analyzer] Static analyzer script for updating reference results

The script updates reference results from the previous run, and stages them.

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

Added:
cfe/trunk/utils/analyzer/SATestUpdateDiffs.py   (with props)

Added: cfe/trunk/utils/analyzer/SATestUpdateDiffs.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestUpdateDiffs.py?rev=313950=auto
==
--- cfe/trunk/utils/analyzer/SATestUpdateDiffs.py (added)
+++ cfe/trunk/utils/analyzer/SATestUpdateDiffs.py Thu Sep 21 18:43:12 2017
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+
+"""
+Update reference results for static analyzer.
+"""
+
+from subprocess import check_call, check_output, CalledProcessError
+import csv
+import os
+import sys
+
+Verbose = 1
+def runCmd(Command):
+if Verbose:
+print "Executing %s" % Command
+check_call(Command, shell=True)
+
+def updateReferenceResults(ProjName, ProjBuildMode):
+ProjDir = SATestBuild.getProjectDir(ProjName)
+
+RefResultsPath = os.path.join(ProjDir,
+SATestBuild.getSBOutputDirName(IsReferenceBuild=True))
+CreatedResultsPath = os.path.join(ProjDir,
+SATestBuild.getSBOutputDirName(IsReferenceBuild=False))
+
+if not os.path.exists(CreatedResultsPath):
+print >> sys.stderr, "New results not found, was SATestBuild.py "\
+ "previously run?"
+sys.exit(-1)
+
+# Remove reference results.
+runCmd('git rm -r "%s"' % (RefResultsPath,))
+
+# Replace reference results with a freshly computed once.
+runCmd('cp -r "%s" "%s"' % (CreatedResultsPath, RefResultsPath,))
+
+# Run cleanup script.
+with open(SATestBuild.getBuildLogPath(RefResultsPath), "wb+")
+as PBuildLogFile:
+SATestBuild.runCleanupScript(ProjDir, PBuildLogFile)
+
+SATestBuild.normalizeReferenceResults(ProjDir, RefResultsPath, 
ProjBuildMode)
+
+# Clean up the generated difference results.
+SATestBuild.cleanupReferenceResults(RefResultsPath)
+
+# Remove the created .diffs file before adding.
+runCmd('rm -f "%s/*/%s"' % (RefResultsPath, 
SATestBuild.DiffsSummaryFileName))
+
+runCmd('git add "%s"' % (RefResultsPath,))
+
+def main(argv):
+if len(argv) == 2 and argv[1] in ('-h', '--help'):
+print >> sys.stderr, "Update static analyzer reference results based "\
+ "\non the previous run of SATestBuild.py.\n"
+ "\nN.B.: Assumes that SATestBuild.py was just 
run."
+sys.exit(-1)
+
+with SATestBuild.projectFileHandler() as f:
+for (ProjName, ProjBuildMode) in SATestBuild.iterateOverProjects(f):
+updateReferenceResults(ProjName, int(ProjBuildMode))
+
+if __name__ == '__main__':
+main(sys.argv)

Propchange: cfe/trunk/utils/analyzer/SATestUpdateDiffs.py
--
svn:executable = *


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


r313949 - [Analyzer] Refactor analyzer testing scripts.

2017-09-21 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep 21 18:41:16 2017
New Revision: 313949

URL: http://llvm.org/viewvc/llvm-project?rev=313949=rev
Log:
[Analyzer] Refactor analyzer testing scripts.

 - Exporting needed function for future reuse.
 - Idiomatic python: using with `file as f` instead of `try/finally`.
 - Fixing some indentation issues.
 - No need to reinvent python `multiprocessing.getCPUCount()`
 - Removing a function parameter which is always the same under all invocations.
 - Adding some docstrings.

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

Modified:
cfe/trunk/utils/analyzer/CmpRuns.py
cfe/trunk/utils/analyzer/SATestAdd.py
cfe/trunk/utils/analyzer/SATestBuild.py

Modified: cfe/trunk/utils/analyzer/CmpRuns.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/CmpRuns.py?rev=313949=313948=313949=diff
==
--- cfe/trunk/utils/analyzer/CmpRuns.py (original)
+++ cfe/trunk/utils/analyzer/CmpRuns.py Thu Sep 21 18:41:16 2017
@@ -28,7 +28,6 @@ Usage:
 
 import os
 import plistlib
-import CmpRuns
 
 # Information about analysis run:
 # path - the analysis output directory

Modified: cfe/trunk/utils/analyzer/SATestAdd.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestAdd.py?rev=313949=313948=313949=diff
==
--- cfe/trunk/utils/analyzer/SATestAdd.py (original)
+++ cfe/trunk/utils/analyzer/SATestAdd.py Thu Sep 21 18:41:16 2017
@@ -65,7 +65,7 @@ def addNewProject(ID, BuildMode) :
 sys.exit(-1)
 
 # Build the project.
-SATestBuild.testProject(ID, BuildMode, IsReferenceBuild=True, Dir=Dir)
+SATestBuild.testProject(ID, BuildMode, IsReferenceBuild=True)
 
 # Add the project ID to the project map.
 ProjectMapPath = os.path.join(CurDir, SATestBuild.ProjectMapFile)

Modified: cfe/trunk/utils/analyzer/SATestBuild.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestBuild.py?rev=313949=313948=313949=diff
==
--- cfe/trunk/utils/analyzer/SATestBuild.py (original)
+++ cfe/trunk/utils/analyzer/SATestBuild.py Thu Sep 21 18:41:16 2017
@@ -53,30 +53,12 @@ import time
 import plistlib
 import argparse
 from subprocess import check_call, check_output, CalledProcessError
+import multiprocessing
 
 #--
 # Helper functions.
 #--
 
-def detectCPUs():
-"""
-Detects the number of CPUs on a system. Cribbed from pp.
-"""
-# Linux, Unix and MacOS:
-if hasattr(os, "sysconf"):
-if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
-# Linux & Unix:
-ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
-if isinstance(ncpus, int) and ncpus > 0:
-return ncpus
-else: # OSX:
-return int(capture(['sysctl', '-n', 'hw.ncpu']))
-# Windows:
-if os.environ.has_key("NUMBER_OF_PROCESSORS"):
-ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
-if ncpus > 0:
-return ncpus
-return 1 # Default
 
 def which(command, paths = None):
"""which(command, [paths]) - Look up the given command in the paths string
@@ -151,7 +133,7 @@ if not Clang:
 sys.exit(-1)
 
 # Number of jobs.
-Jobs = int(math.ceil(detectCPUs() * 0.75))
+Jobs = int(math.ceil(multiprocessing.cpu_count() * 0.75))
 
 # Project map stores info about all the "registered" projects.
 ProjectMapFile = "projectMap.csv"
@@ -306,7 +288,7 @@ def runScanBuild(Dir, SBOutputDir, PBuil
 # to speed up analysis.  xcodebuild will
 # automatically use the maximum number of cores.
 if (Command.startswith("make ") or Command == "make") and \
-"-j" not in Command:
+"-j" not in Command:
 Command += " -j%d" % Jobs
 SBCommand = SBPrefix + Command
 if Verbose == 1:
@@ -430,11 +412,8 @@ def buildProject(Dir, SBOutputDir, Proje
 assert(not os.path.exists(SBOutputDir))
 os.makedirs(os.path.join(SBOutputDir, LogFolderName))
 
-# Open the log file.
-PBuildLogFile = open(BuildLogPath, "wb+")
-
 # Build and analyze the project.
-try:
+with open(BuildLogPath, "wb+") as PBuildLogFile:
 if (ProjectBuildMode == 1):
 downloadAndPatch(Dir, PBuildLogFile)
 runCleanupScript(Dir, PBuildLogFile)
@@ -442,31 +421,32 @@ def buildProject(Dir, SBOutputDir, Proje
 else:
 runAnalyzePreprocessed(Dir, SBOutputDir, ProjectBuildMode)
 
-if IsReferenceBuild :
+if IsReferenceBuild:
 runCleanupScript(Dir, PBuildLogFile)
-
-# Make the absolute paths relative in the reference results.
-for (DirPath, 

[PATCH] D37656: [cfi] Set function attributes for __cfi_* functions.

2017-09-21 Thread Eric Christopher via Phabricator via cfe-commits
echristo added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:2917
+CodeGenFunction , llvm::Function *F,
+bool ForceThumb) {
+  StringRef TargetCPU = CGF.getTarget().getTargetOpts().CPU;

eugenis wrote:
> echristo wrote:
> > I don't think we should be force setting thumb anywhere, it should be 
> > handled on a function by function basis the way we do all of the target 
> > attribute stuff.
> We want this function to be Thumb even if the rest of the module is ARM. It 
> lets us use 2x less memory in the implementation of __cfi_slowpath here:
> https://clang.llvm.org/docs/ControlFlowIntegrityDesign.html#cfi-slowpath
> 
> This function does not have source, so it can not have target attributes, too.
> 
> Are you suggesting faking a piece of AST (FunctionDecl with attached 
> attributes) and then using the regular attribute setting code?
> 
> 
Aha. Didn't remember that part of the design.

And yeah, that sounds good. And it doesn't really matter if the function has 
any source code as to whether or not it has attributes. There's no inheritance 
structure going on here so every function should have them.



Comment at: clang/lib/CodeGen/CGExpr.cpp:2961-2963
+  // attributes as SetLLVMFunctionAttributes sets. In particular, __cfi_check
+  // must use the default calling convention for the platform. ABI-changing
+  // flags like -mhard-float should not affect __cfi_check.

eugenis wrote:
> echristo wrote:
> > This is odd. Can you explain this a bit more?
> __cfi_check is called from compiler-rt or libdl.so, so it can not have any 
> fancy calling convention. It must use what's standard on the platform.
> 
> OK, __cfi_check has no floating-point parameters, so -mhard-float would not 
> be a problem. 
Yeah, I think this falls in on the earlier comment. Should probably add the 
defaults to a bit of AST or something?


https://reviews.llvm.org/D37656



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


[PATCH] D38040: [OpenMP] Add an additional test for D34888

2017-09-21 Thread Gheorghe-Teodor Bercea via Phabricator via cfe-commits
gtbercea added a comment.

In https://reviews.llvm.org/D38040#878090, @Hahnfeld wrote:

> Hi Doru,
>
> if I remember correctly I submitted https://reviews.llvm.org/D34888 for a 
> crash when mapping a scalar value with nested regions.
>  I've marked another test in this file that the codegen for `tofrom` is 
> correct. So I don't know if this test checks some other conditions?
>
> Jonas


Hi Jonas,

The test is verifying whether the parameter is passed to the kernel correctly. 
I believe it was not passed as a reference before the patch.

In addition to that, something that was in my previous patch is related to this 
code:

  DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  D, Level, 
[&](OMPClauseMappableExprCommon::MappableExprComponentListRef

In particular with the Level variable. Should the Level variable actually be 
Level + 1 in this case?

Thanks,

--Doru


Repository:
  rL LLVM

https://reviews.llvm.org/D38040



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


r313948 - Fix tracking of whether a destructor would be deleted.

2017-09-21 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Thu Sep 21 18:04:22 2017
New Revision: 313948

URL: http://llvm.org/viewvc/llvm-project?rev=313948=rev
Log:
Fix tracking of whether a destructor would be deleted.

I've been unable to find any cases whose behavior is actually changed by this,
but only because an implicitly deleted destructor also results in it being
impossible to have a trivial (non-deleted) copy constructor, which the place
where this really matters (choosing whether to pass a class in registers)
happens to also check.

Added:
cfe/trunk/test/CXX/special/class.dtor/p5-implicit.cpp
Modified:
cfe/trunk/include/clang/AST/DeclCXX.h
cfe/trunk/lib/Sema/SemaDecl.cpp

Modified: cfe/trunk/include/clang/AST/DeclCXX.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclCXX.h?rev=313948=313947=313948=diff
==
--- cfe/trunk/include/clang/AST/DeclCXX.h (original)
+++ cfe/trunk/include/clang/AST/DeclCXX.h Thu Sep 21 18:04:22 2017
@@ -838,7 +838,10 @@ public:
 
   /// \brief \c true if a defaulted destructor for this class would be deleted.
   bool defaultedDestructorIsDeleted() const {
-return !data().DefaultedDestructorIsDeleted;
+assert((!needsOverloadResolutionForDestructor() ||
+(data().DeclaredSpecialMembers & SMF_Destructor)) &&
+   "this property has not yet been computed by Sema");
+return data().DefaultedDestructorIsDeleted;
   }
 
   /// \brief \c true if we know for sure that this class has a single,
@@ -985,6 +988,15 @@ public:
 data().DefaultedMoveConstructorIsDeleted = true;
   }
 
+  /// \brief Set that we attempted to declare an implicit destructor,
+  /// but overload resolution failed so we deleted it.
+  void setImplicitDestructorIsDeleted() {
+assert((data().DefaultedDestructorIsDeleted ||
+needsOverloadResolutionForDestructor()) &&
+   "destructor should not be deleted");
+data().DefaultedDestructorIsDeleted = true;
+  }
+
   /// \brief Determine whether this class should get an implicit move
   /// constructor or if any existing special member function inhibits this.
   bool needsImplicitMoveConstructor() const {

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=313948=313947=313948=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Thu Sep 21 18:04:22 2017
@@ -15119,8 +15119,10 @@ void Sema::ActOnFields(Scope *S, SourceL
 if (CXXRecordDecl *CXXRecord = dyn_cast(Record)) {
   auto *Dtor = CXXRecord->getDestructor();
   if (Dtor && Dtor->isImplicit() &&
-  ShouldDeleteSpecialMember(Dtor, CXXDestructor))
+  ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
+CXXRecord->setImplicitDestructorIsDeleted();
 SetDeclDeleted(Dtor, CXXRecord->getLocation());
+  }
 }
 
 if (Record->hasAttrs()) {

Added: cfe/trunk/test/CXX/special/class.dtor/p5-implicit.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/special/class.dtor/p5-implicit.cpp?rev=313948=auto
==
--- cfe/trunk/test/CXX/special/class.dtor/p5-implicit.cpp (added)
+++ cfe/trunk/test/CXX/special/class.dtor/p5-implicit.cpp Thu Sep 21 18:04:22 
2017
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -std=c++11 %s -ast-dump | FileCheck %s
+
+struct A { ~A() = delete; };
+// CHECK-LABEL: CXXRecordDecl {{.*}} struct A
+// CHECK: Destructor trivial user_declared
+
+struct B : A {};
+// CHECK-LABEL: CXXRecordDecl {{.*}} struct B
+// CHECK: Destructor trivial needs_overload_resolution
+
+struct C : B {};
+// CHECK-LABEL: CXXRecordDecl {{.*}} struct C
+// CHECK: Destructor trivial needs_overload_resolution
+
+struct D { ~D(); };
+struct E : D {};
+union U {
+  E e;
+};
+// CHECK-LABEL: CXXRecordDecl {{.*}} union U
+// CHECK: Destructor non_trivial needs_implicit defaulted_is_deleted


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


[PATCH] D37656: [cfi] Set function attributes for __cfi_* functions.

2017-09-21 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:2917
+CodeGenFunction , llvm::Function *F,
+bool ForceThumb) {
+  StringRef TargetCPU = CGF.getTarget().getTargetOpts().CPU;

echristo wrote:
> I don't think we should be force setting thumb anywhere, it should be handled 
> on a function by function basis the way we do all of the target attribute 
> stuff.
We want this function to be Thumb even if the rest of the module is ARM. It 
lets us use 2x less memory in the implementation of __cfi_slowpath here:
https://clang.llvm.org/docs/ControlFlowIntegrityDesign.html#cfi-slowpath

This function does not have source, so it can not have target attributes, too.

Are you suggesting faking a piece of AST (FunctionDecl with attached 
attributes) and then using the regular attribute setting code?





Comment at: clang/lib/CodeGen/CGExpr.cpp:2961-2963
+  // attributes as SetLLVMFunctionAttributes sets. In particular, __cfi_check
+  // must use the default calling convention for the platform. ABI-changing
+  // flags like -mhard-float should not affect __cfi_check.

echristo wrote:
> This is odd. Can you explain this a bit more?
__cfi_check is called from compiler-rt or libdl.so, so it can not have any 
fancy calling convention. It must use what's standard on the platform.

OK, __cfi_check has no floating-point parameters, so -mhard-float would not be 
a problem. 


https://reviews.llvm.org/D37656



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


[PATCH] D38083: [clangd] Skip informative qualifier chunks.

2017-09-21 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 116297.
ilya-biryukov added a comment.

- Fixed CHECK-DAG typo.


https://reviews.llvm.org/D38083

Files:
  clangd/ClangdUnit.cpp
  test/clangd/completion-qualifiers.test


Index: test/clangd/completion-qualifiers.test
===
--- /dev/null
+++ test/clangd/completion-qualifiers.test
@@ -0,0 +1,18 @@
+# RUN: clangd -run-synchronously < %s | FileCheck %s
+Content-Length: 125
+
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+Content-Length: 297
+
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"class
 Foo {\n  public:\nint foo() const;\nint bar() const;\n};\n\nclass Bar 
: public Foo {\n  int foo() const;\n};\n\nvoid test() {\n  Bar().\n}"}}}
+Content-Length: 151
+
+{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":11,"character":8}}}
+# CHECK: {"jsonrpc":"2.0","id":2,"result":[
+# CHECK-DAG: {"label":"foo() 
const","kind":2,"detail":"int","sortText":"200035foo","filterText":"foo","insertText":"foo","insertTextFormat":1}
+# CHECK-DAG: {"label":"bar() 
const","kind":2,"detail":"int","sortText":"37bar","filterText":"bar","insertText":"bar","insertTextFormat":1}
+# CHECK-DAG: {"label":"Foo::foo() 
const","kind":2,"detail":"int","sortText":"37foo","filterText":"foo","insertText":"foo","insertTextFormat":1}
+# CHECK: ]}
+Content-Length: 44
+
+{"jsonrpc":"2.0","id":4,"method":"shutdown"}
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -409,6 +409,11 @@
 
 }; // CompletionItemsCollector
 
+bool isInformativeQualifierChunk(CodeCompletionString::Chunk const ) {
+  return Chunk.Kind == CodeCompletionString::CK_Informative &&
+ StringRef(Chunk.Text).endswith("::");
+}
+
 class PlainTextCompletionItemsCollector final
 : public CompletionItemsCollector {
 
@@ -421,6 +426,11 @@
   void ProcessChunks(const CodeCompletionString ,
  CompletionItem ) const override {
 for (const auto  : CCS) {
+  // Informative qualifier chunks only clutter completion results, skip
+  // them.
+  if (isInformativeQualifierChunk(Chunk))
+continue;
+
   switch (Chunk.Kind) {
   case CodeCompletionString::CK_TypedText:
 // There's always exactly one CK_TypedText chunk.
@@ -453,6 +463,11 @@
  CompletionItem ) const override {
 unsigned ArgCount = 0;
 for (const auto  : CCS) {
+  // Informative qualifier chunks only clutter completion results, skip
+  // them.
+  if (isInformativeQualifierChunk(Chunk))
+continue;
+
   switch (Chunk.Kind) {
   case CodeCompletionString::CK_TypedText:
 // The piece of text that the user is expected to type to match


Index: test/clangd/completion-qualifiers.test
===
--- /dev/null
+++ test/clangd/completion-qualifiers.test
@@ -0,0 +1,18 @@
+# RUN: clangd -run-synchronously < %s | FileCheck %s
+Content-Length: 125
+
+{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"processId":123,"rootPath":"clangd","capabilities":{},"trace":"off"}}
+Content-Length: 297
+
+{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"uri":"file:///main.cpp","languageId":"cpp","version":1,"text":"class Foo {\n  public:\nint foo() const;\nint bar() const;\n};\n\nclass Bar : public Foo {\n  int foo() const;\n};\n\nvoid test() {\n  Bar().\n}"}}}
+Content-Length: 151
+
+{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{"textDocument":{"uri":"file:///main.cpp"},"position":{"line":11,"character":8}}}
+# CHECK: {"jsonrpc":"2.0","id":2,"result":[
+# CHECK-DAG: {"label":"foo() const","kind":2,"detail":"int","sortText":"200035foo","filterText":"foo","insertText":"foo","insertTextFormat":1}
+# CHECK-DAG: {"label":"bar() const","kind":2,"detail":"int","sortText":"37bar","filterText":"bar","insertText":"bar","insertTextFormat":1}
+# CHECK-DAG: {"label":"Foo::foo() const","kind":2,"detail":"int","sortText":"37foo","filterText":"foo","insertText":"foo","insertTextFormat":1}
+# CHECK: ]}
+Content-Length: 44
+
+{"jsonrpc":"2.0","id":4,"method":"shutdown"}
Index: clangd/ClangdUnit.cpp
===
--- clangd/ClangdUnit.cpp
+++ clangd/ClangdUnit.cpp
@@ -409,6 +409,11 @@
 
 }; // CompletionItemsCollector
 
+bool isInformativeQualifierChunk(CodeCompletionString::Chunk const ) {
+  return Chunk.Kind == CodeCompletionString::CK_Informative &&
+ StringRef(Chunk.Text).endswith("::");
+}
+
 class PlainTextCompletionItemsCollector final
 : public CompletionItemsCollector {
 
@@ 

[PATCH] D38083: [clangd] Skip informative qualifier chunks.

2017-09-21 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added inline comments.



Comment at: test/clangd/completion-qualifiers.test:12
+# CHECK: {"jsonrpc":"2.0","id":2,"result":[
+# CHEKC-DAG: {"label":"foo() 
const","kind":2,"detail":"int","sortText":"00035foo","filterText":"foo","insertText":"foo","insertTextFormat":1}
+# CHEKC-DAG: {"label":"bar() 
const","kind":2,"detail":"int","sortText":"00037bar","filterText":"bar","insertText":"bar","insertTextFormat":1}

rwols wrote:
> CHECK-DAG typo?
Totally! Thanks for spotting this.


https://reviews.llvm.org/D38083



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


[PATCH] D38134: [OpenCL] Emit enqueued block as kernel

2017-09-21 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 3 inline comments as done.
yaxunl added a comment.

In https://reviews.llvm.org/D38134#877831, @Anastasia wrote:

> Now if we have a block which is being called and enqueued at the same time, 
> will we generate 2 functions for it? Could we add such test case btw?


Yes. It is covered by test/CodeGenOpenCL/cl20-device-side-enqueue.cl, line 246, 
250, and 256.

> I feel it would be much simpler if we could always generate the kernel 
> metadata for blocks. A lot of special case code would be removed if we do 
> this. OpenCL doesn't prevent kernel functions to be used just as normal 
> functions (6.7.1) so it should be a perfectly valid thing to do. Do you seen 
> any issues with that?

The special cases in metadata generation code is due to the first argument of 
LLVM block invoke function is not defined in BlockDecl. Emitting metadata for 
all block invoke functions does not help here.




Comment at: lib/CodeGen/CGBlocks.cpp:1255
 // Allocate a stack slot to let the debug info survive the RA.
-Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
+Address alloc = CreateMemTemp(
+!PV.isIndirect() ? D->getType()

Anastasia wrote:
> Is there any test that covers this?
Yes. This is covered by test/CodeGenOpenCL/amdgpu-enqueue-kernel.cl where the 
block struct is passed directly to the kernel instead of by a pointer.



Comment at: lib/CodeGen/CGOpenCLRuntime.cpp:113
+
+llvm::Value *CGOpenCLRuntime::emitOpenCLEnqueuedBlock(CodeGenFunction ,
+  const Expr *E) {

Anastasia wrote:
> I am not particularly in favour of duplicating CodeGen functionality as it 
> typically has so many special cases that are hard to catch. Is this logic 
> needed in order to pass to block literal information  that the block is 
> enqueued?
This code is needed to emit separate functions for a block which is directly 
called and also enqueued as a kernel. Since the kernel needs to have proper 
calling convention and ABI, it cannot be emitted as the same function as when 
the block is called directly. Since it is OpenCL specific code, I found it is 
cleaner to separate this code as member of CGOpenCLRuntime instead of fitting 
it into CGF.EmitBlockLiteral.



Comment at: lib/CodeGen/CodeGenFunction.cpp:535
+if (i == 0 && IsBlock) {
+  ty = CGF.CGM.getTargetCodeGenInfo().getEnqueuedBlockArgumentType(
+  ASTCtx, *CGF.BlockInfo);

Anastasia wrote:
> I don't quite understand why we need to special case this? As far as I 
> undertsnad block argument is a `generic void* ` type but it's being cast to a 
> concrete block struct inside the block function. Do we gain anything from 
> having it a specific type here?
This argument is not part of BlockDecl. BlockDecl only has arguments shown up 
in the source code. The first argument in the LLVM block invoke function is 
generated by codegen and there is no correspondence in AST, so it has to be 
handled as a special case.


https://reviews.llvm.org/D38134



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


r313945 - Add support for attribute 'noescape'.

2017-09-21 Thread Akira Hatanaka via cfe-commits
Author: ahatanak
Date: Thu Sep 21 17:41:05 2017
New Revision: 313945

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

The attribute informs the compiler that the annotated pointer parameter
of a function cannot escape and enables IRGen to attach attribute
'nocapture' to parameters that are annotated with the attribute. That is
the only optimization that currently takes advantage of 'noescape', but
there are other optimizations that will be added later that improves
IRGen for ObjC blocks.

This recommits r313722, which was reverted in r313725 because clang
couldn't build compiler-rt. It failed to build because there were
function declarations that were missing 'noescape'. That has been fixed
in r313929.

rdar://problem/19886775

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

Modified:
cfe/trunk/include/clang/AST/ASTContext.h
cfe/trunk/include/clang/AST/Type.h
cfe/trunk/include/clang/Basic/Attr.td
cfe/trunk/include/clang/Basic/AttrDocs.td
cfe/trunk/include/clang/Basic/DiagnosticGroups.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/lib/AST/ASTContext.cpp
cfe/trunk/lib/AST/ItaniumMangle.cpp
cfe/trunk/lib/AST/TypePrinter.cpp
cfe/trunk/lib/CodeGen/CGCall.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaDeclCXX.cpp
cfe/trunk/lib/Sema/SemaDeclObjC.cpp
cfe/trunk/lib/Sema/SemaOverload.cpp
cfe/trunk/lib/Sema/SemaType.cpp
cfe/trunk/test/Misc/ast-dump-attr.cpp
cfe/trunk/test/Misc/pragma-attribute-supported-attributes-list.test

Modified: cfe/trunk/include/clang/AST/ASTContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/ASTContext.h?rev=313945=313944=313945=diff
==
--- cfe/trunk/include/clang/AST/ASTContext.h (original)
+++ cfe/trunk/include/clang/AST/ASTContext.h Thu Sep 21 17:41:05 2017
@@ -2413,9 +2413,30 @@ public:
 
   QualType mergeObjCGCQualifiers(QualType, QualType);
 
-  bool doFunctionTypesMatchOnExtParameterInfos(
- const FunctionProtoType *FromFunctionType,
- const FunctionProtoType *ToFunctionType);
+  /// This function merges the ExtParameterInfo lists of two functions. It
+  /// returns true if the lists are compatible. The merged list is returned in
+  /// NewParamInfos.
+  ///
+  /// \param FirstFnType The type of the first function.
+  ///
+  /// \param SecondFnType The type of the second function.
+  ///
+  /// \param CanUseFirst This flag is set to true if the first function's
+  /// ExtParameterInfo list can be used as the composite list of
+  /// ExtParameterInfo.
+  ///
+  /// \param CanUseSecond This flag is set to true if the second function's
+  /// ExtParameterInfo list can be used as the composite list of
+  /// ExtParameterInfo.
+  ///
+  /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
+  /// empty if none of the flags are set.
+  ///
+  bool mergeExtParameterInfo(
+  const FunctionProtoType *FirstFnType,
+  const FunctionProtoType *SecondFnType,
+  bool , bool ,
+  SmallVectorImpl );
 
   void ResetObjCLayout(const ObjCContainerDecl *CD);
 

Modified: cfe/trunk/include/clang/AST/Type.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/Type.h?rev=313945=313944=313945=diff
==
--- cfe/trunk/include/clang/AST/Type.h (original)
+++ cfe/trunk/include/clang/AST/Type.h Thu Sep 21 17:41:05 2017
@@ -3149,6 +3149,7 @@ public:
   ABIMask = 0x0F,
   IsConsumed  = 0x10,
   HasPassObjSize  = 0x20,
+  IsNoEscape  = 0x40,
 };
 unsigned char Data;
 
@@ -3189,6 +3190,19 @@ public:
   return Copy;
 }
 
+bool isNoEscape() const {
+  return Data & IsNoEscape;
+}
+
+ExtParameterInfo withIsNoEscape(bool NoEscape) const {
+  ExtParameterInfo Copy = *this;
+  if (NoEscape)
+Copy.Data |= IsNoEscape;
+  else
+Copy.Data &= ~IsNoEscape;
+  return Copy;
+}
+
 unsigned char getOpaqueValue() const { return Data; }
 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
   ExtParameterInfo result;

Modified: cfe/trunk/include/clang/Basic/Attr.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?rev=313945=313944=313945=diff
==
--- cfe/trunk/include/clang/Basic/Attr.td (original)
+++ cfe/trunk/include/clang/Basic/Attr.td Thu Sep 21 17:41:05 2017
@@ -1396,6 +1396,12 @@ def ObjCKindOf : TypeAttr {
   let Documentation = [Undocumented];
 }
 
+def NoEscape : Attr {
+  let Spellings = [GNU<"noescape">, CXX11<"clang", "noescape">];
+  let Subjects = SubjectList<[ParmVar]>;
+  let Documentation = [NoEscapeDocs];
+}
+
 def AssumeAligned : InheritableAttr {
   let Spellings = 

r313944 - [Analyzer] Log when auto-synthesized body is used.

2017-09-21 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep 21 17:37:12 2017
New Revision: 313944

URL: http://llvm.org/viewvc/llvm-project?rev=313944=rev
Log:
[Analyzer] Log when auto-synthesized body is used.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp?rev=313944=313943=313944=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp Thu Sep 21 17:37:12 2017
@@ -21,6 +21,9 @@
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/Debug.h"
+
+#define DEBUG_TYPE "static-analyzer-call-event"
 
 using namespace clang;
 using namespace ento;
@@ -343,7 +346,6 @@ ArrayRef AnyFunctionCall::
   return D->parameters();
 }
 
-
 RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const {
   const FunctionDecl *FD = getDecl();
   // Note that the AnalysisDeclContext will have the FunctionDecl with
@@ -352,8 +354,17 @@ RuntimeDefinition AnyFunctionCall::getRu
 AnalysisDeclContext *AD =
   getLocationContext()->getAnalysisDeclContext()->
   getManager()->getContext(FD);
-if (AD->getBody())
-  return RuntimeDefinition(AD->getDecl());
+bool IsAutosynthesized;
+Stmt* Body = AD->getBody(IsAutosynthesized);
+DEBUG({
+if (IsAutosynthesized)
+  llvm::dbgs() << "Using autosynthesized body for " << FD->getName()
+   << "\n";
+});
+if (Body) {
+  const Decl* Decl = AD->getDecl();
+  return RuntimeDefinition(Decl);
+}
   }
 
   return RuntimeDefinition();


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


[PATCH] D37656: [cfi] Set function attributes for __cfi_* functions.

2017-09-21 Thread Eric Christopher via Phabricator via cfe-commits
echristo added inline comments.



Comment at: clang/lib/CodeGen/CGExpr.cpp:2917
+CodeGenFunction , llvm::Function *F,
+bool ForceThumb) {
+  StringRef TargetCPU = CGF.getTarget().getTargetOpts().CPU;

I don't think we should be force setting thumb anywhere, it should be handled 
on a function by function basis the way we do all of the target attribute stuff.



Comment at: clang/lib/CodeGen/CGExpr.cpp:2926-2935
+  Features.reserve(DefaultFeatures.size() + ForceThumb);
+  if (ForceThumb && (Triple.isARM() || Triple.isThumb())) {
+for (auto  : DefaultFeatures)
+  if (S != "-thumb-mode" && S != "+thumb-mode")
+Features.push_back(S);
+Features.push_back("+thumb-mode");
+  } else {

All of this should be handled in lib/Basic/Targets/ARM.cpp 
ARMTargetInfo::initFeatureMap ?



Comment at: clang/lib/CodeGen/CGExpr.cpp:2961-2963
+  // attributes as SetLLVMFunctionAttributes sets. In particular, __cfi_check
+  // must use the default calling convention for the platform. ABI-changing
+  // flags like -mhard-float should not affect __cfi_check.

This is odd. Can you explain this a bit more?


https://reviews.llvm.org/D37656



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


LLVM buildmaster will be updated and restarted tonight

2017-09-21 Thread Galina Kistanova via cfe-commits
Hello everyone,

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

Thanks

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


[PATCH] D38118: [CodeGen][ObjC] Build the global block structure before emitting the body of global block invoke functions

2017-09-21 Thread John McCall via Phabricator via cfe-commits
rjmccall accepted this revision.
rjmccall added a comment.
This revision is now accepted and ready to land.

LGTM with one tweak.




Comment at: lib/CodeGen/CGBlocks.cpp:1124
LocalDeclMap,
-   false);
+   false, true);
   }

Please /*comment*/ the meaning of these bools.


https://reviews.llvm.org/D38118



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


r313943 - Extend -ast-dump for CXXRecordDecl to dump the flags from the DefinitionData.

2017-09-21 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Thu Sep 21 17:11:15 2017
New Revision: 313943

URL: http://llvm.org/viewvc/llvm-project?rev=313943=rev
Log:
Extend -ast-dump for CXXRecordDecl to dump the flags from the DefinitionData.

Modified:
cfe/trunk/lib/AST/ASTDumper.cpp
cfe/trunk/test/Frontend/float16.cpp
cfe/trunk/test/Misc/ast-dump-decl.cpp
cfe/trunk/test/Misc/ast-dump-invalid.cpp
cfe/trunk/test/Misc/pragma-attribute-cxx-subject-match-rules.cpp
cfe/trunk/test/Misc/pragma-attribute-cxx.cpp
cfe/trunk/test/Modules/cxx-templates.cpp
cfe/trunk/test/SemaTemplate/default-expr-arguments-3.cpp

Modified: cfe/trunk/lib/AST/ASTDumper.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/AST/ASTDumper.cpp?rev=313943=313942=313943=diff
==
--- cfe/trunk/lib/AST/ASTDumper.cpp (original)
+++ cfe/trunk/lib/AST/ASTDumper.cpp Thu Sep 21 17:11:15 2017
@@ -1376,6 +1376,128 @@ void ASTDumper::VisitCXXRecordDecl(const
   if (!D->isCompleteDefinition())
 return;
 
+  dumpChild([=] {
+{
+  ColorScope Color(*this, DeclKindNameColor);
+  OS << "DefinitionData";
+}
+#define FLAG(fn, name) if (D->fn()) OS << " " #name;
+FLAG(isParsingBaseSpecifiers, parsing_base_specifiers);
+
+FLAG(isGenericLambda, generic);
+FLAG(isLambda, lambda);
+
+FLAG(canPassInRegisters, pass_in_registers);
+FLAG(isEmpty, empty);
+FLAG(isAggregate, aggregate);
+FLAG(isStandardLayout, standard_layout);
+FLAG(isTriviallyCopyable, trivially_copyable);
+FLAG(isPOD, pod);
+FLAG(isTrivial, trivial);
+FLAG(isPolymorphic, polymorphic);
+FLAG(isAbstract, abstract);
+FLAG(isLiteral, literal);
+
+FLAG(hasUserDeclaredConstructor, has_user_declared_ctor);
+FLAG(hasConstexprNonCopyMoveConstructor, has_constexpr_non_copy_move_ctor);
+FLAG(hasMutableFields, has_mutable_fields);
+FLAG(hasVariantMembers, has_variant_members);
+FLAG(allowConstDefaultInit, can_const_default_init);
+
+dumpChild([=] {
+  {
+ColorScope Color(*this, DeclKindNameColor);
+OS << "DefaultConstructor";
+  }
+  FLAG(hasDefaultConstructor, exists);
+  FLAG(hasTrivialDefaultConstructor, trivial);
+  FLAG(hasNonTrivialDefaultConstructor, non_trivial);
+  FLAG(hasUserProvidedDefaultConstructor, user_provided);
+  FLAG(hasConstexprDefaultConstructor, constexpr);
+  FLAG(needsImplicitDefaultConstructor, needs_implicit);
+  FLAG(defaultedDefaultConstructorIsConstexpr, defaulted_is_constexpr);
+});
+
+dumpChild([=] {
+  {
+ColorScope Color(*this, DeclKindNameColor);
+OS << "CopyConstructor";
+  }
+  FLAG(hasSimpleCopyConstructor, simple);
+  FLAG(hasTrivialCopyConstructor, trivial);
+  FLAG(hasNonTrivialCopyConstructor, non_trivial);
+  FLAG(hasUserDeclaredCopyConstructor, user_declared);
+  FLAG(hasCopyConstructorWithConstParam, has_const_param);
+  FLAG(needsImplicitCopyConstructor, needs_implicit);
+  FLAG(needsOverloadResolutionForCopyConstructor,
+   needs_overload_resolution);
+  if (!D->needsOverloadResolutionForCopyConstructor())
+FLAG(defaultedCopyConstructorIsDeleted, defaulted_is_deleted);
+  FLAG(implicitCopyConstructorHasConstParam, implicit_has_const_param);
+});
+
+dumpChild([=] {
+  {
+ColorScope Color(*this, DeclKindNameColor);
+OS << "MoveConstructor";
+  }
+  FLAG(hasMoveConstructor, exists);
+  FLAG(hasSimpleMoveConstructor, simple);
+  FLAG(hasTrivialMoveConstructor, trivial);
+  FLAG(hasNonTrivialMoveConstructor, non_trivial);
+  FLAG(hasUserDeclaredMoveConstructor, user_declared);
+  FLAG(needsImplicitMoveConstructor, needs_implicit);
+  FLAG(needsOverloadResolutionForMoveConstructor,
+   needs_overload_resolution);
+  if (!D->needsOverloadResolutionForMoveConstructor())
+FLAG(defaultedMoveConstructorIsDeleted, defaulted_is_deleted);
+});
+
+dumpChild([=] {
+  {
+ColorScope Color(*this, DeclKindNameColor);
+OS << "CopyAssignment";
+  }
+  FLAG(hasTrivialCopyAssignment, trivial);
+  FLAG(hasNonTrivialCopyAssignment, non_trivial);
+  FLAG(hasCopyAssignmentWithConstParam, has_const_param);
+  FLAG(hasUserDeclaredCopyAssignment, user_declared);
+  FLAG(needsImplicitCopyAssignment, needs_implicit);
+  FLAG(needsOverloadResolutionForCopyAssignment, 
needs_overload_resolution);
+  FLAG(implicitCopyAssignmentHasConstParam, implicit_has_const_param);
+});
+
+dumpChild([=] {
+  {
+ColorScope Color(*this, DeclKindNameColor);
+OS << "MoveAssignment";
+  }
+  FLAG(hasMoveAssignment, exists);
+  FLAG(hasSimpleMoveAssignment, simple);
+  FLAG(hasTrivialMoveAssignment, trivial);
+  FLAG(hasNonTrivialMoveAssignment, non_trivial);
+  FLAG(hasUserDeclaredMoveAssignment, user_declared);
+  

[PATCH] D38159: [clang] Fix printf fixit for objc specific types

2017-09-21 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
alexshap created this revision.

Let's take a look at the following example: 
for the triple thumbv7-apple-ios8.0.0 ssize_t is long and size_t is unsigned 
long,
while NSInteger is int and NSUinteger is unsigned int.
Following 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
Clang will catch it and insert a cast to long, for example
 printf("%zd", getNSInteger())
will be replaced with 
 printf("%zd", (long)getNSInteger())
but since the underlying type of ssize_t is long the specifier "%zd" is not 
getting replaced.
This diff changes this behavior to enabling replacing the specifier "%zd" with 
the correct one.

Test plan: make check-all


Repository:
  rL LLVM

https://reviews.llvm.org/D38159

Files:
  lib/Sema/SemaChecking.cpp
  test/FixIt/fixit-format-ios.m


Index: test/FixIt/fixit-format-ios.m
===
--- test/FixIt/fixit-format-ios.m
+++ test/FixIt/fixit-format-ios.m
@@ -0,0 +1,27 @@
+// RUN: cp %s %t
+// RUN: %clang_cc1 -triple thumbv7-apple-ios8.0.0 -fsyntax-only -fblocks 
-Wformat -fixit %t
+// RUN: grep -v CHECK %t | FileCheck %s
+
+int printf(const char * restrict, ...);
+typedef unsigned int NSUInteger;
+typedef int NSInteger;
+NSUInteger getNSUInteger();
+NSInteger getNSInteger();
+
+void test() {
+  // For thumbv7-apple-ios8.0.0 
+  // the underlying type of size_t is unsigned long 
+  // and for ssize_t it is long.
+
+  printf("test 1: %zu", getNSUInteger()); 
+  // CHECK: printf("test 1: %lu", (unsigned long)getNSUInteger());
+
+  printf("test 2: %zu %zu", getNSUInteger(), getNSUInteger());
+  // CHECK: printf("test 2: %lu %lu", (unsigned long)getNSUInteger(), 
(unsigned long)getNSUInteger());
+
+  printf("test 3: %zd", getNSInteger()); 
+  // CHECK: printf("test 3: %ld", (long)getNSInteger());
+
+  printf("test 4: %zd %zd", getNSInteger(), getNSInteger());
+  // CHECK: printf("test 4: %ld %ld", (long)getNSInteger(), 
(long)getNSInteger());
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -6346,7 +6346,7 @@
   CastFix << ")";
 
   SmallVector Hints;
-  if (!AT.matchesType(S.Context, IntendedTy))
+  if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 
 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
 
   if (const CStyleCastExpr *CCast = dyn_cast(E)) {


Index: test/FixIt/fixit-format-ios.m
===
--- test/FixIt/fixit-format-ios.m
+++ test/FixIt/fixit-format-ios.m
@@ -0,0 +1,27 @@
+// RUN: cp %s %t
+// RUN: %clang_cc1 -triple thumbv7-apple-ios8.0.0 -fsyntax-only -fblocks -Wformat -fixit %t
+// RUN: grep -v CHECK %t | FileCheck %s
+
+int printf(const char * restrict, ...);
+typedef unsigned int NSUInteger;
+typedef int NSInteger;
+NSUInteger getNSUInteger();
+NSInteger getNSInteger();
+
+void test() {
+  // For thumbv7-apple-ios8.0.0 
+  // the underlying type of size_t is unsigned long 
+  // and for ssize_t it is long.
+
+  printf("test 1: %zu", getNSUInteger()); 
+  // CHECK: printf("test 1: %lu", (unsigned long)getNSUInteger());
+
+  printf("test 2: %zu %zu", getNSUInteger(), getNSUInteger());
+  // CHECK: printf("test 2: %lu %lu", (unsigned long)getNSUInteger(), (unsigned long)getNSUInteger());
+
+  printf("test 3: %zd", getNSInteger()); 
+  // CHECK: printf("test 3: %ld", (long)getNSInteger());
+
+  printf("test 4: %zd %zd", getNSInteger(), getNSInteger());
+  // CHECK: printf("test 4: %ld %ld", (long)getNSInteger(), (long)getNSInteger());
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -6346,7 +6346,7 @@
   CastFix << ")";
 
   SmallVector Hints;
-  if (!AT.matchesType(S.Context, IntendedTy))
+  if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 
 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
 
   if (const CStyleCastExpr *CCast = dyn_cast(E)) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37656: [cfi] Set function attributes for __cfi_* functions.

2017-09-21 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis added a comment.

ping


https://reviews.llvm.org/D37656



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


[PATCH] D37822: [OpenCL] Clean up and add missing fields for block struct

2017-09-21 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In https://reviews.llvm.org/D37822#877903, @Anastasia wrote:

> In https://reviews.llvm.org/D37822#877572, @yaxunl wrote:
>
> > In https://reviews.llvm.org/D37822#873876, @Anastasia wrote:
> >
> > > In https://reviews.llvm.org/D37822#872446, @yaxunl wrote:
> > >
> > > > In https://reviews.llvm.org/D37822#872291, @Anastasia wrote:
> > > >
> > > > > Could you please explain a bit more why the alignment have to be put 
> > > > > explicitly in the struct? I am just not very convinced this is 
> > > > > general enough.
> > > >
> > > >
> > > > The captured variables are fields of the block literal struct. Due to 
> > > > alignment requirement of these fields, there is alignment requirement of
> > > >  the block literal struct. The ISA of the block invoke function is 
> > > > generated with the assumption of these alignments. If the block literal 
> > > > is
> > > >  allocated at a memory address not satisfying the alignment 
> > > > requirement, the kernel behavior is undefined.
> > > >
> > > > Generally, __enqueue_kernel library function needs to prepare the 
> > > > kernel argument before launching the kernel. It usually does this by 
> > > > copying
> > > >  the block literal to some buffer then pass the address of the buffer 
> > > > to the kernel. Then the address of the buffer has to satisfy the 
> > > > alignment
> > > >  requirement.
> > > >
> > > > If this block literal struct is not general enough, how about add 
> > > > another field as target reserved size, and leave the remaining space of 
> > > > header for
> > > >  target specific use. And add a target hook to allow target fill the 
> > > > reserved space, e.g.
> > > >
> > > >   struct __opencl_block_literal {
> > > > int total_size;
> > > > int align;
> > > > __generic void *invoke;
> > > > int target_reserved_size; /* round up to 4 bytes */
> > > > int target_reserved[];
> > > > /* captures */
> > > >   };
> > > >
> > >
> > >
> > > I like the idea of the target reserved part actually. But not sure how it 
> > > could be used without adding any target specific methods?
> >
> >
> > If we decide to add target reserved fields, I can add target hooks to fill 
> > these fields. However I would suggest to leave this for future since I 
> > don't see there is need for other fields for now.
>
>
> I could imagine it can be usefull for some vendor implementations.




> 
> 
>>> However, I am still not clear why the alignment of this struct has to be 
>>> different from any other struct Clang produces. Normally the alignment of 
>>> objects have to be known during IR generation to put them correctly in the 
>>> attributes of generated alloca, store and loads. But as a field inside 
>>> struct I don't know how it can be useful. I would imagine `enqueue_kernel` 
>>> would just operate on the block as if it would be an arbitrary buffer of 
>>> data. Also would size of the struct not account for any padding to make 
>>> sure the alignment can be deduced based on it correctly?
>> 
>> enqueue_kernel needs to pass the block struct to the kernel. Let's assume it 
>> does this by copying the block struct to a buffer. If enqueue_kernel does 
>> not know the alignment of the struct, it can only put it at an arbitrary 
>> address in the buffer. Then the kernel has to copy the struct to an aligned 
>> private memory and load the fields. However, if the enqueued_kernel knows 
>> the alignment of the struct, it can put it at an address satisfying the 
>> alignment. Then the kernel can load the fields directly from the buffer, 
>> skips the step of copying to an aligned private memory. Therefore, alignment 
>> of the block struct is usually a useful information for enqueue_kernel. I 
>> think that's why in the SPIRV spec OpEnqueueKernel requires an alignment 
>> operand for the block context.
> 
> Ok, I just think in C if you use `malloc` to obtain a pointer to some memory 
> location it doesn't take any alignment information. Then you can use the 
> pointer to copy any data including the struct into the location its pointed 
> to. And the pointer can be used later on correctly. I think the alignment is 
> deduced in this case from the type or the size of an object. Do you know 
> where the alignment information is used for SPIRV call? Also how is the block 
> represented in SPIRV?

If you just use malloc and put your struct in it, there is no guarantee that 
your struct is aligned at the required alignment, then your kernel cannot load 
a field directly from that memory. For example, if your first field is an int 
and the instruction can only load an int from an addr aligned at 4, and your 
malloc'ed addr is aligned at 1, then you cannot load that int directly. 
Instead, you need to copy the 4 bytes to an addr aligned at 4, then use that 
instruction to load it. If you use posix_memalign to get an aligned buffer, 
then your kernel can generate more efficient code.

OpEnqueueKernel instruction in SPIR-V is for representing 

Re: r313386 - [Sema] Error out early for tags defined inside an enumeration.

2017-09-21 Thread Richard Smith via cfe-commits
On 15 September 2017 at 12:51, Volodymyr Sapsai via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: vsapsai
> Date: Fri Sep 15 12:51:42 2017
> New Revision: 313386
>
> URL: http://llvm.org/viewvc/llvm-project?rev=313386=rev
> Log:
> [Sema] Error out early for tags defined inside an enumeration.
>
> This fixes PR28903 by avoiding access check for inner enum constant. We
> are performing access check because one enum constant references another
> and because enum is defined in CXXRecordDecl. But access check doesn't
> work because FindDeclaringClass doesn't expect more than one EnumDecl
> and because inner enum has access AS_none due to not being an immediate
> child of a record.
>
> The change detects an enum is defined in wrong place and allows to skip
> parsing its body. Access check is skipped together with body parsing.
> There was no crash in C, added test case to cover the new error.
>
> rdar://problem/28530809
>
> Reviewers: rnk, doug.gregor, rsmith
>
> Reviewed By: doug.gregor
>
> Subscribers: cfe-commits
>
> Differential Revision: https://reviews.llvm.org/D37089
>
>
> Modified:
> cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> cfe/trunk/lib/Sema/SemaDecl.cpp
> cfe/trunk/test/Sema/enum.c
> cfe/trunk/test/SemaCXX/enum.cpp
>
> Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/
> DiagnosticSemaKinds.td?rev=313386=313385=313386=diff
> 
> ==
> --- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
> +++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Fri Sep 15
> 12:51:42 2017
> @@ -1335,6 +1335,8 @@ def err_type_defined_in_alias_template :
>"%0 cannot be defined in a type alias template">;
>  def err_type_defined_in_condition : Error<
>"%0 cannot be defined in a condition">;
> +def err_type_defined_in_enum : Error<
> +  "%0 cannot be defined in an enumeration">;
>
>  def note_pure_virtual_function : Note<
>"unimplemented pure virtual method %0 in %1">;
>
> Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/
> SemaDecl.cpp?rev=313386=313385=313386=diff
> 
> ==
> --- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
> +++ cfe/trunk/lib/Sema/SemaDecl.cpp Fri Sep 15 12:51:42 2017
> @@ -13928,6 +13928,12 @@ CreateNewDecl:
>  Invalid = true;
>}
>
> +  if (!Invalid && TUK == TUK_Definition && DC->getDeclKind() ==
> Decl::Enum) {
> +Diag(New->getLocation(), diag::err_type_defined_in_enum)
> +  << Context.getTagDeclType(New);
> +Invalid = true;
> +  }
>

This looks like the wrong fix. As noted elsewhere, this is wrong in C. And
in C++, the relevant context is a type-specifier, which should be rejected
due to the check 7 lines above.

It looks like the actual bug is that we don't consider the type within a
C99 compound literal to be a type-specifier. The fact that the context is
an enumeration is irrelevant.


> +
>// Maybe add qualifier info.
>if (SS.isNotEmpty()) {
>  if (SS.isSet()) {
>
> Modified: cfe/trunk/test/Sema/enum.c
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/
> enum.c?rev=313386=313385=313386=diff
> 
> ==
> --- cfe/trunk/test/Sema/enum.c (original)
> +++ cfe/trunk/test/Sema/enum.c Fri Sep 15 12:51:42 2017
> @@ -123,3 +123,14 @@ int NegativeShortTest[NegativeShort == -
>  // PR24610
>  enum Color { Red, Green, Blue }; // expected-note{{previous use is here}}
>  typedef struct Color NewColor; // expected-error {{use of 'Color' with
> tag type that does not match previous declaration}}
> +
> +// PR28903
> +struct PR28903 {
> +  enum {
> +PR28903_A = (enum { // expected-error-re {{'enum PR28903::(anonymous
> at {{.*}})' cannot be defined in an enumeration}}
> +  PR28903_B,
> +  PR28903_C = PR28903_B
> +})0
> +  };
> +  int makeStructNonEmpty;
> +};
>
> Modified: cfe/trunk/test/SemaCXX/enum.cpp
> URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/test/
> SemaCXX/enum.cpp?rev=313386=313385=313386=diff
> 
> ==
> --- cfe/trunk/test/SemaCXX/enum.cpp (original)
> +++ cfe/trunk/test/SemaCXX/enum.cpp Fri Sep 15 12:51:42 2017
> @@ -110,3 +110,13 @@ enum { overflow = 123456 * 234567 };
>  // expected-warning@-2 {{not an integral constant expression}}
>  // expected-note@-3 {{value 28958703552 is outside the range of
> representable values}}
>  #endif
> +
> +// PR28903
> +struct PR28903 {
> +  enum {
> +PR28903_A = (enum { // expected-error-re {{'PR28903::(anonymous enum
> at {{.*}})' cannot be defined in an enumeration}}
> +  PR28903_B,
> +  PR28903_C = PR28903_B
> +})
> +  };
> +};
>
>
> ___
> 

r313928 - Resubmit "[lit] Refactor out some more common lit configuration code."

2017-09-21 Thread Zachary Turner via cfe-commits
Author: zturner
Date: Thu Sep 21 15:16:40 2017
New Revision: 313928

URL: http://llvm.org/viewvc/llvm-project?rev=313928=rev
Log:
Resubmit "[lit] Refactor out some more common lit configuration code."

There were two issues, one Python 3 specific related to Unicode,
and another which is that the tool substitution for lld no longer
rejected matches where a / preceded the tool name.

Modified:
cfe/trunk/test/lit.cfg.py

Modified: cfe/trunk/test/lit.cfg.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/lit.cfg.py?rev=313928=313927=313928=diff
==
--- cfe/trunk/test/lit.cfg.py (original)
+++ cfe/trunk/test/lit.cfg.py Thu Sep 21 15:16:40 2017
@@ -10,6 +10,7 @@ import lit.formats
 import lit.util
 
 from lit.llvm import llvm_config
+from lit.llvm import ToolFilter
 
 # Configuration file for the 'lit' test runner.
 
@@ -112,55 +113,12 @@ config.substitutions.append( ('%PATH%',
 if config.clang_examples:
 config.available_features.add('examples')
 
-# Note that when substituting %clang_cc1 also fill in the include directory of
-# the builtin headers. Those are part of even a freestanding environment, but
-# Clang relies on the driver to locate them.
-def getClangBuiltinIncludeDir(clang):
-# FIXME: Rather than just getting the version, we should have clang print
-# out its resource dir here in an easy to scrape form.
-cmd = subprocess.Popen([clang, '-print-file-name=include'],
-   stdout=subprocess.PIPE,
-   env=config.environment)
-if not cmd.stdout:
-  lit_config.fatal("Couldn't find the include dir for Clang ('%s')" % 
clang)
-dir = cmd.stdout.read().strip()
-if sys.platform in ['win32'] and not llvm_config.use_lit_shell:
-# Don't pass dosish path separator to msys bash.exe.
-dir = dir.replace('\\', '/')
-# Ensure the result is an ascii string, across Python2.5+ - Python3.
-return str(dir.decode('ascii'))
-
-def makeItaniumABITriple(triple):
-m = re.match(r'(\w+)-(\w+)-(\w+)', triple)
-if not m:
-  lit_config.fatal("Could not turn '%s' into Itanium ABI triple" % triple)
-if m.group(3).lower() != 'win32':
-  # All non-win32 triples use the Itanium ABI.
-  return triple
-return m.group(1) + '-' + m.group(2) + '-mingw32'
-
-def makeMSABITriple(triple):
-m = re.match(r'(\w+)-(\w+)-(\w+)', triple)
-if not m:
-  lit_config.fatal("Could not turn '%s' into MS ABI triple" % triple)
-isa = m.group(1).lower()
-vendor = m.group(2).lower()
-os = m.group(3).lower()
-if os == 'win32':
-  # If the OS is win32, we're done.
-  return triple
-if isa.startswith('x86') or isa == 'amd64' or re.match(r'i\d86', isa):
-  # For x86 ISAs, adjust the OS.
-  return isa + '-' + vendor + '-win32'
-# -win32 is not supported for non-x86 targets; use a default.
-return 'i686-pc-win32'
-
+builtin_include_dir = llvm_config.get_clang_builtin_include_dir(config.clang)
 config.substitutions.append( ('%clang_analyze_cc1',
   '%clang_cc1 -analyze %analyze') )
 config.substitutions.append( ('%clang_cc1',
   '%s -cc1 -internal-isystem %s -nostdsysteminc'
-  % (config.clang,
- getClangBuiltinIncludeDir(config.clang))) )
+  % (config.clang, builtin_include_dir)) )
 config.substitutions.append( ('%clang_cpp', ' ' + config.clang +
   ' --driver-mode=cpp '))
 config.substitutions.append( ('%clang_cl', ' ' + config.clang +
@@ -168,16 +126,20 @@ config.substitutions.append( ('%clang_cl
 config.substitutions.append( ('%clangxx', ' ' + config.clang +
   ' --driver-mode=g++ '))
 config.substitutions.append( ('%clang', ' ' + config.clang + ' ') )
-config.substitutions.append( ('%test_debuginfo', ' ' + config.llvm_src_root + 
'/utils/test_debuginfo.pl ') )
-config.substitutions.append( ('%itanium_abi_triple', 
makeItaniumABITriple(config.target_triple)) )
-config.substitutions.append( ('%ms_abi_triple', 
makeMSABITriple(config.target_triple)) )
-config.substitutions.append( ('%resource_dir', 
getClangBuiltinIncludeDir(config.clang)) )
+config.substitutions.append( ('%test_debuginfo',
+ ' ' + config.llvm_src_root +  
'/utils/test_debuginfo.pl ') )
+config.substitutions.append( ('%itanium_abi_triple',
+ 
llvm_config.make_itanium_abi_triple(config.target_triple)) )
+config.substitutions.append( ('%ms_abi_triple',
+ 
llvm_config.make_msabi_triple(config.target_triple)) )
+config.substitutions.append( ('%resource_dir', builtin_include_dir) )
 config.substitutions.append( ('%python', config.python_executable) )
 
 # The host triple might not be set, at least if we're compiling clang from
 # an already installed llvm.
 

r313927 - [Analyzer] Use CC environment variable to select analyzer path in SATestBuild.

2017-09-21 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep 21 15:12:49 2017
New Revision: 313927

URL: http://llvm.org/viewvc/llvm-project?rev=313927=rev
Log:
[Analyzer] Use CC environment variable to select analyzer path in SATestBuild.

This change is required to easily test the given checkout of the analyzer,
rather than the one bundled with a system compiler.

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

Modified:
cfe/trunk/utils/analyzer/SATestBuild.py

Modified: cfe/trunk/utils/analyzer/SATestBuild.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestBuild.py?rev=313927=313926=313927=diff
==
--- cfe/trunk/utils/analyzer/SATestBuild.py (original)
+++ cfe/trunk/utils/analyzer/SATestBuild.py Thu Sep 21 15:12:49 2017
@@ -142,7 +142,10 @@ def getSBOutputDirName(IsReferenceBuild)
 #--
 
 # Find Clang for static analysis.
-Clang = which("clang", os.environ['PATH'])
+if 'CC' in os.environ:
+Clang = os.environ['CC']
+else:
+Clang = which("clang", os.environ['PATH'])
 if not Clang:
 print "Error: cannot find 'clang' in PATH"
 sys.exit(-1)


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


[PATCH] D38158: [Sema] Null check in BuildDeclarationNameExpr

2017-09-21 Thread Yi Kong via Phabricator via cfe-commits
kongyi created this revision.
kongyi added a project: clang.

Qualtype may point to null if we cannot infer its type yet.

Fixes PR33843


Repository:
  rL LLVM

https://reviews.llvm.org/D38158

Files:
  lib/Sema/SemaExpr.cpp
  test/SemaCXX/typo-correction-crash.cpp


Index: test/SemaCXX/typo-correction-crash.cpp
===
--- test/SemaCXX/typo-correction-crash.cpp
+++ test/SemaCXX/typo-correction-crash.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -std=c++14 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++17 -verify %s
 auto check1() {
   return 1;
   return s; // expected-error {{use of undeclared identifier 's'}}
@@ -19,3 +19,5 @@
 FooRecord::NestedNamespace::type x; // expected-error {{no member named 
'NestedNamespace' in 'FooRecord'; did you mean 
'BarNamespace::NestedNamespace'?}}
 
 void cast_expr(int g) { +int(n)(g); } // expected-error {{undeclared 
identifier 'n'}}
+
+void bind() { for (const auto& [test,_] : _test_) { }; } // expected-error 
{{undeclared identifier '_test_'}}
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -2803,6 +2803,8 @@
 
   {
 QualType type = VD->getType();
+if (type.isNull())
+  return ExprError();
 if (auto *FPT = type->getAs()) {
   // C++ [except.spec]p17:
   //   An exception-specification is considered to be needed when:


Index: test/SemaCXX/typo-correction-crash.cpp
===
--- test/SemaCXX/typo-correction-crash.cpp
+++ test/SemaCXX/typo-correction-crash.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -std=c++14 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++17 -verify %s
 auto check1() {
   return 1;
   return s; // expected-error {{use of undeclared identifier 's'}}
@@ -19,3 +19,5 @@
 FooRecord::NestedNamespace::type x; // expected-error {{no member named 'NestedNamespace' in 'FooRecord'; did you mean 'BarNamespace::NestedNamespace'?}}
 
 void cast_expr(int g) { +int(n)(g); } // expected-error {{undeclared identifier 'n'}}
+
+void bind() { for (const auto& [test,_] : _test_) { }; } // expected-error {{undeclared identifier '_test_'}}
Index: lib/Sema/SemaExpr.cpp
===
--- lib/Sema/SemaExpr.cpp
+++ lib/Sema/SemaExpr.cpp
@@ -2803,6 +2803,8 @@
 
   {
 QualType type = VD->getType();
+if (type.isNull())
+  return ExprError();
 if (auto *FPT = type->getAs()) {
   // C++ [except.spec]p17:
   //   An exception-specification is considered to be needed when:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D37822: [OpenCL] Clean up and add missing fields for block struct

2017-09-21 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 116277.
yaxunl marked 6 inline comments as done.
yaxunl added a comment.

Revise by Anastasia's comments.


https://reviews.llvm.org/D37822

Files:
  lib/CodeGen/CGBlocks.cpp
  lib/CodeGen/CGOpenCLRuntime.cpp
  lib/CodeGen/CGOpenCLRuntime.h
  test/CodeGen/blocks-opencl.cl
  test/CodeGenOpenCL/blocks.cl
  test/CodeGenOpenCL/cl20-device-side-enqueue.cl

Index: test/CodeGenOpenCL/cl20-device-side-enqueue.cl
===
--- test/CodeGenOpenCL/cl20-device-side-enqueue.cl
+++ test/CodeGenOpenCL/cl20-device-side-enqueue.cl
@@ -7,7 +7,7 @@
 typedef struct {int a;} ndrange_t;
 
 // N.B. The check here only exists to set BL_GLOBAL
-// COMMON: @block_G =  addrspace(1) constant void (i8 addrspace(3)*) addrspace(4)* addrspacecast (void (i8 addrspace(3)*) addrspace(1)* bitcast ({ i8**, i32, i32, i8*, %struct.__block_descriptor addrspace(2)* } addrspace(1)* [[BL_GLOBAL:@__block_literal_global(\.[0-9]+)?]] to void (i8 addrspace(3)*) addrspace(1)*) to void (i8 addrspace(3)*) addrspace(4)*)
+// COMMON: @block_G =  addrspace(1) constant void (i8 addrspace(3)*) addrspace(4)* addrspacecast (void (i8 addrspace(3)*) addrspace(1)* bitcast ({ i32, i32, i8 addrspace(4)* } addrspace(1)* [[BL_GLOBAL:@__block_literal_global(\.[0-9]+)?]] to void (i8 addrspace(3)*) addrspace(1)*) to void (i8 addrspace(3)*) addrspace(4)*)
 const bl_t block_G = (bl_t) ^ (local void *a) {};
 
 kernel void device_side_enqueue(global int *a, global int *b, int i) {
@@ -27,9 +27,10 @@
   // COMMON: [[NDR:%[a-z0-9]+]] = alloca %struct.ndrange_t, align 4
   // COMMON: [[DEF_Q:%[0-9]+]] = load %opencl.queue_t{{.*}}*, %opencl.queue_t{{.*}}** %default_queue
   // COMMON: [[FLAGS:%[0-9]+]] = load i32, i32* %flags
-  // COMMON: [[BL:%[0-9]+]] = bitcast <{ i8*, i32, i32, i8*, %struct.__block_descriptor addrspace(2)*, i32{{.*}}, i32{{.*}}, i32{{.*}} }>* %block to void ()*
+  // B32: [[BL:%[0-9]+]] = bitcast <{ i32, i32, i8 addrspace(4)*, i32 addrspace(1)*, i32, i32 addrspace(1)* }>* %block to void ()*
+  // B64: [[BL:%[0-9]+]] = bitcast <{ i32, i32, i8 addrspace(4)*, i32 addrspace(1)*, i32 addrspace(1)*, i32 }>* %block to void ()*
   // COMMON: [[BL_I8:%[0-9]+]] = addrspacecast void ()* [[BL]] to i8 addrspace(4)*
-  // COMMON: call i32 @__enqueue_kernel_basic(%opencl.queue_t{{.*}}* [[DEF_Q]], i32 [[FLAGS]], %struct.ndrange_t* byval [[NDR]]{{(.[0-9]+)?}}, i8 addrspace(4)* [[BL_I8]])
+  // COMMON: call i32 @__enqueue_kernel_basic(%opencl.queue_t{{.*}}* [[DEF_Q]], i32 [[FLAGS]], %struct.ndrange_t* byval [[NDR]]{{([0-9]+)?}}, i8 addrspace(4)* [[BL_I8]])
   enqueue_kernel(default_queue, flags, ndrange,
  ^(void) {
a[i] = b[i];
@@ -39,7 +40,7 @@
   // COMMON: [[FLAGS:%[0-9]+]] = load i32, i32* %flags
   // COMMON: [[WAIT_EVNT:%[0-9]+]] = addrspacecast %opencl.clk_event_t{{.*}}** %event_wait_list to %opencl.clk_event_t{{.*}}* addrspace(4)*
   // COMMON: [[EVNT:%[0-9]+]] = addrspacecast %opencl.clk_event_t{{.*}}** %clk_event to %opencl.clk_event_t{{.*}}* addrspace(4)*
-  // COMMON: [[BL:%[0-9]+]] = bitcast <{ i8*, i32, i32, i8*, %struct.__block_descriptor addrspace(2)*, i32{{.*}}, i32{{.*}}, i32{{.*}} }>* %block3 to void ()*
+  // COMMON: [[BL:%[0-9]+]] = bitcast <{ i32, i32, i8 addrspace(4)*, i32{{.*}}, i32{{.*}}, i32{{.*}} }>* %block3 to void ()*
   // COMMON: [[BL_I8:%[0-9]+]] = addrspacecast void ()* [[BL]] to i8 addrspace(4)*
   // COMMON: call i32 @__enqueue_kernel_basic_events(%opencl.queue_t{{.*}}* [[DEF_Q]], i32 [[FLAGS]],  %struct.ndrange_t* {{.*}}, i32 2, %opencl.clk_event_t{{.*}}* addrspace(4)* [[WAIT_EVNT]], %opencl.clk_event_t{{.*}}* addrspace(4)* [[EVNT]], i8 addrspace(4)* [[BL_I8]])
   enqueue_kernel(default_queue, flags, ndrange, 2, _wait_list, _event,
@@ -52,11 +53,11 @@
   // B32: %[[TMP:.*]] = alloca [1 x i32]
   // B32: %[[TMP1:.*]] = getelementptr [1 x i32], [1 x i32]* %[[TMP]], i32 0, i32 0
   // B32: store i32 256, i32* %[[TMP1]], align 4
-  // B32: call i32 @__enqueue_kernel_vaargs(%opencl.queue_t{{.*}}* [[DEF_Q]], i32 [[FLAGS]], %struct.ndrange_t* [[NDR]]{{(.[0-9]+)?}}, i8 addrspace(4)* addrspacecast (i8 addrspace(1)* bitcast ({ i8**, i32, i32, i8*, %struct.__block_descriptor addrspace(2)* } addrspace(1)* @__block_literal_global{{(.[0-9]+)?}} to i8 addrspace(1)*) to i8 addrspace(4)*), i32 1, i32* %[[TMP1]])
+  // B32: call i32 @__enqueue_kernel_vaargs(%opencl.queue_t{{.*}}* [[DEF_Q]], i32 [[FLAGS]], %struct.ndrange_t* [[NDR]]{{([0-9]+)?}}, i8 addrspace(4)* addrspacecast (i8 addrspace(1)* bitcast ({ i32, i32, i8 addrspace(4)* } addrspace(1)* @__block_literal_global{{(.[0-9]+)?}} to i8 addrspace(1)*) to i8 addrspace(4)*), i32 1, i32* %[[TMP1]])
   // B64: %[[TMP:.*]] = alloca [1 x i64]
   // B64: %[[TMP1:.*]] = getelementptr [1 x i64], [1 x i64]* %[[TMP]], i32 0, i32 0
   // B64: store i64 256, i64* %[[TMP1]], align 8
-  // B64: call i32 @__enqueue_kernel_vaargs(%opencl.queue_t{{.*}}* [[DEF_Q]], i32 [[FLAGS]], 

[PATCH] D32520: Support __fp16 vectors

2017-09-21 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added inline comments.



Comment at: lib/CodeGen/CGExprScalar.cpp:1042
+}
+
+assert(SrcElementTy->isFloatingPointTy() &&

bruno wrote:
> What happens if the SrcElementTy is float and DstElementTy isn't? Seems like 
> it will hit the assertion below.
That's not supposed to happen since there are only three cases we have to 
consider here:

1. truncation from an int vector to a short vector
2. promotion from a half vector to a float vector
3. truncation from a float vector to a half vector

I've cleaned up the assertions and moved them up to make the code clearer.



Comment at: lib/Sema/SemaExpr.cpp:7511
+  // If this is a compound assignment, allow converting the RHS to the type
+  // of the LHS.
+  if (IsCompAssign && isVector(LHSType, Context.HalfTy)) {

bruno wrote:
> Since it seems that you're always doing the same conversion (the only 
> variable input here is the number of elements), can you update the comment to 
> mention the exact conversion?
It turns out this code isn't needed at all. I accidentally left the code in 
that I had in my local branch. The conversions between half vectors and float 
vectors take place after the operands are checked, so both the LHS and the RHS 
are still half vectors at this point.

Sorry for causing confusion.



Comment at: lib/Sema/SemaExpr.cpp:11537
+  // Some of the binary operations require promoting operands of half vector
+  // and truncating the result. For now, we do this only when HalfArgsAndReturn
+  // is set (that is, when the target is arm or arm64).

bruno wrote:
> What about `of half vector and truncating the result` to `of half vector to 
> float and truncating the result back to half`
I also changed the comment in CreateBuiltinUnaryOp.



Comment at: lib/Sema/SemaExpr.cpp:11978
+// truncating the result. For now, we do this only when HalfArgsAndReturns
+// is set (that is, when the target is arm or arm64).
+ConvertHalfVec =

bruno wrote:
> This same logic is used elsewhere in the patch, perhaps factor it out into a 
> static function?
I factored it out to function 'needsConversionOfHalfVec'.


https://reviews.llvm.org/D32520



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


[PATCH] D32520: Support __fp16 vectors

2017-09-21 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 116275.
ahatanak marked 8 inline comments as done.
ahatanak added a comment.

Address review comments.


https://reviews.llvm.org/D32520

Files:
  lib/CodeGen/CGExprScalar.cpp
  lib/Sema/SemaExpr.cpp
  test/CodeGen/fp16vec-ops.c
  test/Sema/fp16vec-sema.c

Index: test/Sema/fp16vec-sema.c
===
--- /dev/null
+++ test/Sema/fp16vec-sema.c
@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+typedef __fp16 half4 __attribute__ ((vector_size (8)));
+typedef float float4 __attribute__ ((vector_size (16)));
+typedef short short4 __attribute__ ((vector_size (8)));
+typedef int int4 __attribute__ ((vector_size (16)));
+
+half4 hv0, hv1;
+float4 fv0, fv1;
+short4 sv0;
+int4 iv0;
+
+void testFP16Vec(int c) {
+  hv0 = hv0 + hv1;
+  hv0 = hv0 - hv1;
+  hv0 = hv0 * hv1;
+  hv0 = hv0 / hv1;
+  hv0 = c ? hv0 : hv1;
+  hv0 += hv1;
+  hv0 -= hv1;
+  hv0 *= hv1;
+  hv0 /= hv1;
+  sv0 = hv0 == hv1;
+  sv0 = hv0 != hv1;
+  sv0 = hv0 < hv1;
+  sv0 = hv0 > hv1;
+  sv0 = hv0 <= hv1;
+  sv0 = hv0 >= hv1;
+  sv0 = hv0 || hv1; // expected-error{{logical expression with vector types 'half4' (vector of 4 '__fp16' values) and 'half4' is only supported in C++}}
+  sv0 = hv0 && hv1; // expected-error{{logical expression with vector types 'half4' (vector of 4 '__fp16' values) and 'half4' is only supported in C++}}
+
+  // Implicit conversion between half vectors and float vectors are not allowed.
+  hv0 = fv0; // expected-error{{assigning to}}
+  fv0 = hv0; // expected-error{{assigning to}}
+  hv0 = (half4)fv0; // expected-error{{invalid conversion between}}
+  fv0 = (float4)hv0; // expected-error{{invalid conversion between}}
+  hv0 = fv0 + fv1; // expected-error{{assigning to}}
+  fv0 = hv0 + hv1; // expected-error{{assigning to}}
+  hv0 = hv0 + fv1; // expected-error{{cannot convert between vector}}
+  hv0 = c ? hv0 : fv1; // expected-error{{cannot convert between vector}}
+  sv0 = hv0 == fv1; // expected-error{{cannot convert between vector}}
+  sv0 = hv0 < fv1; // expected-error{{cannot convert between vector}}
+  sv0 = hv0 || fv1; // expected-error{{cannot convert between vector}} expected-error{{invalid operands to binary expression}}
+  iv0 = hv0 == hv1; // expected-error{{assigning to}}
+
+  // FIXME: clang currently disallows using these operators on vectors, which is
+  // allowed by gcc.
+  sv0 = !hv0; // expected-error{{invalid argument type}}
+  hv0++; // expected-error{{cannot increment value of type}}
+  ++hv0; // expected-error{{cannot increment value of type}}
+}
Index: test/CodeGen/fp16vec-ops.c
===
--- /dev/null
+++ test/CodeGen/fp16vec-ops.c
@@ -0,0 +1,162 @@
+// REQUIRES: arm-registered-target
+// RUN: %clang_cc1 -triple arm64-apple-ios9 -emit-llvm -o - -fallow-half-arguments-and-returns %s | FileCheck %s --check-prefix=CHECK
+// RUN: %clang_cc1 -triple armv7-apple-ios9 -emit-llvm -o - -fallow-half-arguments-and-returns %s | FileCheck %s --check-prefix=CHECK
+
+typedef __fp16 half4 __attribute__ ((vector_size (8)));
+typedef short short4 __attribute__ ((vector_size (8)));
+
+half4 hv0, hv1;
+short4 sv0;
+
+// CHECK-LABEL: testFP16Vec0
+// CHECK: %[[V0:.*]] = load <4 x half>, <4 x half>* @hv0, align 8
+// CHECK: %[[CONV:.*]] = fpext <4 x half> %[[V0]] to <4 x float>
+// CHECK: %[[V1:.*]] = load <4 x half>, <4 x half>* @hv1, align 8
+// CHECK: %[[CONV1:.*]] = fpext <4 x half> %[[V1]] to <4 x float>
+// CHECK: %[[ADD:.*]] = fadd <4 x float> %[[CONV]], %[[CONV1]]
+// CHECK: %[[CONV2:.*]] = fptrunc <4 x float> %[[ADD]] to <4 x half>
+// CHECK: store <4 x half> %[[CONV2]], <4 x half>* @hv0, align 8
+// CHECK: %[[V2:.*]] = load <4 x half>, <4 x half>* @hv0, align 8
+// CHECK: %[[CONV3:.*]] = fpext <4 x half> %[[V2]] to <4 x float>
+// CHECK: %[[V3:.*]] = load <4 x half>, <4 x half>* @hv1, align 8
+// CHECK: %[[CONV4:.*]] = fpext <4 x half> %[[V3]] to <4 x float>
+// CHECK: %[[SUB:.*]] = fsub <4 x float> %[[CONV3]], %[[CONV4]]
+// CHECK: %[[CONV5:.*]] = fptrunc <4 x float> %[[SUB]] to <4 x half>
+// CHECK: store <4 x half> %[[CONV5]], <4 x half>* @hv0, align 8
+// CHECK: %[[V4:.*]] = load <4 x half>, <4 x half>* @hv0, align 8
+// CHECK: %[[CONV6:.*]] = fpext <4 x half> %[[V4]] to <4 x float>
+// CHECK: %[[V5:.*]] = load <4 x half>, <4 x half>* @hv1, align 8
+// CHECK: %[[CONV7:.*]] = fpext <4 x half> %[[V5]] to <4 x float>
+// CHECK: %[[MUL:.*]] = fmul <4 x float> %[[CONV6]], %[[CONV7]]
+// CHECK: %[[CONV8:.*]] = fptrunc <4 x float> %[[MUL]] to <4 x half>
+// CHECK: store <4 x half> %[[CONV8]], <4 x half>* @hv0, align 8
+// CHECK: %[[V6:.*]] = load <4 x half>, <4 x half>* @hv0, align 8
+// CHECK: %[[CONV9:.*]] = fpext <4 x half> %[[V6]] to <4 x float>
+// CHECK: %[[V7:.*]] = load <4 x half>, <4 x half>* @hv1, align 8
+// CHECK: %[[CONV10:.*]] = fpext <4 x half> %[[V7]] to <4 x float>
+// CHECK: %[[DIV:.*]] = fdiv <4 x float> %[[CONV9]], %[[CONV10]]

r313924 - [Analyzer] Add simple help to SATestAdd.py

2017-09-21 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep 21 14:47:33 2017
New Revision: 313924

URL: http://llvm.org/viewvc/llvm-project?rev=313924=rev
Log:
[Analyzer] Add simple help to SATestAdd.py

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

Modified:
cfe/trunk/utils/analyzer/SATestAdd.py

Modified: cfe/trunk/utils/analyzer/SATestAdd.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/SATestAdd.py?rev=313924=313923=313924=diff
==
--- cfe/trunk/utils/analyzer/SATestAdd.py (original)
+++ cfe/trunk/utils/analyzer/SATestAdd.py Thu Sep 21 14:47:33 2017
@@ -90,11 +90,12 @@ def addNewProject(ID, BuildMode) :
 # TODO: Add an option not to build.
 # TODO: Set the path to the Repository directory.
 if __name__ == '__main__':
-if len(sys.argv) < 2:
-print >> sys.stderr, 'Usage: ', sys.argv[0],\
- 'project_ID ' \
- 'mode - 0 for single file project; ' \
- '1 for scan_build; ' \
+if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
+print >> sys.stderr, 'Add a new project for testing to static 
analyzer'\
+ '\nUsage: ', sys.argv[0],\
+ 'project_ID \n' \
+ 'mode: 0 for single file project, ' \
+ '1 for scan_build, ' \
  '2 for single file c++11 project'
 sys.exit(-1)
 


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


r313923 - [Analyzer] Remove dead code from CmpRuns.py.

2017-09-21 Thread George Karpenkov via cfe-commits
Author: george.karpenkov
Date: Thu Sep 21 14:47:13 2017
New Revision: 313923

URL: http://llvm.org/viewvc/llvm-project?rev=313923=rev
Log:
[Analyzer] Remove dead code from CmpRuns.py.

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

Modified:
cfe/trunk/utils/analyzer/CmpRuns.py

Modified: cfe/trunk/utils/analyzer/CmpRuns.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/analyzer/CmpRuns.py?rev=313923=313922=313923=diff
==
--- cfe/trunk/utils/analyzer/CmpRuns.py (original)
+++ cfe/trunk/utils/analyzer/CmpRuns.py Thu Sep 21 14:47:13 2017
@@ -89,30 +89,6 @@ class AnalysisDiagnostic:
 def getRawData(self):
 return self._data
 
-class multidict:
-def __init__(self, elts=()):
-self.data = {}
-for key,value in elts:
-self[key] = value
-
-def __getitem__(self, item):
-return self.data[item]
-def __setitem__(self, key, value):
-if key in self.data:
-self.data[key].append(value)
-else:
-self.data[key] = [value]
-def items(self):
-return self.data.items()
-def values(self):
-return self.data.values()
-def keys(self):
-return self.data.keys()
-def __len__(self):
-return len(self.data)
-def get(self, key, default=None):
-return self.data.get(key, default)
-
 class CmpOptions:
 def __init__(self, verboseLog=None, rootA="", rootB=""):
 self.rootA = rootA


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


r313922 - Revert "[lit] Refactor out some more common lit configuration code."

2017-09-21 Thread Zachary Turner via cfe-commits
Author: zturner
Date: Thu Sep 21 14:45:45 2017
New Revision: 313922

URL: http://llvm.org/viewvc/llvm-project?rev=313922=rev
Log:
Revert "[lit] Refactor out some more common lit configuration code."

This is breaking several bots.  I have enough information to
investigate, so I'm reverting to green until I get it figured
out.

Modified:
cfe/trunk/test/lit.cfg.py

Modified: cfe/trunk/test/lit.cfg.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/lit.cfg.py?rev=313922=313921=313922=diff
==
--- cfe/trunk/test/lit.cfg.py (original)
+++ cfe/trunk/test/lit.cfg.py Thu Sep 21 14:45:45 2017
@@ -10,7 +10,6 @@ import lit.formats
 import lit.util
 
 from lit.llvm import llvm_config
-from lit.llvm import ToolFilter
 
 # Configuration file for the 'lit' test runner.
 
@@ -113,12 +112,55 @@ config.substitutions.append( ('%PATH%',
 if config.clang_examples:
 config.available_features.add('examples')
 
-builtin_include_dir = llvm_config.get_clang_builtin_include_dir(config.clang)
+# Note that when substituting %clang_cc1 also fill in the include directory of
+# the builtin headers. Those are part of even a freestanding environment, but
+# Clang relies on the driver to locate them.
+def getClangBuiltinIncludeDir(clang):
+# FIXME: Rather than just getting the version, we should have clang print
+# out its resource dir here in an easy to scrape form.
+cmd = subprocess.Popen([clang, '-print-file-name=include'],
+   stdout=subprocess.PIPE,
+   env=config.environment)
+if not cmd.stdout:
+  lit_config.fatal("Couldn't find the include dir for Clang ('%s')" % 
clang)
+dir = cmd.stdout.read().strip()
+if sys.platform in ['win32'] and not llvm_config.use_lit_shell:
+# Don't pass dosish path separator to msys bash.exe.
+dir = dir.replace('\\', '/')
+# Ensure the result is an ascii string, across Python2.5+ - Python3.
+return str(dir.decode('ascii'))
+
+def makeItaniumABITriple(triple):
+m = re.match(r'(\w+)-(\w+)-(\w+)', triple)
+if not m:
+  lit_config.fatal("Could not turn '%s' into Itanium ABI triple" % triple)
+if m.group(3).lower() != 'win32':
+  # All non-win32 triples use the Itanium ABI.
+  return triple
+return m.group(1) + '-' + m.group(2) + '-mingw32'
+
+def makeMSABITriple(triple):
+m = re.match(r'(\w+)-(\w+)-(\w+)', triple)
+if not m:
+  lit_config.fatal("Could not turn '%s' into MS ABI triple" % triple)
+isa = m.group(1).lower()
+vendor = m.group(2).lower()
+os = m.group(3).lower()
+if os == 'win32':
+  # If the OS is win32, we're done.
+  return triple
+if isa.startswith('x86') or isa == 'amd64' or re.match(r'i\d86', isa):
+  # For x86 ISAs, adjust the OS.
+  return isa + '-' + vendor + '-win32'
+# -win32 is not supported for non-x86 targets; use a default.
+return 'i686-pc-win32'
+
 config.substitutions.append( ('%clang_analyze_cc1',
   '%clang_cc1 -analyze %analyze') )
 config.substitutions.append( ('%clang_cc1',
   '%s -cc1 -internal-isystem %s -nostdsysteminc'
-  % (config.clang, builtin_include_dir)) )
+  % (config.clang,
+ getClangBuiltinIncludeDir(config.clang))) )
 config.substitutions.append( ('%clang_cpp', ' ' + config.clang +
   ' --driver-mode=cpp '))
 config.substitutions.append( ('%clang_cl', ' ' + config.clang +
@@ -126,20 +168,16 @@ config.substitutions.append( ('%clang_cl
 config.substitutions.append( ('%clangxx', ' ' + config.clang +
   ' --driver-mode=g++ '))
 config.substitutions.append( ('%clang', ' ' + config.clang + ' ') )
-config.substitutions.append( ('%test_debuginfo',
- ' ' + config.llvm_src_root +  
'/utils/test_debuginfo.pl ') )
-config.substitutions.append( ('%itanium_abi_triple',
- 
llvm_config.make_itanium_abi_triple(config.target_triple)) )
-config.substitutions.append( ('%ms_abi_triple',
- 
llvm_config.make_msabi_triple(config.target_triple)) )
-config.substitutions.append( ('%resource_dir', builtin_include_dir) )
+config.substitutions.append( ('%test_debuginfo', ' ' + config.llvm_src_root + 
'/utils/test_debuginfo.pl ') )
+config.substitutions.append( ('%itanium_abi_triple', 
makeItaniumABITriple(config.target_triple)) )
+config.substitutions.append( ('%ms_abi_triple', 
makeMSABITriple(config.target_triple)) )
+config.substitutions.append( ('%resource_dir', 
getClangBuiltinIncludeDir(config.clang)) )
 config.substitutions.append( ('%python', config.python_executable) )
 
 # The host triple might not be set, at least if we're compiling clang from
 # an already installed llvm.
 if config.host_triple and config.host_triple != 

[PATCH] D35796: [analyzer] Delete with non-virtual destructor check

2017-09-21 Thread Devin Coughlin via Phabricator via cfe-commits
dcoughlin accepted this revision.
dcoughlin added a comment.
This revision is now accepted and ready to land.

This looks good to me! Do you have commit access, or do you need someone to 
commit it for you?


https://reviews.llvm.org/D35796



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


[PATCH] D37861: preserving #pragma clang assume_nonnull in preprocessed output

2017-09-21 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.

Do you want me to commit this for you?


https://reviews.llvm.org/D37861



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


[PATCH] D34512: Add preliminary Cross Translation Unit support library

2017-09-21 Thread Devin Coughlin via Phabricator via cfe-commits
dcoughlin accepted this revision.
dcoughlin added a comment.
This revision is now accepted and ready to land.

> But I also think it wouldn't be good to block this until ClanD indexing 
> reaching a mature state.

I agree 100%.

> All in all, we are willing to reuse as much of ClangD indexing as we can in 
> the future, but I think it is also more aligned with the LLVM Developer 
> Policy to have something working committed and do the development in the repo 
> rather than working separately on a fork.

This sounds good to me. I just wanted to make sure that you were onboard with 
changing this index to use the common indexing infrastructure in the future. 
(Assuming it makes sense to do so, of course).


https://reviews.llvm.org/D34512



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


[libunwind] r313920 - [libunwind] Partially revert r297174 to fix build on at least FreeBSD.

2017-09-21 Thread John Baldwin via cfe-commits
Author: jhb
Date: Thu Sep 21 14:28:48 2017
New Revision: 313920

URL: http://llvm.org/viewvc/llvm-project?rev=313920=rev
Log:
[libunwind] Partially revert r297174 to fix build on at least FreeBSD.

The changes in r297174 moved the #include of  on FreeBSD (and
probably other systems) inside of the open 'libunwind' namespace
causing various system-provided types such as pid_t to be declared in
this namespace rather than the global namespace.  Fix this by moving
the relevant declarations before the 'libunwind' namespace is opened,
but still using the cleaned up declarations from r297174.

Reviewed By: ed, compnerd

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

Modified:
libunwind/trunk/src/AddressSpace.hpp

Modified: libunwind/trunk/src/AddressSpace.hpp
URL: 
http://llvm.org/viewvc/llvm-project/libunwind/trunk/src/AddressSpace.hpp?rev=313920=313919=313920=diff
==
--- libunwind/trunk/src/AddressSpace.hpp (original)
+++ libunwind/trunk/src/AddressSpace.hpp Thu Sep 21 14:28:48 2017
@@ -35,6 +35,75 @@ namespace libunwind {
 #include "EHHeaderParser.hpp"
 #include "Registers.hpp"
 
+#ifdef __APPLE__
+
+  struct dyld_unwind_sections
+  {
+const struct mach_header*   mh;
+const void* dwarf_section;
+uintptr_t   dwarf_section_length;
+const void* compact_unwind_section;
+uintptr_t   compact_unwind_section_length;
+  };
+  #if (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) \
+ && (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1070)) 
\
+  || defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
+// In 10.7.0 or later, libSystem.dylib implements this function.
+extern "C" bool _dyld_find_unwind_sections(void *, dyld_unwind_sections *);
+  #else
+// In 10.6.x and earlier, we need to implement this functionality. Note
+// that this requires a newer version of libmacho (from cctools) than is
+// present in libSystem on 10.6.x (for getsectiondata).
+static inline bool _dyld_find_unwind_sections(void* addr,
+dyld_unwind_sections* 
info) {
+  // Find mach-o image containing address.
+  Dl_info dlinfo;
+  if (!dladdr(addr, ))
+return false;
+#if __LP64__
+  const struct mach_header_64 *mh = (const struct mach_header_64 
*)dlinfo.dli_fbase;
+#else
+  const struct mach_header *mh = (const struct mach_header 
*)dlinfo.dli_fbase;
+#endif
+
+  // Initialize the return struct
+  info->mh = (const struct mach_header *)mh;
+  info->dwarf_section = getsectiondata(mh, "__TEXT", "__eh_frame", 
>dwarf_section_length);
+  info->compact_unwind_section = getsectiondata(mh, "__TEXT", 
"__unwind_info", >compact_unwind_section_length);
+
+  if (!info->dwarf_section) {
+info->dwarf_section_length = 0;
+  }
+
+  if (!info->compact_unwind_section) {
+info->compact_unwind_section_length = 0;
+  }
+
+  return true;
+}
+  #endif
+
+#elif defined(_LIBUNWIND_ARM_EHABI) && defined(_LIBUNWIND_IS_BAREMETAL)
+
+// When statically linked on bare-metal, the symbols for the EH table are 
looked
+// up without going through the dynamic loader.
+extern char __exidx_start;
+extern char __exidx_end;
+
+#elif defined(_LIBUNWIND_ARM_EHABI) || defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
+
+// ELF-based systems may use dl_iterate_phdr() to access sections
+// containing unwinding information. The ElfW() macro for pointer-size
+// independent ELF header traversal is not provided by  on some
+// systems (e.g., FreeBSD). On these systems the data structures are
+// just called Elf_XXX. Define ElfW() locally.
+#include 
+#if !defined(ElfW)
+#define ElfW(type) Elf_##type
+#endif
+
+#endif
+
 namespace libunwind {
 
 /// Used by findUnwindSections() to return info about needed sections.
@@ -265,75 +334,6 @@ LocalAddressSpace::getEncodedP(pint_t 
   return result;
 }
 
-#ifdef __APPLE__
-
-  struct dyld_unwind_sections
-  {
-const struct mach_header*   mh;
-const void* dwarf_section;
-uintptr_t   dwarf_section_length;
-const void* compact_unwind_section;
-uintptr_t   compact_unwind_section_length;
-  };
-  #if (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) \
- && (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1070)) 
\
-  || defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
-// In 10.7.0 or later, libSystem.dylib implements this function.
-extern "C" bool _dyld_find_unwind_sections(void *, dyld_unwind_sections *);
-  #else
-// In 10.6.x and earlier, we need to implement this functionality. Note
-// that this requires a newer version of libmacho (from cctools) than is
-// present in libSystem on 10.6.x (for getsectiondata).
-static inline bool _dyld_find_unwind_sections(void* addr,
- 

r313919 - [lit] Refactor out some more common lit configuration code.

2017-09-21 Thread Zachary Turner via cfe-commits
Author: zturner
Date: Thu Sep 21 14:27:31 2017
New Revision: 313919

URL: http://llvm.org/viewvc/llvm-project?rev=313919=rev
Log:
[lit] Refactor out some more common lit configuration code.

debuginfo-tests has need to reuse a lot of common configuration
from clang and lld, and in general it seems like all of the
projects which are tightly coupled (e.g. lld, clang, llvm, lldb,
etc) can benefit from knowing about one other.  For example,
lldb needs to know various things about how to run clang in its
test suite.  Since there's a lot of common substitutions and
operations that need to be shared among projects, sinking this
up into LLVM makes sense.

In addition, this patch introduces a function add_tool_substitution
which handles all the dirty intricacies of matching tool names
which was previously copied around the various config files.  This
is now a simple straightforward interface which is hard to mess
up.

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

Modified:
cfe/trunk/test/lit.cfg.py

Modified: cfe/trunk/test/lit.cfg.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/lit.cfg.py?rev=313919=313918=313919=diff
==
--- cfe/trunk/test/lit.cfg.py (original)
+++ cfe/trunk/test/lit.cfg.py Thu Sep 21 14:27:31 2017
@@ -10,6 +10,7 @@ import lit.formats
 import lit.util
 
 from lit.llvm import llvm_config
+from lit.llvm import ToolFilter
 
 # Configuration file for the 'lit' test runner.
 
@@ -112,55 +113,12 @@ config.substitutions.append( ('%PATH%',
 if config.clang_examples:
 config.available_features.add('examples')
 
-# Note that when substituting %clang_cc1 also fill in the include directory of
-# the builtin headers. Those are part of even a freestanding environment, but
-# Clang relies on the driver to locate them.
-def getClangBuiltinIncludeDir(clang):
-# FIXME: Rather than just getting the version, we should have clang print
-# out its resource dir here in an easy to scrape form.
-cmd = subprocess.Popen([clang, '-print-file-name=include'],
-   stdout=subprocess.PIPE,
-   env=config.environment)
-if not cmd.stdout:
-  lit_config.fatal("Couldn't find the include dir for Clang ('%s')" % 
clang)
-dir = cmd.stdout.read().strip()
-if sys.platform in ['win32'] and not llvm_config.use_lit_shell:
-# Don't pass dosish path separator to msys bash.exe.
-dir = dir.replace('\\', '/')
-# Ensure the result is an ascii string, across Python2.5+ - Python3.
-return str(dir.decode('ascii'))
-
-def makeItaniumABITriple(triple):
-m = re.match(r'(\w+)-(\w+)-(\w+)', triple)
-if not m:
-  lit_config.fatal("Could not turn '%s' into Itanium ABI triple" % triple)
-if m.group(3).lower() != 'win32':
-  # All non-win32 triples use the Itanium ABI.
-  return triple
-return m.group(1) + '-' + m.group(2) + '-mingw32'
-
-def makeMSABITriple(triple):
-m = re.match(r'(\w+)-(\w+)-(\w+)', triple)
-if not m:
-  lit_config.fatal("Could not turn '%s' into MS ABI triple" % triple)
-isa = m.group(1).lower()
-vendor = m.group(2).lower()
-os = m.group(3).lower()
-if os == 'win32':
-  # If the OS is win32, we're done.
-  return triple
-if isa.startswith('x86') or isa == 'amd64' or re.match(r'i\d86', isa):
-  # For x86 ISAs, adjust the OS.
-  return isa + '-' + vendor + '-win32'
-# -win32 is not supported for non-x86 targets; use a default.
-return 'i686-pc-win32'
-
+builtin_include_dir = llvm_config.get_clang_builtin_include_dir(config.clang)
 config.substitutions.append( ('%clang_analyze_cc1',
   '%clang_cc1 -analyze %analyze') )
 config.substitutions.append( ('%clang_cc1',
   '%s -cc1 -internal-isystem %s -nostdsysteminc'
-  % (config.clang,
- getClangBuiltinIncludeDir(config.clang))) )
+  % (config.clang, builtin_include_dir)) )
 config.substitutions.append( ('%clang_cpp', ' ' + config.clang +
   ' --driver-mode=cpp '))
 config.substitutions.append( ('%clang_cl', ' ' + config.clang +
@@ -168,16 +126,20 @@ config.substitutions.append( ('%clang_cl
 config.substitutions.append( ('%clangxx', ' ' + config.clang +
   ' --driver-mode=g++ '))
 config.substitutions.append( ('%clang', ' ' + config.clang + ' ') )
-config.substitutions.append( ('%test_debuginfo', ' ' + config.llvm_src_root + 
'/utils/test_debuginfo.pl ') )
-config.substitutions.append( ('%itanium_abi_triple', 
makeItaniumABITriple(config.target_triple)) )
-config.substitutions.append( ('%ms_abi_triple', 
makeMSABITriple(config.target_triple)) )
-config.substitutions.append( ('%resource_dir', 
getClangBuiltinIncludeDir(config.clang)) )
+config.substitutions.append( ('%test_debuginfo',
+ 

[PATCH] D36953: [libclang] Keep track of TranslationUnit instance when annotating tokens

2017-09-21 Thread Jonathan B Coe via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL313913: [libclang] Keep track of TranslationUnit instance 
when annotating tokens (authored by jbcoe).

Changed prior to commit:
  https://reviews.llvm.org/D36953?vs=111959=116262#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D36953

Files:
  cfe/trunk/bindings/python/clang/cindex.py
  cfe/trunk/bindings/python/tests/cindex/test_cursor.py


Index: cfe/trunk/bindings/python/clang/cindex.py
===
--- cfe/trunk/bindings/python/clang/cindex.py
+++ cfe/trunk/bindings/python/clang/cindex.py
@@ -3216,6 +3216,7 @@
 def cursor(self):
 """The Cursor this Token corresponds to."""
 cursor = Cursor()
+cursor._tu = self._tu
 
 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
 
Index: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
===
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py
@@ -395,6 +395,28 @@
 assert tokens[0].spelling == 'int'
 assert tokens[1].spelling == 'foo'
 
+def test_get_token_cursor():
+"""Ensure we can map tokens to cursors."""
+tu = get_tu('class A {}; int foo(A var = A());', lang='cpp')
+foo = get_cursor(tu, 'foo')
+
+for cursor in foo.walk_preorder():
+if cursor.kind.is_expression() and not cursor.kind.is_statement():
+break
+else:
+assert False, "Could not find default value expression"
+
+tokens = list(cursor.get_tokens())
+assert len(tokens) == 4, [t.spelling for t in tokens]
+assert tokens[0].spelling == '='
+assert tokens[1].spelling == 'A'
+assert tokens[2].spelling == '('
+assert tokens[3].spelling == ')'
+t_cursor = tokens[1].cursor
+assert t_cursor.kind == CursorKind.TYPE_REF
+r_cursor = t_cursor.referenced # should not raise an exception
+assert r_cursor.kind == CursorKind.CLASS_DECL
+
 def test_get_arguments():
 tu = get_tu('void foo(int i, int j);')
 foo = get_cursor(tu, 'foo')


Index: cfe/trunk/bindings/python/clang/cindex.py
===
--- cfe/trunk/bindings/python/clang/cindex.py
+++ cfe/trunk/bindings/python/clang/cindex.py
@@ -3216,6 +3216,7 @@
 def cursor(self):
 """The Cursor this Token corresponds to."""
 cursor = Cursor()
+cursor._tu = self._tu
 
 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
 
Index: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
===
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py
@@ -395,6 +395,28 @@
 assert tokens[0].spelling == 'int'
 assert tokens[1].spelling == 'foo'
 
+def test_get_token_cursor():
+"""Ensure we can map tokens to cursors."""
+tu = get_tu('class A {}; int foo(A var = A());', lang='cpp')
+foo = get_cursor(tu, 'foo')
+
+for cursor in foo.walk_preorder():
+if cursor.kind.is_expression() and not cursor.kind.is_statement():
+break
+else:
+assert False, "Could not find default value expression"
+
+tokens = list(cursor.get_tokens())
+assert len(tokens) == 4, [t.spelling for t in tokens]
+assert tokens[0].spelling == '='
+assert tokens[1].spelling == 'A'
+assert tokens[2].spelling == '('
+assert tokens[3].spelling == ')'
+t_cursor = tokens[1].cursor
+assert t_cursor.kind == CursorKind.TYPE_REF
+r_cursor = t_cursor.referenced # should not raise an exception
+assert r_cursor.kind == CursorKind.CLASS_DECL
+
 def test_get_arguments():
 tu = get_tu('void foo(int i, int j);')
 foo = get_cursor(tu, 'foo')
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r313913 - [libclang] Keep track of TranslationUnit instance when annotating tokens

2017-09-21 Thread Jonathan Coe via cfe-commits
Author: jbcoe
Date: Thu Sep 21 13:48:43 2017
New Revision: 313913

URL: http://llvm.org/viewvc/llvm-project?rev=313913=rev
Log:
[libclang] Keep track of TranslationUnit instance when annotating tokens

Summary:
Previously the `_tu` was not propagated to the returned cursor, leading to 
errors when calling any
method on that cursor (e.g. `cursor.referenced`).

Reviewers: jbcoe, rsmith

Reviewed By: jbcoe

Subscribers: cfe-commits

Tags: #clang

Patch by jklaehn (Johann Klähn)

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

Modified:
cfe/trunk/bindings/python/clang/cindex.py
cfe/trunk/bindings/python/tests/cindex/test_cursor.py

Modified: cfe/trunk/bindings/python/clang/cindex.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/clang/cindex.py?rev=313913=313912=313913=diff
==
--- cfe/trunk/bindings/python/clang/cindex.py (original)
+++ cfe/trunk/bindings/python/clang/cindex.py Thu Sep 21 13:48:43 2017
@@ -3216,6 +3216,7 @@ class Token(Structure):
 def cursor(self):
 """The Cursor this Token corresponds to."""
 cursor = Cursor()
+cursor._tu = self._tu
 
 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
 

Modified: cfe/trunk/bindings/python/tests/cindex/test_cursor.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/bindings/python/tests/cindex/test_cursor.py?rev=313913=313912=313913=diff
==
--- cfe/trunk/bindings/python/tests/cindex/test_cursor.py (original)
+++ cfe/trunk/bindings/python/tests/cindex/test_cursor.py Thu Sep 21 13:48:43 
2017
@@ -395,6 +395,28 @@ def test_get_tokens():
 assert tokens[0].spelling == 'int'
 assert tokens[1].spelling == 'foo'
 
+def test_get_token_cursor():
+"""Ensure we can map tokens to cursors."""
+tu = get_tu('class A {}; int foo(A var = A());', lang='cpp')
+foo = get_cursor(tu, 'foo')
+
+for cursor in foo.walk_preorder():
+if cursor.kind.is_expression() and not cursor.kind.is_statement():
+break
+else:
+assert False, "Could not find default value expression"
+
+tokens = list(cursor.get_tokens())
+assert len(tokens) == 4, [t.spelling for t in tokens]
+assert tokens[0].spelling == '='
+assert tokens[1].spelling == 'A'
+assert tokens[2].spelling == '('
+assert tokens[3].spelling == ')'
+t_cursor = tokens[1].cursor
+assert t_cursor.kind == CursorKind.TYPE_REF
+r_cursor = t_cursor.referenced # should not raise an exception
+assert r_cursor.kind == CursorKind.CLASS_DECL
+
 def test_get_arguments():
 tu = get_tu('void foo(int i, int j);')
 foo = get_cursor(tu, 'foo')


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


[PATCH] D38040: [OpenMP] Add an additional test for D34888

2017-09-21 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

Hi Doru,

if I remember correctly I submitted https://reviews.llvm.org/D34888 for a crash 
when mapping a scalar value with nested regions.
I've marked another test in this file that the codegen for `tofrom` is correct. 
So I don't know if this test checks some other conditions?

Jonas




Comment at: test/OpenMP/target_map_codegen.cpp:1773
   // CK19: call void [[CALL23:@.+]](i32* {{[^,]+}})
   #pragma omp target map(always, tofrom: a)
   {

`tofrom` is tested here...


Repository:
  rL LLVM

https://reviews.llvm.org/D38040



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


r313911 - Remove svn-properties for file added in 313909 (NFC)

2017-09-21 Thread Erich Keane via cfe-commits
Author: erichkeane
Date: Thu Sep 21 13:31:01 2017
New Revision: 313911

URL: http://llvm.org/viewvc/llvm-project?rev=313911=rev
Log:
Remove svn-properties for file added in 313909 (NFC)

Modified:
cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp   (props changed)

Propchange: cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp
--
--- svn:eol-style (original)
+++ svn:eol-style (removed)
@@ -1 +0,0 @@
-native

Propchange: cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp
--
--- svn:keywords (original)
+++ svn:keywords (removed)
@@ -1 +0,0 @@
-Author Date Id Rev URL

Propchange: cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp
--
--- svn:mime-type (original)
+++ svn:mime-type (removed)
@@ -1 +0,0 @@
-text/plain


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


RE: r313907 - Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Keane, Erich via cfe-commits
Fixed in 313909.

-Original Message-
From: Friedman, Eli [mailto:efrie...@codeaurora.org] 
Sent: Thursday, September 21, 2017 1:14 PM
To: Keane, Erich ; cfe-commits@lists.llvm.org
Subject: Re: r313907 - Suppress Wsign-conversion for enums with matching 
underlying type

On 9/21/2017 12:58 PM, Erich Keane via cfe-commits wrote:
> Author: erichkeane
> Date: Thu Sep 21 12:58:55 2017
> New Revision: 313907
>
> URL: http://llvm.org/viewvc/llvm-project?rev=313907=rev
> Log:
> Suppress Wsign-conversion for enums with matching underlying type
>
> As reported here: https://bugs.llvm.org/show_bug.cgi?id=34692
>
> A non-defined enum with a backing type was always defaulting to being 
> treated as a signed type. IN the case where it IS defined, the 
> signed-ness of the actual items is used.
>
> This patch uses the underlying type's signed-ness in the non-defined 
> case to test signed-comparision.
>
> Differential Revision: https://reviews.llvm.org/D38145
>
> Modified:
>  cfe/trunk/lib/Sema/SemaChecking.cpp

Missing testcase?

-El

--
Employee of Qualcomm Innovation Center, Inc.
Qualcomm Innovation Center, Inc. is a member of Code Aurora Forum, a Linux 
Foundation Collaborative Project

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


r313909 - Add testcase I forgot to add in R313907.

2017-09-21 Thread Erich Keane via cfe-commits
Author: erichkeane
Date: Thu Sep 21 13:14:08 2017
New Revision: 313909

URL: http://llvm.org/viewvc/llvm-project?rev=313909=rev
Log:
Add testcase I forgot to add in R313907.

Added:
cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp   (with props)

Added: cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp?rev=313909=auto
==
--- cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp (added)
+++ cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp Thu Sep 21 13:14:08 
2017
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wsign-conversion -std=c++11 %s
+
+unsigned int test() {
+  short foo;
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+
+unsigned int test3() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : signed char;
+  u8 foo{static_cast(0)};
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+unsigned int test2() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : unsigned char;
+  u8 foo{static_cast(0)};
+  return foo;
+}

Propchange: cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp
--
svn:eol-style = native

Propchange: cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp
--
svn:keywords = Author Date Id Rev URL

Propchange: cfe/trunk/test/SemaCXX/warn-sign-conversion-cpp11.cpp
--
svn:mime-type = text/plain


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


RE: r313907 - Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Keane, Erich via cfe-commits
Ugg... good catch, thanks.

-Original Message-
From: Friedman, Eli [mailto:efrie...@codeaurora.org] 
Sent: Thursday, September 21, 2017 1:14 PM
To: Keane, Erich ; cfe-commits@lists.llvm.org
Subject: Re: r313907 - Suppress Wsign-conversion for enums with matching 
underlying type

On 9/21/2017 12:58 PM, Erich Keane via cfe-commits wrote:
> Author: erichkeane
> Date: Thu Sep 21 12:58:55 2017
> New Revision: 313907
>
> URL: http://llvm.org/viewvc/llvm-project?rev=313907=rev
> Log:
> Suppress Wsign-conversion for enums with matching underlying type
>
> As reported here: https://bugs.llvm.org/show_bug.cgi?id=34692
>
> A non-defined enum with a backing type was always defaulting to being 
> treated as a signed type. IN the case where it IS defined, the 
> signed-ness of the actual items is used.
>
> This patch uses the underlying type's signed-ness in the non-defined 
> case to test signed-comparision.
>
> Differential Revision: https://reviews.llvm.org/D38145
>
> Modified:
>  cfe/trunk/lib/Sema/SemaChecking.cpp

Missing testcase?

-El

--
Employee of Qualcomm Innovation Center, Inc.
Qualcomm Innovation Center, Inc. is a member of Code Aurora Forum, a Linux 
Foundation Collaborative Project

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


Re: r313907 - Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Friedman, Eli via cfe-commits

On 9/21/2017 12:58 PM, Erich Keane via cfe-commits wrote:

Author: erichkeane
Date: Thu Sep 21 12:58:55 2017
New Revision: 313907

URL: http://llvm.org/viewvc/llvm-project?rev=313907=rev
Log:
Suppress Wsign-conversion for enums with matching underlying type

As reported here: https://bugs.llvm.org/show_bug.cgi?id=34692

A non-defined enum with a backing type was always defaulting to
being treated as a signed type. IN the case where it IS defined,
the signed-ness of the actual items is used.

This patch uses the underlying type's signed-ness in the non-defined
case to test signed-comparision.

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

Modified:
 cfe/trunk/lib/Sema/SemaChecking.cpp


Missing testcase?

-El

--
Employee of Qualcomm Innovation Center, Inc.
Qualcomm Innovation Center, Inc. is a member of Code Aurora Forum, a Linux 
Foundation Collaborative Project

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


[PATCH] D38151: [clang] Fix isExternC matcher docs

2017-09-21 Thread Alexander Shaposhnikov via Phabricator via cfe-commits
alexshap created this revision.
Herald added a subscriber: klimek.

The wording in the documentation for the matcher isExternC appears to be 
misleading since this
matcher is applicable to functions and variables as well. 
This diff changes the comment regenerates the html file.


Repository:
  rL LLVM

https://reviews.llvm.org/D38151

Files:
  docs/LibASTMatchersReference.html
  include/clang/ASTMatchers/ASTMatchers.h


Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -3533,16 +3533,21 @@
   return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
 }
 
-/// \brief Matches extern "C" function declarations.
+/// \brief Matches extern "C" function or variable declarations.
 ///
 /// Given:
 /// \code
 ///   extern "C" void f() {}
 ///   extern "C" { void g() {} }
 ///   void h() {}
+///   extern "C" int x = 1;
+///   extern "C" int y = 2;
+///   int z = 3;
 /// \endcode
 /// functionDecl(isExternC())
-///   matches the declaration of f and g, but not the declaration h
+///   matches the declaration of f and g, but not the declaration of h.
+/// varDecl(isExternC())
+///   matches the declaration of x and y, but not the declaration of z.
 AST_POLYMORPHIC_MATCHER(isExternC, 
AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
VarDecl)) {
   return Node.isExternC();
Index: docs/LibASTMatchersReference.html
===
--- docs/LibASTMatchersReference.html
+++ docs/LibASTMatchersReference.html
@@ -2741,19 +2741,22 @@
 Usable as: Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html;>FunctionDecl,
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1VarDecl.html;>VarDecl,
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html;>CXXRecordDecl
 
 
-
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html;>FunctionDeclisExternC
-Matches extern "C" 
function declarations.
+Matches extern "C" 
function or variable declarations.
 
 Given:
   extern "C" void f() {}
   extern "C" { void g() {} }
   void h() {}
+  extern "C" int x = 1;
+  extern "C" int y = 2;
+  int z = 3;
 functionDecl(isExternC())
-  matches the declaration of f and g, but not the declaration h
+  matches the declaration of f and g, but not the declaration of h.
+varDecl(isExternC())
+  matches the declaration of x and y, but not the declaration of z.
 
 
-
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html;>FunctionDeclisInline
 Matches function and 
namespace declarations that are marked with
 the inline keyword.
@@ -3680,19 +3683,22 @@
 Usable as: Matcherhttp://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html;>FunctionDecl,
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1VarDecl.html;>VarDecl,
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html;>CXXRecordDecl
 
 
-
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1VarDecl.html;>VarDeclisExternC
-Matches extern "C" 
function declarations.
+Matches extern "C" 
function or variable declarations.
 
 Given:
   extern "C" void f() {}
   extern "C" { void g() {} }
   void h() {}
+  extern "C" int x = 1;
+  extern "C" int y = 2;
+  int z = 3;
 functionDecl(isExternC())
-  matches the declaration of f and g, but not the declaration h
+  matches the declaration of f and g, but not the declaration of h.
+varDecl(isExternC())
+  matches the declaration of x and y, but not the declaration of z.
 
 
-
 Matcherhttp://clang.llvm.org/doxygen/classclang_1_1VarDecl.html;>VarDeclisStaticStorageClass
 Matches 
variablefunction declarations that have "static" storage
 class specifier ("static" keyword) written in the source.


Index: include/clang/ASTMatchers/ASTMatchers.h
===
--- include/clang/ASTMatchers/ASTMatchers.h
+++ include/clang/ASTMatchers/ASTMatchers.h
@@ -3533,16 +3533,21 @@
   return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
 }
 
-/// \brief Matches extern "C" function declarations.
+/// \brief Matches extern "C" function or variable declarations.
 ///
 /// Given:
 /// \code
 ///   extern "C" void f() {}
 ///   extern "C" { void g() {} }
 ///   void h() {}
+///   extern "C" int x = 1;
+///   extern "C" int y = 2;
+///   int z = 3;
 /// \endcode
 /// functionDecl(isExternC())
-///   matches the declaration of f and g, but not the declaration h
+///   matches the declaration of f and g, but not the declaration of h.
+/// varDecl(isExternC())
+///   matches the declaration of x and y, but not the declaration of z.
 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
VarDecl)) {
   return Node.isExternC();
Index: docs/LibASTMatchersReference.html

[PATCH] D38145: Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Erich Keane via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL313907: Suppress Wsign-conversion for enums with matching 
underlying type (authored by erichkeane).

Changed prior to commit:
  https://reviews.llvm.org/D38145?vs=116245=116252#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D38145

Files:
  cfe/trunk/lib/Sema/SemaChecking.cpp


Index: cfe/trunk/lib/Sema/SemaChecking.cpp
===
--- cfe/trunk/lib/Sema/SemaChecking.cpp
+++ cfe/trunk/lib/Sema/SemaChecking.cpp
@@ -8171,8 +8171,11 @@
 // For enum types, use the known bit width of the enumerators.
 if (const EnumType *ET = dyn_cast(T)) {
   EnumDecl *Enum = ET->getDecl();
+  // In C++11, enums without definitions can have an explicitly specified
+  // underlying type.  Use this type to compute the range.
   if (!Enum->isCompleteDefinition())
-return IntRange(C.getIntWidth(QualType(T, 0)), false);
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 
   unsigned NumPositive = Enum->getNumPositiveBits();
   unsigned NumNegative = Enum->getNumNegativeBits();


Index: cfe/trunk/lib/Sema/SemaChecking.cpp
===
--- cfe/trunk/lib/Sema/SemaChecking.cpp
+++ cfe/trunk/lib/Sema/SemaChecking.cpp
@@ -8171,8 +8171,11 @@
 // For enum types, use the known bit width of the enumerators.
 if (const EnumType *ET = dyn_cast(T)) {
   EnumDecl *Enum = ET->getDecl();
+  // In C++11, enums without definitions can have an explicitly specified
+  // underlying type.  Use this type to compute the range.
   if (!Enum->isCompleteDefinition())
-return IntRange(C.getIntWidth(QualType(T, 0)), false);
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 
   unsigned NumPositive = Enum->getNumPositiveBits();
   unsigned NumNegative = Enum->getNumNegativeBits();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r313907 - Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Erich Keane via cfe-commits
Author: erichkeane
Date: Thu Sep 21 12:58:55 2017
New Revision: 313907

URL: http://llvm.org/viewvc/llvm-project?rev=313907=rev
Log:
Suppress Wsign-conversion for enums with matching underlying type

As reported here: https://bugs.llvm.org/show_bug.cgi?id=34692

A non-defined enum with a backing type was always defaulting to
being treated as a signed type. IN the case where it IS defined,
the signed-ness of the actual items is used.

This patch uses the underlying type's signed-ness in the non-defined
case to test signed-comparision.

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

Modified:
cfe/trunk/lib/Sema/SemaChecking.cpp

Modified: cfe/trunk/lib/Sema/SemaChecking.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaChecking.cpp?rev=313907=313906=313907=diff
==
--- cfe/trunk/lib/Sema/SemaChecking.cpp (original)
+++ cfe/trunk/lib/Sema/SemaChecking.cpp Thu Sep 21 12:58:55 2017
@@ -8171,8 +8171,11 @@ struct IntRange {
 // For enum types, use the known bit width of the enumerators.
 if (const EnumType *ET = dyn_cast(T)) {
   EnumDecl *Enum = ET->getDecl();
+  // In C++11, enums without definitions can have an explicitly specified
+  // underlying type.  Use this type to compute the range.
   if (!Enum->isCompleteDefinition())
-return IntRange(C.getIntWidth(QualType(T, 0)), false);
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 
   unsigned NumPositive = Enum->getNumPositiveBits();
   unsigned NumNegative = Enum->getNumNegativeBits();


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


[PATCH] D37861: preserving #pragma clang assume_nonnull in preprocessed output

2017-09-21 Thread Zbigniew Sarbinowski via Phabricator via cfe-commits
zibi added a comment.

ping


https://reviews.llvm.org/D37861



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


[PATCH] D37881: [Sema] Prevent InstantiateClass from checking unrelated exception specs.

2017-09-21 Thread Volodymyr Sapsai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL313906: [Sema] Prevent InstantiateClass from checking 
unrelated exception specs. (authored by vsapsai).

Changed prior to commit:
  https://reviews.llvm.org/D37881?vs=116056=116250#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D37881

Files:
  cfe/trunk/include/clang/Sema/Sema.h
  cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
  cfe/trunk/test/SemaTemplate/crash-unparsed-exception.cpp
  cfe/trunk/test/SemaTemplate/default-arguments-cxx0x.cpp

Index: cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
===
--- cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
+++ cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
@@ -2026,12 +2026,11 @@
   bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
   LocalInstantiationScope Scope(*this, MergeWithParentScope);
 
-  // All dllexported classes created during instantiation should be fully
-  // emitted after instantiation completes. We may not be ready to emit any
-  // delayed classes already on the stack, so save them away and put them back
-  // later.
-  decltype(DelayedDllExportClasses) ExportedClasses;
-  std::swap(ExportedClasses, DelayedDllExportClasses);
+  // Some class state isn't processed immediately but delayed till class
+  // instantiation completes. We may not be ready to handle any delayed state
+  // already on the stack as it might correspond to a different class, so save
+  // it now and put it back later.
+  SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
 
   // Pull attributes from the pattern onto the instantiation.
   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
@@ -2118,9 +2117,6 @@
   // default arg exprs for default constructors if necessary now.
   ActOnFinishCXXNonNestedClass(Instantiation);
 
-  // Put back the delayed exported classes that we moved out of the way.
-  std::swap(ExportedClasses, DelayedDllExportClasses);
-
   // Instantiate late parsed attributes, and attach them to their decls.
   // See Sema::InstantiateAttrs
   for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
Index: cfe/trunk/include/clang/Sema/Sema.h
===
--- cfe/trunk/include/clang/Sema/Sema.h
+++ cfe/trunk/include/clang/Sema/Sema.h
@@ -10503,6 +10503,36 @@
   SmallVector DelayedDllExportClasses;
 
 private:
+  class SavePendingParsedClassStateRAII {
+  public:
+SavePendingParsedClassStateRAII(Sema ) : S(S) { swapSavedState(); }
+
+~SavePendingParsedClassStateRAII() {
+  assert(S.DelayedExceptionSpecChecks.empty() &&
+ "there shouldn't be any pending delayed exception spec checks");
+  assert(S.DelayedDefaultedMemberExceptionSpecs.empty() &&
+ "there shouldn't be any pending delayed defaulted member "
+ "exception specs");
+  assert(S.DelayedDllExportClasses.empty() &&
+ "there shouldn't be any pending delayed DLL export classes");
+  swapSavedState();
+}
+
+  private:
+Sema 
+decltype(DelayedExceptionSpecChecks) SavedExceptionSpecChecks;
+decltype(DelayedDefaultedMemberExceptionSpecs)
+SavedDefaultedMemberExceptionSpecs;
+decltype(DelayedDllExportClasses) SavedDllExportClasses;
+
+void swapSavedState() {
+  SavedExceptionSpecChecks.swap(S.DelayedExceptionSpecChecks);
+  SavedDefaultedMemberExceptionSpecs.swap(
+  S.DelayedDefaultedMemberExceptionSpecs);
+  SavedDllExportClasses.swap(S.DelayedDllExportClasses);
+}
+  };
+
   /// \brief Helper class that collects misaligned member designations and
   /// their location info for delayed diagnostics.
   struct MisalignedMember {
Index: cfe/trunk/test/SemaTemplate/default-arguments-cxx0x.cpp
===
--- cfe/trunk/test/SemaTemplate/default-arguments-cxx0x.cpp
+++ cfe/trunk/test/SemaTemplate/default-arguments-cxx0x.cpp
@@ -87,3 +87,30 @@
 A<1> m_target;
   };
 }
+
+// rdar://problem/34167492
+// Template B is instantiated during checking if defaulted A copy constructor
+// is constexpr. For this we check if S copy constructor is constexpr. And
+// for this we check S constructor template with default argument that mentions
+// template B. In  turn, template instantiation triggers checking defaulted
+// members exception spec. The problem is that it checks defaulted members not
+// for instantiated class only, but all defaulted members so far. In this case
+// we try to check exception spec for A default constructor which requires
+// initializer for the field _a. But initializers are added after constexpr
+// check so we reject the code because cannot find _a initializer.
+namespace rdar34167492 {
+  template  struct B { using type = bool; };
+
+  template  struct S {
+S() noexcept;
+
+template ::type = true>
+S(const 

r313906 - [Sema] Prevent InstantiateClass from checking unrelated exception specs.

2017-09-21 Thread Volodymyr Sapsai via cfe-commits
Author: vsapsai
Date: Thu Sep 21 12:54:12 2017
New Revision: 313906

URL: http://llvm.org/viewvc/llvm-project?rev=313906=rev
Log:
[Sema] Prevent InstantiateClass from checking unrelated exception specs.

Sema::InstantiateClass should check only exception specs added during
class instantiation and ignore already present delayed specs. This fixes
a case where we instantiate a class before parsing member initializers,
check exceptions for a different class and fail to find a member
initializer. Which is required for comparing exception specs for
explicitly-defaulted and implicit default constructor. With the fix we
are still checking exception specs but only after member initializers
are present.

Removing errors in crash-unparsed-exception.cpp is acceptable according
to discussion in PR24000 because other compilers accept code in
crash-unparsed-exception.cpp as valid.

rdar://problem/34167492

Reviewers: davide, rsmith

Reviewed By: rsmith

Subscribers: dim, cfe-commits

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


Modified:
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
cfe/trunk/test/SemaTemplate/crash-unparsed-exception.cpp
cfe/trunk/test/SemaTemplate/default-arguments-cxx0x.cpp

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=313906=313905=313906=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Thu Sep 21 12:54:12 2017
@@ -10503,6 +10503,36 @@ public:
   SmallVector DelayedDllExportClasses;
 
 private:
+  class SavePendingParsedClassStateRAII {
+  public:
+SavePendingParsedClassStateRAII(Sema ) : S(S) { swapSavedState(); }
+
+~SavePendingParsedClassStateRAII() {
+  assert(S.DelayedExceptionSpecChecks.empty() &&
+ "there shouldn't be any pending delayed exception spec checks");
+  assert(S.DelayedDefaultedMemberExceptionSpecs.empty() &&
+ "there shouldn't be any pending delayed defaulted member "
+ "exception specs");
+  assert(S.DelayedDllExportClasses.empty() &&
+ "there shouldn't be any pending delayed DLL export classes");
+  swapSavedState();
+}
+
+  private:
+Sema 
+decltype(DelayedExceptionSpecChecks) SavedExceptionSpecChecks;
+decltype(DelayedDefaultedMemberExceptionSpecs)
+SavedDefaultedMemberExceptionSpecs;
+decltype(DelayedDllExportClasses) SavedDllExportClasses;
+
+void swapSavedState() {
+  SavedExceptionSpecChecks.swap(S.DelayedExceptionSpecChecks);
+  SavedDefaultedMemberExceptionSpecs.swap(
+  S.DelayedDefaultedMemberExceptionSpecs);
+  SavedDllExportClasses.swap(S.DelayedDllExportClasses);
+}
+  };
+
   /// \brief Helper class that collects misaligned member designations and
   /// their location info for delayed diagnostics.
   struct MisalignedMember {

Modified: cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp?rev=313906=313905=313906=diff
==
--- cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp (original)
+++ cfe/trunk/lib/Sema/SemaTemplateInstantiate.cpp Thu Sep 21 12:54:12 2017
@@ -2026,12 +2026,11 @@ Sema::InstantiateClass(SourceLocation Po
   bool MergeWithParentScope = 
!Instantiation->isDefinedOutsideFunctionOrMethod();
   LocalInstantiationScope Scope(*this, MergeWithParentScope);
 
-  // All dllexported classes created during instantiation should be fully
-  // emitted after instantiation completes. We may not be ready to emit any
-  // delayed classes already on the stack, so save them away and put them back
-  // later.
-  decltype(DelayedDllExportClasses) ExportedClasses;
-  std::swap(ExportedClasses, DelayedDllExportClasses);
+  // Some class state isn't processed immediately but delayed till class
+  // instantiation completes. We may not be ready to handle any delayed state
+  // already on the stack as it might correspond to a different class, so save
+  // it now and put it back later.
+  SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
 
   // Pull attributes from the pattern onto the instantiation.
   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
@@ -2118,9 +2117,6 @@ Sema::InstantiateClass(SourceLocation Po
   // default arg exprs for default constructors if necessary now.
   ActOnFinishCXXNonNestedClass(Instantiation);
 
-  // Put back the delayed exported classes that we moved out of the way.
-  std::swap(ExportedClasses, DelayedDllExportClasses);
-
   // Instantiate late parsed attributes, and attach them to their decls.
   // See Sema::InstantiateAttrs
   for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),

Modified: 

[PATCH] D38145: Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 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


https://reviews.llvm.org/D38145



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


[PATCH] D38145: Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 116245.
erichkeane marked an inline comment as done.

https://reviews.llvm.org/D38145

Files:
  lib/Sema/SemaChecking.cpp
  test/SemaCXX/warn-sign-conversion-cpp11.cpp


Index: test/SemaCXX/warn-sign-conversion-cpp11.cpp
===
--- /dev/null
+++ test/SemaCXX/warn-sign-conversion-cpp11.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wsign-conversion -std=c++11 %s
+
+unsigned int test() {
+  short foo;
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+
+unsigned int test3() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : signed char;
+  u8 foo{static_cast(0)};
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+unsigned int test2() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : unsigned char;
+  u8 foo{static_cast(0)};
+  return foo;
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -8171,8 +8171,11 @@
 // For enum types, use the known bit width of the enumerators.
 if (const EnumType *ET = dyn_cast(T)) {
   EnumDecl *Enum = ET->getDecl();
+  // In C++11, enums without definitions can have an explicitly specified
+  // underlying type.  Use this type to compute the range.
   if (!Enum->isCompleteDefinition())
-return IntRange(C.getIntWidth(QualType(T, 0)), false);
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 
   unsigned NumPositive = Enum->getNumPositiveBits();
   unsigned NumNegative = Enum->getNumNegativeBits();


Index: test/SemaCXX/warn-sign-conversion-cpp11.cpp
===
--- /dev/null
+++ test/SemaCXX/warn-sign-conversion-cpp11.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wsign-conversion -std=c++11 %s
+
+unsigned int test() {
+  short foo;
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+
+unsigned int test3() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : signed char;
+  u8 foo{static_cast(0)};
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+unsigned int test2() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : unsigned char;
+  u8 foo{static_cast(0)};
+  return foo;
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -8171,8 +8171,11 @@
 // For enum types, use the known bit width of the enumerators.
 if (const EnumType *ET = dyn_cast(T)) {
   EnumDecl *Enum = ET->getDecl();
+  // In C++11, enums without definitions can have an explicitly specified
+  // underlying type.  Use this type to compute the range.
   if (!Enum->isCompleteDefinition())
-return IntRange(C.getIntWidth(QualType(T, 0)), false);
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 
   unsigned NumPositive = Enum->getNumPositiveBits();
   unsigned NumNegative = Enum->getNumNegativeBits();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D38145: Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: lib/Sema/SemaChecking.cpp:8176
+  // underlying type, so that when someone specifies the type as
+  // "unsigned" it doesn't cause sign-conversion type warnings.
   if (!Enum->isCompleteDefinition())

efriedma wrote:
> Explicitly referencing sign-conversion warnings here isn't really helpful.  
> Maybe something more like "Incomplete enums without definitions can have an 
> explicitly specified underlying type. Use that type here to compute the 
> range."
Ok, got it.  I DO note that (IIRC) enums with an underlying type are not 
considered 'incomplete', so I modified your text slightly.  Thanks for the help.



Comment at: test/SemaCXX/sign-conversion.cpp:21
+  return foo;
+}

efriedma wrote:
> There's an existing file test/SemaCXX/warn-sign-conversion.cpp for C++ 
> sign-conversion tests.
Thanks for pointing that out! Unfortunately, that file is very dependent on it 
being C++98, and this test requires c++11 or greater.  I DID rename the test 
file to better match that one however.



Comment at: test/SemaCXX/warn-sign-conversion-cpp11.cpp:11
+  // For a non-defined enum, use the underlying type.
+  enum u8 : char;
+  u8 foo{static_cast(0)};

efriedma wrote:
> The signedness of "char" can vary based on the host; probably simplest to 
> write out "signed char".
Right, good catch.


https://reviews.llvm.org/D38145



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


[PATCH] D38145: Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: lib/Sema/SemaChecking.cpp:8176
+  // underlying type, so that when someone specifies the type as
+  // "unsigned" it doesn't cause sign-conversion type warnings.
   if (!Enum->isCompleteDefinition())

Explicitly referencing sign-conversion warnings here isn't really helpful.  
Maybe something more like "Incomplete enums without definitions can have an 
explicitly specified underlying type. Use that type here to compute the range."



Comment at: test/SemaCXX/warn-sign-conversion-cpp11.cpp:11
+  // For a non-defined enum, use the underlying type.
+  enum u8 : char;
+  u8 foo{static_cast(0)};

The signedness of "char" can vary based on the host; probably simplest to write 
out "signed char".


https://reviews.llvm.org/D38145



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


[PATCH] D38145: Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 116244.
erichkeane marked 2 inline comments as done.
erichkeane added a comment.

Updated based on Eli's feedback.


https://reviews.llvm.org/D38145

Files:
  lib/Sema/SemaChecking.cpp
  test/SemaCXX/warn-sign-conversion-cpp11.cpp


Index: test/SemaCXX/warn-sign-conversion-cpp11.cpp
===
--- /dev/null
+++ test/SemaCXX/warn-sign-conversion-cpp11.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wsign-conversion -std=c++11 %s
+
+unsigned int test() {
+  short foo;
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+
+unsigned int test3() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : char;
+  u8 foo{static_cast(0)};
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+unsigned int test2() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : unsigned char;
+  u8 foo{static_cast(0)};
+  return foo;
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -8171,8 +8171,12 @@
 // For enum types, use the known bit width of the enumerators.
 if (const EnumType *ET = dyn_cast(T)) {
   EnumDecl *Enum = ET->getDecl();
+  // Enums without definitions should use the signed-ness of the
+  // underlying type, so that when someone specifies the type as
+  // "unsigned" it doesn't cause sign-conversion type warnings.
   if (!Enum->isCompleteDefinition())
-return IntRange(C.getIntWidth(QualType(T, 0)), false);
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 
   unsigned NumPositive = Enum->getNumPositiveBits();
   unsigned NumNegative = Enum->getNumNegativeBits();


Index: test/SemaCXX/warn-sign-conversion-cpp11.cpp
===
--- /dev/null
+++ test/SemaCXX/warn-sign-conversion-cpp11.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wsign-conversion -std=c++11 %s
+
+unsigned int test() {
+  short foo;
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+
+unsigned int test3() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : char;
+  u8 foo{static_cast(0)};
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+unsigned int test2() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : unsigned char;
+  u8 foo{static_cast(0)};
+  return foo;
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -8171,8 +8171,12 @@
 // For enum types, use the known bit width of the enumerators.
 if (const EnumType *ET = dyn_cast(T)) {
   EnumDecl *Enum = ET->getDecl();
+  // Enums without definitions should use the signed-ness of the
+  // underlying type, so that when someone specifies the type as
+  // "unsigned" it doesn't cause sign-conversion type warnings.
   if (!Enum->isCompleteDefinition())
-return IntRange(C.getIntWidth(QualType(T, 0)), false);
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 
   unsigned NumPositive = Enum->getNumPositiveBits();
   unsigned NumNegative = Enum->getNumNegativeBits();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D38046: [Atomic][X8664] set max atomic inline/promote width according to the target

2017-09-21 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:
  rL LLVM

https://reviews.llvm.org/D38046



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


[PATCH] D38147: [CUDA] Fixed order of words in the names of shfl builtins.

2017-09-21 Thread Artem Belevich via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL313899: [CUDA] Fixed order of words in the names of shfl 
builtins. (authored by tra).

Changed prior to commit:
  https://reviews.llvm.org/D38147?vs=116228=116238#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D38147

Files:
  cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h


Index: cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
===
--- cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
+++ cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
@@ -148,13 +148,12 @@
  __nvvm_shfl_sync_idx_f32, 0x1f);
 // We use 0 rather than 31 as our mask, because shfl.up applies to lanes >=
 // maxLane.
-__MAKE_SYNC_SHUFFLES(__shfl_sync_up, __nvvm_shfl_sync_up_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_up_sync, __nvvm_shfl_sync_up_i32,
  __nvvm_shfl_sync_up_f32, 0);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_down, __nvvm_shfl_sync_down_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_down_sync, __nvvm_shfl_sync_down_i32,
  __nvvm_shfl_sync_down_f32, 0x1f);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_xor, __nvvm_shfl_sync_bfly_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_xor_sync, __nvvm_shfl_sync_bfly_i32,
  __nvvm_shfl_sync_bfly_f32, 0x1f);
-
 #pragma pop_macro("__MAKE_SYNC_SHUFFLES")
 
 inline __device__ void __syncwarp(unsigned int mask = 0x) {


Index: cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
===
--- cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
+++ cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
@@ -148,13 +148,12 @@
  __nvvm_shfl_sync_idx_f32, 0x1f);
 // We use 0 rather than 31 as our mask, because shfl.up applies to lanes >=
 // maxLane.
-__MAKE_SYNC_SHUFFLES(__shfl_sync_up, __nvvm_shfl_sync_up_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_up_sync, __nvvm_shfl_sync_up_i32,
  __nvvm_shfl_sync_up_f32, 0);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_down, __nvvm_shfl_sync_down_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_down_sync, __nvvm_shfl_sync_down_i32,
  __nvvm_shfl_sync_down_f32, 0x1f);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_xor, __nvvm_shfl_sync_bfly_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_xor_sync, __nvvm_shfl_sync_bfly_i32,
  __nvvm_shfl_sync_bfly_f32, 0x1f);
-
 #pragma pop_macro("__MAKE_SYNC_SHUFFLES")
 
 inline __device__ void __syncwarp(unsigned int mask = 0x) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r313899 - [CUDA] Fixed order of words in the names of shfl builtins.

2017-09-21 Thread Artem Belevich via cfe-commits
Author: tra
Date: Thu Sep 21 11:46:39 2017
New Revision: 313899

URL: http://llvm.org/viewvc/llvm-project?rev=313899=rev
Log:
[CUDA] Fixed order of words in the names of shfl builtins.

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

Modified:
cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h

Modified: cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h?rev=313899=313898=313899=diff
==
--- cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h (original)
+++ cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h Thu Sep 21 11:46:39 2017
@@ -148,13 +148,12 @@ __MAKE_SYNC_SHUFFLES(__shfl_sync, __nvvm
  __nvvm_shfl_sync_idx_f32, 0x1f);
 // We use 0 rather than 31 as our mask, because shfl.up applies to lanes >=
 // maxLane.
-__MAKE_SYNC_SHUFFLES(__shfl_sync_up, __nvvm_shfl_sync_up_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_up_sync, __nvvm_shfl_sync_up_i32,
  __nvvm_shfl_sync_up_f32, 0);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_down, __nvvm_shfl_sync_down_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_down_sync, __nvvm_shfl_sync_down_i32,
  __nvvm_shfl_sync_down_f32, 0x1f);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_xor, __nvvm_shfl_sync_bfly_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_xor_sync, __nvvm_shfl_sync_bfly_i32,
  __nvvm_shfl_sync_bfly_f32, 0x1f);
-
 #pragma pop_macro("__MAKE_SYNC_SHUFFLES")
 
 inline __device__ void __syncwarp(unsigned int mask = 0x) {


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


[PATCH] D38148: [NVPTX] Implemented bar.warp.sync, barrier.sync, and vote{.sync} instructions/intrinsics/builtins.

2017-09-21 Thread Artem Belevich via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL313898: [NVPTX] Implemented bar.warp.sync, barrier.sync, and 
vote{.sync}… (authored by tra).

Changed prior to commit:
  https://reviews.llvm.org/D38148?vs=116236=116237#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D38148

Files:
  cfe/trunk/include/clang/Basic/BuiltinsNVPTX.def
  cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
  cfe/trunk/test/CodeGen/builtins-nvptx-ptx60.cu
  cfe/trunk/test/CodeGen/builtins-nvptx.c
  llvm/trunk/include/llvm/IR/IntrinsicsNVVM.td
  llvm/trunk/lib/Target/NVPTX/NVPTXInstrInfo.td
  llvm/trunk/lib/Target/NVPTX/NVPTXIntrinsics.td
  llvm/trunk/test/CodeGen/NVPTX/barrier.ll
  llvm/trunk/test/CodeGen/NVPTX/vote.ll

Index: llvm/trunk/lib/Target/NVPTX/NVPTXInstrInfo.td
===
--- llvm/trunk/lib/Target/NVPTX/NVPTXInstrInfo.td
+++ llvm/trunk/lib/Target/NVPTX/NVPTXInstrInfo.td
@@ -155,6 +155,9 @@
 def true : Predicate<"true">;
 
 def hasPTX31 : Predicate<"Subtarget->getPTXVersion() >= 31">;
+def hasPTX60 : Predicate<"Subtarget->getPTXVersion() >= 60">;
+
+def hasSM30 : Predicate<"Subtarget->getSmVersion() >= 30">;
 
 def useFP16Math: Predicate<"Subtarget->allowFP16Math()">;
 
Index: llvm/trunk/lib/Target/NVPTX/NVPTXIntrinsics.td
===
--- llvm/trunk/lib/Target/NVPTX/NVPTXIntrinsics.td
+++ llvm/trunk/lib/Target/NVPTX/NVPTXIntrinsics.td
@@ -71,6 +71,38 @@
 def INT_BAR_SYNC : NVPTXInst<(outs), (ins i32imm:$i), "bar.sync \t$i;",
  [(int_nvvm_bar_sync imm:$i)]>;
 
+def INT_BAR_WARP_SYNC_I : NVPTXInst<(outs), (ins i32imm:$i), "bar.warp.sync \t$i;",
+ [(int_nvvm_bar_warp_sync imm:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+def INT_BAR_WARP_SYNC_R : NVPTXInst<(outs), (ins Int32Regs:$i), "bar.warp.sync \t$i;",
+ [(int_nvvm_bar_warp_sync Int32Regs:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+
+def INT_BARRIER_SYNC_I : NVPTXInst<(outs), (ins i32imm:$i), "barrier.sync \t$i;",
+   [(int_nvvm_barrier_sync imm:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+def INT_BARRIER_SYNC_R : NVPTXInst<(outs), (ins Int32Regs:$i), "barrier.sync \t$i;",
+   [(int_nvvm_barrier_sync Int32Regs:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+
+def INT_BARRIER_SYNC_CNT_RR : NVPTXInst<(outs), (ins Int32Regs:$id, Int32Regs:$cnt),
+ "barrier.sync \t$id, $cnt;",
+ [(int_nvvm_barrier_sync_cnt Int32Regs:$id, Int32Regs:$cnt)]>,
+Requires<[hasPTX60, hasSM30]>;
+def INT_BARRIER_SYNC_CNT_RI : NVPTXInst<(outs), (ins Int32Regs:$id, i32imm:$cnt),
+ "barrier.sync \t$id, $cnt;",
+ [(int_nvvm_barrier_sync_cnt Int32Regs:$id, imm:$cnt)]>,
+Requires<[hasPTX60, hasSM30]>;
+def INT_BARRIER_SYNC_CNT_IR : NVPTXInst<(outs), (ins i32imm:$id, Int32Regs:$cnt),
+ "barrier.sync \t$id, $cnt;",
+ [(int_nvvm_barrier_sync_cnt imm:$id, Int32Regs:$cnt)]>,
+Requires<[hasPTX60, hasSM30]>;
+def INT_BARRIER_SYNC_CNT_II : NVPTXInst<(outs), (ins i32imm:$id, i32imm:$cnt),
+ "barrier.sync \t$id, $cnt;",
+ [(int_nvvm_barrier_sync_cnt imm:$id, imm:$cnt)]>,
+Requires<[hasPTX60, hasSM30]>;
+
+
 // shfl.{up,down,bfly,idx}.b32
 multiclass SHFL {
   // The last two parameters to shfl can be regs or imms.  ptxas is smart
@@ -184,6 +216,37 @@
 defm INT_SHFL_SYNC_IDX_I32 : SHFL_SYNC;
 defm INT_SHFL_SYNC_IDX_F32 : SHFL_SYNC;
 
+
+// vote.{all,any,uni,ballot}
+multiclass VOTE {
+  def : NVPTXInst<(outs regclass:$dest), (ins Int1Regs:$pred),
+  "vote." # mode # " \t$dest, $pred;",
+  [(set regclass:$dest, (IntOp Int1Regs:$pred))]>,
+Requires<[hasPTX60, hasSM30]>;
+}
+
+defm VOTE_ALL : VOTE;
+defm VOTE_ANY : VOTE;
+defm VOTE_UNI : VOTE;
+defm VOTE_BALLOT : VOTE;
+
+// vote.sync.{all,any,uni,ballot}
+multiclass VOTE_SYNC {
+  def i : NVPTXInst<(outs regclass:$dest), (ins i32imm:$mask, Int1Regs:$pred),
+  "vote.sync." # mode # " \t$dest, $pred, $mask;",
+  [(set regclass:$dest, (IntOp imm:$mask, Int1Regs:$pred))]>,
+  Requires<[hasPTX60, hasSM30]>;
+  def r : NVPTXInst<(outs regclass:$dest), (ins Int32Regs:$mask, Int1Regs:$pred),
+  "vote.sync." # mode #" \t$dest, $pred, $mask;",
+  [(set regclass:$dest, (IntOp Int32Regs:$mask, Int1Regs:$pred))]>,
+  Requires<[hasPTX60, hasSM30]>;
+}
+
+defm VOTE_SYNC_ALL : VOTE_SYNC;
+defm VOTE_SYNC_ANY : 

r313898 - [NVPTX] Implemented bar.warp.sync, barrier.sync, and vote{.sync} instructions/intrinsics/builtins.

2017-09-21 Thread Artem Belevich via cfe-commits
Author: tra
Date: Thu Sep 21 11:44:49 2017
New Revision: 313898

URL: http://llvm.org/viewvc/llvm-project?rev=313898=rev
Log:
[NVPTX] Implemented bar.warp.sync, barrier.sync, and vote{.sync} 
instructions/intrinsics/builtins.

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

Modified:
cfe/trunk/include/clang/Basic/BuiltinsNVPTX.def
cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
cfe/trunk/test/CodeGen/builtins-nvptx-ptx60.cu
cfe/trunk/test/CodeGen/builtins-nvptx.c

Modified: cfe/trunk/include/clang/Basic/BuiltinsNVPTX.def
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/BuiltinsNVPTX.def?rev=313898=313897=313898=diff
==
--- cfe/trunk/include/clang/Basic/BuiltinsNVPTX.def (original)
+++ cfe/trunk/include/clang/Basic/BuiltinsNVPTX.def Thu Sep 21 11:44:49 2017
@@ -378,6 +378,9 @@ BUILTIN(__nvvm_bar0_popc, "ii", "")
 BUILTIN(__nvvm_bar0_and, "ii", "")
 BUILTIN(__nvvm_bar0_or, "ii", "")
 BUILTIN(__nvvm_bar_sync, "vi", "n")
+TARGET_BUILTIN(__nvvm_bar_warp_sync, "vUi", "n", "ptx60")
+TARGET_BUILTIN(__nvvm_barrier_sync, "vUi", "n", "ptx60")
+TARGET_BUILTIN(__nvvm_barrier_sync_cnt, "vUiUi", "n", "ptx60")
 
 // Shuffle
 
@@ -399,6 +402,17 @@ TARGET_BUILTIN(__nvvm_shfl_sync_bfly_f32
 TARGET_BUILTIN(__nvvm_shfl_sync_idx_i32, "iU", "", "ptx60")
 TARGET_BUILTIN(__nvvm_shfl_sync_idx_f32, "fUifii", "", "ptx60")
 
+// Vote
+BUILTIN(__nvvm_vote_all, "bb", "")
+BUILTIN(__nvvm_vote_any, "bb", "")
+BUILTIN(__nvvm_vote_uni, "bb", "")
+BUILTIN(__nvvm_vote_ballot, "Uib", "")
+
+TARGET_BUILTIN(__nvvm_vote_all_sync, "bUib", "", "ptx60")
+TARGET_BUILTIN(__nvvm_vote_any_sync, "bUib", "", "ptx60")
+TARGET_BUILTIN(__nvvm_vote_uni_sync, "bUib", "", "ptx60")
+TARGET_BUILTIN(__nvvm_vote_ballot_sync, "UiUib", "", "ptx60")
+
 // Membar
 
 BUILTIN(__nvvm_membar_cta, "v", "")

Modified: cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h?rev=313898=313897=313898=diff
==
--- cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h (original)
+++ cfe/trunk/lib/Headers/__clang_cuda_intrinsics.h Thu Sep 21 11:44:49 2017
@@ -157,6 +157,37 @@ __MAKE_SYNC_SHUFFLES(__shfl_sync_xor, __
 
 #pragma pop_macro("__MAKE_SYNC_SHUFFLES")
 
+inline __device__ void __syncwarp(unsigned int mask = 0x) {
+  return __nvvm_bar_warp_sync(mask);
+}
+
+inline __device__ void __barrier_sync(unsigned int id) {
+  __nvvm_barrier_sync(id);
+}
+
+inline __device__ void __barrier_sync_count(unsigned int id,
+unsigned int count) {
+  __nvvm_barrier_sync_cnt(id, count);
+}
+
+inline __device__ int __all_sync(unsigned int mask, int pred) {
+  return __nvvm_vote_sync_all(mask, pred);
+}
+
+inline __device__ int __any_sync(unsigned int mask, int pred) {
+  return __nvvm_vote_sync_any(mask, pred);
+}
+
+inline __device__ int __uni_sync(unsigned int mask, int pred) {
+  return __nvvm_vote_sync_uni(mask, pred);
+}
+
+inline __device__ unsigned int __ballot_sync(unsigned int mask, int pred) {
+  return __nvvm_vote_sync_ballot(mask, pred);
+}
+
+inline __device__ activemask() { return __nvvm_vote.ballot(1); }
+
 #endif // __CUDA_VERSION >= 9000 && (!defined(__CUDA_ARCH__) ||
// __CUDA_ARCH__ >= 300)
 

Modified: cfe/trunk/test/CodeGen/builtins-nvptx-ptx60.cu
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/builtins-nvptx-ptx60.cu?rev=313898=313897=313898=diff
==
--- cfe/trunk/test/CodeGen/builtins-nvptx-ptx60.cu (original)
+++ cfe/trunk/test/CodeGen/builtins-nvptx-ptx60.cu Thu Sep 21 11:44:49 2017
@@ -10,8 +10,27 @@
 #define __shared__ __attribute__((shared))
 #define __constant__ __attribute__((constant))
 
-// CHECK-LABEL: nvvm_shfl_sync
-__device__ void nvvm_shfl_sync(unsigned mask, int i, float f, int a, int b) {
+// We have to keep all builtins that depend on particular target feature in the
+// same function, because the codegen will stop after the very first function
+// that encounters an error, so -verify will not be able to find errors in
+// subsequent functions.
+
+// CHECK-LABEL: nvvm_sync
+__device__ void nvvm_sync(unsigned mask, int i, float f, int a, int b,
+  bool pred) {
+  // CHECK: call void @llvm.nvvm.bar.warp.sync(i32
+  // expected-error@+1 {{'__nvvm_bar_warp_sync' needs target feature ptx60}}
+  __nvvm_bar_warp_sync(mask);
+  // CHECK: call void @llvm.nvvm.barrier.sync(i32
+  // expected-error@+1 {{'__nvvm_barrier_sync' needs target feature ptx60}}
+  __nvvm_barrier_sync(mask);
+  // CHECK: call void @llvm.nvvm.barrier.sync.cnt(i32
+  // expected-error@+1 {{'__nvvm_barrier_sync_cnt' needs target feature ptx60}}
+  __nvvm_barrier_sync_cnt(mask, i);
+
+  //
+  // SHFL.SYNC
+  //
   // CHECK: call i32 

[PATCH] D38145: Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added inline comments.



Comment at: lib/Sema/SemaChecking.cpp:8176
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 

Maybe add a comment noting what can trigger this case?



Comment at: test/SemaCXX/sign-conversion.cpp:21
+  return foo;
+}

There's an existing file test/SemaCXX/warn-sign-conversion.cpp for C++ 
sign-conversion tests.


https://reviews.llvm.org/D38145



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


[PATCH] D38148: [NVPTX] Implemented bar.warp.sync, barrier.sync, and vote{.sync} instructions/intrinsics/builtins.

2017-09-21 Thread Artem Belevich via Phabricator via cfe-commits
tra updated this revision to Diff 116236.
tra added a comment.

Fixed a typo in one test.


https://reviews.llvm.org/D38148

Files:
  clang/include/clang/Basic/BuiltinsNVPTX.def
  clang/lib/Headers/__clang_cuda_intrinsics.h
  clang/test/CodeGen/builtins-nvptx-ptx60.cu
  clang/test/CodeGen/builtins-nvptx.c
  llvm/include/llvm/IR/IntrinsicsNVVM.td
  llvm/lib/Target/NVPTX/NVPTXInstrInfo.td
  llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
  llvm/test/CodeGen/NVPTX/barrier.ll
  llvm/test/CodeGen/NVPTX/vote.ll

Index: llvm/test/CodeGen/NVPTX/vote.ll
===
--- /dev/null
+++ llvm/test/CodeGen/NVPTX/vote.ll
@@ -0,0 +1,65 @@
+; RUN: llc < %s -march=nvptx64 -mcpu=sm_30 -mattr=+ptx60 | FileCheck %s
+
+declare i1 @llvm.nvvm.vote.all(i1)
+; CHECK-LABEL: .func{{.*}}vote.all
+define i1 @vote.all(i1 %pred) {
+  ; CHECK: vote.all.pred
+  %val = call i1 @llvm.nvvm.vote.all(i1 %pred)
+  ret i1 %val
+}
+
+declare i1 @llvm.nvvm.vote.any(i1)
+; CHECK-LABEL: .func{{.*}}vote.any
+define i1 @vote.any(i1 %pred) {
+  ; CHECK: vote.any.pred
+  %val = call i1 @llvm.nvvm.vote.any(i1 %pred)
+  ret i1 %val
+}
+
+declare i1 @llvm.nvvm.vote.uni(i1)
+; CHECK-LABEL: .func{{.*}}vote.uni
+define i1 @vote.uni(i1 %pred) {
+  ; CHECK: vote.uni.pred
+  %val = call i1 @llvm.nvvm.vote.uni(i1 %pred)
+  ret i1 %val
+}
+
+declare i32 @llvm.nvvm.vote.ballot(i1)
+; CHECK-LABEL: .func{{.*}}vote.ballot
+define i32 @vote.ballot(i1 %pred) {
+  ; CHECK: vote.ballot.b32
+  %val = call i32 @llvm.nvvm.vote.ballot(i1 %pred)
+  ret i32 %val
+}
+
+declare i1 @llvm.nvvm.vote.all.sync(i32, i1)
+; CHECK-LABEL: .func{{.*}}vote.sync.all
+define i1 @vote.sync.all(i32 %mask, i1 %pred) {
+  ; CHECK: vote.sync.all.pred
+  %val = call i1 @llvm.nvvm.vote.all.sync(i32 %mask, i1 %pred)
+  ret i1 %val
+}
+
+declare i1 @llvm.nvvm.vote.any.sync(i32, i1)
+; CHECK-LABEL: .func{{.*}}vote.sync.any
+define i1 @vote.sync.any(i32 %mask, i1 %pred) {
+  ; CHECK: vote.sync.any.pred
+  %val = call i1 @llvm.nvvm.vote.any.sync(i32 %mask, i1 %pred)
+  ret i1 %val
+}
+
+declare i1 @llvm.nvvm.vote.uni.sync(i32, i1)
+; CHECK-LABEL: .func{{.*}}vote.sync.uni
+define i1 @vote.sync.uni(i32 %mask, i1 %pred) {
+  ; CHECK: vote.sync.uni.pred
+  %val = call i1 @llvm.nvvm.vote.uni.sync(i32 %mask, i1 %pred)
+  ret i1 %val
+}
+
+declare i32 @llvm.nvvm.vote.ballot.sync(i32, i1)
+; CHECK-LABEL: .func{{.*}}vote.sync.ballot
+define i32 @vote.sync.ballot(i32 %mask, i1 %pred) {
+  ; CHECK: vote.sync.ballot.b32
+  %val = call i32 @llvm.nvvm.vote.ballot.sync(i32 %mask, i1 %pred)
+  ret i32 %val
+}
Index: llvm/test/CodeGen/NVPTX/barrier.ll
===
--- /dev/null
+++ llvm/test/CodeGen/NVPTX/barrier.ll
@@ -0,0 +1,32 @@
+; RUN: llc < %s -march=nvptx64 -mcpu=sm_30 -mattr=+ptx60 | FileCheck %s
+
+declare void @llvm.nvvm.bar.warp.sync(i32)
+declare void @llvm.nvvm.barrier.sync(i32)
+declare void @llvm.nvvm.barrier.sync.cnt(i32, i32)
+
+; CHECK-LABEL: .func{{.*}}barrier.sync
+define void @barrier.sync(i32 %id, i32 %cnt) {
+  ; CHECK: ld.param.u32 	[[ID:%r[0-9]+]], [barrier.sync_param_0];
+  ; CHECK: ld.param.u32 	[[CNT:%r[0-9]+]], [barrier.sync_param_1];
+
+  ; CHECK:  barrier.sync [[ID]], [[CNT]];
+  call void @llvm.nvvm.barrier.sync.cnt(i32 %id, i32 %cnt)
+  ; CHECK:  barrier.sync [[ID]], 2;
+  call void @llvm.nvvm.barrier.sync.cnt(i32 %id, i32 2)
+  ; CHECK:  barrier.sync 3, [[CNT]];
+  call void @llvm.nvvm.barrier.sync.cnt(i32 3, i32 %cnt)
+  ; CHECK:  barrier.sync 4, 5;
+  call void @llvm.nvvm.barrier.sync.cnt(i32 4, i32 5)
+
+  ; CHECK: barrier.sync [[ID]];
+  call void @llvm.nvvm.barrier.sync(i32 %id)
+  ; CHECK: barrier.sync 1;
+  call void @llvm.nvvm.barrier.sync(i32 1)
+
+  ; CHECK: bar.warp.sync [[ID]];
+  call void @llvm.nvvm.bar.warp.sync(i32 %id)
+  ; CHECK: bar.warp.sync 6;
+  call void @llvm.nvvm.bar.warp.sync(i32 6)
+  ret void;
+}
+
Index: llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
===
--- llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
+++ llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
@@ -71,6 +71,38 @@
 def INT_BAR_SYNC : NVPTXInst<(outs), (ins i32imm:$i), "bar.sync \t$i;",
  [(int_nvvm_bar_sync imm:$i)]>;
 
+def INT_BAR_WARP_SYNC_I : NVPTXInst<(outs), (ins i32imm:$i), "bar.warp.sync \t$i;",
+ [(int_nvvm_bar_warp_sync imm:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+def INT_BAR_WARP_SYNC_R : NVPTXInst<(outs), (ins Int32Regs:$i), "bar.warp.sync \t$i;",
+ [(int_nvvm_bar_warp_sync Int32Regs:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+
+def INT_BARRIER_SYNC_I : NVPTXInst<(outs), (ins i32imm:$i), "barrier.sync \t$i;",
+   [(int_nvvm_barrier_sync imm:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+def INT_BARRIER_SYNC_R : NVPTXInst<(outs), (ins Int32Regs:$i), "barrier.sync \t$i;",
+   

[PATCH] D38148: [NVPTX] Implemented bar.warp.sync, barrier.sync, and vote{.sync} instructions/intrinsics/builtins.

2017-09-21 Thread Artem Belevich via Phabricator via cfe-commits
tra created this revision.
Herald added subscribers: hiraditya, sanjoy, jholewinski.

https://reviews.llvm.org/D38148

Files:
  clang/include/clang/Basic/BuiltinsNVPTX.def
  clang/lib/Headers/__clang_cuda_intrinsics.h
  clang/test/CodeGen/builtins-nvptx-ptx60.cu
  clang/test/CodeGen/builtins-nvptx.c
  llvm/include/llvm/IR/IntrinsicsNVVM.td
  llvm/lib/Target/NVPTX/NVPTXInstrInfo.td
  llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
  llvm/test/CodeGen/NVPTX/barrier.ll
  llvm/test/CodeGen/NVPTX/vote.ll

Index: llvm/test/CodeGen/NVPTX/vote.ll
===
--- /dev/null
+++ llvm/test/CodeGen/NVPTX/vote.ll
@@ -0,0 +1,65 @@
+; RUN: llc < %s -march=nvptx64 -mcpu=sm_30 -mattr=+ptx60 | FileCheck %s
+
+declare i1 @llvm.nvvm.vote.all(i1)
+; CHECK-LABEL: .func{{.*}}vote.all
+define i1 @vote.all(i1 %pred) {
+  ; CHECK: vote.all.pred
+  %val = call i1 @llvm.nvvm.vote.all(i1 %pred)
+  ret i1 %val
+}
+
+declare i1 @llvm.nvvm.vote.any(i1)
+; CHECK-LABEL: .func{{.*}}vote.any
+define i1 @vote.any(i1 %pred) {
+  ; CHECK: vote.any.pred
+  %val = call i1 @llvm.nvvm.vote.any(i1 %pred)
+  ret i1 %val
+}
+
+declare i1 @llvm.nvvm.vote.uni(i1)
+; CHECK-LABEL: .func{{.*}}vote.uni
+define i1 @vote.uni(i1 %pred) {
+  ; CHECK: vote.uni.pred
+  %val = call i1 @llvm.nvvm.vote.uni(i1 %pred)
+  ret i1 %val
+}
+
+declare i32 @llvm.nvvm.vote.ballot(i1)
+; CHECK-LABEL: .func{{.*}}vote.ballot
+define i32 @vote.ballot(i1 %pred) {
+  ; CHECK: vote.ballot.b32
+  %val = call i32 @llvm.nvvm.vote.ballot(i1 %pred)
+  ret i32 %val
+}
+
+declare i1 @llvm.nvvm.vote.all.sync(i32, i1)
+; CHECK-LABEL: .func{{.*}}vote.sync.all
+define i1 @vote.sync.all(i32 %mask, i1 %pred) {
+  ; CHECK: vote.sync.all.pred
+  %val = call i1 @llvm.nvvm.vote.all.sync(i32 %mask, i1 %pred)
+  ret i1 %val
+}
+
+declare i1 @llvm.nvvm.vote.any.sync(i32, i1)
+; CHECK-LABEL: .func{{.*}}vote.sync.any
+define i1 @vote.sync.any(i32 %mask, i1 %pred) {
+  ; CHECK: vote.sync.any.pred
+  %val = call i1 @llvm.nvvm.vote.any.sync(i32 %mask, i1 %pred)
+  ret i1 %val
+}
+
+declare i1 @llvm.nvvm.vote.uni.sync(i32, i1)
+; CHECK-LABEL: .func{{.*}}vote.sync.uni
+define i1 @vote.sync.uni(i32 %mask, i1 %pred) {
+  ; CHECK: vote.sync.uni.pred
+  %val = call i1 @llvm.nvvm.vote.uni.sync(i32 %mask, i1 %pred)
+  ret i1 %val
+}
+
+declare i32 @llvm.nvvm.vote.ballot.sync(i32, i1)
+; CHECK-LABEL: .func{{.*}}vote.sync.ballot
+define i32 @vote.sync.ballot(i32 %mask, i1 %pred) {
+  ; CHECK: vote.sync.ballot.b32
+  %val = call i32 @llvm.nvvm.vote.ballot.sync(i32 %mask, i1 %pred)
+  ret i32 %val
+}
Index: llvm/test/CodeGen/NVPTX/barrier.ll
===
--- /dev/null
+++ llvm/test/CodeGen/NVPTX/barrier.ll
@@ -0,0 +1,32 @@
+; RUN: llc < %s -march=nvptx64 -mcpu=sm_30 -mattr=+ptx60 | FileCheck %s
+
+declare void @llvm.nvvm.bar.warp.sync(i32)
+declare void @llvm.nvvm.barrier.sync(i32)
+declare void @llvm.nvvm.barrier.sync.cnt(i32, i32)
+
+; CHECK-LABEL: .func{{.*}}barrier.sync
+define void @barrier.sync(i32 %id, i32 %cnt) {
+  ; CHECK: ld.param.u32 	[[ID:%r[0-9]+]], [barrier.sync_param_0];
+  ; CHECK: ld.param.u32 	[[CNT:%r[0-9]+]], [barrier.sync_param_1];
+
+  ; CHECK:  barrier.sync [[ID]], [[CNT]];
+  call void @llvm.nvvm.barrier.sync.cnt(i32 %id, i32 %cnt)
+  ; CHECK:  barrier.sync [[ID]], 2;
+  call void @llvm.nvvm.barrier.sync.cnt(i32 %id, i32 2)
+  ; CHECK:  barrier.sync 3, [[CNT]];
+  call void @llvm.nvvm.barrier.sync.cnt(i32 3, i32 %cnt)
+  ; CHECK:  barrier.sync 4, 5;
+  call void @llvm.nvvm.barrier.sync.cnt(i32 4, i32 5)
+
+  ; CHECK: barrier.sync [[ID]];
+  call void @llvm.nvvm.barrier.sync(i32 %id)
+  ; CHECK: barrier.sync 1;
+  call void @llvm.nvvm.barrier.sync(i32 1)
+
+  ; CHECK: bar.warp.sync [[ID]];
+  call void @llvm.nvvm.bar.warp.sync(i32 %id)
+  ; CHECK: bar.warp.sync 6;
+  call void @llvm.nvvm.bar.warp.sync(i32 6)
+  ret void;
+}
+
Index: llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
===
--- llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
+++ llvm/lib/Target/NVPTX/NVPTXIntrinsics.td
@@ -71,6 +71,38 @@
 def INT_BAR_SYNC : NVPTXInst<(outs), (ins i32imm:$i), "bar.sync \t$i;",
  [(int_nvvm_bar_sync imm:$i)]>;
 
+def INT_BAR_WARP_SYNC_I : NVPTXInst<(outs), (ins i32imm:$i), "bar.warp.sync \t$i;",
+ [(int_nvvm_bar_warp_sync imm:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+def INT_BAR_WARP_SYNC_R : NVPTXInst<(outs), (ins Int32Regs:$i), "bar.warp.sync \t$i;",
+ [(int_nvvm_bar_warp_sync Int32Regs:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+
+def INT_BARRIER_SYNC_I : NVPTXInst<(outs), (ins i32imm:$i), "barrier.sync \t$i;",
+   [(int_nvvm_barrier_sync imm:$i)]>,
+Requires<[hasPTX60, hasSM30]>;
+def INT_BARRIER_SYNC_R : NVPTXInst<(outs), (ins Int32Regs:$i), "barrier.sync \t$i;",
+   

[PATCH] D36562: [Bitfield] Make the bitfield a separate location if it has width of legal integer type and its bit offset is naturally aligned for the type

2017-09-21 Thread Wei Mi via Phabricator via cfe-commits
wmi updated this revision to Diff 116232.
wmi added a comment.

Changes following the discussion:

- Put the bitfield split logic under an option and off by default.
- When sanitizer is enabled, the option for bitfield split will be ignored and 
a warning message will be emitted.

In addition, a test is added.


Repository:
  rL LLVM

https://reviews.llvm.org/D36562

Files:
  include/clang/Basic/DiagnosticDriverKinds.td
  include/clang/Driver/Options.td
  include/clang/Frontend/CodeGenOptions.def
  lib/CodeGen/CGExpr.cpp
  lib/Driver/ToolChains/Clang.cpp
  lib/Frontend/CompilerInvocation.cpp
  test/CodeGenCXX/bitfield-split.cpp

Index: test/CodeGenCXX/bitfield-split.cpp
===
--- test/CodeGenCXX/bitfield-split.cpp
+++ test/CodeGenCXX/bitfield-split.cpp
@@ -0,0 +1,161 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsplit-bitfields -emit-llvm \
+// RUN:  -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -fsplit-bitfields -emit-llvm \
+// RUN:  -fsanitize=address -o - %s | FileCheck %s --check-prefix=SANITIZE
+// Check -fsplit-bitfields will be ignored since sanitizer is enabled.
+
+struct S1 {
+  unsigned f1:2;
+  unsigned f2:6;
+  unsigned f3:8;
+  unsigned f4:4;
+  unsigned f5:8;
+};
+
+S1 a1;
+unsigned read8_1() {
+  // CHECK-LABEL: @_Z7read8_1v
+  // CHECK: %bf.load = load i8, i8* getelementptr (i8, i8* bitcast (%struct.S1* @a1 to i8*), i32 1), align 1
+  // CHECK-NEXT: %bf.cast = zext i8 %bf.load to i32
+  // CHECK-NEXT: ret i32 %bf.cast
+  // SANITIZE-LABEL: @_Z7read8_1v
+  // SANITIZE: %bf.load = load i32, i32* getelementptr inbounds {{.*}}, align 4
+  // SANITIZE: %bf.lshr = lshr i32 %bf.load, 8
+  // SANITIZE: %bf.clear = and i32 %bf.lshr, 255
+  // SANITIZE: ret i32 %bf.clear
+  return a1.f3;
+}
+void write8_1() {
+  // CHECK-LABEL: @_Z8write8_1v
+  // CHECK: store i8 3, i8* getelementptr (i8, i8* bitcast (%struct.S1* @a1 to i8*), i32 1), align 1
+  // CHECK-NEXT: ret void
+  // SANITIZE-LABEL: @_Z8write8_1v
+  // SANITIZE: %bf.load = load i32, i32* getelementptr inbounds {{.*}}, align 4
+  // SANITIZE-NEXT: %bf.clear = and i32 %bf.load, -65281
+  // SANITIZE-NEXT: %bf.set = or i32 %bf.clear, 768
+  // SANITIZE-NEXT: store i32 %bf.set, i32* getelementptr inbounds {{.*}}, align 4
+  // SANITIZE-NEXT: ret void
+  a1.f3 = 3;
+}
+
+unsigned read8_2() {
+  // CHECK-LABEL: @_Z7read8_2v
+  // CHECK: %bf.load = load i32, i32* getelementptr inbounds (%struct.S1, %struct.S1* @a1, i32 0, i32 0), align 4
+  // CHECK-NEXT: %bf.lshr = lshr i32 %bf.load, 20
+  // CHECK-NEXT: %bf.clear = and i32 %bf.lshr, 255
+  // CHECK-NEXT: ret i32 %bf.clear
+  // SANITIZE-LABEL: @_Z7read8_2v
+  // SANITIZE: %bf.load = load i32, i32* getelementptr inbounds {{.*}}, align 4
+  // SANITIZE-NEXT: %bf.lshr = lshr i32 %bf.load, 20
+  // SANITIZE-NEXT: %bf.clear = and i32 %bf.lshr, 255
+  // SANITIZE-NEXT: ret i32 %bf.clear
+  return a1.f5;
+}
+void write8_2() {
+  // CHECK-LABEL: @_Z8write8_2v
+  // CHECK: %bf.load = load i32, i32* getelementptr inbounds (%struct.S1, %struct.S1* @a1, i32 0, i32 0), align 4
+  // CHECK-NEXT: %bf.clear = and i32 %bf.load, -267386881
+  // CHECK-NEXT: %bf.set = or i32 %bf.clear, 3145728
+  // CHECK-NEXT: store i32 %bf.set, i32* getelementptr inbounds (%struct.S1, %struct.S1* @a1, i32 0, i32 0), align 4
+  // CHECK-NEXT: ret void
+  // SANITIZE-LABEL: @_Z8write8_2v
+  // SANITIZE: %bf.load = load i32, i32* getelementptr inbounds {{.*}}, align 4
+  // SANITIZE-NEXT: %bf.clear = and i32 %bf.load, -267386881
+  // SANITIZE-NEXT: %bf.set = or i32 %bf.clear, 3145728
+  // SANITIZE-NEXT: store i32 %bf.set, i32* getelementptr inbounds {{.*}}, align 4
+  // SANITIZE-NEXT: ret void
+  a1.f5 = 3;
+}
+
+struct S2 {
+  unsigned long f1:16;
+  unsigned long f2:16;
+  unsigned long f3:6;
+};
+
+S2 a2;
+unsigned read16_1() {
+  // CHECK-LABEL: @_Z8read16_1v
+  // CHECK: %bf.load = load i16, i16* bitcast (%struct.S2* @a2 to i16*), align 2
+  // CHECK-NEXT: %bf.cast = zext i16 %bf.load to i64
+  // CHECK-NEXT: %conv = trunc i64 %bf.cast to i32
+  // CHECK-NEXT: ret i32 %conv
+  // SANITIZE-LABEL: @_Z8read16_1v
+  // SANITIZE: %bf.load = load i64, i64* bitcast {{.*}}, align 8
+  // SANITIZE-NEXT: %bf.clear = and i64 %bf.load, 65535
+  // SANITIZE-NEXT: %conv = trunc i64 %bf.clear to i32
+  // SANITIZE-NEXT: ret i32 %conv
+  return a2.f1;
+}
+unsigned read16_2() {
+  // CHECK-LABEL: @_Z8read16_2v
+  // CHECK: %bf.load = load i16, i16* bitcast (i8* getelementptr (i8, i8* bitcast (%struct.S2* @a2 to i8*), i32 2) to i16*), align 2
+  // CHECK-NEXT: %bf.cast = zext i16 %bf.load to i64
+  // CHECK-NEXT: %conv = trunc i64 %bf.cast to i32
+  // CHECK-NEXT: ret i32 %conv
+  // SANITIZE-LABEL: @_Z8read16_2v
+  // SANITIZE: %bf.load = load i64, i64* bitcast {{.*}}, align 8
+  // SANITIZE-NEXT: %bf.lshr = lshr i64 %bf.load, 16
+  // SANITIZE-NEXT: %bf.clear = and i64 %bf.lshr, 65535
+  // SANITIZE-NEXT: %conv = trunc i64 %bf.clear to i32
+  // 

[PATCH] D37822: [OpenCL] Clean up and add missing fields for block struct

2017-09-21 Thread Brian Sumner via Phabricator via cfe-commits
b-sumner added a comment.

In https://reviews.llvm.org/D37822#877903, @Anastasia wrote:

> In https://reviews.llvm.org/D37822#877572, @yaxunl wrote:
>
> > In https://reviews.llvm.org/D37822#873876, @Anastasia wrote:
> >
> > > In https://reviews.llvm.org/D37822#872446, @yaxunl wrote:
> > >
> > > > In https://reviews.llvm.org/D37822#872291, @Anastasia wrote:
> > > >
> > > > > Could you please explain a bit more why the alignment have to be put 
> > > > > explicitly in the struct? I am just not very convinced this is 
> > > > > general enough.
> > > >
> > > >
> > > > The captured variables are fields of the block literal struct. Due to 
> > > > alignment requirement of these fields, there is alignment requirement of
> > > >  the block literal struct. The ISA of the block invoke function is 
> > > > generated with the assumption of these alignments. If the block literal 
> > > > is
> > > >  allocated at a memory address not satisfying the alignment 
> > > > requirement, the kernel behavior is undefined.
> > > >
> > > > Generally, __enqueue_kernel library function needs to prepare the 
> > > > kernel argument before launching the kernel. It usually does this by 
> > > > copying
> > > >  the block literal to some buffer then pass the address of the buffer 
> > > > to the kernel. Then the address of the buffer has to satisfy the 
> > > > alignment
> > > >  requirement.
> > > >
> > > > If this block literal struct is not general enough, how about add 
> > > > another field as target reserved size, and leave the remaining space of 
> > > > header for
> > > >  target specific use. And add a target hook to allow target fill the 
> > > > reserved space, e.g.
> > > >
> > > >   struct __opencl_block_literal {
> > > > int total_size;
> > > > int align;
> > > > __generic void *invoke;
> > > > int target_reserved_size; /* round up to 4 bytes */
> > > > int target_reserved[];
> > > > /* captures */
> > > >   };
> > > >
> > >
> > >
> > > I like the idea of the target reserved part actually. But not sure how it 
> > > could be used without adding any target specific methods?
> >
> >
> > If we decide to add target reserved fields, I can add target hooks to fill 
> > these fields. However I would suggest to leave this for future since I 
> > don't see there is need for other fields for now.
>
>
> I could imagine it can be usefull for some vendor implementations.
>
> >> However, I am still not clear why the alignment of this struct has to be 
> >> different from any other struct Clang produces. Normally the alignment of 
> >> objects have to be known during IR generation to put them correctly in the 
> >> attributes of generated alloca, store and loads. But as a field inside 
> >> struct I don't know how it can be useful. I would imagine `enqueue_kernel` 
> >> would just operate on the block as if it would be an arbitrary buffer of 
> >> data. Also would size of the struct not account for any padding to make 
> >> sure the alignment can be deduced based on it correctly?
> > 
> > enqueue_kernel needs to pass the block struct to the kernel. Let's assume 
> > it does this by copying the block struct to a buffer. If enqueue_kernel 
> > does not know the alignment of the struct, it can only put it at an 
> > arbitrary address in the buffer. Then the kernel has to copy the struct to 
> > an aligned private memory and load the fields. However, if the 
> > enqueued_kernel knows the alignment of the struct, it can put it at an 
> > address satisfying the alignment. Then the kernel can load the fields 
> > directly from the buffer, skips the step of copying to an aligned private 
> > memory. Therefore, alignment of the block struct is usually a useful 
> > information for enqueue_kernel. I think that's why in the SPIRV spec 
> > OpEnqueueKernel requires an alignment operand for the block context.
>
> Ok, I just think in C if you use `malloc` to obtain a pointer to some memory 
> location it doesn't take any alignment information. Then you can use the 
> pointer to copy any data including the struct into the location its pointed 
> to. And the pointer can be used later on correctly. I think the alignment is 
> deduced in this case from the type or the size of an object. Do you know 
> where the alignment information is used for SPIRV call? Also how is the block 
> represented in SPIRV?


Actually malloc alignment is not sufficient more many uses such as CPU 
supported vectors, e.g. AVX512 or passed to create buffer with 
use-host-pointer.  In such cases you need posix_memalign or some similar API.  
Having the alignment means it is available if needed.  If an implementation 
doesn't need it, there is no harm is there?


https://reviews.llvm.org/D37822



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


[PATCH] D38113: OpenCL: Assume functions are convergent

2017-09-21 Thread Justin Lebar via Phabricator via cfe-commits
jlebar added a comment.

> The problem of adding this attribute conservatively for all functions is that 
> it prevents some optimizations to happen.

function-attrs removes the convergent attribute from anything it can prove does 
not call a convergent function.

I agree this is a nonoptimal solution.  A better way would be to assume that 
any cuda/opencl function is convergent and then figure out what isn't.  This 
would let you generate correct cuda/opencl code in a front-end without worrying 
about this attribute.

One problem with this approach is, suppose you call an external function, whose 
body llvm cannot see.  We need some way to mark this function as 
not-convergent, so that its callers can also be inferred to be not convergent.  
LLVM currently only has a "convergent" attribute.  In the absence of a new 
"not-convergent" attribute, the only way we can tell LLVM that this external 
function is not convergent is to leave off the attribute.  But then this means 
we assume all functions without the convergent attribute are not convergent, 
and thus we have to add the attribute everywhere, as this patch does.

OTOH if we added a not-convergent attribute, we'd have to have rules about what 
happens if both attributes are on a function, and everywhere that checked 
whether a function was convergent would become significantly more complicated.  
I'm not sure that's worthwhile.


https://reviews.llvm.org/D38113



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


[PATCH] D37822: [OpenCL] Clean up and add missing fields for block struct

2017-09-21 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In https://reviews.llvm.org/D37822#877572, @yaxunl wrote:

> In https://reviews.llvm.org/D37822#873876, @Anastasia wrote:
>
> > In https://reviews.llvm.org/D37822#872446, @yaxunl wrote:
> >
> > > In https://reviews.llvm.org/D37822#872291, @Anastasia wrote:
> > >
> > > > Could you please explain a bit more why the alignment have to be put 
> > > > explicitly in the struct? I am just not very convinced this is general 
> > > > enough.
> > >
> > >
> > > The captured variables are fields of the block literal struct. Due to 
> > > alignment requirement of these fields, there is alignment requirement of
> > >  the block literal struct. The ISA of the block invoke function is 
> > > generated with the assumption of these alignments. If the block literal is
> > >  allocated at a memory address not satisfying the alignment requirement, 
> > > the kernel behavior is undefined.
> > >
> > > Generally, __enqueue_kernel library function needs to prepare the kernel 
> > > argument before launching the kernel. It usually does this by copying
> > >  the block literal to some buffer then pass the address of the buffer to 
> > > the kernel. Then the address of the buffer has to satisfy the alignment
> > >  requirement.
> > >
> > > If this block literal struct is not general enough, how about add another 
> > > field as target reserved size, and leave the remaining space of header for
> > >  target specific use. And add a target hook to allow target fill the 
> > > reserved space, e.g.
> > >
> > >   struct __opencl_block_literal {
> > > int total_size;
> > > int align;
> > > __generic void *invoke;
> > > int target_reserved_size; /* round up to 4 bytes */
> > > int target_reserved[];
> > > /* captures */
> > >   };
> > >
> >
> >
> > I like the idea of the target reserved part actually. But not sure how it 
> > could be used without adding any target specific methods?
>
>
> If we decide to add target reserved fields, I can add target hooks to fill 
> these fields. However I would suggest to leave this for future since I don't 
> see there is need for other fields for now.


I could imagine it can be usefull for some vendor implementations.

>> However, I am still not clear why the alignment of this struct has to be 
>> different from any other struct Clang produces. Normally the alignment of 
>> objects have to be known during IR generation to put them correctly in the 
>> attributes of generated alloca, store and loads. But as a field inside 
>> struct I don't know how it can be useful. I would imagine `enqueue_kernel` 
>> would just operate on the block as if it would be an arbitrary buffer of 
>> data. Also would size of the struct not account for any padding to make sure 
>> the alignment can be deduced based on it correctly?
> 
> enqueue_kernel needs to pass the block struct to the kernel. Let's assume it 
> does this by copying the block struct to a buffer. If enqueue_kernel does not 
> know the alignment of the struct, it can only put it at an arbitrary address 
> in the buffer. Then the kernel has to copy the struct to an aligned private 
> memory and load the fields. However, if the enqueued_kernel knows the 
> alignment of the struct, it can put it at an address satisfying the 
> alignment. Then the kernel can load the fields directly from the buffer, 
> skips the step of copying to an aligned private memory. Therefore, alignment 
> of the block struct is usually a useful information for enqueue_kernel. I 
> think that's why in the SPIRV spec OpEnqueueKernel requires an alignment 
> operand for the block context.

Ok, I just think in C if you use `malloc` to obtain a pointer to some memory 
location it doesn't take any alignment information. Then you can use the 
pointer to copy any data including the struct into the location its pointed to. 
And the pointer can be used later on correctly. I think the alignment is 
deduced in this case from the type or the size of an object. Do you know where 
the alignment information is used for SPIRV call? Also how is the block 
represented in SPIRV?


https://reviews.llvm.org/D37822



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


[PATCH] D38147: [CUDA] Fixed order of words in the names of shfl builtins.

2017-09-21 Thread Justin Lebar via Phabricator via cfe-commits
jlebar added a comment.

Naturally they're different orders in the PTX and CUDA.  :)


https://reviews.llvm.org/D38147



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


[PATCH] D38147: [CUDA] Fixed order of words in the names of shfl builtins.

2017-09-21 Thread Artem Belevich via Phabricator via cfe-commits
tra created this revision.
Herald added a subscriber: sanjoy.

https://reviews.llvm.org/D38147

Files:
  clang/lib/Headers/__clang_cuda_intrinsics.h


Index: clang/lib/Headers/__clang_cuda_intrinsics.h
===
--- clang/lib/Headers/__clang_cuda_intrinsics.h
+++ clang/lib/Headers/__clang_cuda_intrinsics.h
@@ -148,13 +148,12 @@
  __nvvm_shfl_sync_idx_f32, 0x1f);
 // We use 0 rather than 31 as our mask, because shfl.up applies to lanes >=
 // maxLane.
-__MAKE_SYNC_SHUFFLES(__shfl_sync_up, __nvvm_shfl_sync_up_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_up_sync, __nvvm_shfl_sync_up_i32,
  __nvvm_shfl_sync_up_f32, 0);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_down, __nvvm_shfl_sync_down_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_down_sync, __nvvm_shfl_sync_down_i32,
  __nvvm_shfl_sync_down_f32, 0x1f);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_xor, __nvvm_shfl_sync_bfly_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_xor_sync, __nvvm_shfl_sync_bfly_i32,
  __nvvm_shfl_sync_bfly_f32, 0x1f);
-
 #pragma pop_macro("__MAKE_SYNC_SHUFFLES")
 
 inline __device__ void __syncwarp(unsigned int mask = 0x) {


Index: clang/lib/Headers/__clang_cuda_intrinsics.h
===
--- clang/lib/Headers/__clang_cuda_intrinsics.h
+++ clang/lib/Headers/__clang_cuda_intrinsics.h
@@ -148,13 +148,12 @@
  __nvvm_shfl_sync_idx_f32, 0x1f);
 // We use 0 rather than 31 as our mask, because shfl.up applies to lanes >=
 // maxLane.
-__MAKE_SYNC_SHUFFLES(__shfl_sync_up, __nvvm_shfl_sync_up_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_up_sync, __nvvm_shfl_sync_up_i32,
  __nvvm_shfl_sync_up_f32, 0);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_down, __nvvm_shfl_sync_down_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_down_sync, __nvvm_shfl_sync_down_i32,
  __nvvm_shfl_sync_down_f32, 0x1f);
-__MAKE_SYNC_SHUFFLES(__shfl_sync_xor, __nvvm_shfl_sync_bfly_i32,
+__MAKE_SYNC_SHUFFLES(__shfl_xor_sync, __nvvm_shfl_sync_bfly_i32,
  __nvvm_shfl_sync_bfly_f32, 0x1f);
-
 #pragma pop_macro("__MAKE_SYNC_SHUFFLES")
 
 inline __device__ void __syncwarp(unsigned int mask = 0x) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D38113: OpenCL: Assume functions are convergent

2017-09-21 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

The problem of adding this attribute conservatively for all functions is that 
it prevents some optimizations to happen. I agree to commit this as a temporary 
fix to guarantee correctness of generated code. But if we ask to add the 
`convergent` attribute into the spec we can avoid doing this in the compiler?


https://reviews.llvm.org/D38113



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


[PATCH] D38009: [Sema] Fix using old initializer during switch statement transformation.

2017-09-21 Thread Volodymyr Sapsai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL313896: [Sema] Fix using old initializer during switch 
statement transformation. (authored by vsapsai).

Changed prior to commit:
  https://reviews.llvm.org/D38009?vs=115754=116226#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D38009

Files:
  cfe/trunk/lib/Sema/TreeTransform.h
  cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp


Index: cfe/trunk/lib/Sema/TreeTransform.h
===
--- cfe/trunk/lib/Sema/TreeTransform.h
+++ cfe/trunk/lib/Sema/TreeTransform.h
@@ -6601,8 +6601,7 @@
 
   // Rebuild the switch statement.
   StmtResult Switch
-= getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(),
-  S->getInit(), Cond);
+= getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
   if (Switch.isInvalid())
 return StmtError();
 
Index: cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp
===
--- cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp
+++ cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -std=c++1z -verify -emit-llvm-only %s
+// expected-no-diagnostics
+
+// rdar://problem/33888545
+template  class Buffer {};
+
+class A {
+public:
+  int status;
+};
+
+template  A parse(Buffer buffer);
+
+template
+void init_in_if(Buffer buffer) {
+  if (A a = parse(buffer); a.status > 0) {
+  }
+}
+
+template
+void init_in_switch(Buffer buffer) {
+  switch (A a = parse(buffer); a.status) {
+default:
+  break;
+  }
+}
+
+void test() {
+  Buffer<10> buffer;
+  init_in_if(buffer);
+  init_in_switch(buffer);
+}


Index: cfe/trunk/lib/Sema/TreeTransform.h
===
--- cfe/trunk/lib/Sema/TreeTransform.h
+++ cfe/trunk/lib/Sema/TreeTransform.h
@@ -6601,8 +6601,7 @@
 
   // Rebuild the switch statement.
   StmtResult Switch
-= getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(),
-  S->getInit(), Cond);
+= getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
   if (Switch.isInvalid())
 return StmtError();
 
Index: cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp
===
--- cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp
+++ cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -std=c++1z -verify -emit-llvm-only %s
+// expected-no-diagnostics
+
+// rdar://problem/33888545
+template  class Buffer {};
+
+class A {
+public:
+  int status;
+};
+
+template  A parse(Buffer buffer);
+
+template
+void init_in_if(Buffer buffer) {
+  if (A a = parse(buffer); a.status > 0) {
+  }
+}
+
+template
+void init_in_switch(Buffer buffer) {
+  switch (A a = parse(buffer); a.status) {
+default:
+  break;
+  }
+}
+
+void test() {
+  Buffer<10> buffer;
+  init_in_if(buffer);
+  init_in_switch(buffer);
+}
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r313896 - [Sema] Fix using old initializer during switch statement transformation.

2017-09-21 Thread Volodymyr Sapsai via cfe-commits
Author: vsapsai
Date: Thu Sep 21 10:58:27 2017
New Revision: 313896

URL: http://llvm.org/viewvc/llvm-project?rev=313896=rev
Log:
[Sema] Fix using old initializer during switch statement transformation.

It fixes a crash in CodeGen when we are trying to generate code for
initializer expression created before template instantiation, like

CallExpr ''
|-UnresolvedLookupExpr '' lvalue (ADL) = 'parse'
`-DeclRefExpr 'Buffer' lvalue ParmVar 'buffer' 'Buffer'

rdar://problem/33888545

Reviewers: rsmith, ahatanak

Reviewed By: ahatanak

Subscribers: aemerson, kristof.beyls, cfe-commits

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


Added:
cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp
Modified:
cfe/trunk/lib/Sema/TreeTransform.h

Modified: cfe/trunk/lib/Sema/TreeTransform.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/TreeTransform.h?rev=313896=313895=313896=diff
==
--- cfe/trunk/lib/Sema/TreeTransform.h (original)
+++ cfe/trunk/lib/Sema/TreeTransform.h Thu Sep 21 10:58:27 2017
@@ -6601,8 +6601,7 @@ TreeTransform::TransformSwitchS
 
   // Rebuild the switch statement.
   StmtResult Switch
-= getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(),
-  S->getInit(), Cond);
+= getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
   if (Switch.isInvalid())
 return StmtError();
 

Added: cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp?rev=313896=auto
==
--- cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp (added)
+++ cfe/trunk/test/SemaCXX/cxx1z-init-statement-template.cpp Thu Sep 21 
10:58:27 2017
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -std=c++1z -verify -emit-llvm-only %s
+// expected-no-diagnostics
+
+// rdar://problem/33888545
+template  class Buffer {};
+
+class A {
+public:
+  int status;
+};
+
+template  A parse(Buffer buffer);
+
+template
+void init_in_if(Buffer buffer) {
+  if (A a = parse(buffer); a.status > 0) {
+  }
+}
+
+template
+void init_in_switch(Buffer buffer) {
+  switch (A a = parse(buffer); a.status) {
+default:
+  break;
+  }
+}
+
+void test() {
+  Buffer<10> buffer;
+  init_in_if(buffer);
+  init_in_switch(buffer);
+}


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


[PATCH] D38145: Suppress Wsign-conversion for enums with matching underlying type

2017-09-21 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.

As reported here: https://bugs.llvm.org/show_bug.cgi?id=34692

A non-defined enum with a backing type was always defaulting to 
being treated as a signed type.  IN the case where it IS defined,
the signed-ness of the actual items is used.

This patch uses the underlying type's signed-ness in the non-defined
case to test signed-comparision.


https://reviews.llvm.org/D38145

Files:
  lib/Sema/SemaChecking.cpp
  test/SemaCXX/sign-conversion.cpp


Index: test/SemaCXX/sign-conversion.cpp
===
--- /dev/null
+++ test/SemaCXX/sign-conversion.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wsign-conversion -std=c++11 %s
+
+unsigned int test() {
+  short foo;
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+
+unsigned int test3() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : char;
+  u8 foo{static_cast(0)};
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+unsigned int test2() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : unsigned char;
+  u8 foo{static_cast(0)};
+  return foo;
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -8172,7 +8172,8 @@
 if (const EnumType *ET = dyn_cast(T)) {
   EnumDecl *Enum = ET->getDecl();
   if (!Enum->isCompleteDefinition())
-return IntRange(C.getIntWidth(QualType(T, 0)), false);
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 
   unsigned NumPositive = Enum->getNumPositiveBits();
   unsigned NumNegative = Enum->getNumNegativeBits();


Index: test/SemaCXX/sign-conversion.cpp
===
--- /dev/null
+++ test/SemaCXX/sign-conversion.cpp
@@ -0,0 +1,21 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wsign-conversion -std=c++11 %s
+
+unsigned int test() {
+  short foo;
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+
+unsigned int test3() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : char;
+  u8 foo{static_cast(0)};
+  return foo; // expected-warning {{implicit conversion changes signedness}}
+
+}
+unsigned int test2() {
+  // For a non-defined enum, use the underlying type.
+  enum u8 : unsigned char;
+  u8 foo{static_cast(0)};
+  return foo;
+}
Index: lib/Sema/SemaChecking.cpp
===
--- lib/Sema/SemaChecking.cpp
+++ lib/Sema/SemaChecking.cpp
@@ -8172,7 +8172,8 @@
 if (const EnumType *ET = dyn_cast(T)) {
   EnumDecl *Enum = ET->getDecl();
   if (!Enum->isCompleteDefinition())
-return IntRange(C.getIntWidth(QualType(T, 0)), false);
+return IntRange(C.getIntWidth(QualType(T, 0)),
+!ET->isSignedIntegerOrEnumerationType());
 
   unsigned NumPositive = Enum->getNumPositiveBits();
   unsigned NumNegative = Enum->getNumNegativeBits();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D38134: [OpenCL] Emit enqueued block as kernel

2017-09-21 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

Now if we have a block which is being called and enqueued at the same time, 
will we generate 2 functions for it? Could we add such test case btw?

I feel it would be much simpler if we could always generate the kernel metadata 
for blocks. A lot of special case code would be removed if we do this. OpenCL 
doesn't prevent kernel functions to be used just as normal functions (6.7.1) so 
it should be a perfectly valid thing to do. Do you seen any issues with that?




Comment at: lib/CodeGen/CGBlocks.cpp:1255
 // Allocate a stack slot to let the debug info survive the RA.
-Address alloc = CreateMemTemp(D->getType(), D->getName() + ".addr");
+Address alloc = CreateMemTemp(
+!PV.isIndirect() ? D->getType()

Is there any test that covers this?



Comment at: lib/CodeGen/CGOpenCLRuntime.cpp:113
+
+llvm::Value *CGOpenCLRuntime::emitOpenCLEnqueuedBlock(CodeGenFunction ,
+  const Expr *E) {

I am not particularly in favour of duplicating CodeGen functionality as it 
typically has so many special cases that are hard to catch. Is this logic 
needed in order to pass to block literal information  that the block is 
enqueued?



Comment at: lib/CodeGen/CodeGenFunction.cpp:535
+if (i == 0 && IsBlock) {
+  ty = CGF.CGM.getTargetCodeGenInfo().getEnqueuedBlockArgumentType(
+  ASTCtx, *CGF.BlockInfo);

I don't quite understand why we need to special case this? As far as I 
undertsnad block argument is a `generic void* ` type but it's being cast to a 
concrete block struct inside the block function. Do we gain anything from 
having it a specific type here?


https://reviews.llvm.org/D38134



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


[PATCH] D38109: [fixup][Sema] Allow in C to define tags inside enumerations.

2017-09-21 Thread Volodymyr Sapsai via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL313894: [fixup][Sema] Allow in C to define tags inside 
enumerations. (authored by vsapsai).

Changed prior to commit:
  https://reviews.llvm.org/D38109?vs=116110=116219#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D38109

Files:
  cfe/trunk/lib/Sema/SemaDecl.cpp
  cfe/trunk/test/Sema/enum.c


Index: cfe/trunk/lib/Sema/SemaDecl.cpp
===
--- cfe/trunk/lib/Sema/SemaDecl.cpp
+++ cfe/trunk/lib/Sema/SemaDecl.cpp
@@ -13916,7 +13916,8 @@
 Invalid = true;
   }
 
-  if (!Invalid && TUK == TUK_Definition && DC->getDeclKind() == Decl::Enum) {
+  if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
+  DC->getDeclKind() == Decl::Enum) {
 Diag(New->getLocation(), diag::err_type_defined_in_enum)
   << Context.getTagDeclType(New);
 Invalid = true;
Index: cfe/trunk/test/Sema/enum.c
===
--- cfe/trunk/test/Sema/enum.c
+++ cfe/trunk/test/Sema/enum.c
@@ -125,9 +125,10 @@
 typedef struct Color NewColor; // expected-error {{use of 'Color' with tag 
type that does not match previous declaration}}
 
 // PR28903
+// In C it is valid to define tags inside enums.
 struct PR28903 {
   enum {
-PR28903_A = (enum { // expected-error-re {{'enum PR28903::(anonymous at 
{{.*}})' cannot be defined in an enumeration}}
+PR28903_A = (enum {
   PR28903_B,
   PR28903_C = PR28903_B
 })0


Index: cfe/trunk/lib/Sema/SemaDecl.cpp
===
--- cfe/trunk/lib/Sema/SemaDecl.cpp
+++ cfe/trunk/lib/Sema/SemaDecl.cpp
@@ -13916,7 +13916,8 @@
 Invalid = true;
   }
 
-  if (!Invalid && TUK == TUK_Definition && DC->getDeclKind() == Decl::Enum) {
+  if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
+  DC->getDeclKind() == Decl::Enum) {
 Diag(New->getLocation(), diag::err_type_defined_in_enum)
   << Context.getTagDeclType(New);
 Invalid = true;
Index: cfe/trunk/test/Sema/enum.c
===
--- cfe/trunk/test/Sema/enum.c
+++ cfe/trunk/test/Sema/enum.c
@@ -125,9 +125,10 @@
 typedef struct Color NewColor; // expected-error {{use of 'Color' with tag type that does not match previous declaration}}
 
 // PR28903
+// In C it is valid to define tags inside enums.
 struct PR28903 {
   enum {
-PR28903_A = (enum { // expected-error-re {{'enum PR28903::(anonymous at {{.*}})' cannot be defined in an enumeration}}
+PR28903_A = (enum {
   PR28903_B,
   PR28903_C = PR28903_B
 })0
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r313894 - [fixup][Sema] Allow in C to define tags inside enumerations.

2017-09-21 Thread Volodymyr Sapsai via cfe-commits
Author: vsapsai
Date: Thu Sep 21 10:41:30 2017
New Revision: 313894

URL: http://llvm.org/viewvc/llvm-project?rev=313894=rev
Log:
[fixup][Sema] Allow in C to define tags inside enumerations.

Fix for too aggressive error err_type_defined_in_enum introduced in
r313386. Defining tags inside enumerations is prohibited in C++ but
allowed in C.

Reviewers: aaron.ballman, rnk, doug.gregor

Reviewed By: rnk

Subscribers: alberto_magni, cfe-commits

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

Modified:
cfe/trunk/lib/Sema/SemaDecl.cpp
cfe/trunk/test/Sema/enum.c

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=313894=313893=313894=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Thu Sep 21 10:41:30 2017
@@ -13916,7 +13916,8 @@ CreateNewDecl:
 Invalid = true;
   }
 
-  if (!Invalid && TUK == TUK_Definition && DC->getDeclKind() == Decl::Enum) {
+  if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
+  DC->getDeclKind() == Decl::Enum) {
 Diag(New->getLocation(), diag::err_type_defined_in_enum)
   << Context.getTagDeclType(New);
 Invalid = true;

Modified: cfe/trunk/test/Sema/enum.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/enum.c?rev=313894=313893=313894=diff
==
--- cfe/trunk/test/Sema/enum.c (original)
+++ cfe/trunk/test/Sema/enum.c Thu Sep 21 10:41:30 2017
@@ -125,9 +125,10 @@ enum Color { Red, Green, Blue }; // expe
 typedef struct Color NewColor; // expected-error {{use of 'Color' with tag 
type that does not match previous declaration}}
 
 // PR28903
+// In C it is valid to define tags inside enums.
 struct PR28903 {
   enum {
-PR28903_A = (enum { // expected-error-re {{'enum PR28903::(anonymous at 
{{.*}})' cannot be defined in an enumeration}}
+PR28903_A = (enum {
   PR28903_B,
   PR28903_C = PR28903_B
 })0


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


r313892 - [lit] Rename lld and clang lit configs to end in .py

2017-09-21 Thread Zachary Turner via cfe-commits
Author: zturner
Date: Thu Sep 21 10:38:13 2017
New Revision: 313892

URL: http://llvm.org/viewvc/llvm-project?rev=313892=rev
Log:
[lit] Rename lld and clang lit configs to end in .py

This follows in line with a previous patch of renaming LLVM's.

Working on these files is difficult in certain operating systems
and/or environments that don't like handling python code with a
non .py file extension.

Added:
cfe/trunk/test/Unit/lit.cfg.py
cfe/trunk/test/Unit/lit.site.cfg.py.in
cfe/trunk/test/lit.cfg.py
cfe/trunk/test/lit.site.cfg.py.in
Removed:
cfe/trunk/test/Unit/lit.cfg
cfe/trunk/test/Unit/lit.site.cfg.in
cfe/trunk/test/lit.cfg
cfe/trunk/test/lit.site.cfg.in
Modified:
cfe/trunk/test/CMakeLists.txt

Modified: cfe/trunk/test/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CMakeLists.txt?rev=313892=313891=313892=diff
==
--- cfe/trunk/test/CMakeLists.txt (original)
+++ cfe/trunk/test/CMakeLists.txt Thu Sep 21 10:38:13 2017
@@ -26,13 +26,17 @@ llvm_canonicalize_cmake_booleans(
   HAVE_LIBZ)
 
 configure_lit_site_cfg(
-  ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
-  ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg
+  ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.py.in
+  ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg.py
+  MAIN_CONFIG
+  ${CMAKE_CURRENT_SOURCE_DIR}/lit.cfg.py
   )
 
 configure_lit_site_cfg(
-  ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.in
-  ${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg
+  ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.py.in
+  ${CMAKE_CURRENT_BINARY_DIR}/Unit/lit.site.cfg.py
+  MAIN_CONFIG
+  ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.cfg.py
   )
 
 option(CLANG_TEST_USE_VG "Run Clang tests under Valgrind" OFF)

Removed: cfe/trunk/test/Unit/lit.cfg
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Unit/lit.cfg?rev=313891=auto
==
--- cfe/trunk/test/Unit/lit.cfg (original)
+++ cfe/trunk/test/Unit/lit.cfg (removed)
@@ -1,51 +0,0 @@
-# -*- Python -*-
-
-# Configuration file for the 'lit' test runner.
-
-import os
-import platform
-import subprocess
-
-import lit.formats
-import lit.util
-
-# name: The name of this test suite.
-config.name = 'Clang-Unit'
-
-# suffixes: A list of file extensions to treat as test files.
-config.suffixes = []
-
-# test_source_root: The root path where tests are located.
-# test_exec_root: The root path where tests should be run.
-config.test_exec_root = os.path.join(config.clang_obj_root, 'unittests')
-config.test_source_root = config.test_exec_root
-
-# testFormat: The test format to use to interpret tests.
-config.test_format = lit.formats.GoogleTest(config.llvm_build_mode, 'Tests')
-
-# Propagate the temp directory. Windows requires this because it uses \Windows\
-# if none of these are present.
-if 'TMP' in os.environ:
-config.environment['TMP'] = os.environ['TMP']
-if 'TEMP' in os.environ:
-config.environment['TEMP'] = os.environ['TEMP']
-
-# Propagate path to symbolizer for ASan/MSan.
-for symbolizer in ['ASAN_SYMBOLIZER_PATH', 'MSAN_SYMBOLIZER_PATH']:
-if symbolizer in os.environ:
-config.environment[symbolizer] = os.environ[symbolizer]
-
-shlibpath_var = ''
-if platform.system() == 'Linux':
-shlibpath_var = 'LD_LIBRARY_PATH'
-elif platform.system() == 'Darwin':
-shlibpath_var = 'DYLD_LIBRARY_PATH'
-elif platform.system() == 'Windows':
-shlibpath_var = 'PATH'
-
-# in stand-alone builds, shlibdir is clang's build tree
-# while llvm_libs_dir is installed LLVM (and possibly older clang)
-shlibpath = os.path.pathsep.join((config.shlibdir, config.llvm_libs_dir,
- config.environment.get(shlibpath_var,'')))
-
-config.environment[shlibpath_var] = shlibpath

Added: cfe/trunk/test/Unit/lit.cfg.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Unit/lit.cfg.py?rev=313892=auto
==
--- cfe/trunk/test/Unit/lit.cfg.py (added)
+++ cfe/trunk/test/Unit/lit.cfg.py Thu Sep 21 10:38:13 2017
@@ -0,0 +1,51 @@
+# -*- Python -*-
+
+# Configuration file for the 'lit' test runner.
+
+import os
+import platform
+import subprocess
+
+import lit.formats
+import lit.util
+
+# name: The name of this test suite.
+config.name = 'Clang-Unit'
+
+# suffixes: A list of file extensions to treat as test files.
+config.suffixes = []
+
+# test_source_root: The root path where tests are located.
+# test_exec_root: The root path where tests should be run.
+config.test_exec_root = os.path.join(config.clang_obj_root, 'unittests')
+config.test_source_root = config.test_exec_root
+
+# testFormat: The test format to use to interpret tests.
+config.test_format = lit.formats.GoogleTest(config.llvm_build_mode, 'Tests')
+
+# Propagate the temp directory. Windows requires this because it uses \Windows\
+# if none of these are present.
+if 'TMP' in os.environ:

[PATCH] D37925: Allow specifying sanitizers in blacklists

2017-09-21 Thread Vlad Tsyrklevich via Phabricator via cfe-commits
vlad.tsyrklevich added inline comments.



Comment at: lib/AST/Decl.cpp:3953
 ReasonToReject = 5;  // is standard layout.
-  else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
+  else if (Blacklist.isBlacklistedLocation(ASanMask, getLocation(),
+   "field-padding"))

eugenis wrote:
> Looks like this is another case of missing "& LangOpts.Sanitize.Mask" ?
Indeed.



Comment at: lib/Basic/XRayLists.cpp:29
   // whether it's treated as a "never" instrument function.
-  if (AlwaysInstrument->inSection("fun", FunctionName, "arg1"))
+  if (AlwaysInstrument->inSection("xray_always_instrument", "fun", 
FunctionName,
+  "arg1"))

eugenis wrote:
> It feels redundant to have AlwaysInstrument and NeverInstrument lists, and 
> then the same distinction in section names. Maybe sections could be named 
> "xray" in  both cases? Or, better, the lists could be merged into a single 
> list with always and never sections? There is also an issue of backward 
> compatibility. Anyway, that's for xray devs to decide. @dberris 
I chose this approach for backwards compatibility, but I'd defer to what 
@dberris thinks is best.


https://reviews.llvm.org/D37925



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


[PATCH] D37925: Allow specifying sanitizers in blacklists

2017-09-21 Thread Vlad Tsyrklevich via Phabricator via cfe-commits
vlad.tsyrklevich updated this revision to Diff 116213.
vlad.tsyrklevich marked 5 inline comments as done.
vlad.tsyrklevich added a comment.

- sanitizerCompile -> createSanitizerSections
- ASanMask -> AsanMask and fix another bug relating to ANDing with 
LangOpts.Sanitize.Mask


https://reviews.llvm.org/D37925

Files:
  docs/ControlFlowIntegrity.rst
  docs/SanitizerSpecialCaseList.rst
  include/clang/Basic/SanitizerBlacklist.h
  include/clang/Basic/SanitizerSpecialCaseList.h
  lib/AST/Decl.cpp
  lib/Basic/CMakeLists.txt
  lib/Basic/SanitizerBlacklist.cpp
  lib/Basic/SanitizerSpecialCaseList.cpp
  lib/Basic/XRayLists.cpp
  lib/CodeGen/CGClass.cpp
  lib/CodeGen/CGDeclCXX.cpp
  lib/CodeGen/CGExpr.cpp
  lib/CodeGen/CodeGenFunction.cpp
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/CodeGenModule.h
  test/CodeGen/Inputs/sanitizer-special-case-list.sanitized.txt
  test/CodeGen/Inputs/sanitizer-special-case-list.unsanitized1.txt
  test/CodeGen/Inputs/sanitizer-special-case-list.unsanitized2.txt
  test/CodeGen/Inputs/sanitizer-special-case-list.unsanitized3.txt
  test/CodeGen/Inputs/sanitizer-special-case-list.unsanitized4.txt
  test/CodeGen/sanitizer-special-case-list.c
  test/CodeGenCXX/cfi-blacklist.cpp

Index: test/CodeGenCXX/cfi-blacklist.cpp
===
--- test/CodeGenCXX/cfi-blacklist.cpp
+++ test/CodeGenCXX/cfi-blacklist.cpp
@@ -1,6 +1,18 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple -fvisibility hidden -fms-extensions -fsanitize=cfi-vcall -emit-llvm -o - %s | FileCheck --check-prefix=CHECK --check-prefix=NOBL %s
-// RUN: echo "type:std::*" > %t.txt
-// RUN: %clang_cc1 -triple %itanium_abi_triple -fvisibility hidden -fms-extensions -fsanitize=cfi-vcall -fsanitize-blacklist=%t.txt -emit-llvm -o - %s | FileCheck --check-prefix=CHECK --check-prefix=NOSTD %s
+
+// Check that blacklisting cfi and cfi-vcall work correctly
+// RUN: echo "[cfi-vcall]" > %t.vcall.txt
+// RUN: echo "type:std::*" >> %t.vcall.txt
+// RUN: %clang_cc1 -triple %itanium_abi_triple -fvisibility hidden -fms-extensions -fsanitize=cfi-vcall -fsanitize-blacklist=%t.vcall.txt -emit-llvm -o - %s | FileCheck --check-prefix=CHECK --check-prefix=NOSTD %s
+//
+// RUN: echo "[cfi]" > %t.cfi.txt
+// RUN: echo "type:std::*" >> %t.cfi.txt
+// RUN: %clang_cc1 -triple %itanium_abi_triple -fvisibility hidden -fms-extensions -fsanitize=cfi-vcall -fsanitize-blacklist=%t.cfi.txt -emit-llvm -o - %s | FileCheck --check-prefix=CHECK --check-prefix=NOSTD %s
+
+// Check that blacklisting non-vcall modes does not affect vcalls
+// RUN: echo "[cfi-icall|cfi-nvcall|cfi-cast-strict|cfi-derived-cast|cfi-unrelated-cast]" > %t.other.txt
+// RUN: echo "type:std::*" >> %t.other.txt
+// RUN: %clang_cc1 -triple %itanium_abi_triple -fvisibility hidden -fms-extensions -fsanitize=cfi-vcall -fsanitize-blacklist=%t.other.txt -emit-llvm -o - %s | FileCheck --check-prefix=CHECK --check-prefix=NOBL %s
 
 struct S1 {
   virtual void f();
Index: test/CodeGen/sanitizer-special-case-list.c
===
--- /dev/null
+++ test/CodeGen/sanitizer-special-case-list.c
@@ -0,0 +1,26 @@
+// Verify that blacklist sections correctly select sanitizers to apply blacklist entries to.
+//
+// RUN: %clang_cc1 -fsanitize=unsigned-integer-overflow,cfi-icall -fsanitize-blacklist=%S/Inputs/sanitizer-special-case-list.unsanitized1.txt -emit-llvm %s -o - | FileCheck %s --check-prefix=UNSANITIZED
+// RUN: %clang_cc1 -fsanitize=unsigned-integer-overflow,cfi-icall -fsanitize-blacklist=%S/Inputs/sanitizer-special-case-list.unsanitized2.txt -emit-llvm %s -o - | FileCheck %s --check-prefix=UNSANITIZED
+// RUN: %clang_cc1 -fsanitize=unsigned-integer-overflow,cfi-icall -fsanitize-blacklist=%S/Inputs/sanitizer-special-case-list.unsanitized3.txt -emit-llvm %s -o - | FileCheck %s --check-prefix=UNSANITIZED
+// RUN: %clang_cc1 -fsanitize=unsigned-integer-overflow,cfi-icall -fsanitize-blacklist=%S/Inputs/sanitizer-special-case-list.unsanitized4.txt -emit-llvm %s -o - | FileCheck %s --check-prefix=UNSANITIZED
+//
+// RUN: %clang_cc1 -fsanitize=unsigned-integer-overflow,cfi-icall -fsanitize-blacklist=%S/Inputs/sanitizer-special-case-list.sanitized.txt -emit-llvm %s -o - | FileCheck %s --check-prefix=SANITIZED
+
+unsigned i;
+
+// SANITIZED: @overflow
+// UNSANITIZED: @overflow
+unsigned overflow() {
+  // SANITIZED: call {{.*}}void @__ubsan
+  // UNSANITIZED-NOT: call {{.*}}void @__ubsan
+  return i * 37;
+}
+
+// SANITIZED: @cfi
+// UNSANITIZED: @cfi
+void cfi(void (*fp)()) {
+  // SANITIZED: llvm.type.test
+  // UNSANITIZED-NOT: llvm.type.test
+  fp();
+}
Index: test/CodeGen/Inputs/sanitizer-special-case-list.unsanitized4.txt
===
--- /dev/null
+++ test/CodeGen/Inputs/sanitizer-special-case-list.unsanitized4.txt
@@ -0,0 +1,4 @@
+[c*]
+fun:*cfi*
+[u*]
+fun:*overflow*
Index: test/CodeGen/Inputs/sanitizer-special-case-list.unsanitized3.txt

[PATCH] D36487: Emit section information for extern variables.

2017-09-21 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added inline comments.



Comment at: lib/CodeGen/CodeGenModule.cpp:2434
+// Emit section information for extern variables.
+if (D->hasExternalStorage() && !D->isThisDeclarationADefinition()) {
+  if (const SectionAttr *SA = D->getAttr())

efriedma wrote:
> eandrews wrote:
> > efriedma wrote:
> > > Why do you specifically check "D->hasExternalStorage() && 
> > > !D->isThisDeclarationADefinition()", instead of just setting the section 
> > > unconditionally?
> > I noticed that you enter GetOrCreateLLVMGlobal( ) whenever the extern 
> > variable is declared as well as when it is defined. The flow of the program 
> > is different in each case. When the variable is defined, it also enters 
> > EmitGlobalVarDefinition( ). There is existing code handling section 
> > information here. I added the check in GetOrCreateLLVMGlobal( ) so the 
> > block gets skipped for variable definition, since its already handled 
> > elsewhere.
> I would rather just call setSection unconditionally here, as opposed to 
> trying to guess whether the global will eventually be defined.
> 
> I'm also sort of concerned the behavior here could be weird if a section 
> attribute is added on a redeclaration (e.g. what happens if you write `extern 
> int x; int y =  extern int x __attribute((section("foo")));`)... maybe we 
> should emit a warning?
@efriedma  I modified the patch to emit a warning in the scenario you 
mentioned. A warning is also emitted for the following - 

```extern int x;  int *y= int x __attribute__((section("foo"))); 
```
I thought it made sense to emit the warning for the latter as well. Should I 
restrict the warning to just redeclarations (without definition) instead?


https://reviews.llvm.org/D36487



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


[PATCH] D36487: Emit section information for extern variables.

2017-09-21 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews updated this revision to Diff 116211.
eandrews added a comment.

I've updated the patch based on review comments. The changes include setting 
section unconditionally for extern variables and emitting a warning if section 
attribute is specified on a redeclaration.


https://reviews.llvm.org/D36487

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/CodeGen/CodeGenModule.cpp
  lib/Sema/SemaDecl.cpp
  test/CodeGenCXX/extern-section-attribute.cpp
  test/Sema/attr-section.c


Index: test/Sema/attr-section.c
===
--- test/Sema/attr-section.c
+++ test/Sema/attr-section.c
@@ -19,3 +19,7 @@
 void __attribute__((section("bar,zed"))) test2(void) {} // expected-warning 
{{section does not match previous declaration}}
 
 enum __attribute__((section("NEAR,x"))) e { one }; // expected-error 
{{'section' attribute only applies to functions, methods, properties, and 
global variables}}
+
+extern int a; // expected-note {{previous declaration is here}}
+int *b = 
+extern int a __attribute__((section("foo,zed"))); // expected-warning 
{{section attribute is specified on redeclared variable}}
Index: test/CodeGenCXX/extern-section-attribute.cpp
===
--- /dev/null
+++ test/CodeGenCXX/extern-section-attribute.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple=x86_64-pc-linux-gnu | FileCheck 
%s
+
+extern int aa __attribute__((section(".sdata")));
+// CHECK-DAG: @aa = external global i32, section ".sdata", align 4
+
+extern int bb __attribute__((section(".sdata"))) = 1;
+// CHECK-DAG: @bb = global i32 1, section ".sdata", align 4
+
+int foo() {
+  return aa + bb;
+}
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -2607,6 +2607,14 @@
 }
   }
 
+  // This redeclaration adds a section attribute to a declaration that has
+  // already been ODR-used.
+  if (New->hasAttr() && !Old->hasAttr() &&
+  Old->isUsed()) {
+Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
+Diag(Old->getLocation(), diag::note_previous_declaration);
+  }
+
   if (!Old->hasAttrs())
 return;
 
Index: lib/CodeGen/CodeGenModule.cpp
===
--- lib/CodeGen/CodeGenModule.cpp
+++ lib/CodeGen/CodeGenModule.cpp
@@ -2431,6 +2431,12 @@
   EmitGlobalVarDefinition(D);
 }
 
+// Emit section information for extern variables.
+if (D->hasExternalStorage()) {
+  if (const SectionAttr *SA = D->getAttr())
+GV->setSection(SA->getName());
+}
+
 // Handle XCore specific ABI requirements.
 if (getTriple().getArch() == llvm::Triple::xcore &&
 D->getLanguageLinkage() == CLanguageLinkage &&
Index: include/clang/Basic/DiagnosticSemaKinds.td
===
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -2611,6 +2611,8 @@
   "argument to 'section' attribute is not valid for this target: %0">;
 def warn_mismatched_section : Warning<
   "section does not match previous declaration">, InGroup;
+def warn_attribute_section_on_redeclaration : Warning<
+  "section attribute is specified on redeclared variable">, InGroup;
 
 def err_anonymous_property: Error<
   "anonymous property is not supported">;


Index: test/Sema/attr-section.c
===
--- test/Sema/attr-section.c
+++ test/Sema/attr-section.c
@@ -19,3 +19,7 @@
 void __attribute__((section("bar,zed"))) test2(void) {} // expected-warning {{section does not match previous declaration}}
 
 enum __attribute__((section("NEAR,x"))) e { one }; // expected-error {{'section' attribute only applies to functions, methods, properties, and global variables}}
+
+extern int a; // expected-note {{previous declaration is here}}
+int *b = 
+extern int a __attribute__((section("foo,zed"))); // expected-warning {{section attribute is specified on redeclared variable}}
Index: test/CodeGenCXX/extern-section-attribute.cpp
===
--- /dev/null
+++ test/CodeGenCXX/extern-section-attribute.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -emit-llvm %s -o - -triple=x86_64-pc-linux-gnu | FileCheck %s
+
+extern int aa __attribute__((section(".sdata")));
+// CHECK-DAG: @aa = external global i32, section ".sdata", align 4
+
+extern int bb __attribute__((section(".sdata"))) = 1;
+// CHECK-DAG: @bb = global i32 1, section ".sdata", align 4
+
+int foo() {
+  return aa + bb;
+}
Index: lib/Sema/SemaDecl.cpp
===
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -2607,6 +2607,14 @@
 }
   }
 
+  // This redeclaration adds a section attribute to a declaration that has
+  // already been 

[PATCH] D38075: Fix PR34668 - P0704R1 implementation is too permissive

2017-09-21 Thread Nicolas Lesser via Phabricator via cfe-commits
Rakete added inline comments.



Comment at: lib/Sema/SemaExprCXX.cpp:5185
   if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
 // C++2a allows functions with ref-qualifier & if they are also 
'const'.
+if (Proto->isConst() && !Proto->isVolatile())

tcanens wrote:
> Rakete wrote:
> > I think you should update the comment to something like "also 'const', but 
> > not if they're 'volatile'."
> "if their cv-qualifier-seq is (exactly) 'const'", maybe?
Sure that works too :)


https://reviews.llvm.org/D38075



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


[PATCH] D38101: [Sema] Diagnose tautological comparison with type's min/max values

2017-09-21 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Tried stage2 build, so far only one warning.
But found out that `ubsan_value.h`'s `typedef s128 SIntMax;` crashes this code 
because

  class LLVM_NODISCARD APSInt : public APInt {
  ...
/// \brief Get the correctly-extended \c int64_t value.
int64_t getExtValue() const {
  assert(getMinSignedBits() <= 64 && "Too many bits for int64_t");
  return isSigned() ? getSExtValue() : getZExtValue();
}


Repository:
  rL LLVM

https://reviews.llvm.org/D38101



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


[PATCH] D35743: [clang-format] Adjust space around &/&& of structured bindings

2017-09-21 Thread Chih-Hung Hsieh via Phabricator via cfe-commits
chh updated this revision to Diff 116201.
chh marked 2 inline comments as done.
chh edited the summary of this revision.

https://reviews.llvm.org/D35743

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -11579,24 +11579,59 @@
   EXPECT_EQ("auto const volatile [a, b] = f();",
 format("auto  const   volatile[a, b] = f();"));
   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
-  EXPECT_EQ("auto & [a, b, c] = f();",
+  EXPECT_EQ("auto &[a, b, c] = f();",
 format("auto   &[  a  ,  b,c   ] = f();"));
-  EXPECT_EQ("auto && [a, b, c] = f();",
+  EXPECT_EQ("auto &&[a, b, c] = f();",
 format("auto   &&[  a  ,  b,c   ] = f();"));
-  EXPECT_EQ("auto const & [a, b] = f();", format("auto  const&[a, b] = f();"));
-  EXPECT_EQ("auto const volatile && [a, b] = f();",
+  EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
+  EXPECT_EQ("auto const volatile &&[a, b] = f();",
 format("auto  const  volatile  &&[a, b] = f();"));
-  EXPECT_EQ("auto && [a, b] = f();", format("auto  &&[a, b] = f();"));
+  EXPECT_EQ("auto const &&[a, b] = f();", format("auto  const   &&  [a, b] = f();"));
+  EXPECT_EQ("const auto &[a, b] = f();", format("const  auto  &  [a, b] = f();"));
+  EXPECT_EQ("const auto volatile &&[a, b] = f();",
+format("const  auto   volatile  &&[a, b] = f();"));
+  EXPECT_EQ("volatile const auto &&[a, b] = f();",
+format("volatile  const  auto   &&[a, b] = f();"));
+  EXPECT_EQ("const auto &&[a, b] = f();", format("const  auto  &&  [a, b] = f();"));
 
   // Make sure we don't mistake structured bindings for lambdas.
-  verifyFormat("auto [a, b]{A * i};");
-  verifyFormat("auto const [a, b]{A * i};");
-  verifyFormat("auto const && [a, b]{A * i};");
+  FormatStyle PointerMiddle = getLLVMStyle();
+  PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
+  verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
+  verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
+  verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
+  verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
+  verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
+  verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
+  verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
+  verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
+  verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
+  verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
+  verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
+
+  EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
+format("for (const auto   &&   [a, b] : some_range) {\n}"));
+  EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
+format("for (const auto   &   [a, b] : some_range) {\n}"));
+  EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
+format("for (const auto[a, b] : some_range) {\n}"));
+  EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
+  EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
+  EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
+  EXPECT_EQ("auto const &[x, y](expr);", format("auto  const  &  [x,y]  (expr);"));
+  EXPECT_EQ("auto const &&[x, y](expr);", format("auto  const  &&  [x,y]  (expr);"));
+  EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y] {expr};"));
+  EXPECT_EQ("auto const &[x, y]{expr};", format("auto  const  &  [x,y]  {expr};"));
+  EXPECT_EQ("auto const &&[x, y]{expr};", format("auto  const  &&  [x,y]  {expr};"));
 
   format::FormatStyle Spaces = format::getLLVMStyle();
   Spaces.SpacesInSquareBrackets = true;
   verifyFormat("auto [ a, b ] = f();", Spaces);
-  verifyFormat("auto && [ a, b ] = f();", Spaces);
+  verifyFormat("auto &&[ a, b ] = f();", Spaces);
+  verifyFormat("auto &[ a, b ] = f();", Spaces);
+  verifyFormat("auto const &&[ a, b ] = f();", Spaces);
+  verifyFormat("auto const &[ a, b ] = f();", Spaces);
 }
 
 } // end namespace
Index: lib/Format/TokenAnnotator.cpp
===
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -342,10 +342,10 @@
 bool ColonFound = false;
 
 unsigned BindingIncrease = 1;
-if (Left->is(TT_Unknown)) {
-  if (Left->isCppStructuredBinding(Style)) {
-Left->Type = TT_StructuredBindingLSquare;
-  } else if (StartsObjCMethodExpr) {
+if (Left->isCppStructuredBinding(Style)) {
+  Left->Type = TT_StructuredBindingLSquare;
+} else if (Left->is(TT_Unknown)) {
+  if (StartsObjCMethodExpr) {
 Left->Type = TT_ObjCMethodExpr;
   } else if (Style.Language 

[PATCH] D37150: [clangd] Command line arg to specify compile_commands.json path

2017-09-21 Thread William Enright via Phabricator via cfe-commits
Nebiroth updated this revision to Diff 116198.
Nebiroth added a comment.

More consistent logging in clangdmain.
Restructured argument checking in ClangdMain
Fixed empty compile-commands-dir triggering error messages.
Fixed failing standard tests.


https://reviews.llvm.org/D37150

Files:
  clangd/ClangdLSPServer.cpp
  clangd/ClangdLSPServer.h
  clangd/GlobalCompilationDatabase.cpp
  clangd/GlobalCompilationDatabase.h
  clangd/tool/ClangdMain.cpp

Index: clangd/tool/ClangdMain.cpp
===
--- clangd/tool/ClangdMain.cpp
+++ clangd/tool/ClangdMain.cpp
@@ -11,16 +11,24 @@
 #include "JSONRPCDispatcher.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
-
 #include 
 #include 
 #include 
 #include 
+#include 
 
 using namespace clang;
 using namespace clang::clangd;
 
+static llvm::cl::opt CompileCommandsDir(
+"compile-commands-dir",
+llvm::cl::desc("Specify a path to look for compile_commands.json. If path "
+   "is invalid, clangd will look in the current directory and "
+   "parent paths of each source file."));
+
+
 static llvm::cl::opt
 WorkerThreadsCount("j",
llvm::cl::desc("Number of async workers used by clangd"),
@@ -56,18 +64,44 @@
   if (RunSynchronously)
 WorkerThreadsCount = 0;
 
+  /// Validate command line arguments.
   llvm::raw_ostream  = llvm::outs();
   llvm::raw_ostream  = llvm::errs();
-  JSONOutput Out(Outs, Logs);
+  JSONOutput Out(Outs, Logs);  
 
-  // Change stdin to binary to not lose \r\n on windows.
-  llvm::sys::ChangeStdinToBinary();
+  // If --compile-commands-dir arg was invoked, check value and override default
+  // path.
+  namespace path = llvm::sys::path;
+  llvm::Optional CompileCommandsDirPath;
+
+  if (CompileCommandsDir.empty())
+CompileCommandsDirPath = llvm::None;
+  else
+  {
+if (!llvm::sys::path::is_absolute(CompileCommandsDir)) {
+  llvm::errs() << "Path specified by --compile-commands-dir must be an absolute "
+  "path. The argument will be ignored.\n";
+  CompileCommandsDir = "";
+}
+
+if (!llvm::sys::fs::exists(CompileCommandsDir)) {
+  llvm::errs() << "Path specified by --compile-commands-dir does not exist. The argument will be "
+  "ignored.\n";
+  CompileCommandsDir = "";
+}
+CompileCommandsDirPath = CompileCommandsDir;
+  }  
 
   llvm::Optional ResourceDirRef = None;
   if (!ResourceDir.empty())
 ResourceDirRef = ResourceDir;
 
+  /// Change stdin to binary to not lose \r\n on windows.
+  llvm::sys::ChangeStdinToBinary();  
+
+  /// Initialize and run ClangdLSPServer.
+
   ClangdLSPServer LSPServer(Out, WorkerThreadsCount, EnableSnippets,
-ResourceDirRef);
+ResourceDirRef, CompileCommandsDirPath);
   LSPServer.run(std::cin);
 }
Index: clangd/GlobalCompilationDatabase.h
===
--- clangd/GlobalCompilationDatabase.h
+++ clangd/GlobalCompilationDatabase.h
@@ -45,14 +45,19 @@
 class DirectoryBasedGlobalCompilationDatabase
 : public GlobalCompilationDatabase {
 public:
+  DirectoryBasedGlobalCompilationDatabase(
+  llvm::Optional NewCompileCommandsDir)
+  : CompileCommandsDir(NewCompileCommandsDir) {}
   std::vector
   getCompileCommands(PathRef File) override;
 
   void setExtraFlagsForFile(PathRef File, std::vector ExtraFlags);
 
 private:
-  tooling::CompilationDatabase *getCompilationDatabase(PathRef File);
+  tooling::CompilationDatabase *getCompilationDatabase(PathRef File);  
+  tooling::CompilationDatabase *tryLoadDatabaseFromPath(PathRef File);
 
+  llvm::Optional CompileCommandsDir;
   std::mutex Mutex;
   /// Caches compilation databases loaded from directories(keys are
   /// directories).
Index: clangd/GlobalCompilationDatabase.cpp
===
--- clangd/GlobalCompilationDatabase.cpp
+++ clangd/GlobalCompilationDatabase.cpp
@@ -62,43 +62,54 @@
 }
 
 tooling::CompilationDatabase *
-DirectoryBasedGlobalCompilationDatabase::getCompilationDatabase(PathRef File) {
-  std::lock_guard Lock(Mutex);
-
+DirectoryBasedGlobalCompilationDatabase::tryLoadDatabaseFromPath(PathRef File) {
+  
   namespace path = llvm::sys::path;
+  auto CachedIt = CompilationDatabases.find(File);
+  std::string Error = "";
 
   assert((path::is_absolute(File, path::Style::posix) ||
   path::is_absolute(File, path::Style::windows)) &&
  "path must be absolute");
 
-  for (auto Path = path::parent_path(File); !Path.empty();
-   Path = path::parent_path(Path)) {
-
-auto CachedIt = CompilationDatabases.find(Path);
-if (CachedIt != CompilationDatabases.end())
-  return CachedIt->second.get();
-std::string Error;
-auto CDB = 

[PATCH] D36836: [clang-tidy] Implement readability-function-cognitive-complexity check

2017-09-21 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In https://reviews.llvm.org/D36836#877636, @alexfh wrote:

> > The metric is implemented as per COGNITIVE COMPLEXITY by SonarSource 
> > specification version 1.2 (19 April 2017),
>
> Err, "I did ask them, and received an answer that it is it can be implemented 
> in clang-tidy" might not be enough.


F5372479: original_msg.txt 

  Hello Roman,
  
  It would not, and I would be happy to be notified once done.
  
  Thanks
  
  Olivier
  
  > On Fri, Jul 28, 2017 at 6:17 PM Roman Lebedev  wrote:
  > Hi.
  > 
  > I would like to know, what is the legal status of
  > https://www.sonarsource.com/docs/CognitiveComplexity.pdf ?
  > 
  > If i (or someone else) is to implement the Specification described in
  > that paper,
  > which will produce the same results as the Cognitive Complexity in 
SonarSource
  > as part of some other static analyzer, for example as a LLVM's clang-tidy 
check,
  > would that be illegal thing to do?
  > 
  > Roman.
  -- 
  Olivier Gaudin | SonarSource
  CEO & Co-Founder
  +41 (0)22 510 2424
  http://sonarsource.com

Might not be enough?


Repository:
  rL LLVM

https://reviews.llvm.org/D36836



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


[PATCH] D34512: Add preliminary Cross Translation Unit support library

2017-09-21 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun updated this revision to Diff 116195.
xazax.hun added a comment.

- Unittests now creates temporary files at the correct location
- Temporary files are also cleaned up when the process is terminated
- Absolute paths are handled correctly by the library


https://reviews.llvm.org/D34512

Files:
  include/clang/Basic/AllDiagnostics.h
  include/clang/Basic/CMakeLists.txt
  include/clang/Basic/Diagnostic.td
  include/clang/Basic/DiagnosticCrossTUKinds.td
  include/clang/Basic/DiagnosticIDs.h
  include/clang/CrossTU/CrossTUDiagnostic.h
  include/clang/CrossTU/CrossTranslationUnit.h
  lib/AST/ASTImporter.cpp
  lib/Basic/DiagnosticIDs.cpp
  lib/CMakeLists.txt
  lib/CrossTU/CMakeLists.txt
  lib/CrossTU/CrossTranslationUnit.cpp
  test/Analysis/func-mapping-test.cpp
  test/CMakeLists.txt
  test/lit.cfg
  tools/CMakeLists.txt
  tools/clang-func-mapping/CMakeLists.txt
  tools/clang-func-mapping/ClangFnMapGen.cpp
  tools/diagtool/DiagnosticNames.cpp
  unittests/CMakeLists.txt
  unittests/CrossTU/CMakeLists.txt
  unittests/CrossTU/CrossTranslationUnitTest.cpp

Index: unittests/CrossTU/CrossTranslationUnitTest.cpp
===
--- /dev/null
+++ unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -0,0 +1,138 @@
+//===- unittest/Tooling/CrossTranslationUnitTest.cpp - Tooling unit tests -===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "clang/CrossTU/CrossTranslationUnit.h"
+#include "clang/AST/ASTConsumer.h"
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Tooling/Tooling.h"
+#include "llvm/Config/llvm-config.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/ToolOutputFile.h"
+#include "gtest/gtest.h"
+#include 
+
+namespace clang {
+namespace cross_tu {
+
+namespace {
+
+class CTUASTConsumer : public clang::ASTConsumer {
+public:
+  explicit CTUASTConsumer(clang::CompilerInstance , bool *Success)
+  : CTU(CI), Success(Success) {}
+
+  void HandleTranslationUnit(ASTContext ) {
+const TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
+const FunctionDecl *FD = nullptr;
+for (const Decl *D : TU->decls()) {
+  FD = dyn_cast(D);
+  if (FD && FD->getName() == "f")
+break;
+}
+assert(FD && FD->getName() == "f");
+bool OrigFDHasBody = FD->hasBody();
+
+// Prepare the index file and the AST file.
+int ASTFD;
+llvm::SmallString<256> ASTFileName;
+ASSERT_FALSE(
+llvm::sys::fs::createTemporaryFile("f_ast", "ast", ASTFD, ASTFileName));
+llvm::tool_output_file ASTFile(ASTFileName, ASTFD);
+
+int IndexFD;
+llvm::SmallString<256> IndexFileName;
+ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("index", "txt", IndexFD,
+IndexFileName));
+llvm::tool_output_file IndexFile(IndexFileName, IndexFD);
+IndexFile.os() << "c:@F@f#I# " << ASTFileName << "\n";
+IndexFile.os().flush();
+EXPECT_TRUE(llvm::sys::fs::exists(IndexFileName));
+
+StringRef SourceText = "int f(int) { return 0; }\n";
+// This file must exist since the saved ASTFile will reference it.
+int SourceFD;
+llvm::SmallString<256> SourceFileName;
+ASSERT_FALSE(llvm::sys::fs::createTemporaryFile("input", "cpp", SourceFD,
+SourceFileName));
+llvm::tool_output_file SourceFile(SourceFileName, SourceFD);
+SourceFile.os() << SourceText;
+SourceFile.os().flush();
+EXPECT_TRUE(llvm::sys::fs::exists(SourceFileName));
+
+std::unique_ptr ASTWithDefinition =
+tooling::buildASTFromCode(SourceText, SourceFileName);
+ASTWithDefinition->Save(ASTFileName.str());
+EXPECT_TRUE(llvm::sys::fs::exists(ASTFileName));
+
+// Load the definition from the AST file.
+llvm::Expected NewFDorError =
+CTU.getCrossTUDefinition(FD, "", IndexFileName);
+EXPECT_TRUE((bool)NewFDorError);
+const FunctionDecl *NewFD = *NewFDorError;
+
+*Success = NewFD && NewFD->hasBody() && !OrigFDHasBody;
+  }
+
+private:
+  CrossTranslationUnitContext CTU;
+  bool *Success;
+};
+
+class CTUAction : public clang::ASTFrontendAction {
+public:
+  CTUAction(bool *Success) : Success(Success) {}
+
+protected:
+  std::unique_ptr
+  CreateASTConsumer(clang::CompilerInstance , StringRef) override {
+return llvm::make_unique(CI, Success);
+  }
+
+private:
+  bool *Success;
+};
+
+} // end namespace
+
+TEST(CrossTranslationUnit, CanLoadFunctionDefinition) {
+  bool Success = false;
+  EXPECT_TRUE(tooling::runToolOnCode(new CTUAction(), "int f(int);"));
+  EXPECT_TRUE(Success);
+}
+
+TEST(CrossTranslationUnit, IndexFormatCanBeParsed) {
+  llvm::StringMap Index;
+  Index["a"] = "b";
+  Index["c"] = "d";
+  

[PATCH] D36836: [clang-tidy] Implement readability-function-cognitive-complexity check

2017-09-21 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

> The metric is implemented as per COGNITIVE COMPLEXITY by SonarSource 
> specification version 1.2 (19 April 2017),

Err, "I did ask them, and received an answer that it is it can be implemented 
in clang-tidy" might not be enough.


Repository:
  rL LLVM

https://reviews.llvm.org/D36836



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


[PATCH] D38123: [driver] [cl] Add/fix c++17/c++latest

2017-09-21 Thread Martell Malone via Phabricator via cfe-commits
martell accepted this revision.
martell added a comment.
This revision is now accepted and ready to land.

It seems that msvc enabled some c++17 features when in c++14 mode and they left 
them enabled because projects became dependant on them.
switching to c++17 as the default and removing the c++17 features from c++14 
mode seems like the correct thing to do here even if MS still use c++14 as 
their default.
That should be part of a different patch though because a discussion needs to 
be had on that issue.

LGTM as is.
Thanks for the contribution.


https://reviews.llvm.org/D38123



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


[PATCH] D20689: [clang-tidy] Suspicious Call Argument checker

2017-09-21 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In https://reviews.llvm.org/D20689#871947, @barancsuk wrote:

> @alexfh, would you mind taking a look at the changes that have been 
> introduced in the new patch?
>
> The main improvements are:
>
>   - The checker has been shifted to the module `readability`.
>   - It is checked, whether implicit type conversion is possible from the 
> argument to the parameter.
>
> I have run the modified checker on some large code bases with the 
> following results: (The errors were categorized subjectively.)
> - **PostgreSQL:** 32 renaming opportunities of 39 warnings
> - **Cpython:** 10 renaming opportunities of 15 warnings
> - **Xerces:** 6 renaming opportunities of 8 warnings
> - **FFmpeg**:  5 renaming opportunities of 9 warnings
> - **OpenSSL:** 3 renaming opportunities of 4 warnings
> - **LLVM:** 20 renaming opportunities of 44 warnings


Is there a list of all the warnings? I'd like to take a closer look.

> This article provides some evidence to support the feasibility of the checker 
> as well. 
>  F5358417: icse2016-names.pdf  
>  The authors have proven that argument names are generally very similar to 
> the corresponding parameters' names. 
>  The presented empirical evidence also shows, that argument and parameter 
> name dissimilarities are strong indicators of incorrect argument usages, or 
> they identify renaming opportunities to improve code readability. 
>  Moreover, the authors have even found 3 existing bugs in open source 
> projects.




https://reviews.llvm.org/D20689



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


  1   2   >