[PATCH] D82157: Fix crash on `user defined literals`

2020-07-09 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 276638.
eduucaldas added a comment.

workaround size_t


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82157

Files:
  clang/include/clang/Testing/TestClangConfig.h
  clang/include/clang/Tooling/Syntax/Nodes.h
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/Nodes.cpp
  clang/unittests/Tooling/Syntax/TreeTest.cpp

Index: clang/unittests/Tooling/Syntax/TreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/TreeTest.cpp
+++ clang/unittests/Tooling/Syntax/TreeTest.cpp
@@ -1184,20 +1184,106 @@
 )txt"));
 }
 
-TEST_P(SyntaxTreeTest, IntegerLiteral) {
+TEST_P(SyntaxTreeTest, UserDefinedLiteral) {
+  if (!GetParam().isCXX11OrLater()) {
+return;
+  }
   EXPECT_TRUE(treeDumpEqual(
   R"cpp(
+unsigned operator "" _i(unsigned long long);
+unsigned operator "" _f(long double);
+unsigned operator "" _c(char);
+
+unsigned operator "" _r(const char*); // raw-literal operator
+
+template 
+unsigned operator "" _t();// numeric literal operator template
+
 void test() {
-  12;
-  12u;
-  12l;
-  12ul;
-  014;
-  0XC;
+  12_i;  // call: operator "" _i(12uLL)  | kind: integer
+  1.2_f; // call: operator "" _f(1.2L)   | kind: float
+  '2'_c; // call: operator "" _c('2')| kind: char
+
+  // PROBLEM: How to discover the kind of user-defined-literal from the AST?
+  12_r;  // call: operator "" _r("12")   | kind: integer
+  1.2_r; // call: operator "" _i("1.2")  | kind: float
+  12_t;  // call: operator<'1', '2'> "" _x() | kind: integer
+  1.2_t; // call: operator<'1', '2'> "" _x() | kind: float
 }
-)cpp",
+)cpp",
   R"txt(
 *: TranslationUnit
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_i
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-unsigned
+| |   | |-long
+| |   | `-long
+| |   `-)
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_f
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-long
+| |   | `-double
+| |   `-)
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_c
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | `-char
+| |   `-)
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_r
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-const
+| |   | |-char
+| |   | `-SimpleDeclarator
+| |   |   `-*
+| |   `-)
+| `-;
+|-TemplateDeclaration
+| |-template
+| |-<
+| |-SimpleDeclaration
+| | `-char
+| |-...
+| |->
+| `-SimpleDeclaration
+|   |-unsigned
+|   |-SimpleDeclarator
+|   | |-operator
+|   | |-""
+|   | |-_t
+|   | `-ParametersAndQualifiers
+|   |   |-(
+|   |   `-)
+|   `-;
 `-SimpleDeclaration
   |-void
   |-SimpleDeclarator
@@ -1208,28 +1294,95 @@
   `-CompoundStatement
 |-{
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12
+| |-IntegerUserDefinedLiteralExpression
+| | `-12_i
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12u
+| |-FloatUserDefinedLiteralExpression
+| | `-1.2_f
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12l
+| |-CharUserDefinedLiteralExpression
+| | `-'2'_c
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12ul
+| |-UnknownUserDefinedLiteralExpression
+| | `-12_r
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-014
+| |-UnknownUserDefinedLiteralExpression
+| | `-1.2_r
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-0XC
+| |-UnknownUserDefinedLiteralExpression
+| | `-12_t
+| `-;
+|-ExpressionStatement
+| |-UnknownUserDefinedLiteralExpression
+| | `-1.2_t
+| `-;
+`-}
+)txt"));
+}
+
+TEST_P(SyntaxTreeTest, UserDefinedLiteralString) {
+  if (!GetParam().isCXX11OrLater()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqual(
+  R"cpp(
+typedef decltype(sizeof(void *)) size_t;
+unsigned operator "" _s(const char*, size_t);
+void test() {
+  "12"_s;// call: operator "" _s("12")   | kind: string
+}
+)cpp",
+  R"txt(
+*: TranslationUnit
+|-SimpleDeclaration
+| |-typedef
+| |-decltype
+| |-(
+| |-UnknownExpression
+| | |-sizeof
+| | |-(
+| | |-void
+| | |-*
+| | `-)
+| |-)
+| |-SimpleDeclarator
+| | `-size_t
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_s
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-const
+| |   | |-char
+| |   | `-SimpleDeclarator
+| |   |   `-*
+| |   |-,
+| |   |-SimpleDeclaration
+| |   | `-size_t
+| |   `-)
+| `-;
+`-SimpleDeclaration
+  |-void
+  |-SimpleDeclarato

[PATCH] D82157: Fix crash on `user defined literals`

2020-07-09 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas marked 4 inline comments as done.
eduucaldas added inline comments.



Comment at: clang/include/clang/Tooling/Syntax/Nodes.h:347-357
+/// Expression for an unkonwn user-defined literal. C++ [lex.ext]
+class UnknownUserDefinedLiteralExpression final
+: public UserDefinedLiteralExpression {
+public:
+  UnknownUserDefinedLiteralExpression()
+  : UserDefinedLiteralExpression(
+NodeKind::UnknownUserDefinedLiteralExpression) {}

This is gonna be removed once we are able to distinguish between integer and 
float on raw and template UDL



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:218-219
 auto InitializerEnd = Initializer.getEnd();
-assert(SM.isBeforeInTranslationUnit(End, InitializerEnd) || End == 
InitializerEnd);
+assert(SM.isBeforeInTranslationUnit(End, InitializerEnd) ||
+   End == InitializerEnd);
 End = InitializerEnd;

I know it adds noise, but this is the only place where the formatting doesn't 
obey the llvm clang format.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:732
+case clang::UserDefinedLiteral::LOK_Template:
+  return syntax::NodeKind::UnknownUserDefinedLiteralExpression;
+}

Here we need logic to determine which kind of UDL, if float or integer



Comment at: clang/unittests/Tooling/Syntax/TreeTest.cpp:1309-1310
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12ul
+| |-UnknownUserDefinedLiteralExpression
+| | `-12_r
 | `-;

For raw and template UDL, we don't know yet how to get the information about 
integer of float


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82157



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


[PATCH] D83419: [clangd] Add error() function for creating formatv-style llvm::Errors. NFC

2020-07-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Honestly, I really dislike names in the style of makeError/createError.
My favorite name for this would be Error (i.e. a constructor) but that would 
involve redesigning it (which is a good idea, but an impossible yak-shave).
I guess makeError is still better than the status quo, but not enough to feel 
motivated to clean this up right now. Maybe someone else wants to pick this up?

> I think the key point is that error creates an Error object, and this object 
> must be checked before destructing. error name makes it look like a print 
> function, I'd prefer to add a verb to the name, e.g. makeError

This is exactly backwards IMO - a function used for its value (like this one) 
doesn't need a verb, a function used for its side-effects (like log) does.
https://swift.org/documentation/api-design-guidelines/#strive-for-fluent-usage 
seems pretty well-thought-out to me.
LLVM guidelines don't reflect this, but I haven't been able to find anyone 
making a positive case for them beyond legacy and inertia.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83419



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


[PATCH] D83419: [clangd] Add error() function for creating formatv-style llvm::Errors. NFC

2020-07-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D83419#2140889 , @sammccall wrote:

> Honestly, I really dislike names in the style of makeError/createError.


Sorry, I should give some reasons here:

- not discoverable (`error` is marginally better)
- emphasis on allocation rather than how you're using the error (`error` is 
much better)
- forms part of a cluster of hard to remember names createX vs makeX vs make_x 
(`error` is much better)
- longer, both in characters and words (`error` is better)

It's just an aesthetic irritation but really this is just an aesthetic cleanup.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83419



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


[PATCH] D82938: [clangd] Implement path and URI translation for remote index

2020-07-09 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 276642.
kbobyrev added a comment.

Fix formatting on one line.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82938

Files:
  clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/index/remote/Client.h
  clang-tools-extra/clangd/index/remote/Index.proto
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h
  clang-tools-extra/clangd/index/remote/server/Server.cpp
  clang-tools-extra/clangd/index/remote/unimplemented/UnimplementedClient.cpp
  clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp

Index: clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
===
--- clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
+++ clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
@@ -7,85 +7,257 @@
 //===--===//
 
 #include "../TestTU.h"
+#include "TestFS.h"
+#include "index/Index.h"
+#include "index/Ref.h"
 #include "index/Serialization.h"
+#include "index/Symbol.h"
+#include "index/SymbolID.h"
 #include "index/remote/marshalling/Marshalling.h"
+#include "clang/Index/IndexSymbol.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/StringSaver.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace clangd {
 namespace remote {
 namespace {
 
+using llvm::sys::path::convert_to_slash;
+
+const char *testPathURI(llvm::StringRef Path,
+llvm::UniqueStringSaver &Strings) {
+  const auto URI = URI::createFile(testPath(Path));
+  return Strings.save(URI.toString()).begin();
+}
+
+TEST(RemoteMarshallingTest, URITranslation) {
+  llvm::BumpPtrAllocator Arena;
+  llvm::UniqueStringSaver Strings(Arena);
+  clangd::Ref Original;
+  Original.Location.FileURI =
+  testPathURI("remote/machine/projects/llvm-project/clang-tools-extra/"
+  "clangd/unittests/remote/MarshallingTests.cpp",
+  Strings);
+  auto Serialized =
+  toProtobuf(Original, testPath("remote/machine/projects/llvm-project/"));
+  EXPECT_EQ(Serialized.location().file_path(),
+"clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp");
+  const std::string LocalIndexPrefix = testPath("local/machine/project/");
+  auto Deserialized = fromProtobuf(Serialized, &Strings,
+   testPath("home/my-projects/llvm-project"));
+  EXPECT_TRUE(Deserialized);
+  EXPECT_EQ(Deserialized->Location.FileURI,
+testPathURI("home/my-projects/llvm-project/clang-tools-extra/"
+"clangd/unittests/remote/MarshallingTests.cpp",
+Strings));
+
+  clangd::Ref WithInvalidURI;
+  // Invalid URI results in empty path.
+  WithInvalidURI.Location.FileURI = "This is not a URI";
+  Serialized = toProtobuf(WithInvalidURI, testPath("home/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  // Can not use URIs with scheme different from "file".
+  auto UnittestURI =
+  URI::create(testPath("project/lib/HelloWorld.cpp"), "unittest");
+  EXPECT_TRUE(bool(UnittestURI));
+  WithInvalidURI.Location.FileURI =
+  Strings.save(UnittestURI->toString()).begin();
+  Serialized = toProtobuf(WithInvalidURI, testPath("project/lib/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  Ref WithAbsolutePath;
+  *WithAbsolutePath.mutable_location()->mutable_file_path() =
+  "/usr/local/user/home/HelloWorld.cpp";
+  Deserialized = fromProtobuf(WithAbsolutePath, &Strings, LocalIndexPrefix);
+  // Paths transmitted over the wire can not be absolute, they have to be
+  // relative.
+  EXPECT_FALSE(Deserialized);
+}
+
 TEST(RemoteMarshallingTest, SymbolSerialization) {
-  const auto *Header = R"(
-  // This is a class.
-  class Foo {
-  public:
-Foo();
-
-int Bar;
-  private:
-double Number;
-  };
-  /// This is a function.
-  char baz();
-  template 
-  T getT ();
-  )";
-  const auto TU = TestTU::withHeaderCode(Header);
-  const auto Symbols = TU.headerSymbols();
-  // Sanity check: there are more than 5 symbols available.
-  EXPECT_GE(Symbols.size(), 5UL);
+  clangd::Symbol Sym;
+
+  auto ID = SymbolID::fromStr("057557CEBF6E6B2D");
+  EXPECT_TRUE(bool(ID));
+  Sym.ID = *ID;
+
+  index::SymbolInfo Info;
+  Info.Kind = index::SymbolKind::Function;
+  Info.SubKind = index::SymbolSubKind::AccessorGetter;
+  Info.Lang = index::SymbolLanguage::CXX;
+  Info.Properties = static_cast(
+  index::SymbolProperty::TemplateSpecialization);
+  Sym.SymInfo = Info;
+
   llvm::BumpPtrAllocator Arena;
   llvm::UniqueStringSaver Strings(Arena);
-  for (auto &Sym : Symbols) {
-   

[PATCH] D82938: [clangd] Implement path and URI translation for remote index

2020-07-09 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 276646.
kbobyrev added a comment.

Rebase on top of master


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82938

Files:
  clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/index/remote/Client.h
  clang-tools-extra/clangd/index/remote/Index.proto
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h
  clang-tools-extra/clangd/index/remote/server/Server.cpp
  clang-tools-extra/clangd/index/remote/unimplemented/UnimplementedClient.cpp
  clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp

Index: clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
===
--- clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
+++ clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
@@ -7,85 +7,257 @@
 //===--===//
 
 #include "../TestTU.h"
+#include "TestFS.h"
+#include "index/Index.h"
+#include "index/Ref.h"
 #include "index/Serialization.h"
+#include "index/Symbol.h"
+#include "index/SymbolID.h"
 #include "index/remote/marshalling/Marshalling.h"
+#include "clang/Index/IndexSymbol.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/StringSaver.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace clangd {
 namespace remote {
 namespace {
 
+using llvm::sys::path::convert_to_slash;
+
+const char *testPathURI(llvm::StringRef Path,
+llvm::UniqueStringSaver &Strings) {
+  const auto URI = URI::createFile(testPath(Path));
+  return Strings.save(URI.toString()).begin();
+}
+
+TEST(RemoteMarshallingTest, URITranslation) {
+  llvm::BumpPtrAllocator Arena;
+  llvm::UniqueStringSaver Strings(Arena);
+  clangd::Ref Original;
+  Original.Location.FileURI =
+  testPathURI("remote/machine/projects/llvm-project/clang-tools-extra/"
+  "clangd/unittests/remote/MarshallingTests.cpp",
+  Strings);
+  auto Serialized =
+  toProtobuf(Original, testPath("remote/machine/projects/llvm-project/"));
+  EXPECT_EQ(Serialized.location().file_path(),
+"clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp");
+  const std::string LocalIndexPrefix = testPath("local/machine/project/");
+  auto Deserialized = fromProtobuf(Serialized, &Strings,
+   testPath("home/my-projects/llvm-project"));
+  EXPECT_TRUE(Deserialized);
+  EXPECT_EQ(Deserialized->Location.FileURI,
+testPathURI("home/my-projects/llvm-project/clang-tools-extra/"
+"clangd/unittests/remote/MarshallingTests.cpp",
+Strings));
+
+  clangd::Ref WithInvalidURI;
+  // Invalid URI results in empty path.
+  WithInvalidURI.Location.FileURI = "This is not a URI";
+  Serialized = toProtobuf(WithInvalidURI, testPath("home/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  // Can not use URIs with scheme different from "file".
+  auto UnittestURI =
+  URI::create(testPath("project/lib/HelloWorld.cpp"), "unittest");
+  EXPECT_TRUE(bool(UnittestURI));
+  WithInvalidURI.Location.FileURI =
+  Strings.save(UnittestURI->toString()).begin();
+  Serialized = toProtobuf(WithInvalidURI, testPath("project/lib/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  Ref WithAbsolutePath;
+  *WithAbsolutePath.mutable_location()->mutable_file_path() =
+  "/usr/local/user/home/HelloWorld.cpp";
+  Deserialized = fromProtobuf(WithAbsolutePath, &Strings, LocalIndexPrefix);
+  // Paths transmitted over the wire can not be absolute, they have to be
+  // relative.
+  EXPECT_FALSE(Deserialized);
+}
+
 TEST(RemoteMarshallingTest, SymbolSerialization) {
-  const auto *Header = R"(
-  // This is a class.
-  class Foo {
-  public:
-Foo();
-
-int Bar;
-  private:
-double Number;
-  };
-  /// This is a function.
-  char baz();
-  template 
-  T getT ();
-  )";
-  const auto TU = TestTU::withHeaderCode(Header);
-  const auto Symbols = TU.headerSymbols();
-  // Sanity check: there are more than 5 symbols available.
-  EXPECT_GE(Symbols.size(), 5UL);
+  clangd::Symbol Sym;
+
+  auto ID = SymbolID::fromStr("057557CEBF6E6B2D");
+  EXPECT_TRUE(bool(ID));
+  Sym.ID = *ID;
+
+  index::SymbolInfo Info;
+  Info.Kind = index::SymbolKind::Function;
+  Info.SubKind = index::SymbolSubKind::AccessorGetter;
+  Info.Lang = index::SymbolLanguage::CXX;
+  Info.Properties = static_cast(
+  index::SymbolProperty::TemplateSpecialization);
+  Sym.SymInfo = Info;
+
   llvm::BumpPtrAllocator Arena;
   llvm::UniqueStringSaver Strings(Arena);
-  for (auto &Sym : Symbols) {
-con

[PATCH] D82938: [clangd] Implement path and URI translation for remote index

2020-07-09 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 276647.
kbobyrev added a comment.

Replace Sym in Client response with a more generic name (it can be a reference).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82938

Files:
  clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/index/remote/Client.h
  clang-tools-extra/clangd/index/remote/Index.proto
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h
  clang-tools-extra/clangd/index/remote/server/Server.cpp
  clang-tools-extra/clangd/index/remote/unimplemented/UnimplementedClient.cpp
  clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp

Index: clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
===
--- clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
+++ clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
@@ -7,85 +7,257 @@
 //===--===//
 
 #include "../TestTU.h"
+#include "TestFS.h"
+#include "index/Index.h"
+#include "index/Ref.h"
 #include "index/Serialization.h"
+#include "index/Symbol.h"
+#include "index/SymbolID.h"
 #include "index/remote/marshalling/Marshalling.h"
+#include "clang/Index/IndexSymbol.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/StringSaver.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace clangd {
 namespace remote {
 namespace {
 
+using llvm::sys::path::convert_to_slash;
+
+const char *testPathURI(llvm::StringRef Path,
+llvm::UniqueStringSaver &Strings) {
+  const auto URI = URI::createFile(testPath(Path));
+  return Strings.save(URI.toString()).begin();
+}
+
+TEST(RemoteMarshallingTest, URITranslation) {
+  llvm::BumpPtrAllocator Arena;
+  llvm::UniqueStringSaver Strings(Arena);
+  clangd::Ref Original;
+  Original.Location.FileURI =
+  testPathURI("remote/machine/projects/llvm-project/clang-tools-extra/"
+  "clangd/unittests/remote/MarshallingTests.cpp",
+  Strings);
+  auto Serialized =
+  toProtobuf(Original, testPath("remote/machine/projects/llvm-project/"));
+  EXPECT_EQ(Serialized.location().file_path(),
+"clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp");
+  const std::string LocalIndexPrefix = testPath("local/machine/project/");
+  auto Deserialized = fromProtobuf(Serialized, &Strings,
+   testPath("home/my-projects/llvm-project"));
+  EXPECT_TRUE(Deserialized);
+  EXPECT_EQ(Deserialized->Location.FileURI,
+testPathURI("home/my-projects/llvm-project/clang-tools-extra/"
+"clangd/unittests/remote/MarshallingTests.cpp",
+Strings));
+
+  clangd::Ref WithInvalidURI;
+  // Invalid URI results in empty path.
+  WithInvalidURI.Location.FileURI = "This is not a URI";
+  Serialized = toProtobuf(WithInvalidURI, testPath("home/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  // Can not use URIs with scheme different from "file".
+  auto UnittestURI =
+  URI::create(testPath("project/lib/HelloWorld.cpp"), "unittest");
+  EXPECT_TRUE(bool(UnittestURI));
+  WithInvalidURI.Location.FileURI =
+  Strings.save(UnittestURI->toString()).begin();
+  Serialized = toProtobuf(WithInvalidURI, testPath("project/lib/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  Ref WithAbsolutePath;
+  *WithAbsolutePath.mutable_location()->mutable_file_path() =
+  "/usr/local/user/home/HelloWorld.cpp";
+  Deserialized = fromProtobuf(WithAbsolutePath, &Strings, LocalIndexPrefix);
+  // Paths transmitted over the wire can not be absolute, they have to be
+  // relative.
+  EXPECT_FALSE(Deserialized);
+}
+
 TEST(RemoteMarshallingTest, SymbolSerialization) {
-  const auto *Header = R"(
-  // This is a class.
-  class Foo {
-  public:
-Foo();
-
-int Bar;
-  private:
-double Number;
-  };
-  /// This is a function.
-  char baz();
-  template 
-  T getT ();
-  )";
-  const auto TU = TestTU::withHeaderCode(Header);
-  const auto Symbols = TU.headerSymbols();
-  // Sanity check: there are more than 5 symbols available.
-  EXPECT_GE(Symbols.size(), 5UL);
+  clangd::Symbol Sym;
+
+  auto ID = SymbolID::fromStr("057557CEBF6E6B2D");
+  EXPECT_TRUE(bool(ID));
+  Sym.ID = *ID;
+
+  index::SymbolInfo Info;
+  Info.Kind = index::SymbolKind::Function;
+  Info.SubKind = index::SymbolSubKind::AccessorGetter;
+  Info.Lang = index::SymbolLanguage::CXX;
+  Info.Properties = static_cast(
+  index::SymbolProperty::TemplateSpecialization);
+  Sym.SymInfo = Info;
+
   llvm::BumpPtrAllocator Arena;
   llvm::UniqueStringSave

[PATCH] D81583: Update SystemZ ABI to handle C++20 [[no_unique_address]] attribute

2020-07-09 Thread Ulrich Weigand via Phabricator via cfe-commits
uweigand updated this revision to Diff 276650.
uweigand added a comment.

Drop AllowNoUniqueAddress parameter; address review comment.


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

https://reviews.llvm.org/D81583

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/systemz-abi.cpp


Index: clang/test/CodeGen/systemz-abi.cpp
===
--- clang/test/CodeGen/systemz-abi.cpp
+++ clang/test/CodeGen/systemz-abi.cpp
@@ -23,3 +23,37 @@
 // CHECK-LABEL: define void 
@_Z18pass_agg_float_cpp13agg_float_cpp(%struct.agg_float_cpp* noalias sret 
align 4 %{{.*}}, float %{{.*}})
 // SOFT-FLOAT-LABEL:  define void 
@_Z18pass_agg_float_cpp13agg_float_cpp(%struct.agg_float_cpp* noalias sret 
align 4 %{{.*}}, i32 %{{.*}})
 
+
+// A field member of empty class type in C++ makes the record nonhomogeneous,
+// unless it is marked as [[no_unique_address]].  This does not apply to 
arrays.
+struct empty { };
+struct agg_nofloat_empty { float a; empty dummy; };
+struct agg_nofloat_empty pass_agg_nofloat_empty(struct agg_nofloat_empty arg) 
{ return arg; }
+// CHECK-LABEL: define void 
@_Z22pass_agg_nofloat_empty17agg_nofloat_empty(%struct.agg_nofloat_empty* 
noalias sret align 4 %{{.*}}, i64 %{{.*}})
+// SOFT-FLOAT-LABEL:  define void 
@_Z22pass_agg_nofloat_empty17agg_nofloat_empty(%struct.agg_nofloat_empty* 
noalias sret align 4 %{{.*}}, i64 %{{.*}})
+struct agg_float_empty { float a; [[no_unique_address]] empty dummy; };
+struct agg_float_empty pass_agg_float_empty(struct agg_float_empty arg) { 
return arg; }
+// CHECK-LABEL: define void 
@_Z20pass_agg_float_empty15agg_float_empty(%struct.agg_float_empty* noalias 
sret align 4 %{{.*}}, float %{{.*}})
+// SOFT-FLOAT-LABEL:  define void 
@_Z20pass_agg_float_empty15agg_float_empty(%struct.agg_float_empty* noalias 
sret align 4 %{{.*}}, i32 %{{.*}})
+struct agg_nofloat_emptyarray { float a; [[no_unique_address]] empty dummy[3]; 
};
+struct agg_nofloat_emptyarray pass_agg_nofloat_emptyarray(struct 
agg_nofloat_emptyarray arg) { return arg; }
+// CHECK-LABEL: define void 
@_Z27pass_agg_nofloat_emptyarray22agg_nofloat_emptyarray(%struct.agg_nofloat_emptyarray*
 noalias sret align 4 %{{.*}}, i64 %{{.*}})
+// SOFT-FLOAT-LABEL:  define void 
@_Z27pass_agg_nofloat_emptyarray22agg_nofloat_emptyarray(%struct.agg_nofloat_emptyarray*
 noalias sret align 4 %{{.*}}, i64 %{{.*}})
+
+// And likewise for members of base classes.
+struct noemptybase { empty dummy; };
+struct agg_nofloat_emptybase : noemptybase { float a; };
+struct agg_nofloat_emptybase pass_agg_nofloat_emptybase(struct 
agg_nofloat_emptybase arg) { return arg; }
+// CHECK-LABEL: define void 
@_Z26pass_agg_nofloat_emptybase21agg_nofloat_emptybase(%struct.agg_nofloat_emptybase*
 noalias sret align 4 %{{.*}}, i64 %{{.*}})
+// SOFT-FLOAT-LABEL:  define void 
@_Z26pass_agg_nofloat_emptybase21agg_nofloat_emptybase(%struct.agg_nofloat_emptybase*
 noalias sret align 4 %{{.*}}, i64 %{{.*}})
+struct emptybase { [[no_unique_address]] empty dummy; };
+struct agg_float_emptybase : emptybase { float a; };
+struct agg_float_emptybase pass_agg_float_emptybase(struct agg_float_emptybase 
arg) { return arg; }
+// CHECK-LABEL: define void 
@_Z24pass_agg_float_emptybase19agg_float_emptybase(%struct.agg_float_emptybase* 
noalias sret align 4 %{{.*}}, float %{{.*}})
+// SOFT-FLOAT-LABEL:  define void 
@_Z24pass_agg_float_emptybase19agg_float_emptybase(%struct.agg_float_emptybase* 
noalias sret align 4 %{{.*}}, i32 %{{.*}})
+struct noemptybasearray { [[no_unique_address]] empty dummy[3]; };
+struct agg_nofloat_emptybasearray : noemptybasearray { float a; };
+struct agg_nofloat_emptybasearray pass_agg_nofloat_emptybasearray(struct 
agg_nofloat_emptybasearray arg) { return arg; }
+// CHECK-LABEL: define void 
@_Z31pass_agg_nofloat_emptybasearray26agg_nofloat_emptybasearray(%struct.agg_nofloat_emptybasearray*
 noalias sret align 4 %{{.*}}, i64 %{{.*}})
+// SOFT-FLOAT-LABEL:  define void 
@_Z31pass_agg_nofloat_emptybasearray26agg_nofloat_emptybasearray(%struct.agg_nofloat_emptybasearray*
 noalias sret align 4 %{{.*}}, i64 %{{.*}})
+
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -499,11 +499,15 @@
 
   // Constant arrays of empty records count as empty, strip them off.
   // Constant arrays of zero length always count as empty.
+  bool WasArray = false;
   if (AllowArrays)
 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
   if (AT->getSize() == 0)
 return true;
   FT = AT->getElementType();
+  // The [[no_unique_address]] special case below does not apply to
+  // arrays of C++ empty records, so we need to remember this fact.
+  WasArray = true;
 }
 
   const RecordType *RT = FT->getAs();
@@ -514,7 +518,14 @@
   //
   // FIXME: We should use a predicate for whether this b

[PATCH] D75229: [clang-tidy] Add signal-in-multithreaded-program check

2020-07-09 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

In general, the test files should be cleaned up.




Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-in-multithreaded-program-config-std::thread.cpp:1
+// RUN: %check_clang_tidy %s bugprone-signal-in-multithreaded-program %t \
+// RUN: -config='{CheckOptions: \

Please rename this file to something that doesn't conatain `:` in the name. 
Windows peoples' computers will explode if it's merged like this...



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-in-multithreaded-program-config-std::thread.cpp:5-6
+
+typedef unsigned long int thrd_t;
+typedef int (*thrd_start_t)(void *);
+typedef int sig_atomic_t;

Are these definitions needed for C++ test?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-in-multithreaded-program-config-std::thread.cpp:32
+
+int main(void) {
+  signal(SIGUSR1, handler);

As far as I know, `int main(void)` is **not** valid C++ code. Only `int main()` 
and `int main(int, char**)` are valid, see `[basic.start.main]`/2.

If we are writing C++ test code, let's make it appear as if it was C++ code.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-in-multithreaded-program-noconfig-std::thread.cpp:1
+// RUN: %check_clang_tidy %s bugprone-signal-in-multithreaded-program %t
+

Same rename here.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-signal-in-multithreaded-program-noconfig-thrd_create.cpp:1
+// RUN: %check_clang_tidy %s bugprone-signal-in-multithreaded-program %t
+

thrd_create is a C standard function, and this file looks like a C file to me, 
so why is the extension `.cpp`?


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D75229



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


[PATCH] D83407: [analyzer][StdLibraryFunctionsChecker] Add POSIX networking functions

2020-07-09 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

Are not some functions missing from the list (`shutdown`, `sockatmark`, 
`socket`) (these come from )? And `getnameinfo` comes from 
 with many other functions that are not added.




Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1722
+  ACtx.getPointerType(StructSockaddrTy->withConst());
+  StructSockaddrPtrRestrictTy =
+  ACtx.getLangOpts().C99 ? ACtx.getRestrictType(*StructSockaddrPtrTy)

There could be a generic form of getting the restrict type for a type so 
something like this can be done (this is used relatively often):
`getRestrictTypeIfApplicable(ACtx, StructSockaddrPtrTy)`



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83407



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


[PATCH] D83436: [clangd] Fix error handling in config.yaml parsing.

2020-07-09 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf36518637d7d: [clangd] Fix error handling in config.yaml 
parsing. (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D83436?vs=276574&id=276660#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83436

Files:
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp

Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -98,10 +98,25 @@
 DiagKind(llvm::SourceMgr::DK_Error),
 DiagPos(YAML.point()), DiagRange(llvm::None;
 
-  ASSERT_EQ(Results.size(), 2u);
+  ASSERT_EQ(Results.size(), 1u); // invalid fragment discarded.
   EXPECT_THAT(Results.front().CompileFlags.Add, ElementsAre(Val("first")));
   EXPECT_TRUE(Results.front().If.HasUnrecognizedCondition);
-  EXPECT_THAT(Results.back().CompileFlags.Add, IsEmpty());
+}
+
+TEST(ParseYAML, Invalid) {
+  CapturedDiags Diags;
+  const char *YAML = R"yaml(
+If:
+
+horrible
+---
+- 1
+  )yaml";
+  auto Results = Fragment::parseYAML(YAML, "config.yaml", Diags.callback());
+  EXPECT_THAT(Diags.Diagnostics,
+  ElementsAre(DiagMessage("If should be a dictionary"),
+  DiagMessage("Config should be a dictionary")));
+  ASSERT_THAT(Results, IsEmpty());
 }
 
 } // namespace
Index: clang-tools-extra/clangd/ConfigYAML.cpp
===
--- clang-tools-extra/clangd/ConfigYAML.cpp
+++ clang-tools-extra/clangd/ConfigYAML.cpp
@@ -26,49 +26,47 @@
 
 class Parser {
   llvm::SourceMgr &SM;
+  bool HadError = false;
 
 public:
   Parser(llvm::SourceMgr &SM) : SM(SM) {}
 
   // Tries to parse N into F, returning false if it failed and we couldn't
-  // meaningfully recover (e.g. YAML syntax error broke the stream).
-  // The private parse() helpers follow the same pattern.
+  // meaningfully recover (YAML syntax error, or hard semantic error).
   bool parse(Fragment &F, Node &N) {
 DictParser Dict("Config", this);
-Dict.handle("If", [&](Node &N) { return parse(F.If, N); });
-Dict.handle("CompileFlags",
-[&](Node &N) { return parse(F.CompileFlags, N); });
-return Dict.parse(N);
+Dict.handle("If", [&](Node &N) { parse(F.If, N); });
+Dict.handle("CompileFlags", [&](Node &N) { parse(F.CompileFlags, N); });
+Dict.parse(N);
+return !(N.failed() || HadError);
   }
 
 private:
-  bool parse(Fragment::IfBlock &F, Node &N) {
+  void parse(Fragment::IfBlock &F, Node &N) {
 DictParser Dict("If", this);
 Dict.unrecognized(
 [&](llvm::StringRef) { F.HasUnrecognizedCondition = true; });
 Dict.handle("PathMatch", [&](Node &N) {
   if (auto Values = scalarValues(N))
 F.PathMatch = std::move(*Values);
-  return !N.failed();
 });
-return Dict.parse(N);
+Dict.parse(N);
   }
 
-  bool parse(Fragment::CompileFlagsBlock &F, Node &N) {
+  void parse(Fragment::CompileFlagsBlock &F, Node &N) {
 DictParser Dict("CompileFlags", this);
 Dict.handle("Add", [&](Node &N) {
   if (auto Values = scalarValues(N))
 F.Add = std::move(*Values);
-  return !N.failed();
 });
-return Dict.parse(N);
+Dict.parse(N);
   }
 
   // Helper for parsing mapping nodes (dictionaries).
   // We don't use YamlIO as we want to control over unknown keys.
   class DictParser {
 llvm::StringRef Description;
-std::vector>> Keys;
+std::vector>> Keys;
 std::function Unknown;
 Parser *Outer;
 
@@ -79,7 +77,7 @@
 // Parse is called when Key is encountered, and passed the associated value.
 // It should emit diagnostics if the value is invalid (e.g. wrong type).
 // If Key is seen twice, Parse runs only once and an error is reported.
-void handle(llvm::StringLiteral Key, std::function Parse) {
+void handle(llvm::StringLiteral Key, std::function Parse) {
   for (const auto &Entry : Keys) {
 (void) Entry;
 assert(Entry.first != Key && "duplicate key handler");
@@ -94,16 +92,17 @@
 }
 
 // Process a mapping node and call handlers for each key/value pair.
-bool parse(Node &N) const {
+void parse(Node &N) const {
   if (N.getType() != Node::NK_Mapping) {
 Outer->error(Description + " should be a dictionary", N);
-return false;
+return;
   }
   llvm::SmallSet Seen;
+  // We *must* consume all items, even on error, or the parser will assert.
   for (auto &KV : llvm::cast(N)) {
 auto *K = KV.getKey();
 if (!K) // YAMLParser emitted an error.
-  return false;
+  continue;
 auto Key = Outer->scal

[clang-tools-extra] f365186 - [clangd] Fix error handling in config.yaml parsing.

2020-07-09 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2020-07-09T10:20:18+02:00
New Revision: f36518637d7dfe5f8e619db1bd65dc90c92b5afa

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

LOG: [clangd] Fix error handling in config.yaml parsing.

Summary:
A few things were broken:
 - use of Document::parseBlockNode() is incorrect and prevents moving to the
   next doc in error cases. Use getRoot() instead.
 - bailing out in the middle of iterating over a list/dict isn't allowed,
   unless you are going to throw away the parser: the next skip() asserts.
   Always consume all items.
 - There were two concepts of fatal errors: error-diagnostics and drop-fragment.
   (The latter is the "return false" case in the parser). They didn't coincide.
   Now, parser errors and explicitly emitted error diagnostics are fatal.

Fixes https://github.com/clangd/clangd/issues/452

Reviewers: hokein

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/ConfigYAML.cpp
clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index 1201c9a5d523..0674c6030903 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -26,49 +26,47 @@ using llvm::yaml::SequenceNode;
 
 class Parser {
   llvm::SourceMgr &SM;
+  bool HadError = false;
 
 public:
   Parser(llvm::SourceMgr &SM) : SM(SM) {}
 
   // Tries to parse N into F, returning false if it failed and we couldn't
-  // meaningfully recover (e.g. YAML syntax error broke the stream).
-  // The private parse() helpers follow the same pattern.
+  // meaningfully recover (YAML syntax error, or hard semantic error).
   bool parse(Fragment &F, Node &N) {
 DictParser Dict("Config", this);
-Dict.handle("If", [&](Node &N) { return parse(F.If, N); });
-Dict.handle("CompileFlags",
-[&](Node &N) { return parse(F.CompileFlags, N); });
-return Dict.parse(N);
+Dict.handle("If", [&](Node &N) { parse(F.If, N); });
+Dict.handle("CompileFlags", [&](Node &N) { parse(F.CompileFlags, N); });
+Dict.parse(N);
+return !(N.failed() || HadError);
   }
 
 private:
-  bool parse(Fragment::IfBlock &F, Node &N) {
+  void parse(Fragment::IfBlock &F, Node &N) {
 DictParser Dict("If", this);
 Dict.unrecognized(
 [&](llvm::StringRef) { F.HasUnrecognizedCondition = true; });
 Dict.handle("PathMatch", [&](Node &N) {
   if (auto Values = scalarValues(N))
 F.PathMatch = std::move(*Values);
-  return !N.failed();
 });
-return Dict.parse(N);
+Dict.parse(N);
   }
 
-  bool parse(Fragment::CompileFlagsBlock &F, Node &N) {
+  void parse(Fragment::CompileFlagsBlock &F, Node &N) {
 DictParser Dict("CompileFlags", this);
 Dict.handle("Add", [&](Node &N) {
   if (auto Values = scalarValues(N))
 F.Add = std::move(*Values);
-  return !N.failed();
 });
-return Dict.parse(N);
+Dict.parse(N);
   }
 
   // Helper for parsing mapping nodes (dictionaries).
   // We don't use YamlIO as we want to control over unknown keys.
   class DictParser {
 llvm::StringRef Description;
-std::vector>> Keys;
+std::vector>> Keys;
 std::function Unknown;
 Parser *Outer;
 
@@ -79,7 +77,7 @@ class Parser {
 // Parse is called when Key is encountered, and passed the associated 
value.
 // It should emit diagnostics if the value is invalid (e.g. wrong type).
 // If Key is seen twice, Parse runs only once and an error is reported.
-void handle(llvm::StringLiteral Key, std::function Parse) {
+void handle(llvm::StringLiteral Key, std::function Parse) {
   for (const auto &Entry : Keys) {
 (void) Entry;
 assert(Entry.first != Key && "duplicate key handler");
@@ -94,16 +92,17 @@ class Parser {
 }
 
 // Process a mapping node and call handlers for each key/value pair.
-bool parse(Node &N) const {
+void parse(Node &N) const {
   if (N.getType() != Node::NK_Mapping) {
 Outer->error(Description + " should be a dictionary", N);
-return false;
+return;
   }
   llvm::SmallSet Seen;
+  // We *must* consume all items, even on error, or the parser will assert.
   for (auto &KV : llvm::cast(N)) {
 auto *K = KV.getKey();
 if (!K) // YAMLParser emitted an error.
-  return false;
+  continue;
 auto Key = Outer->scalarValue(*K, "Dictionary key");
 if (!Key)
   continue;
@@ -113,13 +112,12 @@ class Parser {
 }
 auto *Value = KV.getValue();
 if (!Value)

[PATCH] D77493: [clang-tidy] Add do-not-refer-atomic-twice check

2020-07-09 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/DoNotReferAtomicTwiceCheck.cpp:38
+  diag(MatchedRef->getExprLoc(),
+   "Do not refer to '%0' atomic variable twice in an expression")
+  << MatchedVar->getName();

atomic variable '%0'



Comment at: clang-tools-extra/docs/ReleaseNotes.rst:82
+
+  Finds atomic variable which is referred twice in an expression.
+

atomic variable**s** which **are**


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D77493



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


[PATCH] D82938: [clangd] Implement path and URI translation for remote index

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

Rest is just nits, thanks!




Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:38
+/// provided by the client.
+llvm::Optional relativePathToURI(llvm::StringRef RelativePath,
+  llvm::StringRef IndexRoot) {

these functions are nice. It might be clearer to expose them and test them 
directly, particularly for error cases. Up to you.



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:39
+llvm::Optional relativePathToURI(llvm::StringRef RelativePath,
+  llvm::StringRef IndexRoot) {
+  assert(RelativePath == llvm::sys::path::convert_to_slash(

can we add an assert that the index root is valid? (ends with a 
platform-appropriate slash)



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:45
+  if (llvm::sys::path::is_absolute(RelativePath)) {
+elog("{0} is not relative path", RelativePath);
+return llvm::None;

message needs a bit more context. `Remote index client got absolute path from 
server: {0}`?



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:50
+  llvm::sys::path::append(FullPath, RelativePath);
+  const auto Result = URI::createFile(FullPath);
+  return Result.toString();

nit: lots of `const auto` throughout - we tend not to use `const` for local 
values (as opposed to references or pointers) so this is a bit confusing, 
particularly when combined with auto. Up to you though.



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:57
+llvm::Optional uriToRelativePath(llvm::StringRef URI,
+  llvm::StringRef IndexRoot) {
+  auto ParsedURI = URI::parse(URI);

can we add an assert that IndexRoot is valid?



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:60
+  if (!ParsedURI) {
+elog("Can not parse URI {0}: {1}", URI, ParsedURI.takeError());
+return llvm::None;

Similarly: `Remote index got bad URI from client: ...`



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:64
+  if (ParsedURI->scheme() != "file") {
+elog("Can not parse URI with scheme other than \"file\" {0}", URI);
+return llvm::None;

I think it's fine to fold this into the previous check: "bad URI" covers it



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:68
+  llvm::SmallString<256> Result = ParsedURI->body();
+  if (IndexRoot.empty())
+return std::string(Result);

This isn't a valid IndexRoot, we should assert rather than handle this case I 
think.



Comment at: 
clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:131
+  if (!RelativePath)
+return Result;
+  *Result.mutable_file_path() = *RelativePath;

shouldn't this return llvm::None, too? a SymbolLocation isn't valid without a 
path.



Comment at: 
clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:145
+  // If header starts with < or " it is not a URI: do not attempt to parse it.
+  if (Header.front() == '<' || Header.front() == '"') {
+Result.set_header(Header);

nit: isLiteralInclude in Headers.h (sorry, had forgotten about this func).
Calling that function probably avoids the need for the comment too.



Comment at: 
clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:149
+  }
+  auto URI = URI::parse(Header);
+  if (!URI) {

isn't the rest of this uriToRelativePath?



Comment at: 
clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:210
   if (!ID) {
-elog("Cannot convert parse SymbolID {} from Protobuf: {}", ID.takeError(),
+elog("Cannot parse SymbolID {} given Protobuf: {}", ID.takeError(),
  Message.ShortDebugString());

{} with no index is a nice idea but I think not actually supported



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h:19
+// path and passes paths relative to the project root over the wire
+// ("include/HelloWorld.h" in this example). The indexed project root is passed
+// passed to the remote server. It contains absolute path to the project root

nit "is passed passed to the remote server".



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h:20
+// ("include/HelloWorld.h" in this example). The indexed project root is passed
+// passed to the remote server. It contains absolute path to the project roo

[PATCH] D79773: [clang-format] Improve clang-formats handling of concepts

2020-07-09 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a subscriber: klimek.
MyDeveloperDay added a comment.

This issue is caused by the presence of the `;` in the requires clause (`0)>;`) 
inside the template declaration

  template 
  requires std::invocable...>
  struct [[nodiscard]] constant : std::bool_constant < requires
  {
  typename _require_constant_<(std::invoke(F{}, Args{}()...), 0)>;
  } > {};

These below may not be legal C++ examples but show the same behaviour

  struct constant : Foo < typename {
  Foo;
  } > {};
  
  struct constant : Foo { };

This is actually failing in the handling of parsing the `<>`  in 
(`parseAngle()` actually `parseBrace()` inside of that), it is not really 
concepts specific except it may be seen now because of the presence of the `;`

The problem comes about I think because the line is broken by the ";" during 
the `parseBrace` at some point the `Next` token is null, I assume that's 
because the lines are broken by the ';' as such ultimately the < and > rather 
than being seen as TT_TemplateOpener and TT_TemplateCloser are seen as 
TT_BinaryOperators (by default when parseAngle fails)

I'm not sure how I could solve this, I might need help from a higher power 
@klimek


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

https://reviews.llvm.org/D79773



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


[PATCH] D83290: [clangd] Enable async preambles by default

2020-07-09 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1c7c5019a7ad: [clangd] Enable async preambles by default 
(authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83290

Files:
  clang-tools-extra/clangd/ClangdServer.h
  clang-tools-extra/clangd/TUScheduler.h


Index: clang-tools-extra/clangd/TUScheduler.h
===
--- clang-tools-extra/clangd/TUScheduler.h
+++ clang-tools-extra/clangd/TUScheduler.h
@@ -194,7 +194,7 @@
 
 /// Whether to run PreamblePeer asynchronously.
 /// No-op if AsyncThreadsCount is 0.
-bool AsyncPreambleBuilds = false;
+bool AsyncPreambleBuilds = true;
 
 /// Used to create a context that wraps each single operation.
 /// Typically to inject per-file configuration.
Index: clang-tools-extra/clangd/ClangdServer.h
===
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -100,7 +100,7 @@
 bool StorePreamblesInMemory = true;
 /// Reuse even stale preambles, and rebuild them in the background.
 /// This improves latency at the cost of accuracy.
-bool AsyncPreambleBuilds = false;
+bool AsyncPreambleBuilds = true;
 
 /// If true, ClangdServer builds a dynamic in-memory index for symbols in
 /// opened files and uses the index to augment code completion results.


Index: clang-tools-extra/clangd/TUScheduler.h
===
--- clang-tools-extra/clangd/TUScheduler.h
+++ clang-tools-extra/clangd/TUScheduler.h
@@ -194,7 +194,7 @@
 
 /// Whether to run PreamblePeer asynchronously.
 /// No-op if AsyncThreadsCount is 0.
-bool AsyncPreambleBuilds = false;
+bool AsyncPreambleBuilds = true;
 
 /// Used to create a context that wraps each single operation.
 /// Typically to inject per-file configuration.
Index: clang-tools-extra/clangd/ClangdServer.h
===
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -100,7 +100,7 @@
 bool StorePreamblesInMemory = true;
 /// Reuse even stale preambles, and rebuild them in the background.
 /// This improves latency at the cost of accuracy.
-bool AsyncPreambleBuilds = false;
+bool AsyncPreambleBuilds = true;
 
 /// If true, ClangdServer builds a dynamic in-memory index for symbols in
 /// opened files and uses the index to augment code completion results.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 1c7c501 - [clangd] Enable async preambles by default

2020-07-09 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2020-07-09T10:57:45+02:00
New Revision: 1c7c5019a7adfb16e0449ffb1d0e10631998d854

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

LOG: [clangd] Enable async preambles by default

Summary:
We've been testing this internally for a couple weeks now and it seems
to be stable enough. Let's flip the flag before branch cut to increase testing
coverage and have enough time to revert if need be.

Subscribers: ilya-biryukov, javed.absar, MaskRay, jkorous, arphaman, usaxena95, 
cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/ClangdServer.h
clang-tools-extra/clangd/TUScheduler.h

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdServer.h 
b/clang-tools-extra/clangd/ClangdServer.h
index faeec2e88848..ea82081f2440 100644
--- a/clang-tools-extra/clangd/ClangdServer.h
+++ b/clang-tools-extra/clangd/ClangdServer.h
@@ -100,7 +100,7 @@ class ClangdServer {
 bool StorePreamblesInMemory = true;
 /// Reuse even stale preambles, and rebuild them in the background.
 /// This improves latency at the cost of accuracy.
-bool AsyncPreambleBuilds = false;
+bool AsyncPreambleBuilds = true;
 
 /// If true, ClangdServer builds a dynamic in-memory index for symbols in
 /// opened files and uses the index to augment code completion results.

diff  --git a/clang-tools-extra/clangd/TUScheduler.h 
b/clang-tools-extra/clangd/TUScheduler.h
index f33470f4e894..05c06da13380 100644
--- a/clang-tools-extra/clangd/TUScheduler.h
+++ b/clang-tools-extra/clangd/TUScheduler.h
@@ -194,7 +194,7 @@ class TUScheduler {
 
 /// Whether to run PreamblePeer asynchronously.
 /// No-op if AsyncThreadsCount is 0.
-bool AsyncPreambleBuilds = false;
+bool AsyncPreambleBuilds = true;
 
 /// Used to create a context that wraps each single operation.
 /// Typically to inject per-file configuration.



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


[PATCH] D79437: [clang-tidy] Add fsetpos argument checker

2020-07-09 Thread Whisperity via Phabricator via cfe-commits
whisperity added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-fsetpos-argument-check.cpp:1
+// RUN: %check_clang_tidy %s bugprone-fsetpos-argument-check %t
+

This is a C, not a C++ file, the extension should show it. In addition, a 
similar test should be added that uses `std::fgetpos()` and `std::fsetpos()`, 
and shows the matching still works.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D79437



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


[PATCH] D83055: [clang][Driver] Fix tool path priority test failures

2020-07-09 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett updated this revision to Diff 276671.
DavidSpickett added a comment.

- Updated rm/mv command lines to account for $DEFAULT_TRIPLE being the same as 
%target_triple.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83055

Files:
  clang/test/Driver/program-path-priority.c
  clang/test/lit.cfg.py

Index: clang/test/lit.cfg.py
===
--- clang/test/lit.cfg.py
+++ clang/test/lit.cfg.py
@@ -46,6 +46,8 @@
 config.substitutions.append(
 ('%src_include_dir', config.clang_src_dir + '/include'))
 
+config.substitutions.append(
+('%target_triple', config.target_triple))
 
 # Propagate path to symbolizer for ASan/MSan.
 llvm_config.with_system_environment(
Index: clang/test/Driver/program-path-priority.c
===
--- clang/test/Driver/program-path-priority.c
+++ clang/test/Driver/program-path-priority.c
@@ -13,6 +13,11 @@
 /// so only name priority is accounted for, unless we fail to find
 /// anything at all in the prefix.
 
+/// Note: All matches are expected to be at the end of file paths.
+/// So we match " on the end to account for build systems that
+/// put the name of the compiler in the build path.
+/// E.g. /build/gcc_X.Y.Z/0/...
+
 /// Symlink clang to a new dir which will be its
 /// "program path" for these tests
 // RUN: rm -rf %t && mkdir -p %t
@@ -21,14 +26,18 @@
 /// No gccs at all, nothing is found
 // RUN: env "PATH=" %t/clang -### -target notreal-none-elf %s 2>&1 | \
 // RUN:   FileCheck --check-prefix=NO_NOTREAL_GCC %s
-// NO_NOTREAL_GCC-NOT: notreal-none-elf-gcc
-// NO_NOTREAL_GCC-NOT: /gcc
+// NO_NOTREAL_GCC-NOT: notreal-none-elf-gcc"
+/// Some systems will have "gcc-x.y.z" so for this first check
+/// make sure we don't find "gcc" or "gcc-x.y.z". If we do find either
+/// then there is no point continuing as this copy of clang is not
+/// isolated as we expected.
+// NO_NOTREAL_GCC-NOT: {{/gcc[^/]*"}}
 
 /// -gcc in program path is found
 // RUN: touch %t/notreal-none-elf-gcc && chmod +x %t/notreal-none-elf-gcc
 // RUN: env "PATH=" %t/clang -### -target notreal-none-elf %s 2>&1 | \
 // RUN:   FileCheck --check-prefix=PROG_PATH_NOTREAL_GCC %s
-// PROG_PATH_NOTREAL_GCC: notreal-none-elf-gcc
+// PROG_PATH_NOTREAL_GCC: notreal-none-elf-gcc"
 
 /// -gcc on the PATH is found
 // RUN: mkdir -p %t/env
@@ -36,74 +45,89 @@
 // RUN: touch %t/env/notreal-none-elf-gcc && chmod +x %t/env/notreal-none-elf-gcc
 // RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 | \
 // RUN:   FileCheck --check-prefix=ENV_PATH_NOTREAL_GCC %s
-// ENV_PATH_NOTREAL_GCC: env/notreal-none-elf-gcc
+// ENV_PATH_NOTREAL_GCC: env/notreal-none-elf-gcc"
 
 /// -gcc in program path is preferred to one on the PATH
 // RUN: touch %t/notreal-none-elf-gcc && chmod +x %t/notreal-none-elf-gcc
 // RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 | \
 // RUN:   FileCheck --check-prefix=BOTH_NOTREAL_GCC %s
-// BOTH_NOTREAL_GCC: notreal-none-elf-gcc
-// BOTH_NOTREAL_GCC-NOT: env/notreal-none-elf-gcc
+// BOTH_NOTREAL_GCC: notreal-none-elf-gcc"
+// BOTH_NOTREAL_GCC-NOT: env/notreal-none-elf-gcc"
 
 /// On program path, -gcc is preferred to plain gcc
 // RUN: touch %t/gcc && chmod +x %t/gcc
 // RUN: env "PATH=" %t/clang -### -target notreal-none-elf %s 2>&1 | \
 // RUN:   FileCheck --check-prefix=NOTREAL_GCC_PREFERRED %s
-// NOTREAL_GCC_PREFERRED: notreal-none-elf-gcc
-// NOTREAL_GCC_PREFERRED-NOT: /gcc
+// NOTREAL_GCC_PREFERRED: notreal-none-elf-gcc"
+// NOTREAL_GCC_PREFERRED-NOT: /gcc"
 
 /// -gcc on the PATH is preferred to gcc in program path
 // RUN: rm %t/notreal-none-elf-gcc
 // RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 | \
 // RUN:   FileCheck --check-prefix=NOTREAL_PATH_OVER_GCC_PROG %s
-// NOTREAL_PATH_OVER_GCC_PROG: env/notreal-none-elf-gcc
-// NOTREAL_PATH_OVER_GCC_PROG-NOT: /gcc
+// NOTREAL_PATH_OVER_GCC_PROG: env/notreal-none-elf-gcc"
+// NOTREAL_PATH_OVER_GCC_PROG-NOT: /gcc"
 
 /// -gcc on the PATH is preferred to gcc on the PATH
 // RUN: rm %t/gcc
 // RUN: touch %t/env/gcc && chmod +x %t/env/gcc
 // RUN: env "PATH=%t/env/" %t/clang -### -target notreal-none-elf %s 2>&1 | \
 // RUN:   FileCheck --check-prefix=NOTREAL_PATH_OVER_GCC_PATH %s
-// NOTREAL_PATH_OVER_GCC_PATH: env/notreal-none-elf-gcc
-// NOTREAL_PATH_OVER_GCC_PATH-NOT: /gcc
+// NOTREAL_PATH_OVER_GCC_PATH: env/notreal-none-elf-gcc"
+// NOTREAL_PATH_OVER_GCC_PATH-NOT: /gcc"
+
+/// We cannot trust clang --version, or cmake's LLVM_DEFAULT_TARGET_TRIPLE
+/// to give us the one and only default triple.
+/// Can't trust cmake because on Darwin, triples have a verison appended to them.
+/// (and clang uses the versioned string to search)
+/// Can't trust --version because it will pad 3 item triples to 4 e.g.
+/// powerpc64le-linux-gnu -> powerpc64le-unknown-linux-gnu
+/// (and clang uses t

[PATCH] D82756: Port some floating point options to new option marshalling infrastructure

2020-07-09 Thread Daniel Grumberg via Phabricator via cfe-commits
dang added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1176
+defm reciprocal_math : OptInFFlag< "reciprocal-math", "Allow division 
operations to be reassociated", "", "", [], "LangOpts->AllowRecip">;
+def fapprox_func : Flag<["-"], "fapprox-func">, Group, 
Flags<[CC1Option, NoDriverOption]>,
+  MarshallingInfoFlag<"LangOpts->ApproxFunc", "false">;

Anastasia wrote:
> could this also be OptInFFlag?
The aim was to keep the driver semantics the same as before and this was not 
something you could control with the driver, so I left it as just a CC1 flag. 
However if it makes sense to be able to control this from the driver then we 
can definitely make this `OptInFFLag`.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:2805
 CmdArgs.push_back("-menable-unsafe-fp-math");
+ApproxFunc = true;
+  }

Anastasia wrote:
> Is this a bug fix ?
No, in current trunk approximating floating point functions was something that 
was implied by other optimization flags, i.e. disabling math errno, enabling 
associative/reciprocal math, disabling signed zeros and disabling trapping math 
and -ffast-math which does all the previously mentioned things. This patch 
moves this logic in the driver by introducing a new CC1 flag for this so that 
parsing CC1 options can be more easily automated. This just reflects the logic 
that was previously inside cc1.



Comment at: clang/test/CodeGen/fp-function-attrs.cpp:2
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -ffast-math -ffinite-math-only 
-menable-unsafe-fp-math \
+// RUN:   -menable-no-infs -menable-no-nans -fno-signed-zeros 
-freciprocal-math \
+// RUN:   -fapprox-func -mreassociate -ffp-contract=fast -emit-llvm -o - %s | 
FileCheck %s

Anastasia wrote:
> Not clear why do you need to pass these extra flags now?
Previously passing -ffast-math to CC1 implied all these other flags. I am 
trying to make CC1 option parsing as simple as possible, so that we can then 
make it easy to generate a command line from a CompilerInvocation instance. You 
can refer to [[ http://lists.llvm.org/pipermail/cfe-dev/2020-May/065421.html | 
http://lists.llvm.org/pipermail/cfe-dev/2020-May/065421.html ]] for more 
details on why we want to be able to do this


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82756



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


[PATCH] D83374: [analyzer][tests] Fix zip unpacking

2020-07-09 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D83374#2139505 , @NoQ wrote:

> I thought the OS always ignores those? Ok anyway fair enough!


I thought so too, but it looks like `glob` works in mysterious ways


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83374



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


[PATCH] D82157: Fix crash on `user defined literals`

2020-07-09 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 276678.
eduucaldas added a comment.

Polishing patch


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82157

Files:
  clang/include/clang/Tooling/Syntax/Nodes.h
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/Nodes.cpp
  clang/unittests/Tooling/Syntax/TreeTest.cpp

Index: clang/unittests/Tooling/Syntax/TreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/TreeTest.cpp
+++ clang/unittests/Tooling/Syntax/TreeTest.cpp
@@ -1184,20 +1184,106 @@
 )txt"));
 }
 
-TEST_P(SyntaxTreeTest, IntegerLiteral) {
+TEST_P(SyntaxTreeTest, UserDefinedLiteral) {
+  if (!GetParam().isCXX11OrLater()) {
+return;
+  }
   EXPECT_TRUE(treeDumpEqual(
   R"cpp(
+unsigned operator "" _i(unsigned long long);
+unsigned operator "" _f(long double);
+unsigned operator "" _c(char);
+
+unsigned operator "" _r(const char*); // raw-literal operator
+
+template 
+unsigned operator "" _t();// numeric literal operator template
+
 void test() {
-  12;
-  12u;
-  12l;
-  12ul;
-  014;
-  0XC;
+  12_i;  // call: operator "" _i(12uLL)  | kind: integer
+  1.2_f; // call: operator "" _f(1.2L)   | kind: float
+  '2'_c; // call: operator "" _c('2')| kind: char
+
+  // PROBLEM: How to discover the kind of user-defined-literal from the AST?
+  12_r;  // call: operator "" _r("12")   | kind: integer
+  1.2_r; // call: operator "" _i("1.2")  | kind: float
+  12_t;  // call: operator<'1', '2'> "" _x() | kind: integer
+  1.2_t; // call: operator<'1', '2'> "" _x() | kind: float
 }
-)cpp",
+)cpp",
   R"txt(
 *: TranslationUnit
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_i
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-unsigned
+| |   | |-long
+| |   | `-long
+| |   `-)
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_f
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-long
+| |   | `-double
+| |   `-)
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_c
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | `-char
+| |   `-)
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_r
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-const
+| |   | |-char
+| |   | `-SimpleDeclarator
+| |   |   `-*
+| |   `-)
+| `-;
+|-TemplateDeclaration
+| |-template
+| |-<
+| |-SimpleDeclaration
+| | `-char
+| |-...
+| |->
+| `-SimpleDeclaration
+|   |-unsigned
+|   |-SimpleDeclarator
+|   | |-operator
+|   | |-""
+|   | |-_t
+|   | `-ParametersAndQualifiers
+|   |   |-(
+|   |   `-)
+|   `-;
 `-SimpleDeclaration
   |-void
   |-SimpleDeclarator
@@ -1208,28 +1294,95 @@
   `-CompoundStatement
 |-{
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12
+| |-IntegerUserDefinedLiteralExpression
+| | `-12_i
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12u
+| |-FloatUserDefinedLiteralExpression
+| | `-1.2_f
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12l
+| |-CharUserDefinedLiteralExpression
+| | `-'2'_c
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12ul
+| |-UnknownUserDefinedLiteralExpression
+| | `-12_r
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-014
+| |-UnknownUserDefinedLiteralExpression
+| | `-1.2_r
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-0XC
+| |-UnknownUserDefinedLiteralExpression
+| | `-12_t
+| `-;
+|-ExpressionStatement
+| |-UnknownUserDefinedLiteralExpression
+| | `-1.2_t
+| `-;
+`-}
+)txt"));
+}
+
+TEST_P(SyntaxTreeTest, UserDefinedLiteralString) {
+  if (!GetParam().isCXX11OrLater()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqual(
+  R"cpp(
+typedef decltype(sizeof(void *)) size_t;
+unsigned operator "" _s(const char*, size_t);
+void test() {
+  "12"_s;// call: operator "" _s("12")   | kind: string
+}
+)cpp",
+  R"txt(
+*: TranslationUnit
+|-SimpleDeclaration
+| |-typedef
+| |-decltype
+| |-(
+| |-UnknownExpression
+| | |-sizeof
+| | |-(
+| | |-void
+| | |-*
+| | `-)
+| |-)
+| |-SimpleDeclarator
+| | `-size_t
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_s
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-const
+| |   | |-char
+| |   | `-SimpleDeclarator
+| |   |   `-*
+| |   |-,
+| |   |-SimpleDeclaration
+| |   | `-size_t
+| |   `-)
+| `-;
+`-SimpleDeclaration
+  |-void
+  |-SimpleDeclarator
+  | |-test
+  | `-ParametersAndQualifiers
+  | 

[PATCH] D82157: Fix crash on `user defined literals`

2020-07-09 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas added inline comments.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:634
+// `SourceLocation`s. As a result one of these nodes has a valid
+// `SourceLocation` that doesn't point to a token.
+//

gribozavr2 wrote:
> "The semantic AST node for has child nodes that reference two source 
> locations, the location of the beginning of the token (`1`), and the location 
> of the beginning of the UDL suffix (`_`). The UDL suffix location does not 
> point to the beginning of a token, so we can't represent the UDL suffix as a 
> separate syntax tree node."
I changed your comment slightly, WDYT


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82157



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


[clang] 9e7fddb - [yaml][clang-tidy] Fix multiline YAML serialization

2020-07-09 Thread Dmitry Polukhin via cfe-commits

Author: Dmitry Polukhin
Date: 2020-07-09T02:41:58-07:00
New Revision: 9e7fddbd36f567217255c1df1cb816b79f0250af

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

LOG: [yaml][clang-tidy] Fix multiline YAML serialization

Summary:
New line duplication logic introduced in https://reviews.llvm.org/D63482
has two issues: (1) there is no logic that removes duplicate newlines
when clang-apply-replacment reads YAML and (2) in general such logic
should be applied to all strings and should happen on string
serialization level instead in YAML parser.

This diff changes multiline strings quotation from single quote `'` to
double `"`. It solves problems with internal newlines because now they are
escaped. Also double quotation solves the problem with leading whitespace after
newline. In case of single quotation YAML parsers should remove leading
whitespace according to specification. In case of double quotation these
leading are internal space and they are preserved. There is no way to
instruct YAML parsers to preserve leading whitespaces after newline so
double quotation is the only viable option that solves all problems at
once.

Test Plan: check-all

Reviewers: gribozavr, mgehre, yvvan

Subscribers: xazax.hun, hiraditya, cfe-commits, llvm-commits

Tags: #clang-tools-extra, #clang, #llvm

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

Added: 


Modified: 
clang/include/clang/Tooling/ReplacementsYaml.h
clang/unittests/Tooling/ReplacementsYamlTest.cpp
llvm/include/llvm/Support/YAMLTraits.h
llvm/lib/Support/YAMLTraits.cpp
llvm/test/Transforms/LowerMatrixIntrinsics/remarks-shared-subtrees.ll
llvm/unittests/Support/YAMLIOTest.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/ReplacementsYaml.h 
b/clang/include/clang/Tooling/ReplacementsYaml.h
index 2e3e401652e2..83e35d623255 100644
--- a/clang/include/clang/Tooling/ReplacementsYaml.h
+++ b/clang/include/clang/Tooling/ReplacementsYaml.h
@@ -35,13 +35,7 @@ template <> struct 
MappingTraits {
 
 NormalizedReplacement(const IO &, const clang::tooling::Replacement &R)
 : FilePath(R.getFilePath()), Offset(R.getOffset()),
-  Length(R.getLength()), ReplacementText(R.getReplacementText()) {
-  size_t lineBreakPos = ReplacementText.find('\n');
-  while (lineBreakPos != std::string::npos) {
-ReplacementText.replace(lineBreakPos, 1, "\n\n");
-lineBreakPos = ReplacementText.find('\n', lineBreakPos + 2);
-  }
-}
+  Length(R.getLength()), ReplacementText(R.getReplacementText()) {}
 
 clang::tooling::Replacement denormalize(const IO &) {
   return clang::tooling::Replacement(FilePath, Offset, Length,

diff  --git a/clang/unittests/Tooling/ReplacementsYamlTest.cpp 
b/clang/unittests/Tooling/ReplacementsYamlTest.cpp
index c8fe9c4db412..3328d9bad55c 100644
--- a/clang/unittests/Tooling/ReplacementsYamlTest.cpp
+++ b/clang/unittests/Tooling/ReplacementsYamlTest.cpp
@@ -65,7 +65,7 @@ TEST(ReplacementsYamlTest, serializesNewLines) {
"  - FilePath:'/path/to/file1.h'\n"
"Offset:  0\n"
"Length:  0\n"
-   "ReplacementText: '#include \n\n'\n"
+   "ReplacementText: \"#include \\n\"\n"
"...\n",
YamlContentStream.str().c_str());
 }

diff  --git a/llvm/include/llvm/Support/YAMLTraits.h 
b/llvm/include/llvm/Support/YAMLTraits.h
index f93f36037679..44e34a4a09b4 100644
--- a/llvm/include/llvm/Support/YAMLTraits.h
+++ b/llvm/include/llvm/Support/YAMLTraits.h
@@ -649,24 +649,25 @@ inline bool isBool(StringRef S) {
 inline QuotingType needsQuotes(StringRef S) {
   if (S.empty())
 return QuotingType::Single;
+
+  QuotingType MaxQuotingNeeded = QuotingType::None;
   if (isSpace(static_cast(S.front())) ||
   isSpace(static_cast(S.back(
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
   if (isNull(S))
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
   if (isBool(S))
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
   if (isNumeric(S))
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
 
   // 7.3.3 Plain Style
   // Plain scalars must not begin with most indicators, as this would cause
   // ambiguity with other YAML constructs.
   static constexpr char Indicators[] = R"(-?:\,[]{}#&*!|>'"%@`)";
   if (S.find_first_of(Indicators) == 0)
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
 
-  QuotingType MaxQuotingNeeded = QuotingType::None;
   for (unsigned char C : S) {
 // Alphanum is safe.
 if (isAlnum(C))
@@ -684,11 +685,11 @@ inline QuotingType needsQuotes(StringRef S) {
   

[PATCH] D80301: [yaml][clang-tidy] Fix multiline YAML serialization

2020-07-09 Thread Dmitry Polukhin via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9e7fddbd36f5: [yaml][clang-tidy] Fix multiline YAML 
serialization (authored by DmitryPolukhin).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80301

Files:
  clang/include/clang/Tooling/ReplacementsYaml.h
  clang/unittests/Tooling/ReplacementsYamlTest.cpp
  llvm/include/llvm/Support/YAMLTraits.h
  llvm/lib/Support/YAMLTraits.cpp
  llvm/test/Transforms/LowerMatrixIntrinsics/remarks-shared-subtrees.ll
  llvm/unittests/Support/YAMLIOTest.cpp

Index: llvm/unittests/Support/YAMLIOTest.cpp
===
--- llvm/unittests/Support/YAMLIOTest.cpp
+++ llvm/unittests/Support/YAMLIOTest.cpp
@@ -285,10 +285,8 @@
 YOut << Original;
   }
   auto Expected = "---\n"
-  "str1:'a multiline string\n"
-  "foobarbaz'\n"
-  "str2:'another one\r"
-  "foobarbaz'\n"
+  "str1:\"a multiline string\\nfoobarbaz\"\n"
+  "str2:\"another one\\rfoobarbaz\"\n"
   "str3:a one-line string\n"
   "...\n";
   ASSERT_EQ(Serialized, Expected);
Index: llvm/test/Transforms/LowerMatrixIntrinsics/remarks-shared-subtrees.ll
===
--- llvm/test/Transforms/LowerMatrixIntrinsics/remarks-shared-subtrees.ll
+++ llvm/test/Transforms/LowerMatrixIntrinsics/remarks-shared-subtrees.ll
@@ -18,8 +18,7 @@
 ; YAML-NEXT:- String:  ' loads, '
 ; YAML-NEXT:- NumComputeOps:   '0'
 ; YAML-NEXT:- String:  ' compute ops'
-; YAML-NEXT:- String:  ',
-; YAML-NEXT:  additionally '
+; YAML-NEXT:- String:  ",\nadditionally "
 ; YAML-NEXT:- NumStores:   '0'
 ; YAML-NEXT:- String:  ' stores, '
 ; YAML-NEXT:- NumLoads:'4'
@@ -47,8 +46,7 @@
 ; YAML-NEXT:- String:  ' loads, '
 ; YAML-NEXT:- NumComputeOps:   '120'
 ; YAML-NEXT:- String:  ' compute ops'
-; YAML-NEXT:- String:  ',
-; YAML-NEXT:  additionally '
+; YAML-NEXT:- String:  ",\nadditionally "
 ; YAML-NEXT:- NumStores:   '0'
 ; YAML-NEXT:- String:  ' stores, '
 ; YAML-NEXT:- NumLoads:'4'
Index: llvm/lib/Support/YAMLTraits.cpp
===
--- llvm/lib/Support/YAMLTraits.cpp
+++ llvm/lib/Support/YAMLTraits.cpp
@@ -878,12 +878,12 @@
 }
 
 void ScalarTraits::output(const std::string &Val, void *,
- raw_ostream &Out) {
+   raw_ostream &Out) {
   Out << Val;
 }
 
 StringRef ScalarTraits::input(StringRef Scalar, void *,
- std::string &Val) {
+   std::string &Val) {
   Val = Scalar.str();
   return StringRef();
 }
Index: llvm/include/llvm/Support/YAMLTraits.h
===
--- llvm/include/llvm/Support/YAMLTraits.h
+++ llvm/include/llvm/Support/YAMLTraits.h
@@ -649,24 +649,25 @@
 inline QuotingType needsQuotes(StringRef S) {
   if (S.empty())
 return QuotingType::Single;
+
+  QuotingType MaxQuotingNeeded = QuotingType::None;
   if (isSpace(static_cast(S.front())) ||
   isSpace(static_cast(S.back(
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
   if (isNull(S))
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
   if (isBool(S))
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
   if (isNumeric(S))
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
 
   // 7.3.3 Plain Style
   // Plain scalars must not begin with most indicators, as this would cause
   // ambiguity with other YAML constructs.
   static constexpr char Indicators[] = R"(-?:\,[]{}#&*!|>'"%@`)";
   if (S.find_first_of(Indicators) == 0)
-return QuotingType::Single;
+MaxQuotingNeeded = QuotingType::Single;
 
-  QuotingType MaxQuotingNeeded = QuotingType::None;
   for (unsigned char C : S) {
 // Alphanum is safe.
 if (isAlnum(C))
@@ -684,11 +685,11 @@
 case 0x9:
   continue;
 // LF(0xA) and CR(0xD) may delimit values and so require at least single
-// quotes.
+// quotes. LLVM YAML parser cannot handle single quoted multiline so use
+// double quoting to produce valid YAML.
 case 0xA:
 case 0xD:
-  MaxQuotingNeeded = QuotingType::Single;
-  continue;
+  return QuotingType::Double;
 // DEL (0x7F) are excluded from the allowed character range.
 case 0x7F:
   return QuotingType::Double;
Index: clang/unittests/Tooling/ReplacementsYamlTest.cpp
=

[PATCH] D80301: [yaml][clang-tidy] Fix multiline YAML serialization

2020-07-09 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin added a comment.

@aaron.ballman - thank you for the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D80301



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


[PATCH] D83174: Teach AttachPreviousImpl to inherit MSInheritanceAttr attribute

2020-07-09 Thread Vaibhav Garg via Phabricator via cfe-commits
gargvaibhav64 updated this revision to Diff 276680.
gargvaibhav64 marked 3 inline comments as done.
gargvaibhav64 added a comment.

Added a new attribute instead of using the previous one


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

https://reviews.llvm.org/D83174

Files:
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/test/Modules/Inputs/inherit-attribute/a.h
  clang/test/Modules/Inputs/inherit-attribute/b.h
  clang/test/Modules/Inputs/inherit-attribute/c.h
  clang/test/Modules/Inputs/inherit-attribute/module.modulemap
  clang/test/Modules/inherit-attribute.cpp

Index: clang/test/Modules/inherit-attribute.cpp
===
--- /dev/null
+++ clang/test/Modules/inherit-attribute.cpp
@@ -0,0 +1,10 @@
+// RUN: rm -rf %t
+// RUN: %clang_cc1 -fmodules -ast-dump -I%S/Inputs/inherit-attribute -fmodules-cache-path=%t -fimplicit-module-maps -verify %s -fmodules-local-submodule-visibility
+
+#include "b.h"
+#include "c.h"
+
+class Foo;
+
+Foo f;
+// expected-no-diagnostics
\ No newline at end of file
Index: clang/test/Modules/Inputs/inherit-attribute/module.modulemap
===
--- /dev/null
+++ clang/test/Modules/Inputs/inherit-attribute/module.modulemap
@@ -0,0 +1,3 @@
+module "b" { header "b.h" }
+
+module "c" { header "c.h" }
\ No newline at end of file
Index: clang/test/Modules/Inputs/inherit-attribute/c.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/inherit-attribute/c.h
@@ -0,0 +1,7 @@
+#include "a.h"
+
+class Foo;
+class C {
+public:
+  C();
+};
\ No newline at end of file
Index: clang/test/Modules/Inputs/inherit-attribute/b.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/inherit-attribute/b.h
@@ -0,0 +1,12 @@
+#include "a.h"
+
+class Foo;
+
+void bar() {
+  &Foo::step;
+}
+
+class B {
+public:
+  B();
+};
\ No newline at end of file
Index: clang/test/Modules/Inputs/inherit-attribute/a.h
===
--- /dev/null
+++ clang/test/Modules/Inputs/inherit-attribute/a.h
@@ -0,0 +1,10 @@
+#ifndef FOO
+#define FOO
+
+class Foo {
+public:
+  void step(int v);
+  Foo();
+};
+
+#endif
\ No newline at end of file
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -281,6 +281,9 @@
 static Decl *getMostRecentDeclImpl(...);
 static Decl *getMostRecentDecl(Decl *D);
 
+static void mergeInheritableAttributes(ASTReader &Reader, Decl *D,
+   Decl *Previous);
+
 template 
 static void attachPreviousDeclImpl(ASTReader &Reader,
Redeclarable *D, Decl *Previous,
@@ -3531,6 +3534,23 @@
   return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
 }
 
+void ASTDeclReader::mergeInheritableAttributes(ASTReader &Reader, Decl *D,
+   Decl *Previous) {
+  InheritableAttr *NewAttr = nullptr;
+  ASTContext &Context = Reader.getContext();
+  if (Previous->hasAttr() &&
+  !D->hasAttr()) {
+const auto *IA =
+dyn_cast(Previous->getAttr());
+
+NewAttr = new (Context) MSInheritanceAttr(
+IA->getRange(), Context, IA->getBestCase(), IA->getSpellingListIndex());
+
+NewAttr->setInherited(true);
+D->addAttr(NewAttr);
+  }
+}
+
 template
 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
Redeclarable *D,
@@ -3689,6 +3709,12 @@
   if (auto *TD = dyn_cast(D))
 inheritDefaultTemplateArguments(Reader.getContext(),
 cast(Previous), TD);
+
+  // If any of the declaration in the chain contains an Inheritable attribute,
+  // it needs to be added to all the declarations in the redeclarable chain.
+  // FIXME: Only the logic of merging MSInheritableAttr is present, it should
+  // be extended for all inheritable attributes.
+  mergeInheritableAttributes(Reader, D, Previous);
 }
 
 template
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82157: Fix crash on `user defined literals`

2020-07-09 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/lib/Tooling/Syntax/BuildTree.cpp:634
+// `SourceLocation`s. As a result one of these nodes has a valid
+// `SourceLocation` that doesn't point to a token.
+//

eduucaldas wrote:
> gribozavr2 wrote:
> > "The semantic AST node for has child nodes that reference two source 
> > locations, the location of the beginning of the token (`1`), and the 
> > location of the beginning of the UDL suffix (`_`). The UDL suffix location 
> > does not point to the beginning of a token, so we can't represent the UDL 
> > suffix as a separate syntax tree node."
> I changed your comment slightly, WDYT
LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82157



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


[PATCH] D82157: Fix crash on `user defined literals`

2020-07-09 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas updated this revision to Diff 276681.
eduucaldas added a comment.

Document proposed solution for treating raw literal operators and numeric 
template operators


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82157

Files:
  clang/include/clang/Tooling/Syntax/Nodes.h
  clang/lib/Tooling/Syntax/BuildTree.cpp
  clang/lib/Tooling/Syntax/Nodes.cpp
  clang/unittests/Tooling/Syntax/TreeTest.cpp

Index: clang/unittests/Tooling/Syntax/TreeTest.cpp
===
--- clang/unittests/Tooling/Syntax/TreeTest.cpp
+++ clang/unittests/Tooling/Syntax/TreeTest.cpp
@@ -1184,20 +1184,108 @@
 )txt"));
 }
 
-TEST_P(SyntaxTreeTest, IntegerLiteral) {
+TEST_P(SyntaxTreeTest, UserDefinedLiteral) {
+  if (!GetParam().isCXX11OrLater()) {
+return;
+  }
   EXPECT_TRUE(treeDumpEqual(
   R"cpp(
+unsigned operator "" _i(unsigned long long);
+unsigned operator "" _f(long double);
+unsigned operator "" _c(char);
+
+unsigned operator "" _r(const char*); // raw-literal operator
+
+template 
+unsigned operator "" _t();// numeric literal operator template
+
 void test() {
-  12;
-  12u;
-  12l;
-  12ul;
-  014;
-  0XC;
+  12_i;  // call: operator "" _i(12uLL)  | kind: integer
+  1.2_f; // call: operator "" _f(1.2L)   | kind: float
+  '2'_c; // call: operator "" _c('2')| kind: char
+
+  // TODO: Generate `FloatUserDefinedLiteralExpression` and
+  // `IntegerUserDefinedLiteralExpression` instead of
+  // `UnknownUserDefinedLiteralExpression`. See `getUserDefinedLiteralKind`
+  12_r;  // call: operator "" _r("12")   | kind: integer
+  1.2_r; // call: operator "" _i("1.2")  | kind: float
+  12_t;  // call: operator<'1', '2'> "" _x() | kind: integer
+  1.2_t; // call: operator<'1', '2'> "" _x() | kind: float
 }
-)cpp",
+)cpp",
   R"txt(
 *: TranslationUnit
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_i
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-unsigned
+| |   | |-long
+| |   | `-long
+| |   `-)
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_f
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-long
+| |   | `-double
+| |   `-)
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_c
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | `-char
+| |   `-)
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_r
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-const
+| |   | |-char
+| |   | `-SimpleDeclarator
+| |   |   `-*
+| |   `-)
+| `-;
+|-TemplateDeclaration
+| |-template
+| |-<
+| |-SimpleDeclaration
+| | `-char
+| |-...
+| |->
+| `-SimpleDeclaration
+|   |-unsigned
+|   |-SimpleDeclarator
+|   | |-operator
+|   | |-""
+|   | |-_t
+|   | `-ParametersAndQualifiers
+|   |   |-(
+|   |   `-)
+|   `-;
 `-SimpleDeclaration
   |-void
   |-SimpleDeclarator
@@ -1208,28 +1296,95 @@
   `-CompoundStatement
 |-{
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12
+| |-IntegerUserDefinedLiteralExpression
+| | `-12_i
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12u
+| |-FloatUserDefinedLiteralExpression
+| | `-1.2_f
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12l
+| |-CharUserDefinedLiteralExpression
+| | `-'2'_c
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-12ul
+| |-UnknownUserDefinedLiteralExpression
+| | `-12_r
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-014
+| |-UnknownUserDefinedLiteralExpression
+| | `-1.2_r
 | `-;
 |-ExpressionStatement
-| |-IntegerLiteralExpression
-| | `-0XC
+| |-UnknownUserDefinedLiteralExpression
+| | `-12_t
+| `-;
+|-ExpressionStatement
+| |-UnknownUserDefinedLiteralExpression
+| | `-1.2_t
+| `-;
+`-}
+)txt"));
+}
+
+TEST_P(SyntaxTreeTest, UserDefinedLiteralString) {
+  if (!GetParam().isCXX11OrLater()) {
+return;
+  }
+  EXPECT_TRUE(treeDumpEqual(
+  R"cpp(
+typedef decltype(sizeof(void *)) size_t;
+unsigned operator "" _s(const char*, size_t);
+void test() {
+  "12"_s;// call: operator "" _s("12")   | kind: string
+}
+)cpp",
+  R"txt(
+*: TranslationUnit
+|-SimpleDeclaration
+| |-typedef
+| |-decltype
+| |-(
+| |-UnknownExpression
+| | |-sizeof
+| | |-(
+| | |-void
+| | |-*
+| | `-)
+| |-)
+| |-SimpleDeclarator
+| | `-size_t
+| `-;
+|-SimpleDeclaration
+| |-unsigned
+| |-SimpleDeclarator
+| | |-operator
+| | |-""
+| | |-_s
+| | `-ParametersAndQualifiers
+| |   |-(
+| |   |-SimpleDeclaration
+| |   | |-const
+| |   | |-char
+| |   | `-SimpleDeclarat

[PATCH] D69318: [analyzer] Add SufficientSizeArrayIndexingChecker

2020-07-09 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added inline comments.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/SufficientSizeArrayIndexingChecker.cpp:27
+: public Checker> {
+  mutable std::unique_ptr BT;
+

gamesh411 wrote:
> balazske wrote:
> > The bug type can be initialized here:
> > `BT{this, "...", "..."}`
> > How did this compile with only one text argument to constructor? I think 
> > the first is a short name of the bug, second is a category that is not 
> > omittable. The text that is used here should be passed to the `BugReport`. 
> > `BugType::getDescription` returns the "name" of the bug that is the first 
> > argument. But I am not sure what matters from these texts, the code design 
> > looks confusing.
> I think because it is initialized with a `BuiltinBug`, which must be a 
> subclass of BugType. I don't really know what should be preferable nowadays, 
> as this code was actually written more than a year ago. Thanks for pointing 
> out that it can be initialized there, I think lazy initialization seems not 
> that important with this particular checker.
I had even a plan to remove the `BuiltinBug` because it looks confusing and 
does not add real value. New checkers should use `BugType`.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/SufficientSizeArrayIndexingChecker.cpp:50
+  if (isa(Index->IgnoreParenCasts()))
+return;
+

gamesh411 wrote:
> balazske wrote:
> > `if (isa(Index))` should be used. `IntegerLiteral` is a 
> > subclass of `Expr`, not a `QualType`.
> The way I have structured the code is very misleading, sorry for that, I will 
> move the type extraction if lower, where it is actually used.
Probably function `SVB.getConstantVal` can be used to test if there is a 
(compile-time) constant passed to the index. But it may be value of a (const) 
variable.



Comment at: clang/test/Analysis/sufficient-size-array-indexing-32bit.c:37
+const short two_byte_signed_index = 1; // sizeof(short) == 2
+const int four_byte_signed_index = 1;  // sizeof(int) == 4
+

gamesh411 wrote:
> balazske wrote:
> > I do not know if it is safe to make such assumptions about `sizeof`.
> You are definitely right! However it is common as per:
> https://en.cppreference.com/w/cpp/language/types#Data_models
> ```
> Data models
> 
> The choices made by each implementation about the sizes of the fundamental 
> types are collectively known as data model. Four data models found wide 
> acceptance:
> 
> 32 bit systems:
> 
> LP32 or 2/4/4 (int is 16-bit, long and pointer are 32-bit) 
> 
> Win16 API 
> 
> ILP32 or 4/4/4 (int, long, and pointer are 32-bit); 
> 
> Win32 API
> Unix and Unix-like systems (Linux, macOS) 
> 
> 64 bit systems:
> 
> LLP64 or 4/4/8 (int and long are 32-bit, pointer is 64-bit) 
> 
> Win64 API 
> 
> LP64 or 4/8/8 (int is 32-bit, long and pointer are 64-bit) 
> 
> Unix and Unix-like systems (Linux, macOS) 
> 
> Other models are very rare. For example, ILP64 (8/8/8: int, long, and pointer 
> are 64-bit) only appeared in some early 64-bit Unix systems (e.g. Unicos on 
> Cray). 
> ```
> Only ILP32 has 16 bit ints.
> Next idea would be to use fixed-width integer types from `cstdint`. But tests 
> should not use system headers, and there are mentions in test files to 
> `int32_t`, howevery they are just typedefs for int. And I think we 
> maintaining a whole standard library headers is a bit too much a hassle.
Still it would be good to check if the test passes on all the buildbots.



Comment at: clang/test/Analysis/sufficient-size-array-indexing-32bit.c:48
+void ignore_literal_indexing_with_parens() {
+  char a = exactly_4byte_signed_range[(32)]; // nowarning
+}

Does this work in `[32 + 1]` case?



Comment at: clang/test/Analysis/sufficient-size-array-indexing-32bit.c:106
+if (choice >= 1) {
+  c = f(choice)[four_byte_signed_index]; // nowarnining // the value is 
one or two, f returns an array that is correct in size
+}

`choice` can be here only 1. If it could be 1 or 2 we should get no warning 
because the array size may be good or bad. But to test that it is enough that 
`choice` can have any value, like in `test_symbolic_index_handling4`.



Comment at: clang/test/Analysis/sufficient-size-array-indexing-32bit.c:120
+
+void test_symbolic_index_handling4(int choice) {
+  char c;

Here "is a chance that indexing is correct". So no warning should occur?



Comment at: clang/test/Analysis/sufficient-size-array-indexing-64bit.c:1
+// RUN: %clang_analyze_cc1 -triple x86_64 
-analyzer-checker=core,alpha.core.SufficientSizeArrayIndexing %s -verify
+

I could not find difference between this and the previous test file (except the 
multi-dimensional arrays are omitted). It would be better to have a sin

[clang] 397c682 - Fix MSVC "not all control paths return a value" warning. NFC.

2020-07-09 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2020-07-09T11:06:39+01:00
New Revision: 397c68202a990c80a71de2816cee413cd5b5865e

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

LOG: Fix MSVC "not all control paths return a value" warning. NFC.

Added: 


Modified: 
clang/lib/Tooling/Syntax/BuildTree.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/BuildTree.cpp 
b/clang/lib/Tooling/Syntax/BuildTree.cpp
index 361455e69f5a..f9fdf47bff26 100644
--- a/clang/lib/Tooling/Syntax/BuildTree.cpp
+++ b/clang/lib/Tooling/Syntax/BuildTree.cpp
@@ -192,6 +192,7 @@ static syntax::NodeKind getOperatorNodeKind(const 
CXXOperatorCallExpr &E) {
   case OO_None:
 llvm_unreachable("Not an overloadable operator");
   }
+  llvm_unreachable("Unknown OverloadedOperatorKind enum");
 }
 
 /// Gets the range of declarator as defined by the C++ grammar. E.g.



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


[PATCH] D83295: [Analyzer] Hotfix for various crashes in iterator checkers

2020-07-09 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware updated this revision to Diff 276684.
baloghadamsoftware edited the summary of this revision.
baloghadamsoftware added a comment.

Test added for the third fix in this patch.


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

https://reviews.llvm.org/D83295

Files:
  clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
  clang/test/Analysis/iterator-modeling.cpp
  clang/test/Analysis/iterator-range.cpp


Index: clang/test/Analysis/iterator-range.cpp
===
--- clang/test/Analysis/iterator-range.cpp
+++ clang/test/Analysis/iterator-range.cpp
@@ -935,3 +935,7 @@
   // expected-note@-1{{Iterator decremented ahead of its valid range}}
 }
 
+void ptr_iter_diff(cont_with_ptr_iterator &c) {
+  auto i0 = c.begin(), i1 = c.end();
+  ptrdiff_t len = i1 - i0; // no-crash
+}
Index: clang/test/Analysis/iterator-modeling.cpp
===
--- clang/test/Analysis/iterator-modeling.cpp
+++ clang/test/Analysis/iterator-modeling.cpp
@@ -1972,6 +1972,17 @@
   clang_analyzer_express(clang_analyzer_iterator_position(i2)); // 
expected-warning{{$c.end() - 2}}
 }
 
+void ptr_iter_diff(cont_with_ptr_iterator &c) {
+  auto i0 = c.begin(), i1 = c.end();
+  ptrdiff_t len = i1 - i0; // no-crash
+}
+
+void ptr_iter_cmp_nullptr(cont_with_ptr_iterator &c) {
+  auto i0 = c.begin();
+  if (i0 != nullptr) // no-crash
+++i0;
+}
+
 void clang_analyzer_printState();
 
 void print_state(std::vector &V) {
Index: clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
@@ -169,6 +169,8 @@
 verifyDereference(C, LVal);
   } else if (isRandomIncrOrDecrOperator(OK)) {
 SVal RVal = State->getSVal(BO->getRHS(), C.getLocationContext());
+if (!BO->getRHS()->getType()->isIntegralOrEnumerationType())
+  return;
 verifyRandomIncrOrDecr(C, BinaryOperator::getOverloadedOperator(OK), LVal,
RVal);
   }
Index: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
+++ clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp
@@ -272,6 +272,8 @@
 handleComparison(C, BO, Result, LVal, RVal,
  BinaryOperator::getOverloadedOperator(OK));
   } else if (isRandomIncrOrDecrOperator(OK)) {
+if (!BO->getRHS()->getType()->isIntegralOrEnumerationType())
+  return;
 handlePtrIncrOrDecr(C, BO->getLHS(),
 BinaryOperator::getOverloadedOperator(OK), RVal);
   }
@@ -461,6 +463,12 @@
 RPos = getIteratorPosition(State, RVal);
   }
 
+  // If the value for which we just tried to set a new iterator position is
+  // an `SVal`for which no iterator position can be set then the setting was
+  // unsuccessful. We cannot handle the comparison in this case.
+  if (!LPos || !RPos)
+return;
+
   // We cannot make assumptions on `UnknownVal`. Let us conjure a symbol
   // instead.
   if (RetVal.isUnknown()) {


Index: clang/test/Analysis/iterator-range.cpp
===
--- clang/test/Analysis/iterator-range.cpp
+++ clang/test/Analysis/iterator-range.cpp
@@ -935,3 +935,7 @@
   // expected-note@-1{{Iterator decremented ahead of its valid range}}
 }
 
+void ptr_iter_diff(cont_with_ptr_iterator &c) {
+  auto i0 = c.begin(), i1 = c.end();
+  ptrdiff_t len = i1 - i0; // no-crash
+}
Index: clang/test/Analysis/iterator-modeling.cpp
===
--- clang/test/Analysis/iterator-modeling.cpp
+++ clang/test/Analysis/iterator-modeling.cpp
@@ -1972,6 +1972,17 @@
   clang_analyzer_express(clang_analyzer_iterator_position(i2)); // expected-warning{{$c.end() - 2}}
 }
 
+void ptr_iter_diff(cont_with_ptr_iterator &c) {
+  auto i0 = c.begin(), i1 = c.end();
+  ptrdiff_t len = i1 - i0; // no-crash
+}
+
+void ptr_iter_cmp_nullptr(cont_with_ptr_iterator &c) {
+  auto i0 = c.begin();
+  if (i0 != nullptr) // no-crash
+++i0;
+}
+
 void clang_analyzer_printState();
 
 void print_state(std::vector &V) {
Index: clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp
@@ -169,6 +169,8 @@
 verifyDereference(C, LVal);
   } else if (isRandomIncrOrDecrOperator(OK)) {
 SVal RVal = State->getSVal(BO->getRHS(), C.getLocationContext());
+if (!BO->getRHS()->getType()->isIntegralOrEnumerationType())
+  return;
 verifyRandomIncrOrDecr(C, BinaryOpera

[PATCH] D81676: [MSP430] Align the toolchain definition with the TI's msp430-gcc v9.2.0

2020-07-09 Thread Anatoly Trosinenko via Phabricator via cfe-commits
atrosinenko updated this revision to Diff 276686.
atrosinenko added a comment.

Just add the test on `-rtlib=compiler-rt` handling as everything other is ready 
for basic clang_rt.builtins support.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81676

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/MSP430.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/MSP430.cpp
  clang/lib/Driver/ToolChains/MSP430.h
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtend_no_eh.o
  clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtbegin_no_eh.o
  clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/include-fixed/limits.h
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/include/stddef.h
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtend_no_eh.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/include/stdio.h
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/430/crtn.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/430/exceptions/crt0.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/crt0.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/exceptions/crt0.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/crt0.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/exceptions/crt0.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/full-memory-range/crt0.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/full-memory-range/exceptions/crt0.o
  clang/test/Driver/msp430-toolchain.c

Index: clang/test/Driver/msp430-toolchain.c
===
--- clang/test/Driver/msp430-toolchain.c
+++ clang/test/Driver/msp430-toolchain.c
@@ -1,78 +1,269

[clang-tools-extra] 6a3b10e - [change-namespace][NFC] Clean up joinNamespaces

2020-07-09 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2020-07-09T11:29:49+01:00
New Revision: 6a3b10e294feceb94064f32450de5c068a13dd03

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

LOG: [change-namespace][NFC] Clean up joinNamespaces

Added: 


Modified: 
clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp 
b/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp
index e2a70db4102b..61ae7c4cc703 100644
--- a/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp
+++ b/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp
@@ -19,14 +19,8 @@ namespace change_namespace {
 
 namespace {
 
-inline std::string
-joinNamespaces(const llvm::SmallVectorImpl &Namespaces) {
-  if (Namespaces.empty())
-return "";
-  std::string Result(Namespaces.front());
-  for (auto I = Namespaces.begin() + 1, E = Namespaces.end(); I != E; ++I)
-Result += ("::" + *I).str();
-  return Result;
+inline std::string joinNamespaces(ArrayRef Namespaces) {
+  return llvm::join(Namespaces, "::");
 }
 
 // Given "a::b::c", returns {"a", "b", "c"}.



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


[PATCH] D82938: [clangd] Implement path and URI translation for remote index

2020-07-09 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 276692.
kbobyrev marked 15 inline comments as done.
kbobyrev added a comment.

Address post-LGTM round of comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82938

Files:
  clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/index/remote/Client.h
  clang-tools-extra/clangd/index/remote/Index.proto
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h
  clang-tools-extra/clangd/index/remote/server/Server.cpp
  clang-tools-extra/clangd/index/remote/unimplemented/UnimplementedClient.cpp
  clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp

Index: clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
===
--- clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
+++ clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
@@ -7,85 +7,286 @@
 //===--===//
 
 #include "../TestTU.h"
+#include "TestFS.h"
+#include "index/Index.h"
+#include "index/Ref.h"
 #include "index/Serialization.h"
+#include "index/Symbol.h"
+#include "index/SymbolID.h"
 #include "index/remote/marshalling/Marshalling.h"
+#include "clang/Index/IndexSymbol.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/StringSaver.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace clangd {
 namespace remote {
 namespace {
 
+using llvm::sys::path::convert_to_slash;
+
+const char *testPathURI(llvm::StringRef Path,
+llvm::UniqueStringSaver &Strings) {
+  auto URI = URI::createFile(testPath(Path));
+  return Strings.save(URI.toString()).begin();
+}
+
+TEST(RemoteMarshallingTest, URITranslation) {
+  llvm::BumpPtrAllocator Arena;
+  llvm::UniqueStringSaver Strings(Arena);
+  clangd::Ref Original;
+  Original.Location.FileURI =
+  testPathURI("remote/machine/projects/llvm-project/clang-tools-extra/"
+  "clangd/unittests/remote/MarshallingTests.cpp",
+  Strings);
+  auto Serialized =
+  toProtobuf(Original, testPath("remote/machine/projects/llvm-project/"));
+  EXPECT_EQ(Serialized.location().file_path(),
+"clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp");
+  const std::string LocalIndexPrefix = testPath("local/machine/project/");
+  auto Deserialized = fromProtobuf(Serialized, &Strings,
+   testPath("home/my-projects/llvm-project/"));
+  EXPECT_TRUE(Deserialized);
+  EXPECT_EQ(Deserialized->Location.FileURI,
+testPathURI("home/my-projects/llvm-project/clang-tools-extra/"
+"clangd/unittests/remote/MarshallingTests.cpp",
+Strings));
+
+  clangd::Ref WithInvalidURI;
+  // Invalid URI results in empty path.
+  WithInvalidURI.Location.FileURI = "This is not a URI";
+  Serialized = toProtobuf(WithInvalidURI, testPath("home/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  // Can not use URIs with scheme different from "file".
+  auto UnittestURI =
+  URI::create(testPath("project/lib/HelloWorld.cpp"), "unittest");
+  EXPECT_TRUE(bool(UnittestURI));
+  WithInvalidURI.Location.FileURI =
+  Strings.save(UnittestURI->toString()).begin();
+  Serialized = toProtobuf(WithInvalidURI, testPath("project/lib/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  Ref WithAbsolutePath;
+  *WithAbsolutePath.mutable_location()->mutable_file_path() =
+  "/usr/local/user/home/HelloWorld.cpp";
+  Deserialized = fromProtobuf(WithAbsolutePath, &Strings, LocalIndexPrefix);
+  // Paths transmitted over the wire can not be absolute, they have to be
+  // relative.
+  EXPECT_FALSE(Deserialized);
+}
+
 TEST(RemoteMarshallingTest, SymbolSerialization) {
-  const auto *Header = R"(
-  // This is a class.
-  class Foo {
-  public:
-Foo();
-
-int Bar;
-  private:
-double Number;
-  };
-  /// This is a function.
-  char baz();
-  template 
-  T getT ();
-  )";
-  const auto TU = TestTU::withHeaderCode(Header);
-  const auto Symbols = TU.headerSymbols();
-  // Sanity check: there are more than 5 symbols available.
-  EXPECT_GE(Symbols.size(), 5UL);
+  clangd::Symbol Sym;
+
+  auto ID = SymbolID::fromStr("057557CEBF6E6B2D");
+  EXPECT_TRUE(bool(ID));
+  Sym.ID = *ID;
+
+  index::SymbolInfo Info;
+  Info.Kind = index::SymbolKind::Function;
+  Info.SubKind = index::SymbolSubKind::AccessorGetter;
+  Info.Lang = index::SymbolLanguage::CXX;
+  Info.Properties = static_cast(
+  index::SymbolProperty::TemplateSpecialization);
+  Sym.SymInfo = Info;
+
   llvm::BumpPtrAllocator Arena;
   llvm::UniqueStringSaver Str

[PATCH] D81676: [MSP430] Align the toolchain definition with the TI's msp430-gcc v9.2.0

2020-07-09 Thread Anatoly Trosinenko via Phabricator via cfe-commits
atrosinenko updated this revision to Diff 276693.
atrosinenko added a comment.

Just an automatic rebase to (possibly) fix failing "Apply patch" step.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D81676

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Targets/MSP430.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/MSP430.cpp
  clang/lib/Driver/ToolChains/MSP430.h
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/7.3.1/430/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/430/exceptions/crtend_no_eh.o
  clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtbegin_no_eh.o
  clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/exceptions/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/include-fixed/limits.h
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/include/stddef.h
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/exceptions/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/crtend_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtbegin.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtbegin_no_eh.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtend.o
  
clang/test/Driver/Inputs/basic_msp430_tree/lib/gcc/msp430-elf/8.3.1/large/full-memory-range/exceptions/crtend_no_eh.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/include/stdio.h
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/430/crtn.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/430/exceptions/crt0.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/crt0.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/exceptions/crt0.o
  clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/crt0.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/exceptions/crt0.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/full-memory-range/crt0.o
  
clang/test/Driver/Inputs/basic_msp430_tree/msp430-elf/lib/large/full-memory-range/exceptions/crt0.o
  clang/test/Driver/msp430-toolchain.c

Index: clang/test/Driver/msp430-toolchain.c
===
--- clang/test/Driver/msp430-toolchain.c
+++ clang/test/Driver/msp430-toolchain.c
@@ -1,78 +1,269 @@
-// A basic clang -cc1 command-line, and si

[clang-tools-extra] 93bb994 - [clangd] Implement path and URI translation for remote index

2020-07-09 Thread Kirill Bobyrev via cfe-commits

Author: Kirill Bobyrev
Date: 2020-07-09T12:52:55+02:00
New Revision: 93bb9944cb577f0529636dc5acfba16026740962

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

LOG: [clangd] Implement path and URI translation for remote index

Reviewers: sammccall

Reviewed By: sammccall

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

Tags: #clang

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

Added: 


Modified: 
clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
clang-tools-extra/clangd/index/remote/Client.cpp
clang-tools-extra/clangd/index/remote/Client.h
clang-tools-extra/clangd/index/remote/Index.proto
clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h
clang-tools-extra/clangd/index/remote/server/Server.cpp
clang-tools-extra/clangd/index/remote/unimplemented/UnimplementedClient.cpp
clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp 
b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
index 3e25da385d7a..6fc844c18931 100644
--- a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
+++ b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
@@ -32,6 +32,9 @@ llvm::cl::opt IndexLocation(
 llvm::cl::opt
 ExecCommand("c", llvm::cl::desc("Command to execute and then exit"));
 
+llvm::cl::opt ProjectRoot("project-root",
+   llvm::cl::desc("Path to the project"));
+
 static constexpr char Overview[] = R"(
 This is an **experimental** interactive tool to process user-provided search
 queries over given symbol collection obtained via clangd-indexer. The
@@ -326,7 +329,8 @@ struct {
 
 std::unique_ptr openIndex(llvm::StringRef Index) {
   return Index.startswith("remote:")
- ? remote::getClient(Index.drop_front(strlen("remote:")))
+ ? remote::getClient(Index.drop_front(strlen("remote:")),
+ ProjectRoot)
  : loadIndex(Index, /*UseDex=*/true);
 }
 

diff  --git a/clang-tools-extra/clangd/index/remote/Client.cpp 
b/clang-tools-extra/clangd/index/remote/Client.cpp
index c43afd2573a9..b46883193076 100644
--- a/clang-tools-extra/clangd/index/remote/Client.cpp
+++ b/clang-tools-extra/clangd/index/remote/Client.cpp
@@ -10,10 +10,12 @@
 
 #include "Client.h"
 #include "Index.grpc.pb.h"
+#include "index/Index.h"
 #include "index/Serialization.h"
 #include "marshalling/Marshalling.h"
 #include "support/Logger.h"
 #include "support/Trace.h"
+#include "llvm/ADT/StringRef.h"
 
 #include 
 
@@ -27,6 +29,16 @@ class IndexClient : public clangd::SymbolIndex {
   using StreamingCall = std::unique_ptr> (
   remote::SymbolIndex::Stub::*)(grpc::ClientContext *, const RequestT &);
 
+  template 
+  RequestT serializeRequest(ClangdRequestT Request) const {
+return toProtobuf(Request);
+  }
+
+  template <>
+  FuzzyFindRequest serializeRequest(clangd::FuzzyFindRequest Request) const {
+return toProtobuf(Request, ProjectRoot);
+  }
+
   template 
   bool streamRPC(ClangdRequestT Request,
@@ -34,7 +46,7 @@ class IndexClient : public clangd::SymbolIndex {
  CallbackT Callback) const {
 bool FinalResult = false;
 trace::Span Tracer(RequestT::descriptor()->name());
-const auto RPCRequest = toProtobuf(Request);
+const auto RPCRequest = serializeRequest(Request);
 grpc::ClientContext Context;
 std::chrono::system_clock::time_point Deadline =
 std::chrono::system_clock::now() + DeadlineWaitingTime;
@@ -48,10 +60,11 @@ class IndexClient : public clangd::SymbolIndex {
 FinalResult = Reply.final_result();
 continue;
   }
-  auto Sym = fromProtobuf(Reply.stream_result(), &Strings);
-  if (!Sym)
+  auto Response =
+  fromProtobuf(Reply.stream_result(), &Strings, ProjectRoot);
+  if (!Response)
 elog("Received invalid {0}", ReplyT::descriptor()->name());
-  Callback(*Sym);
+  Callback(*Response);
 }
 SPAN_ATTACH(Tracer, "status", Reader->Finish().ok());
 return FinalResult;
@@ -59,9 +72,9 @@ class IndexClient : public clangd::SymbolIndex {
 
 public:
   IndexClient(
-  std::shared_ptr Channel,
+  std::shared_ptr Channel, llvm::StringRef ProjectRoot,
   std::chrono::milliseconds DeadlineTime = std::chrono::milliseconds(1000))
-  : Stub(remote::SymbolIndex::NewStub(Channel)),
+  : Stub(remote::SymbolIndex::NewStub(Channel)), ProjectRoot(ProjectRoot),
 DeadlineWaitingTime(DeadlineTime) {}
 
   void lookup(const clangd::LookupRequest &Request,
@@ -86,22 +99,26 @@ class IndexClient : public clangd::SymbolIndex {
 llvm::f

[PATCH] D82938: [clangd] Implement path and URI translation for remote index

2020-07-09 Thread Kirill Bobyrev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG93bb9944cb57: [clangd] Implement path and URI translation 
for remote index (authored by kbobyrev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82938

Files:
  clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/index/remote/Client.h
  clang-tools-extra/clangd/index/remote/Index.proto
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp
  clang-tools-extra/clangd/index/remote/marshalling/Marshalling.h
  clang-tools-extra/clangd/index/remote/server/Server.cpp
  clang-tools-extra/clangd/index/remote/unimplemented/UnimplementedClient.cpp
  clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp

Index: clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
===
--- clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
+++ clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp
@@ -7,85 +7,286 @@
 //===--===//
 
 #include "../TestTU.h"
+#include "TestFS.h"
+#include "index/Index.h"
+#include "index/Ref.h"
 #include "index/Serialization.h"
+#include "index/Symbol.h"
+#include "index/SymbolID.h"
 #include "index/remote/marshalling/Marshalling.h"
+#include "clang/Index/IndexSymbol.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/StringSaver.h"
+#include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 
 namespace clang {
 namespace clangd {
 namespace remote {
 namespace {
 
+using llvm::sys::path::convert_to_slash;
+
+const char *testPathURI(llvm::StringRef Path,
+llvm::UniqueStringSaver &Strings) {
+  auto URI = URI::createFile(testPath(Path));
+  return Strings.save(URI.toString()).begin();
+}
+
+TEST(RemoteMarshallingTest, URITranslation) {
+  llvm::BumpPtrAllocator Arena;
+  llvm::UniqueStringSaver Strings(Arena);
+  clangd::Ref Original;
+  Original.Location.FileURI =
+  testPathURI("remote/machine/projects/llvm-project/clang-tools-extra/"
+  "clangd/unittests/remote/MarshallingTests.cpp",
+  Strings);
+  auto Serialized =
+  toProtobuf(Original, testPath("remote/machine/projects/llvm-project/"));
+  EXPECT_EQ(Serialized.location().file_path(),
+"clang-tools-extra/clangd/unittests/remote/MarshallingTests.cpp");
+  const std::string LocalIndexPrefix = testPath("local/machine/project/");
+  auto Deserialized = fromProtobuf(Serialized, &Strings,
+   testPath("home/my-projects/llvm-project/"));
+  EXPECT_TRUE(Deserialized);
+  EXPECT_EQ(Deserialized->Location.FileURI,
+testPathURI("home/my-projects/llvm-project/clang-tools-extra/"
+"clangd/unittests/remote/MarshallingTests.cpp",
+Strings));
+
+  clangd::Ref WithInvalidURI;
+  // Invalid URI results in empty path.
+  WithInvalidURI.Location.FileURI = "This is not a URI";
+  Serialized = toProtobuf(WithInvalidURI, testPath("home/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  // Can not use URIs with scheme different from "file".
+  auto UnittestURI =
+  URI::create(testPath("project/lib/HelloWorld.cpp"), "unittest");
+  EXPECT_TRUE(bool(UnittestURI));
+  WithInvalidURI.Location.FileURI =
+  Strings.save(UnittestURI->toString()).begin();
+  Serialized = toProtobuf(WithInvalidURI, testPath("project/lib/"));
+  EXPECT_EQ(Serialized.location().file_path(), "");
+
+  Ref WithAbsolutePath;
+  *WithAbsolutePath.mutable_location()->mutable_file_path() =
+  "/usr/local/user/home/HelloWorld.cpp";
+  Deserialized = fromProtobuf(WithAbsolutePath, &Strings, LocalIndexPrefix);
+  // Paths transmitted over the wire can not be absolute, they have to be
+  // relative.
+  EXPECT_FALSE(Deserialized);
+}
+
 TEST(RemoteMarshallingTest, SymbolSerialization) {
-  const auto *Header = R"(
-  // This is a class.
-  class Foo {
-  public:
-Foo();
-
-int Bar;
-  private:
-double Number;
-  };
-  /// This is a function.
-  char baz();
-  template 
-  T getT ();
-  )";
-  const auto TU = TestTU::withHeaderCode(Header);
-  const auto Symbols = TU.headerSymbols();
-  // Sanity check: there are more than 5 symbols available.
-  EXPECT_GE(Symbols.size(), 5UL);
+  clangd::Symbol Sym;
+
+  auto ID = SymbolID::fromStr("057557CEBF6E6B2D");
+  EXPECT_TRUE(bool(ID));
+  Sym.ID = *ID;
+
+  index::SymbolInfo Info;
+  Info.Kind = index::SymbolKind::Function;
+  Info.SubKind = index::SymbolSubKind::AccessorGetter;
+  Info.Lang = index::SymbolLanguage::CXX;
+  Info.Properties = static_cast(
+  index::SymbolProperty::TemplateSpecialization);
+  Sym.SymInfo = Info;
+
   llvm::BumpPtrAllocator 

[PATCH] D82938: [clangd] Implement path and URI translation for remote index

2020-07-09 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev marked an inline comment as done.
kbobyrev added inline comments.



Comment at: clang-tools-extra/clangd/index/remote/marshalling/Marshalling.cpp:64
+  if (ParsedURI->scheme() != "file") {
+elog("Can not parse URI with scheme other than \"file\" {0}", URI);
+return llvm::None;

sammccall wrote:
> I think it's fine to fold this into the previous check: "bad URI" covers it
But it has different message :( `ParsedURI.takeError` wouldn't make sense here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82938



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


[PATCH] D83215: [AST][RecoveryExpr] Clarify the documentation of RecoveryExpr.

2020-07-09 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 276700.
hokein marked 4 inline comments as done.
hokein added a comment.

refine the doc based on the review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83215

Files:
  clang/include/clang/AST/Expr.h
  clang/lib/AST/ComputeDependence.cpp
  clang/lib/Sema/SemaExpr.cpp


Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -19210,9 +19210,6 @@
 
 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
 ArrayRef SubExprs, QualType T) {
-  // FIXME: enable it for C++, RecoveryExpr is type-dependent to suppress
-  // bogus diagnostics and this trick does not work in C.
-  // FIXME: use containsErrors() to suppress unwanted diags in C.
   if (!Context.getLangOpts().RecoveryAST)
 return ExprError();
 
Index: clang/lib/AST/ComputeDependence.cpp
===
--- clang/lib/AST/ComputeDependence.cpp
+++ clang/lib/AST/ComputeDependence.cpp
@@ -495,11 +495,21 @@
 }
 
 ExprDependence clang::computeDependence(RecoveryExpr *E) {
-  // Mark the expression as value- and instantiation- dependent to reuse
-  // existing suppressions for dependent code, e.g. avoiding
-  // constant-evaluation.
-  // FIXME: drop type+value+instantiation once Error is sufficient to suppress
-  // bogus dianostics.
+  // A dependent expression (typically in template context) can behave
+  // differently from one instantiation to another. The dependence-bits 
describe
+  // how an expression depends on a template parameter.
+  //
+  // We generalize the "dependent" to mean "depends on a template parameter, or
+  // an error".
+  //
+  // RecoveryExpression is
+  //  - always contains-errors: the expression depends on an error;
+  //  - always value-dependent: we never know the value, the value can be
+  //different or unknown depending on how the error is resolved;
+  //  - always instantiation-dependent: historically, this bit is used to
+  //determine whether an expression is dependent;
+  //  - type dependent if we don't know the type (fallback to an opequa
+  //dependent type), or the type is known and dependent;
   auto D = toExprDependence(E->getType()->getDependence()) |
ExprDependence::ValueInstantiation | ExprDependence::Error;
   for (auto *S : E->subExpressions())
Index: clang/include/clang/AST/Expr.h
===
--- clang/include/clang/AST/Expr.h
+++ clang/include/clang/AST/Expr.h
@@ -6212,19 +6212,22 @@
 /// subexpressions of some expression that we could not construct and source
 /// range covered by the expression.
 ///
-/// By default, RecoveryExpr is type-, value- and instantiation-dependent to
-/// take advantage of existing machinery to deal with dependent code in C++,
-/// e.g. RecoveryExpr is preserved in `decltype()` as part of the
-/// `DependentDecltypeType`. In addition to that, clang does not report most
-/// errors on dependent expressions, so we get rid of bogus errors for free.
-/// However, note that unlike other dependent expressions, RecoveryExpr can be
-/// produced in non-template contexts.
-/// In addition, we will preserve the type in RecoveryExpr when the type is
-/// known, e.g. preserving the return type for a broken non-overloaded function
-/// call, a overloaded call where all candidates have the same return type.
+/// By default, RecoveryExpr uses dependence-bits to take advantage of existing
+/// machinery to deal with dependent code in C++, e.g. RecoveryExpr is 
preserved
+/// in `decltype()` as part of the `DependentDecltypeType`. In
+/// addition to that, clang does not report most errors on dependent
+/// expressions, so we get rid of bogus errors for free. However, note that
+/// unlike other dependent expressions, RecoveryExpr can be produced in
+/// non-template contexts. In addition, we will preserve the type in
+/// RecoveryExpr when the type is known, e.g. preserving the return type for a
+/// broken non-overloaded function call, a overloaded call where all candidates
+/// have the same return type.
 ///
 /// One can also reliably suppress all bogus errors on expressions containing
 /// recovery expressions by examining results of Expr::containsErrors().
+///
+/// FIXME: RecoveryExpr is currently generated by default in C++ mode only, as
+/// dependence isn't handled properly on several C-only codepaths.
 class RecoveryExpr final : public Expr,
private llvm::TrailingObjects 
{
 public:


Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -19210,9 +19210,6 @@
 
 ExprResult Sema::CreateRecoveryExpr(SourceLocatio

[PATCH] D83215: [AST][RecoveryExpr] Clarify the documentation of RecoveryExpr.

2020-07-09 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/lib/AST/ComputeDependence.cpp:498
 ExprDependence clang::computeDependence(RecoveryExpr *E) {
-  // Mark the expression as value- and instantiation- dependent to reuse
-  // existing suppressions for dependent code, e.g. avoiding
-  // constant-evaluation.
-  // FIXME: drop type+value+instantiation once Error is sufficient to suppress
-  // bogus dianostics.
+  // RecoveryExpr dependence-bits setting:
+  //   - type-dep is set if we don't know about the type (fallback to an opaque

sammccall wrote:
> I can't really follow this explanation.
> - The first bullet  says when, the other two bullets say why
> - the reasons given don't seem to be very principled ones (e.g. suppressing 
> constant-evaluation is indeed a nice effect of value-dependency, but I don't 
> think it's the *reason* for the value-dependency, rather that the value 
> depends on how the error is resolved)
> - I don't understand the connection between the "setting" list and the 
> "explanations" one.
> 
> 
sorry for the confusion. I have refined the doc, hope it is clearer now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83215



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


[PATCH] D83294: [Fixed Point] Add codegen for fixed-point shifts.

2020-07-09 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan marked an inline comment as done.
ebevhan added inline comments.



Comment at: clang/lib/CodeGen/CGExprScalar.cpp:3603-3604
   auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
-  auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema, true);
+  auto CommonFixedSema = LHSFixedSema.getCommonSemantics(
+  IsShift ? LHSFixedSema : RHSFixedSema, true);
 

leonardchan wrote:
> Could this instead be:
> 
> ```
> auto CommonFixedSema = IsShift ? LHSFixedSema : 
> LHSFixedSema.getCommonSemantics(RHSFixedSema, true);
> ```
> 
> 
In theory, yes, but I'm sort of piggybacking off of D82663, and for the 
signedness to be correct we need to get the 'common' semantic even in the shift 
case.



Comment at: clang/test/Frontend/fixed_point_compound.c:384
+  // CHECK-NEXT:[[TMP4:%.*]] = load i16, i16* @suf, align 2
+  // CHECK-NEXT:[[TMP5:%.*]] = trunc i32 [[TMP3]] to i16
+  // SIGNED-NEXT:   [[TMP6:%.*]] = call i16 @llvm.ushl.sat.i16(i16 [[TMP4]], 
i16 [[TMP5]])

leonardchan wrote:
> This seems very unlikely, but if `i` in this case was a value at least 2^16, 
> the upper half would be cut off and we'd potentially shift by an improper 
> amount for some values of `i` when we should actually clamp to the max value. 
> We should probably still   find the common semantics for both sides if we're 
> doing a shift.
If the value is so large to be cut off by that truncation then the value is 
greater than the bitwidth, which is UB. So I don't think it's an issue.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83294



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


[PATCH] D83213: [AST][RecoveryExpr] Don't set the instantiation-bit.

2020-07-09 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

I think this depends on how we interpret the instantiation-dependent bit. In 
clang, it currently has two semantics:

1. an expression (somehow) depends on a template parameter;
2. an expression is dependent;

Prior to RecoveryExpression being added, 1 and 2 are equal, so we use 
`isInstantiationDependent` to check whether the code is dependent. This is fine.

However since we now generalize the "dependent" concept to mean "depends on a 
template parameter, or an error", checking `isInstantiationDependent()` is 
incomplete to determine the code is dependent.

what we could do?

**Option 1** (what this patch does):

instantiation-dependence still  implies the expression involves a template 
parameter -- if a recovery expression doesn't involves a template parameter, we 
don't set this flag

pros:

- avoid unnecessary instantiations if an AST node doesn't depend on template 
parameters but contain errorss;
- more precise semantics (maybe for better error-tracking, diagnostics), we can 
express a recovery-expr involves a template parameter (`contains-errors` + 
`instantiation-dep`), or not (`contains-erros` + `no instantiation-dep`)

cons:

- as you mentioned above, we violate the "nothing can be dependent if it is not 
instantiation dependent" assumption, which may leads us to fix a long tail of 
bugs (high effort), and the fix is basically adding `containsErrors` to where 
`isInstantiaionDependent` is used.

This makes me feel like we're going back to "use containsErrors everywhere" 
solution. Not sure what pros would buy us, maybe it is not worth the effort.

**Option 2**:

Keep it as it-is now, always set it, then the `instantiation-dependent` would 
mean "an expression depends on a template parameter or an error".

pros:

- everything would work without changing anything!

cons:

- keep using the instantiation name is confusing; we could do clarify the 
document of isInstantiation

While writing this, I'm starting to like the option2, any other thoughts?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83213



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


[PATCH] D79773: [clang-format] Improve clang-formats handling of concepts

2020-07-09 Thread Manuel Klimek via Phabricator via cfe-commits
klimek added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:631-636
+  else if (FormatTok->is(tok::arrow)) {
+// Following the } we can find a trailing return type arrow
+// as part of an implicit conversion constraint.
+nextToken();
+parseStructuralElement();
+  }

I'd have expected this to be just in front of line 629 (if... tok::semi) - does 
that break something? Don't we want to munch the semi after this?



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:2314
+  nextToken();
+  if (FormatTok->Tok.is(tok::less)) {
+while (!FormatTok->Tok.is(tok::greater)) {

MyDeveloperDay wrote:
> miscco wrote:
> > miscco wrote:
> > > I guess you could use `parseBracedList(/*ContinueOnSemicolons=*/false, 
> > > /*IsEnum=*/false,/*ClosingBraceKind=*/tok::greater);` here?
> > To be more specific, I am concerned what happens if you have multiple 
> > template arguments where a linebreak should occur. Is this still happening 
> > here?
> > 
> > 
> > ```
> > template 
> > concept someVeryLongConceptName = 
> > someVeryLongConstraintName1;
> > ```
> This is formatted as
> 
> ```
> template 
> concept someVeryLongConceptName =
> someVeryLongConstraintName1;
> ```
This seems like a very detailed way to parse them; generally, we try to only 
parse rough structure here.


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

https://reviews.llvm.org/D79773



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


[PATCH] D81583: Update SystemZ ABI to handle C++20 [[no_unique_address]] attribute

2020-07-09 Thread Alex Bradbury via Phabricator via cfe-commits
asb added a comment.

This LGTM from a RISC-V perspective. I'll likely follow up with a RISC-V test 
case similar to the SystemZ one post-commit, but given this is really fixing a 
cross-platform ABI issue this seems non-urgent. Thanks for spotting and 
addressing this issue.


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

https://reviews.llvm.org/D81583



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


[clang] b444705 - Make helpers static. NFC.

2020-07-09 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2020-07-09T13:48:56+02:00
New Revision: b44470547e2ec8a52abb67c3f538ecc49ee27970

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

LOG: Make helpers static. NFC.

Added: 


Modified: 
clang/lib/AST/ASTImporter.cpp
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
llvm/lib/IR/AutoUpgrade.cpp
llvm/lib/MC/MCDisassembler/MCDisassembler.cpp
llvm/lib/Target/X86/X86ISelLowering.cpp
llvm/lib/Transforms/Scalar/LowerExpectIntrinsic.cpp
llvm/lib/Transforms/Vectorize/VectorCombine.cpp
mlir/lib/Conversion/SPIRVToLLVM/ConvertSPIRVToLLVM.cpp
mlir/lib/Dialect/Affine/IR/AffineOps.cpp
mlir/lib/Dialect/Linalg/Transforms/Loops.cpp
mlir/test/lib/Transforms/TestLinalgTransforms.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 8ec6db622f0a..fa2421ee826e 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -3655,9 +3655,9 @@ struct FriendCountAndPosition {
 };
 
 template 
-FriendCountAndPosition getFriendCountAndPosition(
+static FriendCountAndPosition getFriendCountAndPosition(
 const FriendDecl *FD,
-std::function GetCanTypeOrDecl) {
+llvm::function_ref GetCanTypeOrDecl) {
   unsigned int FriendCount = 0;
   llvm::Optional FriendPosition;
   const auto *RD = cast(FD->getLexicalDeclContext());
@@ -3679,7 +3679,7 @@ FriendCountAndPosition getFriendCountAndPosition(
   return {FriendCount, *FriendPosition};
 }
 
-FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) {
+static FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) {
   if (FD->getFriendType())
 return getFriendCountAndPosition(FD, [](const FriendDecl *F) {
   if (TypeSourceInfo *TSI = F->getFriendType())

diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 29393c2ca02b..8b575f4f4759 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -726,7 +726,8 @@ StdLibraryFunctionsChecker::findFunctionSummary(const 
CallEvent &Call,
   return findFunctionSummary(FD, C);
 }
 
-llvm::Optional lookupType(StringRef Name, const ASTContext &ACtx) {
+static llvm::Optional lookupType(StringRef Name,
+   const ASTContext &ACtx) {
   IdentifierInfo &II = ACtx.Idents.get(Name);
   auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(&II);
   if (LookupRes.size() == 0)

diff  --git a/llvm/lib/IR/AutoUpgrade.cpp b/llvm/lib/IR/AutoUpgrade.cpp
index 3179cb5b4e36..1e8fdb506619 100644
--- a/llvm/lib/IR/AutoUpgrade.cpp
+++ b/llvm/lib/IR/AutoUpgrade.cpp
@@ -4167,7 +4167,7 @@ void llvm::UpgradeSectionAttributes(Module &M) {
   }
 }
 
-
+namespace {
 // Prior to LLVM 10.0, the strictfp attribute could be used on individual
 // callsites within a function that did not also have the strictfp attribute.
 // Since 10.0, if strict FP semantics are needed within a function, the
@@ -4185,7 +4185,7 @@ struct StrictFPUpgradeVisitor : public 
InstVisitor {
   void visitCallBase(CallBase &Call) {
 if (!Call.isStrictFP())
   return;
-if (dyn_cast(&Call))
+if (isa(&Call))
   return;
 // If we get here, the caller doesn't have the strictfp attribute
 // but this callsite does. Replace the strictfp attribute with nobuiltin.
@@ -4193,6 +4193,7 @@ struct StrictFPUpgradeVisitor : public 
InstVisitor {
 Call.addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
   }
 };
+} // namespace
 
 void llvm::UpgradeFunctionAttributes(Function &F) {
   // If a function definition doesn't have the strictfp attribute,

diff  --git a/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp 
b/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp
index 9cdacb64c4f4..a58e8f6d9bcc 100644
--- a/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp
+++ b/llvm/lib/MC/MCDisassembler/MCDisassembler.cpp
@@ -47,7 +47,7 @@ void 
MCDisassembler::setSymbolizer(std::unique_ptr Symzer) {
   case XCOFF::XMC_##A: 
\
 return P;
 
-uint8_t getSMCPriority(XCOFF::StorageMappingClass SMC) {
+static uint8_t getSMCPriority(XCOFF::StorageMappingClass SMC) {
   switch (SMC) {
 SMC_PCASE(PR, 1)
 SMC_PCASE(RO, 1)

diff  --git a/llvm/lib/Target/X86/X86ISelLowering.cpp 
b/llvm/lib/Target/X86/X86ISelLowering.cpp
index 017bfba94b61..9f3321922d6a 100644
--- a/llvm/lib/Target/X86/X86ISelLowering.cpp
+++ b/llvm/lib/Target/X86/X86ISelLowering.cpp
@@ -42429,7 +42429,7 @@ static SDValue PromoteMaskArithmetic(SDNode *N, 
SelectionDAG &DAG,
   }
 }
 
-unsigned convertIntLogicToFPLogicOpcode(unsigned Op

[PATCH] D82663: [CodeGen] Have CodeGen for fixed-point unsigned with padding emit signed operations.

2020-07-09 Thread Bevin Hansson via Phabricator via cfe-commits
ebevhan added a comment.

In D82663#2140507 , @leonardchan wrote:

> In D82663#2130355 , @ebevhan wrote:
>
> > Well, it's not so much as adding the bit, but adding the information that 
> > the bit exists. That means either new intrinsics for all of the operations, 
> > or adding flags to the existing ones. That's a fair bit of added 
> > complexity. Also,  +  would do virtually 
> > the exact same thing as the new unsigned-with-padding operations, so the 
> > utility of adding all of it is a bit questionable.
>
>
> Could the work involved just be adding the flags, then in 
> `llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp` for unsigned 
> operations, choosing between the signed/unsigned underlying `ISD` when 
> lowering intrinsics to DAG? I think you could just pass the padding bit to 
> `FixedPointIntrinsicToOpcode` and handle it from there. This is just off the 
> top of my head so I could be missing other things.


It wouldn't just be restricted to fixed-point intrinsics, though. It would have 
to be added to intrinsics like uadd.sat and usub.sat as well, which aren't 
really tied to fixed-point at all. Changing the semantics of those intrinsics 
would be unfortunate for targets that have started using them for their own 
instructions. I don't really think it's an option to move the padding semantic 
info into the IR; the intrinsic interface is fairly lean, and I think keeping 
it that way is a good idea.

I could change the emission to not be so heavy-handed and only use signed 
operations for the intrinsics, rather than everything. That makes 
EmitFixedPointBinOp a bit messier, though.




Comment at: clang/lib/Basic/FixedPoint.cpp:143-158
+  // For codegen purposes, make unsigned with padding semantics signed instead.
+  // This means that we will generate signed operations. The result from these
+  // operations is defined, since ending up with a negative result is undefined
+  // for nonsaturating semantics, and for saturating semantics we will
+  // perform a clamp-to-zero in the last conversion to result semantics (since
+  // we are going from saturating signed to saturating unsigned).
+  //

leonardchan wrote:
> If this is exclusively for codegen purposes with binary operations, would it 
> be clearer to move this to `EmitFixedPointBinOp`? If 
> `UnsignedPaddingIsSigned` doesn't need to be used for stuff like constant 
> evaluation, it might be clearer not to provide it for everyone.
FixedPointSemantics is immutable except for saturation, unfortunately. I'd end 
up having to reconstruct the semantics object from scratch immediately after 
calling getCommonSemantics.



Comment at: clang/test/Frontend/fixed_point_add.c:290-294
+  // UNSIGNED-NEXT: [[USA_EXT:%[a-z0-9]+]] = zext i16 [[USA]] to i40
+  // UNSIGNED-NEXT: [[I_EXT:%[a-z0-9]+]] = zext i32 [[I]] to i40
+  // UNSIGNED-NEXT: [[I:%[a-z0-9]+]] = shl i40 [[I_EXT]], 7
+  // UNSIGNED-NEXT: [[SUM:%[0-9]+]] = add i40 [[USA_EXT]], [[I]]
+  // UNSIGNED-NEXT: [[RES:%[a-z0-9]+]] = trunc i40 [[SUM]] to i16

leonardchan wrote:
> If this is a workaround for not being able to convey the padding bit to LLVM 
> intrinsics, I think we should only limit changes to instances we would use 
> intrinsics.
I suppose this makes sense, but the logic will be a bit more convoluted in that 
case.

It is true that in most cases, the clamp-to-zero resulting from the 
signed->unsigned conversion at the end isn't even necessary. For addition, 
multiplication, division and shift, the result of positive operands can never 
become negative, so there's no point to the clamp.

It just felt more general to do it for all of them instead of littering 
EmitFixedPointBinOp with special cases. But perhaps it would be better to deal 
with each case individually instead. Still feels like that would make the 
implementation less clean.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82663



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


[PATCH] D83419: [clangd] Add error() function for creating formatv-style llvm::Errors. NFC

2020-07-09 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

> Sorry, I should give some reasons here:

These are sensible reasons. My only (not a strong) concern is that "error" is 
quite special, we need to be careful to choose it -- note that there is an 
`error` function in glibc which is used for error-reporting.

maybe there are other better names (`stringError`?) other than 
`createError`/`makeError`.

> I guess makeError is still better than the status quo, but not enough to feel 
> motivated to clean this up right now. Maybe someone else wants to pick this 
> up?

unless you strongly insist on `error` name, I'm happy to help with (looks like 
it's just a low-hanging rename fruit). I think this is a nice cleanup, we 
should make it happen (either using `error` or other names).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83419



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


[PATCH] D72705: [analyzer] Added new checker 'alpha.unix.ErrorReturn'.

2020-07-09 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

After reading @martong's comment D72705#2035844 
 and @balazske's comment 
D72705#2086994 , I think there is a 
need to argue across all paths of execution within the function, and as such 
this is a dataflow problem.

In D72705#2086994 , @balazske wrote:

>   c = fgetc(fd);
>   if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@' || c == EOF || 
> c == '\n') { ... }
>  
>
>
> The first `c == '+'` is found by the checker and reported as false positive 
> (the later `c == EOF` is not found). Such a case can be found if the checker 
> can collect expressions that are separated by `||` or `&&` and the symbol to 
> check occurs in these and there is only a simple comparison.


Our current dataflow analyses definitely have to make judgement of which block 
(and in that, which `CFGStmt`s) **reads** or **writes** a variable/expression. 
You can actually register an observer for expression writes (or in other terms, 
//kills//), so I don't think it'd be too challenging to do this with reads.

`DeadStoresChecker` is a great example for a checker that utilizes dataflow and 
pathsensitive analyses.

In D72705#1863381 , @Szelethus wrote:

> In D72705#1859711 , @balazske wrote:
>
> > Generally, is it a problem if there are multiple checkers that may detect 
> > same defects but with different approach?
>
>
> If avoidable, yes. If not, I think its an acceptable sacrifice.


Mind that since D80905  landed, the tone has 
shifted, if a more checker detects a specific bug (like double free) but a more 
general checker does as well (as passing garbage value to a function) we're 
okay with that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72705



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


[PATCH] D82800: [OPENMP50] extend array section for stride (Parsing/Sema/AST)

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

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82800



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


[PATCH] D83474: Add support for specifying only a denormalizer

2020-07-09 Thread Daniel Grumberg via Phabricator via cfe-commits
dang created this revision.
dang added a reviewer: Bigcheese.
Herald added subscribers: llvm-commits, cfe-commits, dexonsmith.
Herald added projects: clang, LLVM.

This commit adds a denormalyzer for optimization level.
Depends on D83406 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83474

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp
  llvm/include/llvm/Option/OptParser.td
  llvm/utils/TableGen/OptParserEmitter.cpp

Index: llvm/utils/TableGen/OptParserEmitter.cpp
===
--- llvm/utils/TableGen/OptParserEmitter.cpp
+++ llvm/utils/TableGen/OptParserEmitter.cpp
@@ -63,8 +63,11 @@
 public:
   using Ptr = std::unique_ptr;
 
-  const char *MacroName;
+  static constexpr const char *MacroNameSerializing = "OPTION_WITH_SERIALIZING";
+  static constexpr const char *MacroNameParsing = "OPTION_WITH_PARSING";
+
   const Record &R;
+  bool CanParse;
   bool ShouldAlwaysEmit;
   StringRef KeyPath;
   StringRef DefaultValue;
@@ -95,31 +98,36 @@
   static constexpr const char *ValueTablesDecl =
   "static const SimpleEnumValueTable SimpleEnumValueTables[] = ";
 
-  MarshallingInfo(const Record &R)
-  : MacroName("OPTION_WITH_MARSHALLING"), R(R) {}
-  MarshallingInfo(const char *MacroName, const Record &R)
-  : MacroName(MacroName), R(R){};
+  MarshallingInfo(const Record &R) : R(R) {}
 
   virtual ~MarshallingInfo() = default;
 
-  virtual void emit(raw_ostream &OS) const {
-write_cstring(OS, StringRef(getOptionSpelling(R)));
-OS << ", ";
-OS << ShouldAlwaysEmit;
-OS << ", ";
-OS << KeyPath;
-OS << ", ";
-emitScopedNormalizedValue(OS, DefaultValue);
-OS << ", ";
-OS << Normalizer;
-OS << ", ";
-OS << Denormalizer;
-OS << ", ";
-OS << ValueMerger;
+  virtual void
+  emitParsing(raw_ostream &OS,
+  llvm::function_ref
+  WriteOptRecordFields) const {
+if (!CanParse)
+  return;
+OS << "#ifdef " << MacroNameParsing << "\n";
+OS << MacroNameParsing << "(";
+WriteOptRecordFields(OS, R);
 OS << ", ";
-OS << ValueExtractor;
+emitParsingFields(OS);
+OS << ")\n";
+OS << "#endif // " << MacroNameParsing << "\n";
+  }
+
+  virtual void
+  emitSerialiazing(raw_ostream &OS,
+   llvm::function_ref
+   WriteOptRecordFields) const {
+OS << "#ifdef " << MacroNameSerializing << "\n";
+OS << MacroNameSerializing << "(";
+WriteOptRecordFields(OS, R);
 OS << ", ";
-OS << TableIndex;
+emitSerializingFields(OS);
+OS << ")\n";
+OS << "#endif // " << MacroNameSerializing << "\n";
   }
 
   Optional emitValueTable(raw_ostream &OS) const {
@@ -138,6 +146,35 @@
 return StringRef(ValueTableName);
   }
 
+protected:
+  void emitParsingFields(raw_ostream &OS) const {
+OS << KeyPath;
+OS << ", ";
+emitScopedNormalizedValue(OS, DefaultValue);
+OS << ", ";
+OS << Normalizer;
+OS << ", ";
+OS << ValueMerger;
+OS << ", ";
+OS << TableIndex;
+  }
+
+  void emitSerializingFields(raw_ostream &OS) const {
+OS << KeyPath;
+OS << ", ";
+emitScopedNormalizedValue(OS, DefaultValue);
+OS << ", ";
+write_cstring(OS, StringRef(getOptionSpelling(R)));
+OS << ", ";
+OS << ShouldAlwaysEmit;
+OS << ", ";
+OS << Denormalizer;
+OS << ", ";
+OS << ValueExtractor;
+OS << ", ";
+OS << TableIndex;
+  }
+
 private:
   void emitScopedNormalizedValue(raw_ostream &OS,
  StringRef NormalizedValue) const {
@@ -154,24 +191,45 @@
   const Record &NegOption;
 
   MarshallingInfoBooleanFlag(const Record &Option, const Record &NegOption)
-  : MarshallingInfo("OPTION_WITH_MARSHALLING_BOOLEAN", Option),
-NegOption(NegOption) {}
-
-  void emit(raw_ostream &OS) const override {
-MarshallingInfo::emit(OS);
+  : MarshallingInfo(Option), NegOption(NegOption) {}
+
+  void emitParsing(raw_ostream &OS,
+   llvm::function_ref
+   WriteOptRecordFields) const override {
+if (!CanParse)
+  return;
+OS << "#ifdef " << MacroNameParsing << "_BOOLEAN\n";
+OS << MacroNameParsing << "_BOOLEAN(";
+WriteOptRecordFields(OS, R);
+OS << ", ";
+emitParsingFields(OS);
 OS << ", ";
 OS << getOptionName(NegOption);
+OS << ")\n";
+OS << "#endif // " << MacroNameParsing << "_BOOLEAN\n";
+  }
+
+  void emitSerialiazing(raw_ostream &OS,
+llvm::function_ref
+WriteOptRecordFields) const override {
+OS << "#ifdef " << MacroNameSerializing << "_BOOLEAN\n";
+OS << MacroNameSerializing << "_BOOLEAN(";
+WriteOptRecordFields(OS, R);
+OS << ", ";
+emitSerializingFields(OS);
 OS << ", ";
 write_cstring(OS, getOptionSpelling(NegOption));
+OS << ")\n";
+OS << "#endif // " <

[PATCH] D83475: [analyzer] Add CTUImportCppThreshold for C++ files

2020-07-09 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: gamesh411, Szelethus.
Herald added subscribers: cfe-commits, ASDenysPetrov, steakhal, Charusso, 
dkrupp, donat.nagy, mikhail.ramalho, a.sidorin, rnkovacs, szepet, 
baloghadamsoftware, xazax.hun, whisperity.
Herald added a project: clang.

The default CTUImportThreshold (8) seems to be too conservative with C projects.
We increase this value to 24 and we introduce another threshold for C++ source
files (defaulted to 8) because their AST is way more compilcated than C source
files.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83475

Files:
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/ctu-import-threshold.c


Index: clang/test/Analysis/ctu-import-threshold.c
===
--- clang/test/Analysis/ctu-import-threshold.c
+++ clang/test/Analysis/ctu-import-threshold.c
@@ -1,5 +1,6 @@
 // Ensure analyzer option 'ctu-import-threshold' is a recognized option.
 //
 // RUN: %clang_cc1 -analyze -analyzer-config ctu-import-threshold=30 -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-config ctu-import-cpp-threshold=30 
-verify %s
 //
 // expected-no-diagnostics
Index: clang/test/Analysis/analyzer-config.c
===
--- clang/test/Analysis/analyzer-config.c
+++ clang/test/Analysis/analyzer-config.c
@@ -42,7 +42,8 @@
 // CHECK-NEXT: cplusplus.Move:WarnOn = KnownsAndLocals
 // CHECK-NEXT: crosscheck-with-z3 = false
 // CHECK-NEXT: ctu-dir = ""
-// CHECK-NEXT: ctu-import-threshold = 8
+// CHECK-NEXT: ctu-import-cpp-threshold = 8
+// CHECK-NEXT: ctu-import-threshold = 24
 // CHECK-NEXT: ctu-index-name = externalDefMap.txt
 // CHECK-NEXT: ctu-invocation-list = invocations.yaml
 // CHECK-NEXT: deadcode.DeadStores:ShowFixIts = false
Index: clang/lib/CrossTU/CrossTranslationUnit.cpp
===
--- clang/lib/CrossTU/CrossTranslationUnit.cpp
+++ clang/lib/CrossTU/CrossTranslationUnit.cpp
@@ -367,7 +367,9 @@
 CompilerInstance &CI)
 : Loader(CI, CI.getAnalyzerOpts()->CTUDir,
  CI.getAnalyzerOpts()->CTUInvocationList),
-  LoadGuard(CI.getAnalyzerOpts()->CTUImportThreshold) {}
+  LoadGuard(CI.getASTContext().getLangOpts().CPlusPlus
+? CI.getAnalyzerOpts()->CTUImportCppThreshold
+: CI.getAnalyzerOpts()->CTUImportThreshold) {}
 
 llvm::Expected
 CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFile(
Index: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
===
--- clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -321,9 +321,16 @@
 ANALYZER_OPTION(unsigned, CTUImportThreshold, "ctu-import-threshold",
 "The maximal amount of translation units that is considered "
 "for import when inlining functions during CTU analysis. "
-"Lowering this threshold can alleviate the memory burder of "
+"Lowering this threshold can alleviate the memory burden of "
 "analysis with many interdependent definitions located in "
-"various translation units.",
+"various translation units. This is valid only for non C++ "
+"source files.",
+24u)
+
+ANALYZER_OPTION(unsigned, CTUImportCppThreshold, "ctu-import-cpp-threshold",
+"The maximal amount of translation units that is considered "
+"for import when inlining functions during CTU analysis of C++ 
"
+"source files. ",
 8u)
 
 ANALYZER_OPTION(


Index: clang/test/Analysis/ctu-import-threshold.c
===
--- clang/test/Analysis/ctu-import-threshold.c
+++ clang/test/Analysis/ctu-import-threshold.c
@@ -1,5 +1,6 @@
 // Ensure analyzer option 'ctu-import-threshold' is a recognized option.
 //
 // RUN: %clang_cc1 -analyze -analyzer-config ctu-import-threshold=30 -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-config ctu-import-cpp-threshold=30 -verify %s
 //
 // expected-no-diagnostics
Index: clang/test/Analysis/analyzer-config.c
===
--- clang/test/Analysis/analyzer-config.c
+++ clang/test/Analysis/analyzer-config.c
@@ -42,7 +42,8 @@
 // CHECK-NEXT: cplusplus.Move:WarnOn = KnownsAndLocals
 // CHECK-NEXT: crosscheck-with-z3 = false
 // CHECK-NEXT: ctu-dir = ""
-// CHECK-NEXT: ctu-import-threshold = 8
+// CHECK-NEXT: ctu-import-cpp-threshold = 8
+// CHECK-NEXT: ctu-import-threshold = 24
 // CHECK-NEXT: ctu-index-name = externalDefMap.txt
 // CHECK-NEXT: ctu-invocation-list = invocations.yaml
 // CHECK-NEXT

[PATCH] D82087: AMDGPU/clang: Add builtins for llvm.amdgcn.ballot

2020-07-09 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: clang/lib/Basic/Targets/AMDGPU.cpp:293
+"wavefrontsize32" : "wavefrontsize64";
+  Features.insert(std::make_pair(DefaultWaveSizeFeature, true));
+}

what's the default wave front size in backend for gfx10* before this change?



Comment at: clang/test/CodeGenOpenCL/amdgpu-features.cl:7
+// RUN: %clang_cc1 -triple amdgcn -S -emit-llvm -o - %s | FileCheck 
--check-prefix=NOCPU %s
+// RUN: %clang_cc1 -triple amdgcn -target-feature +wavefrontsize32 -S 
-emit-llvm -o - %s | FileCheck --check-prefix=NOCPU-WAVE32 %s
+// RUN: %clang_cc1 -triple amdgcn -target-feature +wavefrontsize64 -S 
-emit-llvm -o - %s | FileCheck --check-prefix=NOCPU-WAVE64 %s

what happens if both +wavefrontsize32 and +wavefrontsize64 are specified?


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

https://reviews.llvm.org/D82087



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


[PATCH] D83407: [analyzer][StdLibraryFunctionsChecker] Add POSIX networking functions

2020-07-09 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 276715.
martong added a comment.

- Add getRestrictTy


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83407

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-POSIX-socket-sockaddr.cpp
  clang/test/Analysis/std-c-library-functions-POSIX.c

Index: clang/test/Analysis/std-c-library-functions-POSIX.c
===
--- clang/test/Analysis/std-c-library-functions-POSIX.c
+++ clang/test/Analysis/std-c-library-functions-POSIX.c
@@ -79,6 +79,22 @@
 // CHECK: Loaded summary for: int execv(const char *path, char *const argv[])
 // CHECK: Loaded summary for: int execvp(const char *file, char *const argv[])
 // CHECK: Loaded summary for: int getopt(int argc, char *const argv[], const char *optstring)
+// CHECK: Loaded summary for: int accept(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len)
+// CHECK: Loaded summary for: int bind(int socket, __CONST_SOCKADDR_ARG address, socklen_t address_len)
+// CHECK: Loaded summary for: int getpeername(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len)
+// CHECK: Loaded summary for: int getsockname(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len)
+// CHECK: Loaded summary for: int connect(int socket, __CONST_SOCKADDR_ARG address, socklen_t address_len)
+// CHECK: Loaded summary for: ssize_t recvfrom(int socket, void *restrict buffer, size_t length, int flags, __SOCKADDR_ARG address, socklen_t *restrict address_len)
+// CHECK: Loaded summary for: ssize_t sendto(int socket, const void *message, size_t length, int flags, __CONST_SOCKADDR_ARG dest_addr, socklen_t dest_len)
+// CHECK: Loaded summary for: int listen(int sockfd, int backlog)
+// CHECK: Loaded summary for: ssize_t recv(int sockfd, void *buf, size_t len, int flags)
+// CHECK: Loaded summary for: ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags)
+// CHECK: Loaded summary for: ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags)
+// CHECK: Loaded summary for: int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len)
+// CHECK: Loaded summary for: int getsockopt(int socket, int level, int option_name, void *restrict option_value, socklen_t *restrict option_len)
+// CHECK: Loaded summary for: ssize_t send(int sockfd, const void *buf, size_t len, int flags)
+// CHECK: Loaded summary for: int socketpair(int domain, int type, int protocol, int sv[2])
+// CHECK: Loaded summary for: int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen, char *restrict node, socklen_t nodelen, char *restrict service, socklen_t servicelen, int flags)
 
 long a64l(const char *str64);
 char *l64a(long value);
@@ -171,6 +187,47 @@
 int execvp(const char *file, char *const argv[]);
 int getopt(int argc, char *const argv[], const char *optstring);
 
+// In some libc implementations, sockaddr parameter is a transparent
+// union of the underlying sockaddr_ pointers instead of being a
+// pointer to struct sockaddr.
+// We match that with the joker Irrelevant type.
+struct sockaddr;
+struct sockaddr_at;
+#define __SOCKADDR_ALLTYPES\
+  __SOCKADDR_ONETYPE(sockaddr) \
+  __SOCKADDR_ONETYPE(sockaddr_at)
+#define __SOCKADDR_ONETYPE(type) struct type *__restrict __##type##__;
+#define __SOCKADDR_ONETYPE(type) struct type *__restrict __##type##__;
+typedef union {
+  __SOCKADDR_ALLTYPES
+} __SOCKADDR_ARG __attribute__((__transparent_union__));
+#undef __SOCKADDR_ONETYPE
+#define __SOCKADDR_ONETYPE(type) const struct type *__restrict __##type##__;
+typedef union {
+  __SOCKADDR_ALLTYPES
+} __CONST_SOCKADDR_ARG __attribute__((__transparent_union__));
+#undef __SOCKADDR_ONETYPE
+typedef unsigned socklen_t;
+
+int accept(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len);
+int bind(int socket, __CONST_SOCKADDR_ARG address, socklen_t address_len);
+int getpeername(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len);
+int getsockname(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len);
+int connect(int socket, __CONST_SOCKADDR_ARG address, socklen_t address_len);
+ssize_t recvfrom(int socket, void *restrict buffer, size_t length, int flags, __SOCKADDR_ARG address, socklen_t *restrict address_len);
+ssize_t sendto(int socket, const void *message, size_t length, int flags, __CONST_SOCKADDR_ARG dest_addr, socklen_t dest_len);
+
+int listen(int sockfd, int backlog);
+ssize_t recv(int sockfd, void *buf, size_t len, int flags);
+struct msghdr;
+ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
+ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
+int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len);
+int getsockopt(int socket, int level, int option_name, void *restrict o

[PATCH] D83407: [analyzer][StdLibraryFunctionsChecker] Add POSIX networking functions

2020-07-09 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 276716.
martong marked 2 inline comments as done and an inline comment as not done.
martong added a comment.

- Remove redundant line from test code


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83407

Files:
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/test/Analysis/std-c-library-functions-POSIX-socket-sockaddr.cpp
  clang/test/Analysis/std-c-library-functions-POSIX.c

Index: clang/test/Analysis/std-c-library-functions-POSIX.c
===
--- clang/test/Analysis/std-c-library-functions-POSIX.c
+++ clang/test/Analysis/std-c-library-functions-POSIX.c
@@ -79,6 +79,22 @@
 // CHECK: Loaded summary for: int execv(const char *path, char *const argv[])
 // CHECK: Loaded summary for: int execvp(const char *file, char *const argv[])
 // CHECK: Loaded summary for: int getopt(int argc, char *const argv[], const char *optstring)
+// CHECK: Loaded summary for: int accept(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len)
+// CHECK: Loaded summary for: int bind(int socket, __CONST_SOCKADDR_ARG address, socklen_t address_len)
+// CHECK: Loaded summary for: int getpeername(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len)
+// CHECK: Loaded summary for: int getsockname(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len)
+// CHECK: Loaded summary for: int connect(int socket, __CONST_SOCKADDR_ARG address, socklen_t address_len)
+// CHECK: Loaded summary for: ssize_t recvfrom(int socket, void *restrict buffer, size_t length, int flags, __SOCKADDR_ARG address, socklen_t *restrict address_len)
+// CHECK: Loaded summary for: ssize_t sendto(int socket, const void *message, size_t length, int flags, __CONST_SOCKADDR_ARG dest_addr, socklen_t dest_len)
+// CHECK: Loaded summary for: int listen(int sockfd, int backlog)
+// CHECK: Loaded summary for: ssize_t recv(int sockfd, void *buf, size_t len, int flags)
+// CHECK: Loaded summary for: ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags)
+// CHECK: Loaded summary for: ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags)
+// CHECK: Loaded summary for: int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len)
+// CHECK: Loaded summary for: int getsockopt(int socket, int level, int option_name, void *restrict option_value, socklen_t *restrict option_len)
+// CHECK: Loaded summary for: ssize_t send(int sockfd, const void *buf, size_t len, int flags)
+// CHECK: Loaded summary for: int socketpair(int domain, int type, int protocol, int sv[2])
+// CHECK: Loaded summary for: int getnameinfo(const struct sockaddr *restrict sa, socklen_t salen, char *restrict node, socklen_t nodelen, char *restrict service, socklen_t servicelen, int flags)
 
 long a64l(const char *str64);
 char *l64a(long value);
@@ -171,6 +187,46 @@
 int execvp(const char *file, char *const argv[]);
 int getopt(int argc, char *const argv[], const char *optstring);
 
+// In some libc implementations, sockaddr parameter is a transparent
+// union of the underlying sockaddr_ pointers instead of being a
+// pointer to struct sockaddr.
+// We match that with the joker Irrelevant type.
+struct sockaddr;
+struct sockaddr_at;
+#define __SOCKADDR_ALLTYPES\
+  __SOCKADDR_ONETYPE(sockaddr) \
+  __SOCKADDR_ONETYPE(sockaddr_at)
+#define __SOCKADDR_ONETYPE(type) struct type *__restrict __##type##__;
+typedef union {
+  __SOCKADDR_ALLTYPES
+} __SOCKADDR_ARG __attribute__((__transparent_union__));
+#undef __SOCKADDR_ONETYPE
+#define __SOCKADDR_ONETYPE(type) const struct type *__restrict __##type##__;
+typedef union {
+  __SOCKADDR_ALLTYPES
+} __CONST_SOCKADDR_ARG __attribute__((__transparent_union__));
+#undef __SOCKADDR_ONETYPE
+typedef unsigned socklen_t;
+
+int accept(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len);
+int bind(int socket, __CONST_SOCKADDR_ARG address, socklen_t address_len);
+int getpeername(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len);
+int getsockname(int socket, __SOCKADDR_ARG address, socklen_t *restrict address_len);
+int connect(int socket, __CONST_SOCKADDR_ARG address, socklen_t address_len);
+ssize_t recvfrom(int socket, void *restrict buffer, size_t length, int flags, __SOCKADDR_ARG address, socklen_t *restrict address_len);
+ssize_t sendto(int socket, const void *message, size_t length, int flags, __CONST_SOCKADDR_ARG dest_addr, socklen_t dest_len);
+
+int listen(int sockfd, int backlog);
+ssize_t recv(int sockfd, void *buf, size_t len, int flags);
+struct msghdr;
+ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);
+ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
+int setsockopt(int socket, int level, int option_name, const void *option_value, socklen_t option_len);
+int getsockopt(int socket, int level, int option

[PATCH] D83407: [analyzer][StdLibraryFunctionsChecker] Add POSIX networking functions

2020-07-09 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D83407#2141075 , @balazske wrote:

> Are not some functions missing from the list (`shutdown`, `sockatmark`, 
> `socket`) (these come from )? And `getnameinfo` comes from 
>  with many other functions that are not added.


Yes, there are missing functions, this is not a comprehensive list. I try to be 
careful in the sense that I am adding only those functions that have a summary 
in Cppcheck because those constraints are already validated by their community. 
Of course, the list can be extended anytime, contributions are welcome from 
anybody.




Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1722
+  ACtx.getPointerType(StructSockaddrTy->withConst());
+  StructSockaddrPtrRestrictTy =
+  ACtx.getLangOpts().C99 ? ACtx.getRestrictType(*StructSockaddrPtrTy)

balazske wrote:
> There could be a generic form of getting the restrict type for a type so 
> something like this can be done (this is used relatively often):
> `getRestrictTypeIfApplicable(ACtx, StructSockaddrPtrTy)`
> 
Yes, absolutely, good idea!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83407



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


[PATCH] D83478: [OPENMP]Fix compiler crash for target data directive without actual target codegen.

2020-07-09 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev created this revision.
ABataev added a reviewer: jdoerfert.
Herald added subscribers: sstefan1, guansong, yaxunl.
Herald added a project: clang.

Need to privatize addresses of the captured variables when trying to
emit the body of the target data directive in no target codegen mode.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83478

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/test/OpenMP/target_data_codegen.cpp


Index: clang/test/OpenMP/target_data_codegen.cpp
===
--- clang/test/OpenMP/target_data_codegen.cpp
+++ clang/test/OpenMP/target_data_codegen.cpp
@@ -491,4 +491,23 @@
   {++arg;}
 }
 #endif
+///==///
+// RUN: %clang_cc1 -DCK7 -verify -fopenmp -x c++ -triple 
powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefix 
CK7 --check-prefix CK7-64
+// RUN: %clang_cc1 -DCK7 -fopenmp -x c++ -std=c++11 -triple 
powerpc64le-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -x c++ -triple powerpc64le-unknown-unknown 
-std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s  
--check-prefix CK7 --check-prefix CK7-64
+
+// RUN: %clang_cc1 -DCK7 -verify -fopenmp-simd -x c++ -triple 
powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix 
SIMD-ONLY7 %s
+// RUN: %clang_cc1 -DCK7 -fopenmp-simd -x c++ -std=c++11 -triple 
powerpc64le-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown 
-std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck 
--check-prefix SIMD-ONLY7 %s
+// SIMD-ONLY7-NOT: {{__kmpc|__tgt}}
+#ifdef CK7
+// CK7: test_device_ptr_addr
+void test_device_ptr_addr(int arg) {
+  int *p;
+  // CK7: add nsw i32
+  // CK7: add nsw i32
+  #pragma omp target data use_device_ptr(p) use_device_addr(arg)
+  { ++arg, ++(*p); }
+}
+#endif
 #endif
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -6077,6 +6077,7 @@
 (void)PrivateScope.Privatize();
 RCG(CGF);
   } else {
+OMPLexicalScope Scope(CGF, S, OMPD_unknown);
 RCG(CGF);
   }
 };


Index: clang/test/OpenMP/target_data_codegen.cpp
===
--- clang/test/OpenMP/target_data_codegen.cpp
+++ clang/test/OpenMP/target_data_codegen.cpp
@@ -491,4 +491,23 @@
   {++arg;}
 }
 #endif
+///==///
+// RUN: %clang_cc1 -DCK7 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck %s --check-prefix CK7 --check-prefix CK7-64
+// RUN: %clang_cc1 -DCK7 -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s  --check-prefix CK7 --check-prefix CK7-64
+
+// RUN: %clang_cc1 -DCK7 -verify -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY7 %s
+// RUN: %clang_cc1 -DCK7 -fopenmp-simd -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY7 %s
+// SIMD-ONLY7-NOT: {{__kmpc|__tgt}}
+#ifdef CK7
+// CK7: test_device_ptr_addr
+void test_device_ptr_addr(int arg) {
+  int *p;
+  // CK7: add nsw i32
+  // CK7: add nsw i32
+  #pragma omp target data use_device_ptr(p) use_device_addr(arg)
+  { ++arg, ++(*p); }
+}
+#endif
 #endif
Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -6077,6 +6077,7 @@
 (void)PrivateScope.Privatize();
 RCG(CGF);
   } else {
+OMPLexicalScope Scope(CGF, S, OMPD_unknown);
 RCG(CGF);
   }
 };
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D83475: [analyzer] Add CTUImportCppThreshold for C++ files

2020-07-09 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 accepted this revision.
gamesh411 added a comment.
This revision is now accepted and ready to land.

It will be interesting to see how different C and C++ projects will prove in 
terms of AST complexity, and Decl-size, but I understand that for now, these 
two options are necessary to not penalize C project analysis because of C++ AST 
complexity.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83475



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


[PATCH] D83480: Refactored NumericLiteralParser to not require a Preprocessor

2020-07-09 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

We would like to use NumericLiteralParser in the implementation of the
syntax tree builder, and plumbing a preprocessor there seems
inconvenient and superfluous.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83480

Files:
  clang/include/clang/Lex/LiteralSupport.h
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPExpressions.cpp
  clang/lib/Lex/Preprocessor.cpp
  clang/lib/Sema/SemaExpr.cpp

Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -3634,7 +3634,9 @@
   if (Invalid)
 return ExprError();
 
-  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
+  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
+   PP.getSourceManager(), PP.getLangOpts(),
+   PP.getTargetInfo(), PP.getDiagnostics());
   if (Literal.hadError)
 return ExprError();
 
Index: clang/lib/Lex/Preprocessor.cpp
===
--- clang/lib/Lex/Preprocessor.cpp
+++ clang/lib/Lex/Preprocessor.cpp
@@ -1370,7 +1370,9 @@
   StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
   if (NumberInvalid)
 return false;
-  NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
+  NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
+   getLangOpts(), getTargetInfo(),
+   getDiagnostics());
   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
 return false;
   llvm::APInt APVal(64, 0);
Index: clang/lib/Lex/PPExpressions.cpp
===
--- clang/lib/Lex/PPExpressions.cpp
+++ clang/lib/Lex/PPExpressions.cpp
@@ -295,7 +295,9 @@
 if (NumberInvalid)
   return true; // a diagnostic was already reported
 
-NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
+NumericLiteralParser Literal(Spelling, PeekTok.getLocation(),
+ PP.getSourceManager(), PP.getLangOpts(),
+ PP.getTargetInfo(), PP.getDiagnostics());
 if (Literal.hadError)
   return true; // a diagnostic was already reported.
 
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -525,8 +525,12 @@
 ///
 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
SourceLocation TokLoc,
-   Preprocessor &PP)
-  : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
+   const SourceManager &SM,
+   const LangOptions &LangOpts,
+   const TargetInfo &Target,
+   DiagnosticsEngine &Diags)
+: SM(SM), LangOpts(LangOpts), Target(Target), Diags(Diags),
+  ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
 
   // This routine assumes that the range begin/end matches the regex for integer
   // and FP constants (specifically, the 'pp-number' regex), and assumes that
@@ -572,7 +576,7 @@
   checkSeparator(TokLoc, s, CSK_AfterDigits);
 
   // Initial scan to lookahead for fixed point suffix.
-  if (PP.getLangOpts().FixedPoint) {
+  if (LangOpts.FixedPoint) {
 for (const char *c = s; c != ThisTokEnd; ++c) {
   if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
 saw_fixed_point_suffix = true;
@@ -592,14 +596,14 @@
 switch (*s) {
 case 'R':
 case 'r':
-  if (!PP.getLangOpts().FixedPoint) break;
+  if (!LangOpts.FixedPoint) break;
   if (isFract || isAccum) break;
   if (!(saw_period || saw_exponent)) break;
   isFract = true;
   continue;
 case 'K':
 case 'k':
-  if (!PP.getLangOpts().FixedPoint) break;
+  if (!LangOpts.FixedPoint) break;
   if (isFract || isAccum) break;
   if (!(saw_period || saw_exponent)) break;
   isAccum = true;
@@ -607,7 +611,7 @@
 case 'h':  // FP Suffix for "half".
 case 'H':
   // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
-  if (!(PP.getLangOpts().Half || PP.getLangOpts().FixedPoint)) break;
+  if (!(LangOpts.Half || LangOpts.FixedPoint)) break;
   if (isIntegerLiteral()) break;  // Error for integer constant.
   if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
   isHalf = true;
@@ -621,7 +625,7 @@
   // CUDA host and device may have different _Float16 support, therefore
   // allows f16 literals to avoid false alarm.
   // ToDo: more 

[PATCH] D83475: [analyzer] Add CTUImportCppThreshold for C++ files

2020-07-09 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added inline comments.



Comment at: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def:333
+"for import when inlining functions during CTU analysis of C++ 
"
+"source files. ",
 8u)

extra whitespace at the end


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83475



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


[PATCH] D83475: [analyzer] Add CTUImportCppThreshold for C++ files

2020-07-09 Thread Gabor Marton via Phabricator via cfe-commits
martong updated this revision to Diff 276722.
martong marked an inline comment as done.
martong added a comment.

- Remove extra whitespace


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83475

Files:
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/ctu-import-threshold.c


Index: clang/test/Analysis/ctu-import-threshold.c
===
--- clang/test/Analysis/ctu-import-threshold.c
+++ clang/test/Analysis/ctu-import-threshold.c
@@ -1,5 +1,6 @@
 // Ensure analyzer option 'ctu-import-threshold' is a recognized option.
 //
 // RUN: %clang_cc1 -analyze -analyzer-config ctu-import-threshold=30 -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-config ctu-import-cpp-threshold=30 
-verify %s
 //
 // expected-no-diagnostics
Index: clang/test/Analysis/analyzer-config.c
===
--- clang/test/Analysis/analyzer-config.c
+++ clang/test/Analysis/analyzer-config.c
@@ -42,7 +42,8 @@
 // CHECK-NEXT: cplusplus.Move:WarnOn = KnownsAndLocals
 // CHECK-NEXT: crosscheck-with-z3 = false
 // CHECK-NEXT: ctu-dir = ""
-// CHECK-NEXT: ctu-import-threshold = 8
+// CHECK-NEXT: ctu-import-cpp-threshold = 8
+// CHECK-NEXT: ctu-import-threshold = 24
 // CHECK-NEXT: ctu-index-name = externalDefMap.txt
 // CHECK-NEXT: ctu-invocation-list = invocations.yaml
 // CHECK-NEXT: deadcode.DeadStores:ShowFixIts = false
Index: clang/lib/CrossTU/CrossTranslationUnit.cpp
===
--- clang/lib/CrossTU/CrossTranslationUnit.cpp
+++ clang/lib/CrossTU/CrossTranslationUnit.cpp
@@ -367,7 +367,9 @@
 CompilerInstance &CI)
 : Loader(CI, CI.getAnalyzerOpts()->CTUDir,
  CI.getAnalyzerOpts()->CTUInvocationList),
-  LoadGuard(CI.getAnalyzerOpts()->CTUImportThreshold) {}
+  LoadGuard(CI.getASTContext().getLangOpts().CPlusPlus
+? CI.getAnalyzerOpts()->CTUImportCppThreshold
+: CI.getAnalyzerOpts()->CTUImportThreshold) {}
 
 llvm::Expected
 CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFile(
Index: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
===
--- clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -321,9 +321,16 @@
 ANALYZER_OPTION(unsigned, CTUImportThreshold, "ctu-import-threshold",
 "The maximal amount of translation units that is considered "
 "for import when inlining functions during CTU analysis. "
-"Lowering this threshold can alleviate the memory burder of "
+"Lowering this threshold can alleviate the memory burden of "
 "analysis with many interdependent definitions located in "
-"various translation units.",
+"various translation units. This is valid only for non C++ "
+"source files.",
+24u)
+
+ANALYZER_OPTION(unsigned, CTUImportCppThreshold, "ctu-import-cpp-threshold",
+"The maximal amount of translation units that is considered "
+"for import when inlining functions during CTU analysis of C++ 
"
+"source files.",
 8u)
 
 ANALYZER_OPTION(


Index: clang/test/Analysis/ctu-import-threshold.c
===
--- clang/test/Analysis/ctu-import-threshold.c
+++ clang/test/Analysis/ctu-import-threshold.c
@@ -1,5 +1,6 @@
 // Ensure analyzer option 'ctu-import-threshold' is a recognized option.
 //
 // RUN: %clang_cc1 -analyze -analyzer-config ctu-import-threshold=30 -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-config ctu-import-cpp-threshold=30 -verify %s
 //
 // expected-no-diagnostics
Index: clang/test/Analysis/analyzer-config.c
===
--- clang/test/Analysis/analyzer-config.c
+++ clang/test/Analysis/analyzer-config.c
@@ -42,7 +42,8 @@
 // CHECK-NEXT: cplusplus.Move:WarnOn = KnownsAndLocals
 // CHECK-NEXT: crosscheck-with-z3 = false
 // CHECK-NEXT: ctu-dir = ""
-// CHECK-NEXT: ctu-import-threshold = 8
+// CHECK-NEXT: ctu-import-cpp-threshold = 8
+// CHECK-NEXT: ctu-import-threshold = 24
 // CHECK-NEXT: ctu-index-name = externalDefMap.txt
 // CHECK-NEXT: ctu-invocation-list = invocations.yaml
 // CHECK-NEXT: deadcode.DeadStores:ShowFixIts = false
Index: clang/lib/CrossTU/CrossTranslationUnit.cpp
===
--- clang/lib/CrossTU/CrossTranslationUnit.cpp
+++ clang/lib/CrossTU/CrossTranslationUnit.cpp
@@ -367,7 +367,9 @@
 CompilerInstance &CI)
 : Loader(CI, CI.getAnalyzerOpts

[PATCH] D83295: [Analyzer] Hotfix for various crashes in iterator checkers

2020-07-09 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:275-276
   } else if (isRandomIncrOrDecrOperator(OK)) {
+if (!BO->getRHS()->getType()->isIntegralOrEnumerationType())
+  return;
 handlePtrIncrOrDecr(C, BO->getLHS(),

This doesn't look symmetrical. How does this patch interact with D83190?


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

https://reviews.llvm.org/D83295



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


[clang] 31b0569 - make -fmodules-codegen and -fmodules-debuginfo work also with PCHs

2020-07-09 Thread Luboš Luňák via cfe-commits

Author: Luboš Luňák
Date: 2020-07-09T15:22:26+02:00
New Revision: 31b05692cd33b6dcc39402169b36d895e1aa87f4

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

LOG: make -fmodules-codegen and -fmodules-debuginfo work also with PCHs

Allow to build PCH's (with -building-pch-with-obj and the extra .o file)
with -fmodules-codegen -fmodules-debuginfo to allow emitting shared code
into the extra .o file, similarly to how it works with modules. A bit of
a misnomer, but the underlying functionality is the same. This saves up
to 20% of build time here. The patch is fairly simple, it basically just
duplicates -fmodules checks to also alternatively check
-building-pch-with-obj.

This already got committed as cbc9d22e49b434b6ceb2eb94b67079d02e0a7b74,
but then got reverted in 7ea9a6e0220da36ff2fd1fbc29c2755be23e5166
because of PR44953, as discussed in D74846. This is a corrected version
which does not include two places for the PCH case that aren't included
in the modules -fmodules-codegen path either.

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

Added: 
clang/test/PCH/codegen.cpp

Modified: 
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/lib/Serialization/ASTWriterDecl.cpp
clang/test/Modules/Inputs/codegen-flags/foo.h

Removed: 




diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 74aaf0f9c56e..4a1a995204e5 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -3234,7 +3234,8 @@ ASTReader::ReadASTBlock(ModuleFile &F, unsigned 
ClientLoadCapabilities) {
 case MODULAR_CODEGEN_DECLS:
   // FIXME: Skip reading this record if our ASTConsumer doesn't care about
   // them (ie: if we're not codegenerating this module).
-  if (F.Kind == MK_MainFile)
+  if (F.Kind == MK_MainFile ||
+  getContext().getLangOpts().BuildingPCHWithObjectFile)
 for (unsigned I = 0, N = Record.size(); I != N; ++I)
   EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
   break;

diff  --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index 359d5e567e67..eef4ab16ec15 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -503,8 +503,12 @@ uint64_t ASTDeclReader::GetCurrentCursorOffset() {
 }
 
 void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
-  if (Record.readInt())
+  if (Record.readInt()) {
 Reader.DefinitionSource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
+if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
+Reader.DeclIsFromPCHWithObjectFile(FD))
+  Reader.DefinitionSource[FD] = true;
+  }
   if (auto *CD = dyn_cast(FD)) {
 CD->setNumCtorInitializers(Record.readInt());
 if (CD->getNumCtorInitializers())
@@ -1431,8 +1435,12 @@ ASTDeclReader::RedeclarableResult 
ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
   Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
   }
 
-  if (VD->getStorageDuration() == SD_Static && Record.readInt())
+  if (VD->getStorageDuration() == SD_Static && Record.readInt()) {
 Reader.DefinitionSource[VD] = Loc.F->Kind == ModuleKind::MK_MainFile;
+if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
+Reader.DeclIsFromPCHWithObjectFile(VD))
+  Reader.DefinitionSource[VD] = true;
+  }
 
   enum VarKind {
 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
@@ -1691,8 +1699,12 @@ void ASTDeclReader::ReadCXXDefinitionData(
   Data.ODRHash = Record.readInt();
   Data.HasODRHash = true;
 
-  if (Record.readInt())
+  if (Record.readInt()) {
 Reader.DefinitionSource[D] = Loc.F->Kind == ModuleKind::MK_MainFile;
+if (Reader.getContext().getLangOpts().BuildingPCHWithObjectFile &&
+Reader.DeclIsFromPCHWithObjectFile(D))
+  Reader.DefinitionSource[D] = true;
+  }
 
   Data.NumBases = Record.readInt();
   if (Data.NumBases)

diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 6f364df80f32..2345a12caeb2 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -5688,8 +5688,8 @@ void ASTRecordWriter::AddCXXDefinitionData(const 
CXXRecordDecl *D) {
 
   // getODRHash will compute the ODRHash if it has not been previously 
computed.
   Record->push_back(D->getODRHash());
-  bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
-  Writer->WritingModule && !D->isDependentType();
+  bool ModulesDebugInfo =
+  Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType()

[PATCH] D69778: Make -fmodules-codegen and -fmodules-debuginfo work also with precompiled headers

2020-07-09 Thread Luboš Luňák via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG31b05692cd33: make -fmodules-codegen and -fmodules-debuginfo 
work also with PCHs (authored by llunak).

Changed prior to commit:
  https://reviews.llvm.org/D69778?vs=263839&id=276726#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D69778

Files:
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/Modules/Inputs/codegen-flags/foo.h
  clang/test/PCH/codegen.cpp

Index: clang/test/PCH/codegen.cpp
===
--- /dev/null
+++ clang/test/PCH/codegen.cpp
@@ -0,0 +1,42 @@
+// This test is the PCH version of Modules/codegen-flags.test . It uses its inputs.
+// The purpose of this test is just verify that the codegen options work with PCH as well.
+// All the codegen functionality should be tested in Modules/.
+
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple=x86_64-linux-gnu -fmodules-codegen -x c++-header -building-pch-with-obj -emit-pch %S/../Modules/Inputs/codegen-flags/foo.h -o %t/foo-cg.pch
+// RUN: %clang_cc1 -triple=x86_64-linux-gnu -fmodules-debuginfo -x c++-header -building-pch-with-obj -emit-pch %S/../Modules/Inputs/codegen-flags/foo.h -o %t/foo-di.pch
+
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -debug-info-kind=limited -o - %s -include-pch %t/foo-cg.pch -building-pch-with-obj -fmodules-codegen | FileCheck --check-prefix=CG %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -debug-info-kind=limited -o - %s -include-pch %t/foo-di.pch -building-pch-with-obj -fmodules-debuginfo | FileCheck --check-prefix=DI %s
+
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -debug-info-kind=limited -o - -include-pch %t/foo-cg.pch %S/../Modules/Inputs/codegen-flags/use.cpp | FileCheck --check-prefix=CG-USE %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -debug-info-kind=limited -o - -include-pch %t/foo-di.pch %S/../Modules/Inputs/codegen-flags/use.cpp | FileCheck --check-prefix=DI-USE %s
+
+// Test with template instantiation in the pch.
+
+// RUN: %clang_cc1 -triple=x86_64-linux-gnu -fmodules-codegen -x c++-header -building-pch-with-obj -emit-pch -fpch-instantiate-templates %S/../Modules/Inputs/codegen-flags/foo.h -o %t/foo-cg.pch
+// RUN: %clang_cc1 -triple=x86_64-linux-gnu -fmodules-debuginfo -x c++-header -building-pch-with-obj -emit-pch -fpch-instantiate-templates %S/../Modules/Inputs/codegen-flags/foo.h -o %t/foo-di.pch
+
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -debug-info-kind=limited -o - %s -include-pch %t/foo-cg.pch -building-pch-with-obj -fmodules-codegen | FileCheck --check-prefix=CG %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -debug-info-kind=limited -o - %s -include-pch %t/foo-di.pch -building-pch-with-obj -fmodules-debuginfo | FileCheck --check-prefix=DI %s
+
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -debug-info-kind=limited -o - -include-pch %t/foo-cg.pch %S/../Modules/Inputs/codegen-flags/use.cpp | FileCheck --check-prefix=CG-USE %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -debug-info-kind=limited -o - -include-pch %t/foo-di.pch %S/../Modules/Inputs/codegen-flags/use.cpp | FileCheck --check-prefix=DI-USE %s
+
+
+// CG: define weak_odr void @_Z2f1v
+// CG: DICompileUnit
+// CG-NOT: DICompositeType
+
+// CG-USE: declare void @_Z2f1v
+// CG-USE: DICompileUnit
+// CG-USE: distinct !DICompositeType(tag: DW_TAG_structure_type, name: "foo"
+
+// DI-NOT: define
+// DI: distinct !DICompositeType(tag: DW_TAG_structure_type, name: "foo"
+
+// DI-USE: define linkonce_odr void @_Z2f1v
+// DI-USE: = !DICompositeType(tag: DW_TAG_structure_type, name: "foo", {{.*}}, flags: DIFlagFwdDecl
Index: clang/test/Modules/Inputs/codegen-flags/foo.h
===
--- clang/test/Modules/Inputs/codegen-flags/foo.h
+++ clang/test/Modules/Inputs/codegen-flags/foo.h
@@ -1,4 +1,7 @@
+#ifndef FOO_H
+#define FOO_H
 struct foo {
 };
 inline void f1() {
 }
+#endif
Index: clang/lib/Serialization/ASTWriterDecl.cpp
===
--- clang/lib/Serialization/ASTWriterDecl.cpp
+++ clang/lib/Serialization/ASTWriterDecl.cpp
@@ -2458,9 +2458,10 @@
 
   assert(FD->doesThisDeclarationHaveABody());
   bool ModulesCodegen = false;
-  if (Writer->WritingModule && !FD->isDependentContext()) {
+  if (!FD->isDependentContext()) {
 Optional Linkage;
-if (Writer->WritingModule->Kind == Module::ModuleInterfaceUnit) {
+if (Writer->WritingModule &&
+Writer->WritingModule->Kind == Module::ModuleInterfaceUnit) {
   // When building a C++ Modules TS module interface unit, a strong
   // definition in the module interf

[clang] d12d0b7 - [analyzer] Add CTUImportCppThreshold for C++ files

2020-07-09 Thread Gabor Marton via cfe-commits

Author: Gabor Marton
Date: 2020-07-09T15:36:33+02:00
New Revision: d12d0b73f1c9c3a711c5cc15266a2b493cd712e9

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

LOG: [analyzer] Add CTUImportCppThreshold for C++ files

Summary:
The default CTUImportThreshold (8) seems to be too conservative with C projects.
We increase this value to 24 and we introduce another threshold for C++ source
files (defaulted to 8) because their AST is way more compilcated than C source
files.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
clang/lib/CrossTU/CrossTranslationUnit.cpp
clang/test/Analysis/analyzer-config.c
clang/test/Analysis/ctu-import-threshold.c
clang/unittests/CrossTU/CrossTranslationUnitTest.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index 9ee113c0dcaf..f0359d2dbb3c 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -321,9 +321,16 @@ ANALYZER_OPTION(bool, ShouldDisplayCheckerNameForText, 
"display-checker-name",
 ANALYZER_OPTION(unsigned, CTUImportThreshold, "ctu-import-threshold",
 "The maximal amount of translation units that is considered "
 "for import when inlining functions during CTU analysis. "
-"Lowering this threshold can alleviate the memory burder of "
+"Lowering this threshold can alleviate the memory burden of "
 "analysis with many interdependent definitions located in "
-"various translation units.",
+"various translation units. This is valid only for non C++ "
+"source files.",
+24u)
+
+ANALYZER_OPTION(unsigned, CTUImportCppThreshold, "ctu-import-cpp-threshold",
+"The maximal amount of translation units that is considered "
+"for import when inlining functions during CTU analysis of C++ 
"
+"source files.",
 8u)
 
 ANALYZER_OPTION(

diff  --git a/clang/lib/CrossTU/CrossTranslationUnit.cpp 
b/clang/lib/CrossTU/CrossTranslationUnit.cpp
index 11cc2afbc36d..80465c41d151 100644
--- a/clang/lib/CrossTU/CrossTranslationUnit.cpp
+++ b/clang/lib/CrossTU/CrossTranslationUnit.cpp
@@ -367,7 +367,9 @@ CrossTranslationUnitContext::ASTUnitStorage::ASTUnitStorage(
 CompilerInstance &CI)
 : Loader(CI, CI.getAnalyzerOpts()->CTUDir,
  CI.getAnalyzerOpts()->CTUInvocationList),
-  LoadGuard(CI.getAnalyzerOpts()->CTUImportThreshold) {}
+  LoadGuard(CI.getASTContext().getLangOpts().CPlusPlus
+? CI.getAnalyzerOpts()->CTUImportCppThreshold
+: CI.getAnalyzerOpts()->CTUImportThreshold) {}
 
 llvm::Expected
 CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFile(

diff  --git a/clang/test/Analysis/analyzer-config.c 
b/clang/test/Analysis/analyzer-config.c
index 7599cb052d44..d286f1258c21 100644
--- a/clang/test/Analysis/analyzer-config.c
+++ b/clang/test/Analysis/analyzer-config.c
@@ -43,7 +43,8 @@
 // CHECK-NEXT: cplusplus.SmartPtrModeling:ModelSmartPtrDereference = false
 // CHECK-NEXT: crosscheck-with-z3 = false
 // CHECK-NEXT: ctu-dir = ""
-// CHECK-NEXT: ctu-import-threshold = 8
+// CHECK-NEXT: ctu-import-cpp-threshold = 8
+// CHECK-NEXT: ctu-import-threshold = 24
 // CHECK-NEXT: ctu-index-name = externalDefMap.txt
 // CHECK-NEXT: ctu-invocation-list = invocations.yaml
 // CHECK-NEXT: deadcode.DeadStores:ShowFixIts = false

diff  --git a/clang/test/Analysis/ctu-import-threshold.c 
b/clang/test/Analysis/ctu-import-threshold.c
index 82711b873d10..62bbeda20d5b 100644
--- a/clang/test/Analysis/ctu-import-threshold.c
+++ b/clang/test/Analysis/ctu-import-threshold.c
@@ -1,5 +1,6 @@
 // Ensure analyzer option 'ctu-import-threshold' is a recognized option.
 //
 // RUN: %clang_cc1 -analyze -analyzer-config ctu-import-threshold=30 -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-config ctu-import-cpp-threshold=30 
-verify %s
 //
 // expected-no-diagnostics

diff  --git a/clang/unittests/CrossTU/CrossTranslationUnitTest.cpp 
b/clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
index ceb1437f2520..5495f27f5b32 100644
--- a/clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
+++ b/clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -147,6 +147,7 @@ class CTUAction : public clang::ASTFrontendAction {
   std::unique_ptr
   CreateASTConsumer(clang::CompilerInstance &CI, StringRef) override {
 CI.getAnalyzerOpts()->CTUImportThreshold = OverrideLimit;
+CI.getAnalyzerOpts()->CTUImportCppThreshold = OverrideLimit;

[PATCH] D83475: [analyzer] Add CTUImportCppThreshold for C++ files

2020-07-09 Thread Gabor Marton via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd12d0b73f1c9: [analyzer] Add CTUImportCppThreshold for C++ 
files (authored by martong).

Changed prior to commit:
  https://reviews.llvm.org/D83475?vs=276722&id=276727#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83475

Files:
  clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
  clang/lib/CrossTU/CrossTranslationUnit.cpp
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/ctu-import-threshold.c
  clang/unittests/CrossTU/CrossTranslationUnitTest.cpp


Index: clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
===
--- clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
+++ clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -147,6 +147,7 @@
   std::unique_ptr
   CreateASTConsumer(clang::CompilerInstance &CI, StringRef) override {
 CI.getAnalyzerOpts()->CTUImportThreshold = OverrideLimit;
+CI.getAnalyzerOpts()->CTUImportCppThreshold = OverrideLimit;
 return std::make_unique(CI, Success);
   }
 
Index: clang/test/Analysis/ctu-import-threshold.c
===
--- clang/test/Analysis/ctu-import-threshold.c
+++ clang/test/Analysis/ctu-import-threshold.c
@@ -1,5 +1,6 @@
 // Ensure analyzer option 'ctu-import-threshold' is a recognized option.
 //
 // RUN: %clang_cc1 -analyze -analyzer-config ctu-import-threshold=30 -verify %s
+// RUN: %clang_cc1 -analyze -analyzer-config ctu-import-cpp-threshold=30 
-verify %s
 //
 // expected-no-diagnostics
Index: clang/test/Analysis/analyzer-config.c
===
--- clang/test/Analysis/analyzer-config.c
+++ clang/test/Analysis/analyzer-config.c
@@ -43,7 +43,8 @@
 // CHECK-NEXT: cplusplus.SmartPtrModeling:ModelSmartPtrDereference = false
 // CHECK-NEXT: crosscheck-with-z3 = false
 // CHECK-NEXT: ctu-dir = ""
-// CHECK-NEXT: ctu-import-threshold = 8
+// CHECK-NEXT: ctu-import-cpp-threshold = 8
+// CHECK-NEXT: ctu-import-threshold = 24
 // CHECK-NEXT: ctu-index-name = externalDefMap.txt
 // CHECK-NEXT: ctu-invocation-list = invocations.yaml
 // CHECK-NEXT: deadcode.DeadStores:ShowFixIts = false
Index: clang/lib/CrossTU/CrossTranslationUnit.cpp
===
--- clang/lib/CrossTU/CrossTranslationUnit.cpp
+++ clang/lib/CrossTU/CrossTranslationUnit.cpp
@@ -367,7 +367,9 @@
 CompilerInstance &CI)
 : Loader(CI, CI.getAnalyzerOpts()->CTUDir,
  CI.getAnalyzerOpts()->CTUInvocationList),
-  LoadGuard(CI.getAnalyzerOpts()->CTUImportThreshold) {}
+  LoadGuard(CI.getASTContext().getLangOpts().CPlusPlus
+? CI.getAnalyzerOpts()->CTUImportCppThreshold
+: CI.getAnalyzerOpts()->CTUImportThreshold) {}
 
 llvm::Expected
 CrossTranslationUnitContext::ASTUnitStorage::getASTUnitForFile(
Index: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
===
--- clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -321,9 +321,16 @@
 ANALYZER_OPTION(unsigned, CTUImportThreshold, "ctu-import-threshold",
 "The maximal amount of translation units that is considered "
 "for import when inlining functions during CTU analysis. "
-"Lowering this threshold can alleviate the memory burder of "
+"Lowering this threshold can alleviate the memory burden of "
 "analysis with many interdependent definitions located in "
-"various translation units.",
+"various translation units. This is valid only for non C++ "
+"source files.",
+24u)
+
+ANALYZER_OPTION(unsigned, CTUImportCppThreshold, "ctu-import-cpp-threshold",
+"The maximal amount of translation units that is considered "
+"for import when inlining functions during CTU analysis of C++ 
"
+"source files.",
 8u)
 
 ANALYZER_OPTION(


Index: clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
===
--- clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
+++ clang/unittests/CrossTU/CrossTranslationUnitTest.cpp
@@ -147,6 +147,7 @@
   std::unique_ptr
   CreateASTConsumer(clang::CompilerInstance &CI, StringRef) override {
 CI.getAnalyzerOpts()->CTUImportThreshold = OverrideLimit;
+CI.getAnalyzerOpts()->CTUImportCppThreshold = OverrideLimit;
 return std::make_unique(CI, Success);
   }
 
Index: clang/test/Analysis/ctu-import-threshold.c
===
--- clang/test/Analysis/ctu-import-threshold.c
+++

[PATCH] D83475: [analyzer] Add CTUImportCppThreshold for C++ files

2020-07-09 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def:48-50
 #ifndef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
 /// Create a new analyzer option, but dont generate a method for it in
 /// AnalyzerOptions. It's value depends on the option "user-mode".

This reminds me of some options having different default values depending on 
`-analyzer-config user-mode`. I think that solution, and the one proposed in 
this patch is subpar, but the best solution, turning this entire thing into a 
TableGen file, would be a chore.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83475



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


[PATCH] D71124: [RISCV] support clang driver to select cpu

2020-07-09 Thread Kuan Hsu Chen (Zakk) via Phabricator via cfe-commits
khchen planned changes to this revision.
khchen marked an inline comment as done.
khchen added a comment.

BTW, this patch depends on D77030 , which aim 
to avoid the forcing of any ProcessorModel to have `FeatureRVCHints` feature.
But if we decide to keep the `FeatureRVCHints`, I need to change implementation 
a little.




Comment at: clang/test/Driver/riscv-cpus.c:2
+// Check target CPUs are correctly passed.
+
+// RUN: %clang -target riscv32 -### -c %s 2>&1 -mcpu=rocket-rv32 | FileCheck 
-check-prefix=MCPU-ROCKETCHIP32 %s

asb wrote:
> I think for completeness this test should be validating the interaction of 
> the ABI choosing logic with CPU selection as well. With the implemented logic 
> I believe it should show that lp64d is selected for -mcpu=sifive-u54 and that 
> -mcpu=sifive-u54 -mabi=lp64 will respect the ABI choice
okay, it makes sense to me, I will update this patch soon.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D71124



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


[PATCH] D83475: [analyzer] Add CTUImportCppThreshold for C++ files

2020-07-09 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added a comment.

I don't like this solution t much, but I respect the urgency, and since we 
don't introduce a compatibility issue, I trust we can remove this if we decide 
to change to TableGen. Post-commit LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83475



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


[PATCH] D83286: [analyzer][solver] Track symbol disequalities

2020-07-09 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 276729.
vsavchenko added a comment.

Fix review remarks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83286

Files:
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
  clang/test/Analysis/equality_tracking.c
  clang/test/Analysis/mutually_exclusive_null_fp.cpp

Index: clang/test/Analysis/mutually_exclusive_null_fp.cpp
===
--- /dev/null
+++ clang/test/Analysis/mutually_exclusive_null_fp.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core -verify %s
+
+// rdar://problem/56586853
+// expected-no-diagnostics
+
+struct Data {
+  int x;
+  Data *data;
+};
+
+int compare(Data &a, Data &b) {
+  Data *aData = a.data;
+  Data *bData = b.data;
+
+  // Covers the cases where both pointers are null as well as both pointing to the same buffer.
+  if (aData == bData)
+return 0;
+
+  if (aData && !bData)
+return 1;
+
+  if (!aData && bData)
+return -1;
+
+  return compare(*aData, *bData); // no-warning
+}
Index: clang/test/Analysis/equality_tracking.c
===
--- clang/test/Analysis/equality_tracking.c
+++ clang/test/Analysis/equality_tracking.c
@@ -23,9 +23,8 @@
 return;
   }
   clang_analyzer_eval((a - b) == 0); // expected-warning{{FALSE}}
-  // FIXME: we should track disequality information as well
-  clang_analyzer_eval(b == a); // expected-warning{{UNKNOWN}}
-  clang_analyzer_eval(b != a); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(b == a);   // expected-warning{{FALSE}}
+  clang_analyzer_eval(b != a);   // expected-warning{{TRUE}}
 }
 
 void zeroImpliesReversedEqual(int a, int b) {
@@ -36,9 +35,8 @@
 return;
   }
   clang_analyzer_eval((b - a) == 0); // expected-warning{{FALSE}}
-  // FIXME: we should track disequality information as well
-  clang_analyzer_eval(b == a); // expected-warning{{UNKNOWN}}
-  clang_analyzer_eval(b != a); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(b == a);   // expected-warning{{FALSE}}
+  clang_analyzer_eval(b != a);   // expected-warning{{TRUE}}
 }
 
 void canonicalEqual(int a, int b) {
@@ -73,8 +71,7 @@
   if (a != b && b == c) {
 if (c == 42) {
   clang_analyzer_eval(b == 42); // expected-warning{{TRUE}}
-  // FIXME: we should track disequality information as well
-  clang_analyzer_eval(a != 42); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(a != 42); // expected-warning{{TRUE}}
 }
   }
 }
@@ -144,8 +141,31 @@
 
   if (a != b && b == c) {
 if (c == NULL) {
-  // FIXME: we should track disequality information as well
-  clang_analyzer_eval(a != NULL); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(a != NULL); // expected-warning{{TRUE}}
+}
+  }
+}
+
+void testDisequalitiesAfter(int a, int b, int c) {
+  if (a >= 10 && b <= 42) {
+if (a == b && c == 15 && c != a) {
+  clang_analyzer_eval(b != c);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(a != 15); // expected-warning{{TRUE}}
+  clang_analyzer_eval(b != 15); // expected-warning{{TRUE}}
+  clang_analyzer_eval(b >= 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(a <= 42); // expected-warning{{TRUE}}
+}
+  }
+}
+
+void testDisequalitiesBefore(int a, int b, int c) {
+  if (a >= 10 && b <= 42 && c == 15) {
+if (a == b && c != a) {
+  clang_analyzer_eval(b != c);  // expected-warning{{TRUE}}
+  clang_analyzer_eval(a != 15); // expected-warning{{TRUE}}
+  clang_analyzer_eval(b != 15); // expected-warning{{TRUE}}
+  clang_analyzer_eval(b >= 10); // expected-warning{{TRUE}}
+  clang_analyzer_eval(a <= 42); // expected-warning{{TRUE}}
 }
   }
 }
Index: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -401,6 +401,9 @@
 REGISTER_MAP_WITH_PROGRAMSTATE(ClassMembers, EquivalenceClass, SymbolSet)
 REGISTER_MAP_WITH_PROGRAMSTATE(ConstraintRange, EquivalenceClass, RangeSet)
 
+REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(ClassSet, EquivalenceClass)
+REGISTER_MAP_WITH_PROGRAMSTATE(DisequalityMap, EquivalenceClass, ClassSet)
+
 namespace {
 /// This class encapsulates a set of symbols equal to each other.
 ///
@@ -450,6 +453,26 @@
   LLVM_NODISCARD inline bool isTriviallyDead(ProgramStateRef State,
  SymbolReaper &Reaper);
 
+  LLVM_NODISCARD static inline ProgramStateRef
+  markDisequal(BasicValueFactory &BV, RangeSet::Factory &F,
+   ProgramStateRef State, SymbolRef First, SymbolRef Second);
+  LLVM_NODISCARD static inline ProgramStateRef
+  markDisequal(BasicValueFactory &BV, RangeSet::Factory &F,
+   ProgramStateRef State, Equivalen

[PATCH] D83407: [analyzer][StdLibraryFunctionsChecker] Add POSIX networking functions

2020-07-09 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1735-1747
+  if (!addToFunctionSummaryMap(
+  "accept", Summary(ArgTypes{IntTy, *StructSockaddrPtrRestrictTy,
+ *Socklen_tPtrRestrictTy},
+RetType{IntTy}, NoEvalCall)
+.ArgConstraint(ArgumentCondition(
+0, WithinRange, Range(0, IntMax)
+// Do not add constraints on sockaddr.

This is quite a bit of code duplication -- if we failed to match the precise 
`accept`, we just try again with the middle argument type being unspecified? 
Whats the difference between this and trying to match with `Irrelevant` 
straight away?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83407



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


[PATCH] D83362: Fix warning caused by __builtin_expect_with_probability was not handled in places such as constant folding

2020-07-09 Thread Zhi Zhuang via Phabricator via cfe-commits
LukeZhuang added a comment.

Hi, could you please help me commit this change? Thank you very much!


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

https://reviews.llvm.org/D83362



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


[PATCH] D82657: [AST][RecoveryAST] Preserve the type by default for recovery expression.

2020-07-09 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 276733.
hokein added a comment.

rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82657

Files:
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CXX/temp/temp.constr/temp.constr.order/function-templates.cpp
  clang/test/CXX/temp/temp.decls/temp.variadic/fixed-expansion.cpp
  clang/test/SemaTemplate/dependent-names.cpp


Index: clang/test/SemaTemplate/dependent-names.cpp
===
--- clang/test/SemaTemplate/dependent-names.cpp
+++ clang/test/SemaTemplate/dependent-names.cpp
@@ -173,7 +173,7 @@
 
 
   namespace O {
-void f(char&); // expected-note {{candidate function not viable}}
+int f(char&); // expected-note {{candidate function not viable}}
 
 template struct C {
   static const int n = f(T()); // expected-error {{no matching function}}
Index: clang/test/CXX/temp/temp.decls/temp.variadic/fixed-expansion.cpp
===
--- clang/test/CXX/temp/temp.decls/temp.variadic/fixed-expansion.cpp
+++ clang/test/CXX/temp/temp.decls/temp.variadic/fixed-expansion.cpp
@@ -123,7 +123,10 @@
   template struct S {};
   template using U = S; // expected-note 
2{{template parameter is declared here}}
   template U &f(U, Ts...); // expected-error 
2{{pack expansion used as argument for non-pack parameter of alias template}}
-  S &s1 = f({}, 0, 0.0); // expected-error {{no matching 
function}}
+  // The return type of f is invalid during instantiation, and int is the 
fallback.
+  // FIXME: would be nice to suppress the secondard "cannot bind to a value of 
unrelated type 'int'" diagnostic.
+  S &s1 = f({}, 0, 0.0); // expected-error {{no matching 
function}} \
+  expected-error {{non-const 
lvalue reference to type 'S' cannot bind to a value of 
unrelated type 'int'}}
 }
 
 namespace PR18401 {
Index: clang/test/CXX/temp/temp.constr/temp.constr.order/function-templates.cpp
===
--- clang/test/CXX/temp/temp.constr/temp.constr.order/function-templates.cpp
+++ clang/test/CXX/temp/temp.constr/temp.constr.order/function-templates.cpp
@@ -67,7 +67,8 @@
 // expected-note@-1 {{candidate function [with T = long long, U = int]}}
 
 static_assert(sizeof(f()));
-// expected-error@-1 {{call to 'f' is ambiguous}}
+// expected-error@-1 {{call to 'f' is ambiguous}} \
+   expected-error@-1 {{invalid application of 'sizeof' to an incomplete type 
'void'}}
 
 template
 concept C3 = true;
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2929,8 +2929,8 @@
   // Recovery AST still heavily relies on dependent-type machinery.
   Opts.RecoveryAST =
   Args.hasFlag(OPT_frecovery_ast, OPT_fno_recovery_ast, Opts.CPlusPlus);
-  Opts.RecoveryASTType =
-  Args.hasFlag(OPT_frecovery_ast_type, OPT_fno_recovery_ast_type, false);
+  Opts.RecoveryASTType = Args.hasFlag(
+  OPT_frecovery_ast_type, OPT_fno_recovery_ast_type, Opts.CPlusPlus);
   Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
   Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
   Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);


Index: clang/test/SemaTemplate/dependent-names.cpp
===
--- clang/test/SemaTemplate/dependent-names.cpp
+++ clang/test/SemaTemplate/dependent-names.cpp
@@ -173,7 +173,7 @@
 
 
   namespace O {
-void f(char&); // expected-note {{candidate function not viable}}
+int f(char&); // expected-note {{candidate function not viable}}
 
 template struct C {
   static const int n = f(T()); // expected-error {{no matching function}}
Index: clang/test/CXX/temp/temp.decls/temp.variadic/fixed-expansion.cpp
===
--- clang/test/CXX/temp/temp.decls/temp.variadic/fixed-expansion.cpp
+++ clang/test/CXX/temp/temp.decls/temp.variadic/fixed-expansion.cpp
@@ -123,7 +123,10 @@
   template struct S {};
   template using U = S; // expected-note 2{{template parameter is declared here}}
   template U &f(U, Ts...); // expected-error 2{{pack expansion used as argument for non-pack parameter of alias template}}
-  S &s1 = f({}, 0, 0.0); // expected-error {{no matching function}}
+  // The return type of f is invalid during instantiation, and int is the fallback.
+  // FIXME: would be nice to suppress the secondard "cannot bind to a value of unrelated type 'int'" diagnostic.
+  S &s1 = f({}, 0, 0.0); // expected-error {{no matching function}} \
+  expected-error {{non-const lvalue reference to type 'S' cannot bind to a value of unrelat

[PATCH] D83295: [Analyzer] Hotfix for various crashes in iterator checkers

2020-07-09 Thread Balogh , Ádám via Phabricator via cfe-commits
baloghadamsoftware marked an inline comment as done.
baloghadamsoftware added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:275-276
   } else if (isRandomIncrOrDecrOperator(OK)) {
+if (!BO->getRHS()->getType()->isIntegralOrEnumerationType())
+  return;
 handlePtrIncrOrDecr(C, BO->getLHS(),

Szelethus wrote:
> This doesn't look symmetrical. How does this patch interact with D83190?
This //is// not symmetrical. Since this patch is a hotfix for three bugs, all 
of them cause crashes it is more urgent to land. The other patch should be 
rebased on it.


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

https://reviews.llvm.org/D83295



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


[PATCH] D83295: [Analyzer] Hotfix for various crashes in iterator checkers

2020-07-09 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 accepted this revision.
gamesh411 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:275-276
   } else if (isRandomIncrOrDecrOperator(OK)) {
+if (!BO->getRHS()->getType()->isIntegralOrEnumerationType())
+  return;
 handlePtrIncrOrDecr(C, BO->getLHS(),

Szelethus wrote:
> This doesn't look symmetrical. How does this patch interact with D83190?
I see that patch D83190 will need not only to be rebased, but modified slightly 
to take this early checking into account. I will refer to this review over 
there.


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

https://reviews.llvm.org/D83295



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


[PATCH] D83295: [Analyzer] Hotfix for various crashes in iterator checkers

2020-07-09 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 added a comment.

@Szelethus thanks for being watchful, appreciated c:


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

https://reviews.llvm.org/D83295



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


[PATCH] D83295: [Analyzer] Hotfix for various crashes in iterator checkers

2020-07-09 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus accepted this revision.
Szelethus added a comment.

LGTM, but if we knowingly a subpar solution, we should make that clear in the 
surrounding code. I know the followup patch is around the corner, but just to 
be sure.




Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:275-276
   } else if (isRandomIncrOrDecrOperator(OK)) {
+if (!BO->getRHS()->getType()->isIntegralOrEnumerationType())
+  return;
 handlePtrIncrOrDecr(C, BO->getLHS(),

baloghadamsoftware wrote:
> gamesh411 wrote:
> > Szelethus wrote:
> > > This doesn't look symmetrical. How does this patch interact with D83190?
> > I see that patch D83190 will need not only to be rebased, but modified 
> > slightly to take this early checking into account. I will refer to this 
> > review over there.
> This //is// not symmetrical. Since this patch is a hotfix for three bugs, all 
> of them cause crashes it is more urgent to land. The other patch should be 
> rebased on it.
Please add a FIXME before commiting, if we knowingly add a hack.



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorModeling.cpp:466-470
+  // If the value for which we just tried to set a new iterator position is
+  // an `SVal`for which no iterator position can be set then the setting was
+  // unsuccessful. We cannot handle the comparison in this case.
+  if (!LPos || !RPos)
+return;

Is this always okay? Shouldn't we check what the reason was behind the failure 
to retrieve the position? Is a `TODO: ` at the very least appropriate?



Comment at: clang/lib/StaticAnalyzer/Checkers/IteratorRangeChecker.cpp:172-173
 SVal RVal = State->getSVal(BO->getRHS(), C.getLocationContext());
+if (!BO->getRHS()->getType()->isIntegralOrEnumerationType())
+  return;
 verifyRandomIncrOrDecr(C, BinaryOperator::getOverloadedOperator(OK), LVal,

FIXME:


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

https://reviews.llvm.org/D83295



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


[PATCH] D83407: [analyzer][StdLibraryFunctionsChecker] Add POSIX networking functions

2020-07-09 Thread Gabor Marton via Phabricator via cfe-commits
martong marked an inline comment as done.
martong added inline comments.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1735-1747
+  if (!addToFunctionSummaryMap(
+  "accept", Summary(ArgTypes{IntTy, *StructSockaddrPtrRestrictTy,
+ *Socklen_tPtrRestrictTy},
+RetType{IntTy}, NoEvalCall)
+.ArgConstraint(ArgumentCondition(
+0, WithinRange, Range(0, IntMax)
+// Do not add constraints on sockaddr.

Szelethus wrote:
> This is quite a bit of code duplication -- if we failed to match the precise 
> `accept`, we just try again with the middle argument type being unspecified? 
> Whats the difference between this and trying to match with `Irrelevant` 
> straight away?
>  if we failed to match the precise accept, we just try again with the middle 
> argument type being unspecified?
Yes. And that will be a successful match in the case where `sockaddr` is a 
transparent union.

> Whats the difference between this and trying to match with Irrelevant 
> straight away?
Yeah, it's a good catch. There is no difference with `accept` because we don't 
have any constraints on `sockaddr` anyway. But, the other functions have fewer 
constraints with the transparent union.
Perhaps we should separate the body of the `Summary` from the `Signature` and 
in this case we could reuse that for both signatures. Or as you suggested we 
could just match by default with the `Irrelevant`. What do you think?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83407



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


[PATCH] D83480: Refactored NumericLiteralParser to not require a Preprocessor

2020-07-09 Thread Eduardo Caldas via Phabricator via cfe-commits
eduucaldas accepted this revision.
eduucaldas added a comment.
This revision is now accepted and ready to land.

Additionally, consider applying a similar change to `CharLiteralParser`, for 
consistency.

All the comments are just suggestions. Feel free to land this without answering 
them.




Comment at: clang/include/clang/Lex/LiteralSupport.h:57-59
-  NumericLiteralParser(StringRef TokSpelling,
-   SourceLocation TokLoc,
-   Preprocessor &PP);

We don't need to remove this constructor, we can keep the same signature and 
make it call the new constructor. The same is done for `StringLiteralParser`.

That would allow some callers that don't care much about the implementation 
details to just use the simpler to write version.



Comment at: clang/lib/Lex/LiteralSupport.cpp:766
+  !isValidUDSuffix(LangOpts, StringRef(s, ThisTokEnd - s))) {
+Diags.Report(AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
+ diag::err_invalid_digit)

How about just using `Lexer::AdvanceToTokenCharacter`? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83480



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


[PATCH] D83407: [analyzer][StdLibraryFunctionsChecker] Add POSIX networking functions

2020-07-09 Thread Kristóf Umann via Phabricator via cfe-commits
Szelethus added inline comments.



Comment at: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp:1735-1747
+  if (!addToFunctionSummaryMap(
+  "accept", Summary(ArgTypes{IntTy, *StructSockaddrPtrRestrictTy,
+ *Socklen_tPtrRestrictTy},
+RetType{IntTy}, NoEvalCall)
+.ArgConstraint(ArgumentCondition(
+0, WithinRange, Range(0, IntMax)
+// Do not add constraints on sockaddr.

martong wrote:
> Szelethus wrote:
> > This is quite a bit of code duplication -- if we failed to match the 
> > precise `accept`, we just try again with the middle argument type being 
> > unspecified? Whats the difference between this and trying to match with 
> > `Irrelevant` straight away?
> >  if we failed to match the precise accept, we just try again with the 
> > middle argument type being unspecified?
> Yes. And that will be a successful match in the case where `sockaddr` is a 
> transparent union.
> 
> > Whats the difference between this and trying to match with Irrelevant 
> > straight away?
> Yeah, it's a good catch. There is no difference with `accept` because we 
> don't have any constraints on `sockaddr` anyway. But, the other functions 
> have fewer constraints with the transparent union.
> Perhaps we should separate the body of the `Summary` from the `Signature` and 
> in this case we could reuse that for both signatures. Or as you suggested we 
> could just match by default with the `Irrelevant`. What do you think?
> Perhaps we should separate the body of the Summary from the Signature and in 
> this case we could reuse that for both signatures. Or as you suggested we 
> could just match by default with the Irrelevant. What do you think?

Separating the summary and the signature sounds great! But, that also adds 
sufficiently complex code that would definitely warrant individual tests, so we 
should add that as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83407



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


[clang] 4d4d903 - Fix warning caused by __builtin_expect_with_probability was not handled

2020-07-09 Thread Erich Keane via cfe-commits

Author: Zhi Zhuang
Date: 2020-07-09T08:01:33-07:00
New Revision: 4d4d9037670a3537c14092807a717284ea0c4f92

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

LOG: Fix warning caused by __builtin_expect_with_probability was not handled
in places such as constant folding

Previously some places that should have handled
__builtin_expect_with_probability is missing, so in some case it acts
differently than __builtin_expect.
For example it was not handled in constant folding, thus in the
following program, the "if" condition should be constantly true and
folded, but previously it was not handled and cause warning "control may
reach end of non-void function" (while __builtin_expect does not):

__attribute__((noreturn)) extern void bar();
int foo(int x, int y) {
  if (y) {
if (__builtin_expect_with_probability(1, 1, 1))
  bar();
  }
  else
return 0;
}

Now it's fixed.

Differential Revisions: https://reviews.llvm.org/D83362

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
clang/test/Sema/builtin-expect-with-probability.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index d6dbfb14e60b..a4dc0ccad1e0 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -11231,6 +11231,7 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const 
CallExpr *E,
   }
 
   case Builtin::BI__builtin_expect:
+  case Builtin::BI__builtin_expect_with_probability:
 return Visit(E->getArg(0));
 
   case Builtin::BI__builtin_ffs:

diff  --git a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
index 3eeb1e9a3502..233ce57c3ac9 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionChecker.cpp
@@ -64,10 +64,12 @@ bool BuiltinFunctionChecker::evalCall(const CallEvent &Call,
 
   case Builtin::BI__builtin_unpredictable:
   case Builtin::BI__builtin_expect:
+  case Builtin::BI__builtin_expect_with_probability:
   case Builtin::BI__builtin_assume_aligned:
   case Builtin::BI__builtin_addressof: {
-// For __builtin_unpredictable, __builtin_expect, and
-// __builtin_assume_aligned, just return the value of the subexpression.
+// For __builtin_unpredictable, __builtin_expect,
+// __builtin_expect_with_probability and __builtin_assume_aligned,
+// just return the value of the subexpression.
 // __builtin_addressof is going from a reference to a pointer, but those
 // are represented the same way in the analyzer.
 assert (Call.getNumArgs() > 0);

diff  --git a/clang/test/Sema/builtin-expect-with-probability.cpp 
b/clang/test/Sema/builtin-expect-with-probability.cpp
index 4a5b62a55bbc..3aa20cb0e6dd 100644
--- a/clang/test/Sema/builtin-expect-with-probability.cpp
+++ b/clang/test/Sema/builtin-expect-with-probability.cpp
@@ -1,4 +1,30 @@
 // RUN: %clang_cc1 -fsyntax-only -verify %s
+
+__attribute__((noreturn)) extern void bar();
+
+int test_no_warn(int x) {
+  if (x) {
+if (__builtin_expect_with_probability(1, 1, 1))
+  bar();
+  } else {
+return 0;
+  }
+} // should not emit warn "control may reach end of non-void function" here 
since expr is constantly true, so the "if(__bui..)" should be constantly true 
condition and be ignored
+
+template  void tempf() {
+  static_assert(b == 1, "should be evaluated as 1"); // should not have error 
here
+}
+
+constexpr int constf() {
+  return __builtin_expect_with_probability(1, 1, 1);
+}
+
+void foo() {
+  tempf<__builtin_expect_with_probability(1, 1, 1)>();
+  constexpr int f = constf();
+  static_assert(f == 1, "should be evaluated as 1"); // should not have error 
here
+}
+
 extern int global;
 
 struct S {



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


[PATCH] D83362: Fix warning caused by __builtin_expect_with_probability was not handled in places such as constant folding

2020-07-09 Thread Erich Keane via Phabricator via cfe-commits
erichkeane closed this revision.
erichkeane added a comment.

Gah, misspelled differential revision.


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

https://reviews.llvm.org/D83362



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


[PATCH] D83480: Refactored NumericLiteralParser to not require a Preprocessor

2020-07-09 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr updated this revision to Diff 276740.
gribozavr added a comment.

Addressed code review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83480

Files:
  clang/include/clang/Lex/LiteralSupport.h
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPExpressions.cpp
  clang/lib/Lex/Preprocessor.cpp
  clang/lib/Sema/SemaExpr.cpp

Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -3634,7 +3634,9 @@
   if (Invalid)
 return ExprError();
 
-  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
+  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
+   PP.getSourceManager(), PP.getLangOpts(),
+   PP.getTargetInfo(), PP.getDiagnostics());
   if (Literal.hadError)
 return ExprError();
 
Index: clang/lib/Lex/Preprocessor.cpp
===
--- clang/lib/Lex/Preprocessor.cpp
+++ clang/lib/Lex/Preprocessor.cpp
@@ -1370,7 +1370,9 @@
   StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
   if (NumberInvalid)
 return false;
-  NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
+  NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
+   getLangOpts(), getTargetInfo(),
+   getDiagnostics());
   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
 return false;
   llvm::APInt APVal(64, 0);
Index: clang/lib/Lex/PPExpressions.cpp
===
--- clang/lib/Lex/PPExpressions.cpp
+++ clang/lib/Lex/PPExpressions.cpp
@@ -295,7 +295,9 @@
 if (NumberInvalid)
   return true; // a diagnostic was already reported
 
-NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
+NumericLiteralParser Literal(Spelling, PeekTok.getLocation(),
+ PP.getSourceManager(), PP.getLangOpts(),
+ PP.getTargetInfo(), PP.getDiagnostics());
 if (Literal.hadError)
   return true; // a diagnostic was already reported.
 
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -525,8 +525,12 @@
 ///
 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
SourceLocation TokLoc,
-   Preprocessor &PP)
-  : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
+   const SourceManager &SM,
+   const LangOptions &LangOpts,
+   const TargetInfo &Target,
+   DiagnosticsEngine &Diags)
+: SM(SM), LangOpts(LangOpts), Diags(Diags),
+  ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
 
   // This routine assumes that the range begin/end matches the regex for integer
   // and FP constants (specifically, the 'pp-number' regex), and assumes that
@@ -572,7 +576,7 @@
   checkSeparator(TokLoc, s, CSK_AfterDigits);
 
   // Initial scan to lookahead for fixed point suffix.
-  if (PP.getLangOpts().FixedPoint) {
+  if (LangOpts.FixedPoint) {
 for (const char *c = s; c != ThisTokEnd; ++c) {
   if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
 saw_fixed_point_suffix = true;
@@ -592,14 +596,16 @@
 switch (*s) {
 case 'R':
 case 'r':
-  if (!PP.getLangOpts().FixedPoint) break;
+  if (!LangOpts.FixedPoint)
+break;
   if (isFract || isAccum) break;
   if (!(saw_period || saw_exponent)) break;
   isFract = true;
   continue;
 case 'K':
 case 'k':
-  if (!PP.getLangOpts().FixedPoint) break;
+  if (!LangOpts.FixedPoint)
+break;
   if (isFract || isAccum) break;
   if (!(saw_period || saw_exponent)) break;
   isAccum = true;
@@ -607,7 +613,8 @@
 case 'h':  // FP Suffix for "half".
 case 'H':
   // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
-  if (!(PP.getLangOpts().Half || PP.getLangOpts().FixedPoint)) break;
+  if (!(LangOpts.Half || LangOpts.FixedPoint))
+break;
   if (isIntegerLiteral()) break;  // Error for integer constant.
   if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
   isHalf = true;
@@ -621,8 +628,8 @@
   // CUDA host and device may have different _Float16 support, therefore
   // allows f16 literals to avoid false alarm.
   // ToDo: more precise check for CUDA.
-  if ((PP.getTargetInfo().hasFloat16Type() || PP.getL

[PATCH] D83480: Refactored NumericLiteralParser to not require a Preprocessor

2020-07-09 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/include/clang/Lex/LiteralSupport.h:57-59
-  NumericLiteralParser(StringRef TokSpelling,
-   SourceLocation TokLoc,
-   Preprocessor &PP);

eduucaldas wrote:
> We don't need to remove this constructor, we can keep the same signature and 
> make it call the new constructor. The same is done for `StringLiteralParser`.
> 
> That would allow some callers that don't care much about the implementation 
> details to just use the simpler to write version.
I'd prefer a simpler public API over convenience.



Comment at: clang/lib/Lex/LiteralSupport.cpp:766
+  !isValidUDSuffix(LangOpts, StringRef(s, ThisTokEnd - s))) {
+Diags.Report(AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
+ diag::err_invalid_digit)

eduucaldas wrote:
> How about just using `Lexer::AdvanceToTokenCharacter`? 
Done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83480



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


[PATCH] D83362: Fix warning caused by __builtin_expect_with_probability was not handled in places such as constant folding

2020-07-09 Thread Zhi Zhuang via Phabricator via cfe-commits
LukeZhuang added a comment.

Thank you very much!


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

https://reviews.llvm.org/D83362



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


[PATCH] D83213: [AST][RecoveryExpr] Don't set the instantiation-bit.

2020-07-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D83213#2141387 , @hokein wrote:

> I think this depends on how we interpret the instantiation-dependent bit. In 
> clang, it currently has two semantics:
>
> 1. an expression (somehow) depends on a template parameter;
> 2. an expression is dependent;


Not trying to be difficult, but I'm not sure what you mean by "dependent" in 
#2. Informally, it means the same thing as #1. Formally, C++ defines 
type-dependence and value-dependence for expressions, and the ABI defines 
instantiation-dependence for expressions - AFAIK "dependent" doesn't have a 
formal meaning.

So I'd rather say it has two definitions:

- informally, it (somehow) depends on a template parameter.
- formally (from the C++ABI), an expression is instantiation-dependent if it is 
type-dependent or value-dependent, or it has a subexpression that is 
type-dependent or value-dependent.

To preserve the linkage between these two, **IMO** we need to extend the formal 
definition to errors if and only if we extend the informal definition to 
errors. Accidentally unlinking the two is almost certain to result in subtle 
bugs as either the implementation subtly differs from the spec, or it subtly 
differs from the mental model.
That is, we need to decide whether to make all of these changes:

- (informal) instantiation-dependent means it (somehow) depends on a template 
parameter or error
- (formal) value-dependent means that (informally) an expressions's value 
depends on a tparam or err
- (formal) type-dependent means that (informally) an expression's type depends 
on a tparam or err

The approach so far has been **YES**. This looks like:

- all RecoveryExprs are value-dependent, instantiation-dependent, and 
contains-errors
- RecoveryExprs are type-dependent if we didn't guess the type, or we guessed 
it was a dependent type

Here we make use of existing codepaths that turn off checking in the presence 
of dependent code. We mostly need to check contains-errors to prevent a 
bad-recovery cascade.

The alternate approach is **NO**. This looks like:

- all RecoveryExpr are contains-errors
- a RecoveryExpr are instantiation-dependent if a subexpression is (i.e. refers 
to a template param)
- a RecoveryExpr is value-dependent if one of its direct subexpressions is, or 
if the broken code is likely to yield different values in different template 
instantiations due to the context
- a RecoveryExpr is type-dependent if its type is known to be dependent, or if 
the broken code is likely to yield different types in different template 
instantiations due to the context

Here codepaths that turn off checking need to turn it off for errors explicitly.
There's subtlety in the value-depnedent and type-dependent bits, which probably 
needs to be resolved on a case-by-case basis.
And there's more machinery needed: when an expression's type is not known but 
isn't believed to be dependent, what is it? I think we end up needing to define 
RecoveryType here (the fundamental contains-errors type).

So this is doable and maybe even a good idea (not obvious to me what the 
practical differences are). But it's a large change, not a small one like this 
patch.

> **Option 1** (what this patch does):
> 
> instantiation-dependence still  implies the expression involves a template 
> parameter -- if a recovery expression doesn't involves a template parameter, 
> we don't set this flag

It doesn't make sense IMO to make this change without also saying 
"value-dependence implies the value dependds on a template parameter". It's too 
surprising and hard to reason about, and I don't see a principled reason for 
this distinction.

> Not sure what pros would buy us

That's the thing that surprises me, it's a richer model, it's principled and 
correct... but I have no intuition what we can use it for.

> **Option 2**:
> cons:
> 
> - keep using the instantiation name is confusing; we could do clarify the 
> document of isInstantiation

Yeah. I don't think actually renaming it would be appropriate, but we should be 
really explicit about its non-template meaning, and also give a generalized 
intuitive definition that makes sense. ("Depends in any way on a template 
parameter or error. In a template context, this implies that the resolution of 
this expr may cause instantiation to fail")

> While writing this, I'm starting to like the option2, any other thoughts?

Yeah, I think we'd have to have some concrete benefits to pursue option 1. 
Doing it right is a lot of work.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83213



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


[clang] 67422e4 - [MSP430] Align the _Complex ABI with current msp430-gcc

2020-07-09 Thread Anatoly Trosinenko via cfe-commits

Author: Anatoly Trosinenko
Date: 2020-07-09T18:28:48+03:00
New Revision: 67422e4294754e08f277b1ba22820487eb76b918

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

LOG: [MSP430] Align the _Complex ABI with current msp430-gcc

Assembler output is checked against msp430-gcc 9.2.0.50 from TI.

Reviewed By: asl

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

Added: 
clang/test/CodeGen/msp430-abi-complex.c

Modified: 
clang/lib/CodeGen/TargetInfo.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/TargetInfo.cpp 
b/clang/lib/CodeGen/TargetInfo.cpp
index 801adc29acd1..b83267dec6f0 100644
--- a/clang/lib/CodeGen/TargetInfo.cpp
+++ b/clang/lib/CodeGen/TargetInfo.cpp
@@ -7475,10 +7475,49 @@ ABIArgInfo 
SystemZABIInfo::classifyArgumentType(QualType Ty) const {
 
 namespace {
 
+class MSP430ABIInfo : public DefaultABIInfo {
+  static ABIArgInfo complexArgInfo() {
+ABIArgInfo Info = ABIArgInfo::getDirect();
+Info.setCanBeFlattened(false);
+return Info;
+  }
+
+public:
+  MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
+
+  ABIArgInfo classifyReturnType(QualType RetTy) const {
+if (RetTy->isAnyComplexType())
+  return complexArgInfo();
+
+return DefaultABIInfo::classifyReturnType(RetTy);
+  }
+
+  ABIArgInfo classifyArgumentType(QualType RetTy) const {
+if (RetTy->isAnyComplexType())
+  return complexArgInfo();
+
+return DefaultABIInfo::classifyArgumentType(RetTy);
+  }
+
+  // Just copy the original implementations because
+  // DefaultABIInfo::classify{Return,Argument}Type() are not virtual
+  void computeInfo(CGFunctionInfo &FI) const override {
+if (!getCXXABI().classifyReturnType(FI))
+  FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
+for (auto &I : FI.arguments())
+  I.info = classifyArgumentType(I.type);
+  }
+
+  Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
+QualType Ty) const override {
+return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
+  }
+};
+
 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
 public:
   MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
-  : TargetCodeGenInfo(std::make_unique(CGT)) {}
+  : TargetCodeGenInfo(std::make_unique(CGT)) {}
   void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
CodeGen::CodeGenModule &M) const override;
 };

diff  --git a/clang/test/CodeGen/msp430-abi-complex.c 
b/clang/test/CodeGen/msp430-abi-complex.c
new file mode 100644
index ..faafcd2cde3f
--- /dev/null
+++ b/clang/test/CodeGen/msp430-abi-complex.c
@@ -0,0 +1,226 @@
+// REQUIRES: msp430-registered-target
+// RUN: %clang -target msp430 -Os -S -o- %s | FileCheck %s
+
+volatile int N;
+volatile int i16_1, i16_2;
+volatile long i32_1, i32_2;
+volatile long long i64_1, i64_2;
+volatile float f1, f2;
+volatile double d1, d2;
+
+_Static_assert(sizeof(int) == 2, "Assumption failed");
+_Static_assert(sizeof(long) == 4, "Assumption failed");
+_Static_assert(sizeof(long long) == 8, "Assumption failed");
+
+void complex_i16_arg_first(int _Complex x, int n) {
+// CHECK-LABEL: @complex_i16_arg_first
+  i16_1 = __real__ x;
+// CHECK-DAG: mov r12, &i16_1
+  i16_2 = __imag__ x;
+// CHECK-DAG: mov r13, &i16_2
+  N = n;
+// CHECK-DAG: mov r14, &N
+// CHECK: ret
+}
+
+void complex_i16_arg_second(int n, int _Complex x) {
+// CHECK-LABEL: @complex_i16_arg_second
+  N = n;
+// CHECK-DAG: mov r12, &N
+  i16_1 = __real__ x;
+// CHECK-DAG: mov r13, &i16_1
+  i16_2 = __imag__ x;
+// CHECK-DAG: mov r14, &i16_2
+// CHECK: ret
+}
+
+void complex_i32_arg_first(long _Complex x, int n) {
+// CHECK-LABEL: @complex_i32_arg_first
+  i32_1 = __real__ x;
+// CHECK-DAG: mov r12, &i32_1
+// CHECK-DAG: mov r13, &i32_1+2
+  i32_2 = __imag__ x;
+// CHECK-DAG: mov r14, &i32_2
+// CHECK-DAG: mov r15, &i32_2+2
+  N = n;
+// CHECK-DAG: mov 2(r1), &N
+// CHECK: ret
+}
+
+void complex_i32_arg_second(int n, long _Complex x) {
+// CHECK-LABEL: @complex_i32_arg_second
+  N = n;
+// CHECK-DAG: mov r12, &N
+  i32_1 = __real__ x;
+// CHECK-DAG: mov 2(r1), &i32_1
+// CHECK-DAG: mov 4(r1), &i32_1+2
+  i32_2 = __imag__ x;
+// CHECK-DAG: mov 6(r1), &i32_2
+// CHECK-DAG: mov 8(r1), &i32_2+2
+// CHECK: ret
+}
+
+void complex_i64_arg_first(long long _Complex x, int n) {
+// CHECK-LABEL: @complex_i64_arg_first
+  i64_1 = __real__ x;
+// CHECK-DAG: mov 2(r1), &i64_1
+// CHECK-DAG: mov 4(r1), &i64_1+2
+// CHECK-DAG: mov 6(r1), &i64_1+4
+// CHECK-DAG: mov 8(r1), &i64_1+6
+  i64_2 = __imag__ x;
+// CHECK-DAG: mov 10(r1), &i64_2
+// CHECK-DAG: mov 12(r1), &i64_2+2
+// CHECK-DAG: mov 14(r1), &i64_2+4
+// CHECK-DAG: mov 16(r1), &i64_2+6
+  N = n;
+// CHECK-DAG: mov r12, &N
+// CHECK: ret
+}
+
+void complex_i64_arg_second(int n, 

[PATCH] D77493: [clang-tidy] Add do-not-refer-atomic-twice check

2020-07-09 Thread JF Bastien via Phabricator via cfe-commits
jfb added inline comments.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-do-not-refer-atomic-twice.cpp:10
+_Atomic int n2 = ATOMIC_VAR_INIT(0);
+_Atomic(int) n3 = ATOMIC_VAR_INIT(0);
+

Can you cover `std::atomic` as well?



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-do-not-refer-atomic-twice.cpp:10
+_Atomic int n2 = ATOMIC_VAR_INIT(0);
+_Atomic(int) n3 = ATOMIC_VAR_INIT(0);
+

jfb wrote:
> Can you cover `std::atomic` as well?
We deprecated `ATOMIC_VAR_INIT` in C++20 and C17, I wouldn't use it here (even 
if it's just your own macro).



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/bugprone-do-not-refer-atomic-twice.cpp:77
+  n3++;
+}

Can you check that non-atomic-accesses to the variable also work, for example 
taking the atomic's address, using it in unevaluated `sizeof` / `offsetof`, etc.


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D77493



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


[PATCH] D82646: [MSP430] Align the _Complex ABI with current msp430-gcc

2020-07-09 Thread Anatoly Trosinenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG67422e429475: [MSP430] Align the _Complex ABI with current 
msp430-gcc (authored by atrosinenko).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82646

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/msp430-abi-complex.c

Index: clang/test/CodeGen/msp430-abi-complex.c
===
--- /dev/null
+++ clang/test/CodeGen/msp430-abi-complex.c
@@ -0,0 +1,226 @@
+// REQUIRES: msp430-registered-target
+// RUN: %clang -target msp430 -Os -S -o- %s | FileCheck %s
+
+volatile int N;
+volatile int i16_1, i16_2;
+volatile long i32_1, i32_2;
+volatile long long i64_1, i64_2;
+volatile float f1, f2;
+volatile double d1, d2;
+
+_Static_assert(sizeof(int) == 2, "Assumption failed");
+_Static_assert(sizeof(long) == 4, "Assumption failed");
+_Static_assert(sizeof(long long) == 8, "Assumption failed");
+
+void complex_i16_arg_first(int _Complex x, int n) {
+// CHECK-LABEL: @complex_i16_arg_first
+  i16_1 = __real__ x;
+// CHECK-DAG: mov r12, &i16_1
+  i16_2 = __imag__ x;
+// CHECK-DAG: mov r13, &i16_2
+  N = n;
+// CHECK-DAG: mov r14, &N
+// CHECK: ret
+}
+
+void complex_i16_arg_second(int n, int _Complex x) {
+// CHECK-LABEL: @complex_i16_arg_second
+  N = n;
+// CHECK-DAG: mov r12, &N
+  i16_1 = __real__ x;
+// CHECK-DAG: mov r13, &i16_1
+  i16_2 = __imag__ x;
+// CHECK-DAG: mov r14, &i16_2
+// CHECK: ret
+}
+
+void complex_i32_arg_first(long _Complex x, int n) {
+// CHECK-LABEL: @complex_i32_arg_first
+  i32_1 = __real__ x;
+// CHECK-DAG: mov r12, &i32_1
+// CHECK-DAG: mov r13, &i32_1+2
+  i32_2 = __imag__ x;
+// CHECK-DAG: mov r14, &i32_2
+// CHECK-DAG: mov r15, &i32_2+2
+  N = n;
+// CHECK-DAG: mov 2(r1), &N
+// CHECK: ret
+}
+
+void complex_i32_arg_second(int n, long _Complex x) {
+// CHECK-LABEL: @complex_i32_arg_second
+  N = n;
+// CHECK-DAG: mov r12, &N
+  i32_1 = __real__ x;
+// CHECK-DAG: mov 2(r1), &i32_1
+// CHECK-DAG: mov 4(r1), &i32_1+2
+  i32_2 = __imag__ x;
+// CHECK-DAG: mov 6(r1), &i32_2
+// CHECK-DAG: mov 8(r1), &i32_2+2
+// CHECK: ret
+}
+
+void complex_i64_arg_first(long long _Complex x, int n) {
+// CHECK-LABEL: @complex_i64_arg_first
+  i64_1 = __real__ x;
+// CHECK-DAG: mov 2(r1), &i64_1
+// CHECK-DAG: mov 4(r1), &i64_1+2
+// CHECK-DAG: mov 6(r1), &i64_1+4
+// CHECK-DAG: mov 8(r1), &i64_1+6
+  i64_2 = __imag__ x;
+// CHECK-DAG: mov 10(r1), &i64_2
+// CHECK-DAG: mov 12(r1), &i64_2+2
+// CHECK-DAG: mov 14(r1), &i64_2+4
+// CHECK-DAG: mov 16(r1), &i64_2+6
+  N = n;
+// CHECK-DAG: mov r12, &N
+// CHECK: ret
+}
+
+void complex_i64_arg_second(int n, long long _Complex x) {
+// CHECK-LABEL: @complex_i64_arg_second
+  N = n;
+// CHECK-DAG: mov r12, &N
+  i64_1 = __real__ x;
+// CHECK-DAG: mov 2(r1), &i64_1
+// CHECK-DAG: mov 4(r1), &i64_1+2
+// CHECK-DAG: mov 6(r1), &i64_1+4
+// CHECK-DAG: mov 8(r1), &i64_1+6
+  i64_2 = __imag__ x;
+// CHECK-DAG: mov 10(r1), &i64_2
+// CHECK-DAG: mov 12(r1), &i64_2+2
+// CHECK-DAG: mov 14(r1), &i64_2+4
+// CHECK-DAG: mov 16(r1), &i64_2+6
+// CHECK: ret
+}
+
+void complex_float_arg_first(float _Complex x, int n) {
+// CHECK-LABEL: @complex_float_arg_first
+  f1 = __real__ x;
+// CHECK-DAG: mov r12, &f1
+// CHECK-DAG: mov r13, &f1+2
+  f2 = __imag__ x;
+// CHECK-DAG: mov r14, &f2
+// CHECK-DAG: mov r15, &f2+2
+  N = n;
+// CHECK-DAG: mov 2(r1), &N
+// CHECK: ret
+}
+
+void complex_float_arg_second(int n, float _Complex x) {
+// CHECK-LABEL: @complex_float_arg_second
+  N = n;
+// CHECK-DAG: mov r12, &N
+  f1 = __real__ x;
+// CHECK-DAG: mov 2(r1), &f1
+// CHECK-DAG: mov 4(r1), &f1+2
+  f2 = __imag__ x;
+// CHECK-DAG: mov 6(r1), &f2
+// CHECK-DAG: mov 8(r1), &f2+2
+// CHECK: ret
+}
+
+void complex_double_arg_first(double _Complex x, int n) {
+// CHECK-LABEL: @complex_double_arg_first
+  d1 = __real__ x;
+// CHECK-DAG: mov 2(r1), &d1
+// CHECK-DAG: mov 4(r1), &d1+2
+// CHECK-DAG: mov 6(r1), &d1+4
+// CHECK-DAG: mov 8(r1), &d1+6
+  d2 = __imag__ x;
+// CHECK-DAG: mov 10(r1), &d2
+// CHECK-DAG: mov 12(r1), &d2+2
+// CHECK-DAG: mov 14(r1), &d2+4
+// CHECK-DAG: mov 16(r1), &d2+6
+  N = n;
+// CHECK-DAG: mov r12, &N
+// CHECK: ret
+}
+
+void complex_double_arg_second(int n, double _Complex x) {
+// CHECK-LABEL: @complex_double_arg_second
+  d1 = __real__ x;
+// CHECK-DAG: mov 2(r1), &d1
+// CHECK-DAG: mov 4(r1), &d1+2
+// CHECK-DAG: mov 6(r1), &d1+4
+// CHECK-DAG: mov 8(r1), &d1+6
+  d2 = __imag__ x;
+// CHECK-DAG: mov 10(r1), &d2
+// CHECK-DAG: mov 12(r1), &d2+2
+// CHECK-DAG: mov 14(r1), &d2+4
+// CHECK-DAG: mov 16(r1), &d2+6
+  N = n;
+// CHECK-DAG: mov r12, &N
+// CHECK: ret
+}
+
+int _Complex complex_i16_res(void) {
+// CHECK-LABEL: @complex_i16_res
+  int _Complex res;
+  __real__ res = 0x1122;
+// CHECK-DAG: mov #4386, r12
+  __imag__ res = 0x3344;
+// CHECK-DAG: mov #13124, r13
+  return res;
+

[PATCH] D82800: [OPENMP50] extend array section for stride (Parsing/Sema/AST)

2020-07-09 Thread Chi Chun Chen via Phabricator via cfe-commits
cchen added a comment.

@ABataev , can you commit this patch for me when you have time? Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82800



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


[PATCH] D83419: [clangd] Add error() function for creating formatv-style llvm::Errors. NFC

2020-07-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D83419#2141433 , @hokein wrote:

> > Sorry, I should give some reasons here:
>
> These are sensible reasons. My only (not a strong) concern is that "error" is 
> quite special, we need to be careful to choose it -- note that there is an 
> `error` function in glibc which is used for error-reporting.


Yeah. This is also true of `log` which is is a c standard library function. 
I've seen slightly funny diagnostics when the header is missing, but no worse 
than that. It's not possible to actually call the wrong function here - neither 
of the first two parameters of glibc `error()` can be a string.

> maybe there are other better names (`stringError`?) other than 
> `createError`/`makeError`.

Maybe, it's hard to know what's important enough to include in the name. 
Neither the fact that the implementation stores a string, or that we're 
allocating an object seem to qualify to me.
Maybe something to do with the formatting like `errorV` or `fmtError` or 
something but they seem pretty ugly. The difficulty of being part of the `log` 
family, which doesn't have suffixes...

>> I guess makeError is still better than the status quo, but not enough to 
>> feel motivated to clean this up right now. Maybe someone else wants to pick 
>> this up?
> 
> unless you strongly insist on `error` name, I'm happy to help with (looks 
> like it's just a low-hanging rename fruit). I think this is a nice cleanup, 
> we should make it happen (either using `error` or other names).

Sure. I'm probably letting the perfect be the enemy of the good here, still sad 
about the json::Value::asInt() -> json::Value::getAsInt() thing...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83419



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


[PATCH] D82800: [OPENMP50] extend array section for stride (Parsing/Sema/AST)

2020-07-09 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added a comment.

In D82800#2141818 , @cchen wrote:

> @ABataev , can you commit this patch for me when you have time? Thanks.


I think you can request commit access from Chris Lattner and commit it yourself.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82800



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


[PATCH] D75229: [clang-tidy] Add signal-in-multithreaded-program check

2020-07-09 Thread JF Bastien via Phabricator via cfe-commits
jfb added a comment.

It seems like you don't want this check to trigger on POSIX platforms, given:

> Exceptions CON37-C-EX1: Implementations such as POSIX that provide defined 
> behavior when multithreaded programs use custom signal handlers are exempt 
> from this rule [IEEE Std 1003.1-2013].


Repository:
  rCTE Clang Tools Extra

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

https://reviews.llvm.org/D75229



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


[PATCH] D83480: Refactored NumericLiteralParser to not require a Preprocessor

2020-07-09 Thread Dmitri Gribenko via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3cca818efabb: Refactored NumericLiteralParser to not require 
a Preprocessor (authored by gribozavr).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83480

Files:
  clang/include/clang/Lex/LiteralSupport.h
  clang/lib/Lex/LiteralSupport.cpp
  clang/lib/Lex/PPExpressions.cpp
  clang/lib/Lex/Preprocessor.cpp
  clang/lib/Sema/SemaExpr.cpp

Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -3634,7 +3634,9 @@
   if (Invalid)
 return ExprError();
 
-  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
+  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
+   PP.getSourceManager(), PP.getLangOpts(),
+   PP.getTargetInfo(), PP.getDiagnostics());
   if (Literal.hadError)
 return ExprError();
 
Index: clang/lib/Lex/Preprocessor.cpp
===
--- clang/lib/Lex/Preprocessor.cpp
+++ clang/lib/Lex/Preprocessor.cpp
@@ -1370,7 +1370,9 @@
   StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
   if (NumberInvalid)
 return false;
-  NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
+  NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
+   getLangOpts(), getTargetInfo(),
+   getDiagnostics());
   if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
 return false;
   llvm::APInt APVal(64, 0);
Index: clang/lib/Lex/PPExpressions.cpp
===
--- clang/lib/Lex/PPExpressions.cpp
+++ clang/lib/Lex/PPExpressions.cpp
@@ -295,7 +295,9 @@
 if (NumberInvalid)
   return true; // a diagnostic was already reported
 
-NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
+NumericLiteralParser Literal(Spelling, PeekTok.getLocation(),
+ PP.getSourceManager(), PP.getLangOpts(),
+ PP.getTargetInfo(), PP.getDiagnostics());
 if (Literal.hadError)
   return true; // a diagnostic was already reported.
 
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -525,8 +525,12 @@
 ///
 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
SourceLocation TokLoc,
-   Preprocessor &PP)
-  : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
+   const SourceManager &SM,
+   const LangOptions &LangOpts,
+   const TargetInfo &Target,
+   DiagnosticsEngine &Diags)
+: SM(SM), LangOpts(LangOpts), Diags(Diags),
+  ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
 
   // This routine assumes that the range begin/end matches the regex for integer
   // and FP constants (specifically, the 'pp-number' regex), and assumes that
@@ -572,7 +576,7 @@
   checkSeparator(TokLoc, s, CSK_AfterDigits);
 
   // Initial scan to lookahead for fixed point suffix.
-  if (PP.getLangOpts().FixedPoint) {
+  if (LangOpts.FixedPoint) {
 for (const char *c = s; c != ThisTokEnd; ++c) {
   if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
 saw_fixed_point_suffix = true;
@@ -592,14 +596,16 @@
 switch (*s) {
 case 'R':
 case 'r':
-  if (!PP.getLangOpts().FixedPoint) break;
+  if (!LangOpts.FixedPoint)
+break;
   if (isFract || isAccum) break;
   if (!(saw_period || saw_exponent)) break;
   isFract = true;
   continue;
 case 'K':
 case 'k':
-  if (!PP.getLangOpts().FixedPoint) break;
+  if (!LangOpts.FixedPoint)
+break;
   if (isFract || isAccum) break;
   if (!(saw_period || saw_exponent)) break;
   isAccum = true;
@@ -607,7 +613,8 @@
 case 'h':  // FP Suffix for "half".
 case 'H':
   // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
-  if (!(PP.getLangOpts().Half || PP.getLangOpts().FixedPoint)) break;
+  if (!(LangOpts.Half || LangOpts.FixedPoint))
+break;
   if (isIntegerLiteral()) break;  // Error for integer constant.
   if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
   isHalf = true;
@@ -621,8 +628,8 @@
   // CUDA host and device may have different _Float16 support, therefore
   // allows f16 literals to avoid false alarm.
   // ToDo: m

[clang] 3cca818 - Refactored NumericLiteralParser to not require a Preprocessor

2020-07-09 Thread Dmitri Gribenko via cfe-commits

Author: Dmitri Gribenko
Date: 2020-07-09T17:33:58+02:00
New Revision: 3cca818efabbccdde36b06609cf75ee7caa8e012

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

LOG: Refactored NumericLiteralParser to not require a Preprocessor

Summary:
We would like to use NumericLiteralParser in the implementation of the
syntax tree builder, and plumbing a preprocessor there seems
inconvenient and superfluous.

Reviewers: eduucaldas

Reviewed By: eduucaldas

Subscribers: gribozavr2, cfe-commits

Tags: #clang

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

Added: 


Modified: 
clang/include/clang/Lex/LiteralSupport.h
clang/lib/Lex/LiteralSupport.cpp
clang/lib/Lex/PPExpressions.cpp
clang/lib/Lex/Preprocessor.cpp
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/LiteralSupport.h 
b/clang/include/clang/Lex/LiteralSupport.h
index 6829771b2830..0c4f0fe277b7 100644
--- a/clang/include/clang/Lex/LiteralSupport.h
+++ b/clang/include/clang/Lex/LiteralSupport.h
@@ -40,7 +40,9 @@ void expandUCNs(SmallVectorImpl &Buf, StringRef Input);
 /// of a ppnumber, classifying it as either integer, floating, or erroneous,
 /// determines the radix of the value and can convert it to a useful value.
 class NumericLiteralParser {
-  Preprocessor &PP; // needed for diagnostics
+  const SourceManager &SM;
+  const LangOptions &LangOpts;
+  DiagnosticsEngine &Diags;
 
   const char *const ThisTokBegin;
   const char *const ThisTokEnd;
@@ -54,9 +56,9 @@ class NumericLiteralParser {
   SmallString<32> UDSuffixBuf;
 
 public:
-  NumericLiteralParser(StringRef TokSpelling,
-   SourceLocation TokLoc,
-   Preprocessor &PP);
+  NumericLiteralParser(StringRef TokSpelling, SourceLocation TokLoc,
+   const SourceManager &SM, const LangOptions &LangOpts,
+   const TargetInfo &Target, DiagnosticsEngine &Diags);
   bool hadError : 1;
   bool isUnsigned : 1;
   bool isLong : 1;  // This is *not* set for long long.

diff  --git a/clang/lib/Lex/LiteralSupport.cpp 
b/clang/lib/Lex/LiteralSupport.cpp
index f44614b4bec4..eb16bc8c7da2 100644
--- a/clang/lib/Lex/LiteralSupport.cpp
+++ b/clang/lib/Lex/LiteralSupport.cpp
@@ -525,8 +525,12 @@ static void EncodeUCNEscape(const char *ThisTokBegin, 
const char *&ThisTokBuf,
 ///
 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
SourceLocation TokLoc,
-   Preprocessor &PP)
-  : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
+   const SourceManager &SM,
+   const LangOptions &LangOpts,
+   const TargetInfo &Target,
+   DiagnosticsEngine &Diags)
+: SM(SM), LangOpts(LangOpts), Diags(Diags),
+  ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
 
   // This routine assumes that the range begin/end matches the regex for 
integer
   // and FP constants (specifically, the 'pp-number' regex), and assumes that
@@ -572,7 +576,7 @@ NumericLiteralParser::NumericLiteralParser(StringRef 
TokSpelling,
   checkSeparator(TokLoc, s, CSK_AfterDigits);
 
   // Initial scan to lookahead for fixed point suffix.
-  if (PP.getLangOpts().FixedPoint) {
+  if (LangOpts.FixedPoint) {
 for (const char *c = s; c != ThisTokEnd; ++c) {
   if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
 saw_fixed_point_suffix = true;
@@ -592,14 +596,16 @@ NumericLiteralParser::NumericLiteralParser(StringRef 
TokSpelling,
 switch (*s) {
 case 'R':
 case 'r':
-  if (!PP.getLangOpts().FixedPoint) break;
+  if (!LangOpts.FixedPoint)
+break;
   if (isFract || isAccum) break;
   if (!(saw_period || saw_exponent)) break;
   isFract = true;
   continue;
 case 'K':
 case 'k':
-  if (!PP.getLangOpts().FixedPoint) break;
+  if (!LangOpts.FixedPoint)
+break;
   if (isFract || isAccum) break;
   if (!(saw_period || saw_exponent)) break;
   isAccum = true;
@@ -607,7 +613,8 @@ NumericLiteralParser::NumericLiteralParser(StringRef 
TokSpelling,
 case 'h':  // FP Suffix for "half".
 case 'H':
   // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
-  if (!(PP.getLangOpts().Half || PP.getLangOpts().FixedPoint)) break;
+  if (!(LangOpts.Half || LangOpts.FixedPoint))
+break;
   if (isIntegerLiteral()) break;  // Error for integer constant.
   if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
   isHalf = true;
@@ -621,8 +628,8 @@ NumericLiteralParser::N

[PATCH] D82800: [OPENMP50] extend array section for stride (Parsing/Sema/AST)

2020-07-09 Thread Chi Chun Chen via Phabricator via cfe-commits
cchen added a comment.

In D82800#2141819 , @ABataev wrote:

> In D82800#2141818 , @cchen wrote:
>
> > @ABataev , can you commit this patch for me when you have time? Thanks.
>
>
> I think you can request commit access from Chris Lattner and commit it 
> yourself.


I'll do that, thanks for telling!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82800



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


[PATCH] D83490: [cmake] Support running compiler-rt tests in CrossWinToARMLinux.cmake

2020-07-09 Thread Sergej Jaskiewicz via Phabricator via cfe-commits
broadwaylamb created this revision.
broadwaylamb added a reviewer: vvereschaka.
Herald added subscribers: cfe-commits, danielkiss, kristof.beyls, mgorny, 
dberris.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D83490

Files:
  clang/cmake/caches/CrossWinToARMLinux.cmake


Index: clang/cmake/caches/CrossWinToARMLinux.cmake
===
--- clang/cmake/caches/CrossWinToARMLinux.cmake
+++ clang/cmake/caches/CrossWinToARMLinux.cmake
@@ -72,6 +72,7 @@
 set(COMPILER_RT_BUILD_LIBFUZZER OFF CACHE BOOL "")
 set(COMPILER_RT_BUILD_PROFILE   OFF CACHE BOOL "")
 set(COMPILER_RT_DEFAULT_TARGET_ONLY ON CACHE BOOL "")
+set(COMPILER_RT_INCLUDE_TESTS   ON CACHE BOOL "")
 
 set(LIBUNWIND_USE_COMPILER_RT   ON CACHE BOOL "")
 set(LIBUNWIND_TARGET_TRIPLE "${CMAKE_C_COMPILER_TARGET}" CACHE 
STRING "")
@@ -108,6 +109,10 @@
   set(DEFAULT_TEST_TARGET_INFO  
"libcxx.test.target_info.LinuxRemoteTI")
 
   # Allow override with the custom values.
+  if(NOT DEFINED COMPILER_RT_EMULATOR)
+set(COMPILER_RT_EMULATOR"\\\"${Python3_EXECUTABLE}\\\" 
\\\"${LLVM_PROJECT_DIR}/libcxx/utils/ssh.py\\\" --execdir %%T --test-executable 
%%t --host ${REMOTE_TEST_USER}@${REMOTE_TEST_HOST} --" CACHE STRING "")
+  endif()
+  
   if(NOT DEFINED LIBUNWIND_TARGET_INFO)
 set(LIBUNWIND_TARGET_INFO   "${DEFAULT_TEST_TARGET_INFO}" 
CACHE STRING "")
   endif()


Index: clang/cmake/caches/CrossWinToARMLinux.cmake
===
--- clang/cmake/caches/CrossWinToARMLinux.cmake
+++ clang/cmake/caches/CrossWinToARMLinux.cmake
@@ -72,6 +72,7 @@
 set(COMPILER_RT_BUILD_LIBFUZZER OFF CACHE BOOL "")
 set(COMPILER_RT_BUILD_PROFILE   OFF CACHE BOOL "")
 set(COMPILER_RT_DEFAULT_TARGET_ONLY ON CACHE BOOL "")
+set(COMPILER_RT_INCLUDE_TESTS   ON CACHE BOOL "")
 
 set(LIBUNWIND_USE_COMPILER_RT   ON CACHE BOOL "")
 set(LIBUNWIND_TARGET_TRIPLE "${CMAKE_C_COMPILER_TARGET}" CACHE STRING "")
@@ -108,6 +109,10 @@
   set(DEFAULT_TEST_TARGET_INFO  "libcxx.test.target_info.LinuxRemoteTI")
 
   # Allow override with the custom values.
+  if(NOT DEFINED COMPILER_RT_EMULATOR)
+set(COMPILER_RT_EMULATOR"\\\"${Python3_EXECUTABLE}\\\" \\\"${LLVM_PROJECT_DIR}/libcxx/utils/ssh.py\\\" --execdir %%T --test-executable %%t --host ${REMOTE_TEST_USER}@${REMOTE_TEST_HOST} --" CACHE STRING "")
+  endif()
+  
   if(NOT DEFINED LIBUNWIND_TARGET_INFO)
 set(LIBUNWIND_TARGET_INFO   "${DEFAULT_TEST_TARGET_INFO}" CACHE STRING "")
   endif()
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D82436: [clangd] Implement textDocument/foldingRange

2020-07-09 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Tests :-)




Comment at: clang-tools-extra/clangd/Protocol.h:1522
+struct FoldingRange {
+  unsigned startLine;
+  llvm::Optional startCharacter;

nit: =0 (and on endLine)



Comment at: clang-tools-extra/clangd/SemanticSelection.cpp:107
+  // FIXME(kirillbobyrev): getDocumentSymbols() is conveniently available but
+  // limited (e.g. doesn't yield blocks inside functions). Replace this with a
+  // more general RecursiveASTVisitor implementation instead.

I think this should mention the contents-of-blocks vs whole-nodes issue too.



Comment at: clang-tools-extra/clangd/SemanticSelection.h:28
 
+/// Retrieves folding ranges in the "main file" section of given AST.
+llvm::Expected> getFoldingRanges(ParsedAST &AST);

I think "main file" section is just a for-now implementation detail, I'd leave 
this out.



Comment at: clang-tools-extra/clangd/tool/ClangdMain.cpp:300
+opt FoldingRanges{
+"folding-rangees",
+cat(Features),

rangees -> ranges


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D82436



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


[PATCH] D82767: clang-format: Explicitly use python3

2020-07-09 Thread serge via Phabricator via cfe-commits
serge-sans-paille added a comment.

In D82767#2132903 , @MyDeveloperDay 
wrote:

> We may not be consistent across all of LLVM
>
>   $ find . -name '*.py' -print -exec /usr/bin/head -2 {} \; | grep "#!" | 
> sort | uniq -c
> 6 #! /usr/bin/env python
> 2 #! /usr/bin/env python3
> 2 #! /usr/bin/python
> 1 #!/bin/env python
>   133 #!/usr/bin/env python
>13 #!/usr/bin/env python3
>49 #!/usr/bin/python
>


My understanding is that explicitly requiring python3 may make sense if the 
script is not backward-compatible with python2, while requiring python means 
the version is not important.
At the end-of-year, we should be able to harmonize shebangs to #!/usr/bin/env 
python3 or #!/usr/bin/env python


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

https://reviews.llvm.org/D82767



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


[PATCH] D83426: Unbreak Clang standalone build.

2020-07-09 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd accepted this revision.
compnerd added a comment.
This revision is now accepted and ready to land.

Seems reasonable to me, this seems like it would be useful to downstream 
packagers for Linux distros.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83426



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


  1   2   3   >