[PATCH] D52420: [clangd] Fix crash if pending computations were active on exit

2018-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343067: [clangd] Fix crash if pending computations were 
active on exit (authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52420?vs=166684=167046#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52420

Files:
  clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
  clang-tools-extra/trunk/clangd/ClangdLSPServer.h

Index: clang-tools-extra/trunk/clangd/ClangdLSPServer.h
===
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.h
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.h
@@ -19,6 +19,7 @@
 #include "ProtocolHandlers.h"
 #include "clang/Tooling/Core/Replacement.h"
 #include "llvm/ADT/Optional.h"
+#include 
 
 namespace clang {
 namespace clangd {
@@ -170,7 +171,9 @@
   // Server must be the last member of the class to allow its destructor to exit
   // the worker thread that may otherwise run an async callback on partially
   // destructed instance of ClangdLSPServer.
-  ClangdServer Server;
+  // Set in construtor and destroyed when run() finishes. To ensure all worker
+  // threads exit before run() returns.
+  std::unique_ptr Server;
 };
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
@@ -77,9 +77,9 @@
 applyConfiguration(*Params.initializationOptions);
 
   if (Params.rootUri && *Params.rootUri)
-Server.setRootPath(Params.rootUri->file());
+Server->setRootPath(Params.rootUri->file());
   else if (Params.rootPath && !Params.rootPath->empty())
-Server.setRootPath(*Params.rootPath);
+Server->setRootPath(*Params.rootPath);
 
   CCOpts.EnableSnippets =
   Params.capabilities.textDocument.completion.completionItem.snippetSupport;
@@ -147,7 +147,7 @@
   std::string  = Params.textDocument.text;
 
   DraftMgr.addDraft(File, Contents);
-  Server.addDocument(File, Contents, WantDiagnostics::Yes);
+  Server->addDocument(File, Contents, WantDiagnostics::Yes);
 }
 
 void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams ) {
@@ -164,17 +164,17 @@
 // the client.  It is better to remove the draft and let further operations
 // fail rather than giving wrong results.
 DraftMgr.removeDraft(File);
-Server.removeDocument(File);
+Server->removeDocument(File);
 CDB.invalidate(File);
 elog("Failed to update {0}: {1}", File, Contents.takeError());
 return;
   }
 
-  Server.addDocument(File, *Contents, WantDiags);
+  Server->addDocument(File, *Contents, WantDiags);
 }
 
 void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams ) {
-  Server.onFileEvent(Params);
+  Server->onFileEvent(Params);
 }
 
 void ClangdLSPServer::onCommand(ExecuteCommandParams ) {
@@ -210,7 +210,7 @@
 }
 
 void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams ) {
-  Server.workspaceSymbols(
+  Server->workspaceSymbols(
   Params.query, CCOpts.Limit,
   [this](llvm::Expected> Items) {
 if (!Items)
@@ -230,7 +230,7 @@
 return replyError(ErrorCode::InvalidParams,
   "onRename called for non-added file");
 
-  Server.rename(
+  Server->rename(
   File, Params.position, Params.newName,
   [File, Code,
Params](llvm::Expected> Replacements) {
@@ -252,7 +252,7 @@
 void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams ) {
   PathRef File = Params.textDocument.uri.file();
   DraftMgr.removeDraft(File);
-  Server.removeDocument(File);
+  Server->removeDocument(File);
   CDB.invalidate(File);
 }
 
@@ -264,7 +264,7 @@
 return replyError(ErrorCode::InvalidParams,
   "onDocumentOnTypeFormatting called for non-added file");
 
-  auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
+  auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
   if (ReplacementsOrError)
 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get(;
   else
@@ -280,7 +280,7 @@
 return replyError(ErrorCode::InvalidParams,
   "onDocumentRangeFormatting called for non-added file");
 
-  auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
+  auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
   if (ReplacementsOrError)
 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get(;
   else
@@ -295,16 +295,16 @@
 return replyError(ErrorCode::InvalidParams,
   "onDocumentFormatting called for non-added file");
 
-  auto ReplacementsOrError = Server.formatFile(*Code, File);
+  auto ReplacementsOrError = Server->formatFile(*Code, File);
   if (ReplacementsOrError)
 

[clang-tools-extra] r343067 - [clangd] Fix crash if pending computations were active on exit

2018-09-25 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Tue Sep 25 22:48:29 2018
New Revision: 343067

URL: http://llvm.org/viewvc/llvm-project?rev=343067=rev
Log:
[clangd] Fix crash if pending computations were active on exit

Summary:
Make sure JSONRPCDispatcher outlives the worker threads, they access
its fields to remove the stored cancellations when Context dies.

Reviewers: sammccall, ioeric

Reviewed By: ioeric

Subscribers: MaskRay, jkorous, arphaman, kadircet, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.h

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=343067=343066=343067=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Tue Sep 25 22:48:29 2018
@@ -77,9 +77,9 @@ void ClangdLSPServer::onInitialize(Initi
 applyConfiguration(*Params.initializationOptions);
 
   if (Params.rootUri && *Params.rootUri)
-Server.setRootPath(Params.rootUri->file());
+Server->setRootPath(Params.rootUri->file());
   else if (Params.rootPath && !Params.rootPath->empty())
-Server.setRootPath(*Params.rootPath);
+Server->setRootPath(*Params.rootPath);
 
   CCOpts.EnableSnippets =
   
Params.capabilities.textDocument.completion.completionItem.snippetSupport;
@@ -147,7 +147,7 @@ void ClangdLSPServer::onDocumentDidOpen(
   std::string  = Params.textDocument.text;
 
   DraftMgr.addDraft(File, Contents);
-  Server.addDocument(File, Contents, WantDiagnostics::Yes);
+  Server->addDocument(File, Contents, WantDiagnostics::Yes);
 }
 
 void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams ) 
{
@@ -164,17 +164,17 @@ void ClangdLSPServer::onDocumentDidChang
 // the client.  It is better to remove the draft and let further operations
 // fail rather than giving wrong results.
 DraftMgr.removeDraft(File);
-Server.removeDocument(File);
+Server->removeDocument(File);
 CDB.invalidate(File);
 elog("Failed to update {0}: {1}", File, Contents.takeError());
 return;
   }
 
-  Server.addDocument(File, *Contents, WantDiags);
+  Server->addDocument(File, *Contents, WantDiags);
 }
 
 void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams ) {
-  Server.onFileEvent(Params);
+  Server->onFileEvent(Params);
 }
 
 void ClangdLSPServer::onCommand(ExecuteCommandParams ) {
@@ -210,7 +210,7 @@ void ClangdLSPServer::onCommand(ExecuteC
 }
 
 void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams ) {
-  Server.workspaceSymbols(
+  Server->workspaceSymbols(
   Params.query, CCOpts.Limit,
   [this](llvm::Expected> Items) {
 if (!Items)
@@ -230,7 +230,7 @@ void ClangdLSPServer::onRename(RenamePar
 return replyError(ErrorCode::InvalidParams,
   "onRename called for non-added file");
 
-  Server.rename(
+  Server->rename(
   File, Params.position, Params.newName,
   [File, Code,
Params](llvm::Expected> Replacements) 
{
@@ -252,7 +252,7 @@ void ClangdLSPServer::onRename(RenamePar
 void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams ) {
   PathRef File = Params.textDocument.uri.file();
   DraftMgr.removeDraft(File);
-  Server.removeDocument(File);
+  Server->removeDocument(File);
   CDB.invalidate(File);
 }
 
@@ -264,7 +264,7 @@ void ClangdLSPServer::onDocumentOnTypeFo
 return replyError(ErrorCode::InvalidParams,
   "onDocumentOnTypeFormatting called for non-added file");
 
-  auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
+  auto ReplacementsOrError = Server->formatOnType(*Code, File, 
Params.position);
   if (ReplacementsOrError)
 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get(;
   else
@@ -280,7 +280,7 @@ void ClangdLSPServer::onDocumentRangeFor
 return replyError(ErrorCode::InvalidParams,
   "onDocumentRangeFormatting called for non-added file");
 
-  auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
+  auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
   if (ReplacementsOrError)
 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get(;
   else
@@ -295,7 +295,7 @@ void ClangdLSPServer::onDocumentFormatti
 return replyError(ErrorCode::InvalidParams,
   "onDocumentFormatting called for non-added file");
 
-  auto ReplacementsOrError = Server.formatFile(*Code, File);
+  auto ReplacementsOrError = Server->formatFile(*Code, File);
   if (ReplacementsOrError)
 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get(;
   else
@@ -304,7 +304,7 @@ void ClangdLSPServer::onDocumentFormatti
 }
 
 void 

[clang-tools-extra] r343066 - [clangd] Handle template args for disabled function arg snippets

2018-09-25 Thread Ilya Biryukov via cfe-commits
Author: ibiryukov
Date: Tue Sep 25 22:45:31 2018
New Revision: 343066

URL: http://llvm.org/viewvc/llvm-project?rev=343066=rev
Log:
[clangd] Handle template args for disabled function arg snippets

Reviewers: kadircet, ioeric, sammccall

Reviewed By: kadircet

Subscribers: MaskRay, jkorous, arphaman, cfe-commits

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

Modified:
clang-tools-extra/trunk/clangd/CodeComplete.cpp
clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp

Modified: clang-tools-extra/trunk/clangd/CodeComplete.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CodeComplete.cpp?rev=343066=343065=343066=diff
==
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp (original)
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp Tue Sep 25 22:45:31 2018
@@ -482,13 +482,43 @@ private:
 auto *Snippet = onlyValue<::SnippetSuffix>();
 if (!Snippet)
   // All bundles are function calls.
+  // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g.
+  // we need to complete 'forward<$1>($0)'.
   return "($0)";
-if (!Snippet->empty() && !EnableFunctionArgSnippets &&
-((Completion.Kind == CompletionItemKind::Function) ||
- (Completion.Kind == CompletionItemKind::Method)) &&
-(Snippet->front() == '(') && (Snippet->back() == ')'))
-  // Check whether function has any parameters or not.
-  return Snippet->size() > 2 ? "($0)" : "()";
+if (EnableFunctionArgSnippets)
+  return *Snippet;
+
+// Replace argument snippets with a simplified pattern.
+if (Snippet->empty())
+  return "";
+if (Completion.Kind == CompletionItemKind::Function ||
+Completion.Kind == CompletionItemKind::Method) {
+  // Functions snippets can be of 2 types:
+  // - containing only function arguments, e.g.
+  //   foo(${1:int p1}, ${2:int p2});
+  //   We transform this pattern to '($0)' or '()'.
+  // - template arguments and function arguments, e.g.
+  //   foo<${1:class}>(${2:int p1}).
+  //   We transform this pattern to '<$1>()$0' or '<$0>()'.
+
+  bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()");
+  if (Snippet->front() == '<')
+return EmptyArgs ? "<$1>()$0" : "<$1>($0)";
+  if (Snippet->front() == '(')
+return EmptyArgs ? "()" : "($0)";
+  return *Snippet; // Not an arg snippet?
+}
+if (Completion.Kind == CompletionItemKind::Reference ||
+Completion.Kind == CompletionItemKind::Class) {
+  if (Snippet->front() != '<')
+return *Snippet; // Not an arg snippet?
+
+  // Classes and template using aliases can only have template arguments,
+  // e.g. Foo<${1:class}>.
+  if (llvm::StringRef(*Snippet).endswith("<>"))
+return "<>"; // can happen with defaulted template arguments.
+  return "<$0>";
+}
 return *Snippet;
   }
 

Modified: clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp?rev=343066=343065=343066=diff
==
--- clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp Tue Sep 25 
22:45:31 2018
@@ -1741,32 +1741,65 @@ TEST(CompletionTest, CompletionFunctionA
   CodeCompleteOptions Opts;
   Opts.EnableSnippets = true;
   Opts.EnableFunctionArgSnippets = false;
-  const std::string Header =
-  R"cpp(
+
+  {
+auto Results = completions(
+R"cpp(
   void xfoo();
   void xfoo(int x, int y);
-  void xbar();
-  void f() {
-)cpp";
-  {
-auto Results = completions(Header + "\nxfo^", {}, Opts);
+  void f() { xfo^ })cpp",
+{}, Opts);
 EXPECT_THAT(
 Results.Completions,
 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("()")),
  AllOf(Named("xfoo"), SnippetSuffix("($0)";
   }
   {
-auto Results = completions(Header + "\nxba^", {}, Opts);
+auto Results = completions(
+R"cpp(
+  void xbar();
+  void f() { xba^ })cpp",
+{}, Opts);
 EXPECT_THAT(Results.Completions, UnorderedElementsAre(AllOf(
  Named("xbar"), SnippetSuffix("()";
   }
   {
 Opts.BundleOverloads = true;
-auto Results = completions(Header + "\nxfo^", {}, Opts);
+auto Results = completions(
+R"cpp(
+  void xfoo();
+  void xfoo(int x, int y);
+  void f() { xfo^ })cpp",
+{}, Opts);
 EXPECT_THAT(
 Results.Completions,
 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("($0)";
   }
+  {
+auto Results = completions(
+R"cpp(
+  template 
+  void xfoo(int a, U b);
+  void f() { xfo^ })cpp",

[PATCH] D52422: [clangd] Handle template args for disabled function arg snippets

2018-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343066: [clangd] Handle template args for disabled function 
arg snippets (authored by ibiryukov, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52422?vs=167044=167045#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52422

Files:
  clang-tools-extra/trunk/clangd/CodeComplete.cpp
  clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp

Index: clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/CodeCompleteTests.cpp
@@ -1741,32 +1741,65 @@
   CodeCompleteOptions Opts;
   Opts.EnableSnippets = true;
   Opts.EnableFunctionArgSnippets = false;
-  const std::string Header =
-  R"cpp(
+
+  {
+auto Results = completions(
+R"cpp(
   void xfoo();
   void xfoo(int x, int y);
-  void xbar();
-  void f() {
-)cpp";
-  {
-auto Results = completions(Header + "\nxfo^", {}, Opts);
+  void f() { xfo^ })cpp",
+{}, Opts);
 EXPECT_THAT(
 Results.Completions,
 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("()")),
  AllOf(Named("xfoo"), SnippetSuffix("($0)";
   }
   {
-auto Results = completions(Header + "\nxba^", {}, Opts);
+auto Results = completions(
+R"cpp(
+  void xbar();
+  void f() { xba^ })cpp",
+{}, Opts);
 EXPECT_THAT(Results.Completions, UnorderedElementsAre(AllOf(
  Named("xbar"), SnippetSuffix("()";
   }
   {
 Opts.BundleOverloads = true;
-auto Results = completions(Header + "\nxfo^", {}, Opts);
+auto Results = completions(
+R"cpp(
+  void xfoo();
+  void xfoo(int x, int y);
+  void f() { xfo^ })cpp",
+{}, Opts);
 EXPECT_THAT(
 Results.Completions,
 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("($0)";
   }
+  {
+auto Results = completions(
+R"cpp(
+  template 
+  void xfoo(int a, U b);
+  void f() { xfo^ })cpp",
+{}, Opts);
+EXPECT_THAT(
+Results.Completions,
+UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("<$1>($0)";
+  }
+  {
+auto Results = completions(
+R"cpp(
+  template 
+  class foo_class{};
+  template 
+  using foo_alias = T**;
+  void f() { foo_^ })cpp",
+{}, Opts);
+EXPECT_THAT(
+Results.Completions,
+UnorderedElementsAre(AllOf(Named("foo_class"), SnippetSuffix("<$0>")),
+ AllOf(Named("foo_alias"), SnippetSuffix("<$0>";
+  }
 }
 
 TEST(CompletionTest, SuggestOverrides) {
Index: clang-tools-extra/trunk/clangd/CodeComplete.cpp
===
--- clang-tools-extra/trunk/clangd/CodeComplete.cpp
+++ clang-tools-extra/trunk/clangd/CodeComplete.cpp
@@ -482,13 +482,43 @@
 auto *Snippet = onlyValue<::SnippetSuffix>();
 if (!Snippet)
   // All bundles are function calls.
+  // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g.
+  // we need to complete 'forward<$1>($0)'.
   return "($0)";
-if (!Snippet->empty() && !EnableFunctionArgSnippets &&
-((Completion.Kind == CompletionItemKind::Function) ||
- (Completion.Kind == CompletionItemKind::Method)) &&
-(Snippet->front() == '(') && (Snippet->back() == ')'))
-  // Check whether function has any parameters or not.
-  return Snippet->size() > 2 ? "($0)" : "()";
+if (EnableFunctionArgSnippets)
+  return *Snippet;
+
+// Replace argument snippets with a simplified pattern.
+if (Snippet->empty())
+  return "";
+if (Completion.Kind == CompletionItemKind::Function ||
+Completion.Kind == CompletionItemKind::Method) {
+  // Functions snippets can be of 2 types:
+  // - containing only function arguments, e.g.
+  //   foo(${1:int p1}, ${2:int p2});
+  //   We transform this pattern to '($0)' or '()'.
+  // - template arguments and function arguments, e.g.
+  //   foo<${1:class}>(${2:int p1}).
+  //   We transform this pattern to '<$1>()$0' or '<$0>()'.
+
+  bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()");
+  if (Snippet->front() == '<')
+return EmptyArgs ? "<$1>()$0" : "<$1>($0)";
+  if (Snippet->front() == '(')
+return EmptyArgs ? "()" : "($0)";
+  return *Snippet; // Not an arg snippet?
+}
+if (Completion.Kind == CompletionItemKind::Reference ||
+Completion.Kind == CompletionItemKind::Class) {
+  if (Snippet->front() != '<')
+return *Snippet; // Not an arg snippet?
+
+  // Classes and template using aliases can only have template arguments,
+ 

[PATCH] D52422: [clangd] Handle template args for disabled function arg snippets

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



Comment at: clangd/CodeComplete.cpp:507
+  if (Snippet->front() == '<')
+return EmptyArgs ? "<$0>()" : "<$1>($0)";
+  if (Snippet->front() == '(')

kadircet wrote:
> maybe have something like `<$1>()$0` when arguments are empty so that user 
> can jump to end.
Thanks, this looks consistent with other cases


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52422



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


[PATCH] D52422: [clangd] Handle template args for disabled function arg snippets

2018-09-25 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov updated this revision to Diff 167044.
ilya-biryukov marked an inline comment as done.
ilya-biryukov added a comment.

- Remove debug formatting
- Update snippet for no-arg case with the suggested changes


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52422

Files:
  clangd/CodeComplete.cpp
  unittests/clangd/CodeCompleteTests.cpp

Index: unittests/clangd/CodeCompleteTests.cpp
===
--- unittests/clangd/CodeCompleteTests.cpp
+++ unittests/clangd/CodeCompleteTests.cpp
@@ -1741,32 +1741,65 @@
   CodeCompleteOptions Opts;
   Opts.EnableSnippets = true;
   Opts.EnableFunctionArgSnippets = false;
-  const std::string Header =
-  R"cpp(
+
+  {
+auto Results = completions(
+R"cpp(
   void xfoo();
   void xfoo(int x, int y);
-  void xbar();
-  void f() {
-)cpp";
-  {
-auto Results = completions(Header + "\nxfo^", {}, Opts);
+  void f() { xfo^ })cpp",
+{}, Opts);
 EXPECT_THAT(
 Results.Completions,
 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("()")),
  AllOf(Named("xfoo"), SnippetSuffix("($0)";
   }
   {
-auto Results = completions(Header + "\nxba^", {}, Opts);
+auto Results = completions(
+R"cpp(
+  void xbar();
+  void f() { xba^ })cpp",
+{}, Opts);
 EXPECT_THAT(Results.Completions, UnorderedElementsAre(AllOf(
  Named("xbar"), SnippetSuffix("()";
   }
   {
 Opts.BundleOverloads = true;
-auto Results = completions(Header + "\nxfo^", {}, Opts);
+auto Results = completions(
+R"cpp(
+  void xfoo();
+  void xfoo(int x, int y);
+  void f() { xfo^ })cpp",
+{}, Opts);
 EXPECT_THAT(
 Results.Completions,
 UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("($0)";
   }
+  {
+auto Results = completions(
+R"cpp(
+  template 
+  void xfoo(int a, U b);
+  void f() { xfo^ })cpp",
+{}, Opts);
+EXPECT_THAT(
+Results.Completions,
+UnorderedElementsAre(AllOf(Named("xfoo"), SnippetSuffix("<$1>($0)";
+  }
+  {
+auto Results = completions(
+R"cpp(
+  template 
+  class foo_class{};
+  template 
+  using foo_alias = T**;
+  void f() { foo_^ })cpp",
+{}, Opts);
+EXPECT_THAT(
+Results.Completions,
+UnorderedElementsAre(AllOf(Named("foo_class"), SnippetSuffix("<$0>")),
+ AllOf(Named("foo_alias"), SnippetSuffix("<$0>";
+  }
 }
 
 TEST(CompletionTest, SuggestOverrides) {
Index: clangd/CodeComplete.cpp
===
--- clangd/CodeComplete.cpp
+++ clangd/CodeComplete.cpp
@@ -46,6 +46,7 @@
 #include "clang/Tooling/Core/Replacement.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/Format.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -482,13 +483,43 @@
 auto *Snippet = onlyValue<::SnippetSuffix>();
 if (!Snippet)
   // All bundles are function calls.
+  // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g.
+  // we need to complete 'forward<$1>($0)'.
   return "($0)";
-if (!Snippet->empty() && !EnableFunctionArgSnippets &&
-((Completion.Kind == CompletionItemKind::Function) ||
- (Completion.Kind == CompletionItemKind::Method)) &&
-(Snippet->front() == '(') && (Snippet->back() == ')'))
-  // Check whether function has any parameters or not.
-  return Snippet->size() > 2 ? "($0)" : "()";
+if (EnableFunctionArgSnippets)
+  return *Snippet;
+
+// Replace argument snippets with a simplified pattern.
+if (Snippet->empty())
+  return "";
+if (Completion.Kind == CompletionItemKind::Function ||
+Completion.Kind == CompletionItemKind::Method) {
+  // Functions snippets can be of 2 types:
+  // - containing only function arguments, e.g.
+  //   foo(${1:int p1}, ${2:int p2});
+  //   We transform this pattern to '($0)' or '()'.
+  // - template arguments and function arguments, e.g.
+  //   foo<${1:class}>(${2:int p1}).
+  //   We transform this pattern to '<$1>($0)' or '<$0>()'.
+
+  bool EmptyArgs = llvm::StringRef(*Snippet).endswith("()");
+  if (Snippet->front() == '<')
+return EmptyArgs ? "<$1>()$0" : "<$1>($0)";
+  if (Snippet->front() == '(')
+return EmptyArgs ? "()" : "($0)";
+  return *Snippet; // Not an arg snippet?
+}
+if (Completion.Kind == CompletionItemKind::Reference ||
+Completion.Kind == CompletionItemKind::Class) {
+  if (Snippet->front() != '<')
+return *Snippet; // Not an arg snippet?
+
+  // Classes and template using aliases can only have template arguments,
+  // e.g. 

r343064 - P0859R0: List-initialization is potentially-constant-evaluated and

2018-09-25 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Tue Sep 25 21:36:55 2018
New Revision: 343064

URL: http://llvm.org/viewvc/llvm-project?rev=343064=rev
Log:
P0859R0: List-initialization is potentially-constant-evaluated and
triggers instantiation of constexpr functions.

We mostly implemented this since Clang 6, but missed the template
instantiation case.

We do not implement the '' special case. It appears to
be a mistake / oversight. I've mailed CWG to see if we can remove it.

Added:
cfe/trunk/test/CXX/expr/expr.const/p6.cpp
cfe/trunk/test/CXX/temp/temp.spec/temp.inst/p7.cpp
Modified:
cfe/trunk/lib/Sema/TreeTransform.h
cfe/trunk/www/cxx_status.html

Modified: cfe/trunk/lib/Sema/TreeTransform.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/TreeTransform.h?rev=343064=343063=343064=diff
==
--- cfe/trunk/lib/Sema/TreeTransform.h (original)
+++ cfe/trunk/lib/Sema/TreeTransform.h Tue Sep 25 21:36:55 2018
@@ -3386,6 +3386,11 @@ ExprResult TreeTransform::Trans
   if (Construct && Construct->isStdInitListInitialization())
 return TransformInitializer(Construct->getArg(0), NotCopyInit);
 
+  // Enter a list-init context if this was list initialization.
+  EnterExpressionEvaluationContext Context(
+  getSema(), EnterExpressionEvaluationContext::InitList,
+  Construct->isListInitialization());
+
   SmallVector NewArgs;
   bool ArgChanged = false;
   if (getDerived().TransformExprs(Construct->getArgs(), 
Construct->getNumArgs(),
@@ -9549,6 +9554,9 @@ TreeTransform::TransformInitLis
 
   bool InitChanged = false;
 
+  EnterExpressionEvaluationContext Context(
+  getSema(), EnterExpressionEvaluationContext::InitList);
+
   SmallVector Inits;
   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
   Inits, ))
@@ -10780,9 +10788,14 @@ TreeTransform::TransformCXXCons
 
   bool ArgumentChanged = false;
   SmallVector Args;
-  if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
-  ))
-return ExprError();
+  {
+EnterExpressionEvaluationContext Context(
+getSema(), EnterExpressionEvaluationContext::InitList,
+E->isListInitialization());
+if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
+))
+  return ExprError();
+  }
 
   if (!getDerived().AlwaysRebuild() &&
   T == E->getType() &&
@@ -10865,9 +10878,14 @@ TreeTransform::TransformCXXTemp
   bool ArgumentChanged = false;
   SmallVector Args;
   Args.reserve(E->getNumArgs());
-  if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
- ))
-return ExprError();
+  {
+EnterExpressionEvaluationContext Context(
+getSema(), EnterExpressionEvaluationContext::InitList,
+E->isListInitialization());
+if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
+   ))
+  return ExprError();
+  }
 
   if (!getDerived().AlwaysRebuild() &&
   T == E->getTypeSourceInfo() &&
@@ -11159,9 +11177,14 @@ TreeTransform::TransformCXXUnre
   bool ArgumentChanged = false;
   SmallVector Args;
   Args.reserve(E->arg_size());
-  if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
-  ))
-return ExprError();
+  {
+EnterExpressionEvaluationContext Context(
+getSema(), EnterExpressionEvaluationContext::InitList,
+E->isListInitialization());
+if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
+))
+  return ExprError();
+  }
 
   if (!getDerived().AlwaysRebuild() &&
   T == E->getTypeSourceInfo() &&

Added: cfe/trunk/test/CXX/expr/expr.const/p6.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CXX/expr/expr.const/p6.cpp?rev=343064=auto
==
--- cfe/trunk/test/CXX/expr/expr.const/p6.cpp (added)
+++ cfe/trunk/test/CXX/expr/expr.const/p6.cpp Tue Sep 25 21:36:55 2018
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -std=c++17 -verify %s
+
+template int not_constexpr() { return T::error; }
+template constexpr int is_constexpr() { return T::error; } // 
expected-error {{'::'}}
+
+template int not_constexpr_var = T::error;
+template constexpr int is_constexpr_var = T::error; // 
expected-error {{'::'}}
+template const int is_const_var = T::error; // expected-error 
{{'::'}}
+template const volatile int is_const_volatile_var = T::error;
+template T is_dependent_var = T::error; // expected-error {{'::'}}
+template int _reference_var = T::error; // expected-error 
{{'::'}}
+template float is_float_var = T::error;
+
+void test() {
+  // Do not instantiate functions referenced in unevaluated operands...
+  (void)sizeof(not_constexpr());
+  (void)sizeof(is_constexpr());
+  (void)sizeof(not_constexpr_var);
+  

r343063 - [OPENMP] Add support for OMP5 requires directive + unified_address clause

2018-09-25 Thread Kelvin Li via cfe-commits
Author: kli
Date: Tue Sep 25 21:28:39 2018
New Revision: 343063

URL: http://llvm.org/viewvc/llvm-project?rev=343063=rev
Log:
[OPENMP] Add support for OMP5 requires directive + unified_address clause

Add support for OMP5.0 requires directive and unified_address clause.
Patches to follow will include support for additional clauses.

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

Added:
cfe/trunk/test/OpenMP/requires_unified_address_ast_print.cpp
cfe/trunk/test/OpenMP/requires_unified_address_messages.cpp
Modified:
cfe/trunk/include/clang/AST/DeclOpenMP.h
cfe/trunk/include/clang/AST/OpenMPClause.h
cfe/trunk/include/clang/AST/RecursiveASTVisitor.h
cfe/trunk/include/clang/Basic/DeclNodes.td
cfe/trunk/include/clang/Basic/DiagnosticParseKinds.td
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/include/clang/Basic/OpenMPKinds.def
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/include/clang/Serialization/ASTBitCodes.h
cfe/trunk/lib/AST/ASTDumper.cpp
cfe/trunk/lib/AST/DeclBase.cpp
cfe/trunk/lib/AST/DeclOpenMP.cpp
cfe/trunk/lib/AST/DeclPrinter.cpp
cfe/trunk/lib/AST/OpenMPClause.cpp
cfe/trunk/lib/AST/StmtPrinter.cpp
cfe/trunk/lib/AST/StmtProfile.cpp
cfe/trunk/lib/Basic/OpenMPKinds.cpp
cfe/trunk/lib/CodeGen/CGDecl.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntime.cpp
cfe/trunk/lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
cfe/trunk/lib/CodeGen/CGStmtOpenMP.cpp
cfe/trunk/lib/CodeGen/CodeGenModule.cpp
cfe/trunk/lib/CodeGen/CodeGenModule.h
cfe/trunk/lib/Parse/ParseOpenMP.cpp
cfe/trunk/lib/Sema/SemaOpenMP.cpp
cfe/trunk/lib/Sema/SemaTemplateInstantiateDecl.cpp
cfe/trunk/lib/Sema/TreeTransform.h
cfe/trunk/lib/Serialization/ASTCommon.cpp
cfe/trunk/lib/Serialization/ASTReader.cpp
cfe/trunk/lib/Serialization/ASTReaderDecl.cpp
cfe/trunk/lib/Serialization/ASTWriter.cpp
cfe/trunk/lib/Serialization/ASTWriterDecl.cpp
cfe/trunk/tools/libclang/CIndex.cpp

Modified: cfe/trunk/include/clang/AST/DeclOpenMP.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/AST/DeclOpenMP.h?rev=343063=343062=343063=diff
==
--- cfe/trunk/include/clang/AST/DeclOpenMP.h (original)
+++ cfe/trunk/include/clang/AST/DeclOpenMP.h Tue Sep 25 21:28:39 2018
@@ -18,6 +18,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExternalASTSource.h"
+#include "clang/AST/OpenMPClause.h"
 #include "clang/AST/Type.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/TrailingObjects.h"
@@ -239,6 +240,76 @@ public:
   static bool classofKind(Kind K) { return K == OMPCapturedExpr; }
 };
 
+/// This represents '#pragma omp requires...' directive.
+/// For example
+///
+/// \code
+/// #pragma omp requires unified_address
+/// \endcode
+///
+class OMPRequiresDecl final
+: public Decl,
+  private llvm::TrailingObjects {
+  friend class ASTDeclReader;
+  friend TrailingObjects;
+
+  // Number of clauses associated with this requires declaration
+  unsigned NumClauses = 0;
+
+  virtual void anchor();
+
+  OMPRequiresDecl(Kind DK, DeclContext *DC, SourceLocation L)
+  : Decl(DK, DC, L), NumClauses(0) {}
+
+  /// Returns an array of immutable clauses associated with this requires
+  /// declaration
+  ArrayRef getClauses() const {
+return llvm::makeArrayRef(getTrailingObjects(), NumClauses);
+  }
+
+  /// Returns an array of clauses associated with this requires declaration
+  MutableArrayRef getClauses() {
+return MutableArrayRef(getTrailingObjects(),
+NumClauses);
+  }
+
+  /// Sets an array of clauses to this requires declaration
+  void setClauses(ArrayRef CL);
+
+public:
+  /// Create requires node.
+  static OMPRequiresDecl *Create(ASTContext , DeclContext *DC,
+ SourceLocation L, ArrayRef CL);
+  /// Create deserialized requires node.
+  static OMPRequiresDecl *CreateDeserialized(ASTContext , unsigned ID,
+ unsigned N);
+
+  using clauselist_iterator = MutableArrayRef::iterator;
+  using clauselist_const_iterator = ArrayRef::iterator;
+  using clauselist_range = llvm::iterator_range;
+  using clauselist_const_range = 
llvm::iterator_range;
+
+  unsigned clauselist_size() const { return NumClauses; }
+  bool clauselist_empty() const { return NumClauses == 0; }
+
+  clauselist_range clauselists() {
+return clauselist_range(clauselist_begin(), clauselist_end());
+  }
+  clauselist_const_range clauselists() const {
+return clauselist_const_range(clauselist_begin(), clauselist_end());
+  }
+  clauselist_iterator clauselist_begin() { return getClauses().begin(); }
+  clauselist_iterator clauselist_end() { return getClauses().end(); }
+  clauselist_const_iterator clauselist_begin() const {
+return getClauses().begin();
+  }
+  clauselist_const_iterator clauselist_end() 

[PATCH] D52359: [OPENMP] Add support for OMP5 requires directive + unified_address clause

2018-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC343063: [OPENMP] Add support for OMP5 requires directive + 
unified_address clause (authored by kli, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52359?vs=166471=167042#toc

Repository:
  rC Clang

https://reviews.llvm.org/D52359

Files:
  include/clang/AST/DeclOpenMP.h
  include/clang/AST/OpenMPClause.h
  include/clang/AST/RecursiveASTVisitor.h
  include/clang/Basic/DeclNodes.td
  include/clang/Basic/DiagnosticParseKinds.td
  include/clang/Basic/DiagnosticSemaKinds.td
  include/clang/Basic/OpenMPKinds.def
  include/clang/Sema/Sema.h
  include/clang/Serialization/ASTBitCodes.h
  lib/AST/ASTDumper.cpp
  lib/AST/DeclBase.cpp
  lib/AST/DeclOpenMP.cpp
  lib/AST/DeclPrinter.cpp
  lib/AST/OpenMPClause.cpp
  lib/AST/StmtPrinter.cpp
  lib/AST/StmtProfile.cpp
  lib/Basic/OpenMPKinds.cpp
  lib/CodeGen/CGDecl.cpp
  lib/CodeGen/CGOpenMPRuntime.cpp
  lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
  lib/CodeGen/CGStmtOpenMP.cpp
  lib/CodeGen/CodeGenModule.cpp
  lib/CodeGen/CodeGenModule.h
  lib/Parse/ParseOpenMP.cpp
  lib/Sema/SemaOpenMP.cpp
  lib/Sema/SemaTemplateInstantiateDecl.cpp
  lib/Sema/TreeTransform.h
  lib/Serialization/ASTCommon.cpp
  lib/Serialization/ASTReader.cpp
  lib/Serialization/ASTReaderDecl.cpp
  lib/Serialization/ASTWriter.cpp
  lib/Serialization/ASTWriterDecl.cpp
  test/OpenMP/requires_unified_address_ast_print.cpp
  test/OpenMP/requires_unified_address_messages.cpp
  tools/libclang/CIndex.cpp

Index: include/clang/AST/DeclOpenMP.h
===
--- include/clang/AST/DeclOpenMP.h
+++ include/clang/AST/DeclOpenMP.h
@@ -18,6 +18,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExternalASTSource.h"
+#include "clang/AST/OpenMPClause.h"
 #include "clang/AST/Type.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/TrailingObjects.h"
@@ -239,6 +240,76 @@
   static bool classofKind(Kind K) { return K == OMPCapturedExpr; }
 };
 
+/// This represents '#pragma omp requires...' directive.
+/// For example
+///
+/// \code
+/// #pragma omp requires unified_address
+/// \endcode
+///
+class OMPRequiresDecl final
+: public Decl,
+  private llvm::TrailingObjects {
+  friend class ASTDeclReader;
+  friend TrailingObjects;
+
+  // Number of clauses associated with this requires declaration
+  unsigned NumClauses = 0;
+
+  virtual void anchor();
+
+  OMPRequiresDecl(Kind DK, DeclContext *DC, SourceLocation L)
+  : Decl(DK, DC, L), NumClauses(0) {}
+
+  /// Returns an array of immutable clauses associated with this requires
+  /// declaration
+  ArrayRef getClauses() const {
+return llvm::makeArrayRef(getTrailingObjects(), NumClauses);
+  }
+
+  /// Returns an array of clauses associated with this requires declaration
+  MutableArrayRef getClauses() {
+return MutableArrayRef(getTrailingObjects(),
+NumClauses);
+  }
+
+  /// Sets an array of clauses to this requires declaration
+  void setClauses(ArrayRef CL);
+
+public:
+  /// Create requires node.
+  static OMPRequiresDecl *Create(ASTContext , DeclContext *DC,
+ SourceLocation L, ArrayRef CL);
+  /// Create deserialized requires node.
+  static OMPRequiresDecl *CreateDeserialized(ASTContext , unsigned ID,
+ unsigned N);
+
+  using clauselist_iterator = MutableArrayRef::iterator;
+  using clauselist_const_iterator = ArrayRef::iterator;
+  using clauselist_range = llvm::iterator_range;
+  using clauselist_const_range = llvm::iterator_range;
+
+  unsigned clauselist_size() const { return NumClauses; }
+  bool clauselist_empty() const { return NumClauses == 0; }
+
+  clauselist_range clauselists() {
+return clauselist_range(clauselist_begin(), clauselist_end());
+  }
+  clauselist_const_range clauselists() const {
+return clauselist_const_range(clauselist_begin(), clauselist_end());
+  }
+  clauselist_iterator clauselist_begin() { return getClauses().begin(); }
+  clauselist_iterator clauselist_end() { return getClauses().end(); }
+  clauselist_const_iterator clauselist_begin() const {
+return getClauses().begin();
+  }
+  clauselist_const_iterator clauselist_end() const {
+return getClauses().end();
+  }
+
+  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
+  static bool classofKind(Kind K) { return K == OMPRequires; }
+};
 } // end namespace clang
 
 #endif
Index: include/clang/AST/OpenMPClause.h
===
--- include/clang/AST/OpenMPClause.h
+++ include/clang/AST/OpenMPClause.h
@@ -734,6 +734,37 @@
   }
 };
 
+/// This represents 'unified_address' clause in the '#pragma omp requires'
+/// directive.
+///
+/// \code
+/// #pragma omp requires unified_address
+/// \endcode
+/// In this example directive '#pragma omp requires' has 

[PATCH] D52527: [clang-format] fix Bug 38686: add AfterCaseLabel to BraceWrapping

2018-09-25 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: sammccall, klimek, djasper, krasimir.
Herald added a subscriber: cfe-commits.

https://bugs.llvm.org/show_bug.cgi?id=38686


Repository:
  rC Clang

https://reviews.llvm.org/D52527

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

Index: unittests/Format/FormatTest.cpp
===
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -1069,6 +1069,7 @@
   Style.IndentCaseLabels = true;
   Style.AllowShortBlocksOnASingleLine = false;
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterCaseLabel = true;
   Style.BraceWrapping.AfterControlStatement = true;
   EXPECT_EQ("switch (n)\n"
 "{\n"
@@ -1090,6 +1091,27 @@
"  }\n"
"}",
Style));
+  Style.BraceWrapping.AfterCaseLabel = false;
+  EXPECT_EQ("switch (n)\n"
+"{\n"
+"  case 0: {\n"
+"return false;\n"
+"  }\n"
+"  default: {\n"
+"return true;\n"
+"  }\n"
+"}",
+format("switch (n) {\n"
+   "  case 0:\n"
+   "  {\n"
+   "return false;\n"
+   "  }\n"
+   "  default:\n"
+   "  {\n"
+   "return true;\n"
+   "  }\n"
+   "}",
+   Style));
 }
 
 TEST_F(FormatTest, CaseRanges) {
@@ -1243,6 +1265,7 @@
Style));
   Style.AllowShortCaseLabelsOnASingleLine = true;
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterCaseLabel = true;
   Style.BraceWrapping.AfterControlStatement = true;
   EXPECT_EQ("switch (n)\n"
 "{\n"
Index: lib/Format/UnwrappedLineParser.cpp
===
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -173,10 +173,16 @@
 public:
   CompoundStatementIndenter(UnwrappedLineParser *Parser,
 const FormatStyle , unsigned )
+  : CompoundStatementIndenter(Parser, LineLevel,
+  Style.BraceWrapping.AfterControlStatement,
+  Style.BraceWrapping.IndentBraces) {
+  }
+  CompoundStatementIndenter(UnwrappedLineParser *Parser, unsigned ,
+bool WrapeBrace, bool IndentBrace)
   : LineLevel(LineLevel), OldLineLevel(LineLevel) {
-if (Style.BraceWrapping.AfterControlStatement)
+if (WrapeBrace)
   Parser->addUnwrappedLine();
-if (Style.BraceWrapping.IndentBraces)
+if (IndentBrace)
   ++LineLevel;
   }
   ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
@@ -1888,7 +1894,9 @@
   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
 --Line->Level;
   if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
-CompoundStatementIndenter Indenter(this, Style, Line->Level);
+CompoundStatementIndenter Indenter(this, Line->Level,
+   Style.BraceWrapping.AfterCaseLabel,
+   Style.BraceWrapping.IndentBraces);
 parseBlock(/*MustBeDeclaration=*/false);
 if (FormatTok->Tok.is(tok::kw_break)) {
   if (Style.BraceWrapping.AfterControlStatement)
Index: lib/Format/Format.cpp
===
--- lib/Format/Format.cpp
+++ lib/Format/Format.cpp
@@ -476,6 +476,7 @@
 
 template <> struct MappingTraits {
   static void mapping(IO , FormatStyle::BraceWrappingFlags ) {
+IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel);
 IO.mapOptional("AfterClass", Wrapping.AfterClass);
 IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
 IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
@@ -568,7 +569,7 @@
   if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
 return Style;
   FormatStyle Expanded = Style;
-  Expanded.BraceWrapping = {false, false, false, false, false,
+  Expanded.BraceWrapping = {false, false, false, false, false, false,
 false, false, false, false, false,
 false, false, true,  true,  true};
   switch (Style.BreakBeforeBraces) {
@@ -593,6 +594,7 @@
 Expanded.BraceWrapping.BeforeElse = true;
 break;
   case FormatStyle::BS_Allman:
+Expanded.BraceWrapping.AfterCaseLabel = true;
 Expanded.BraceWrapping.AfterClass = true;
 Expanded.BraceWrapping.AfterControlStatement = true;
 Expanded.BraceWrapping.AfterEnum = true;
@@ -606,7 +608,7 @@
 break;
   case FormatStyle::BS_GNU:
 Expanded.BraceWrapping = {true, true, true, true, true, true, true, true,
-  true, true, true, 

[PATCH] D52440: Emit lifetime markers for temporary function parameter aggregates

2018-09-25 Thread John McCall via Phabricator via cfe-commits
rjmccall added inline comments.



Comment at: lib/CodeGen/CGExpr.cpp:176
+  pushFullExprCleanup(NormalEHLifetimeMarker,
+   Slot.getAddress(), Size);
+}

This is problematic because we're not necessarily in a scope that usefully 
limits the duration of cleanups — we don't push full-expression scopes when 
emitting an arbitrary statement.  Probably we should, but we don't.

If you'd like to take a look at solving that problem first, that would be great.


Repository:
  rC Clang

https://reviews.llvm.org/D52440



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


Re: r342827 - Fix modules build with shared library.

2018-09-25 Thread Shuai Wang via cfe-commits
I'd like to understand this better as well, in particular what would be a
proper fix?

On Tue, Sep 25, 2018 at 2:15 PM David Blaikie  wrote:

> +Shuai Wang
>
> On Tue, Sep 25, 2018 at 2:14 PM David Blaikie  wrote:
>
>> Hey Eric - thanks for the fix - but could you explain the issue here in a
>> bit more detail, as I'm a bit confused (& really interested in
>> understanding any layering problems in LLVM - and fixing them/making sure
>> they're fixed/holding the line/etc)
>>
>> What do you mean by "pull all of the AST matchers library into clang" -
>> how does including a header ever add a link dependency?
>>
>> - Dave
>>
>>
>> On Sat, Sep 22, 2018 at 5:49 PM Eric Fiselier via cfe-commits <
>> cfe-commits@lists.llvm.org> wrote:
>>
>>> Author: ericwf
>>> Date: Sat Sep 22 17:48:05 2018
>>> New Revision: 342827
>>>
>>> URL: http://llvm.org/viewvc/llvm-project?rev=342827=rev
>>> Log:
>>> Fix modules build with shared library.
>>>
>>> r341994 caused clangAnalysis to pull all of the AST matchers
>>> library into clang. Due to inline key functions in the headers,
>>> importing the AST matchers library gives a link dependency on the
>>> AST matchers (and thus the AST), which clang should not
>>> have.
>>>
>>> This patch works around the issues by excluding the offending
>>> libclangAnalysis header in the modulemap.
>>>
>>> Modified:
>>> cfe/trunk/include/clang/module.modulemap
>>>
>>> Modified: cfe/trunk/include/clang/module.modulemap
>>> URL:
>>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/module.modulemap?rev=342827=342826=342827=diff
>>>
>>> ==
>>> --- cfe/trunk/include/clang/module.modulemap (original)
>>> +++ cfe/trunk/include/clang/module.modulemap Sat Sep 22 17:48:05 2018
>>> @@ -5,6 +5,12 @@ module Clang_Analysis {
>>>textual header "Analysis/Analyses/ThreadSafetyOps.def"
>>>
>>>module * { export * }
>>> +
>>> +  // FIXME: Exclude these headers to avoid pulling all of the AST
>>> matchers
>>> +  // library into clang. Due to inline key functions in the headers,
>>> +  // importing the AST matchers library gives a link dependency on the
>>> AST
>>> +  // matchers (and thus the AST), which clang-format should not have.
>>> +  exclude header "Analysis/Analyses/ExprMutationAnalyzer.h"
>>>  }
>>>
>>>  module Clang_AST {
>>>
>>>
>>> ___
>>> cfe-commits mailing list
>>> cfe-commits@lists.llvm.org
>>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>>>
>>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52189: [analyzer] Fix a crash regression on casting opaque symbolic pointers from unrelated base classes to derived classes.

2018-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC343051: [analyzer] Fix a crash on casting symbolic pointers 
to derived classes. (authored by dergachev, committed by ).

Repository:
  rL LLVM

https://reviews.llvm.org/D52189

Files:
  lib/StaticAnalyzer/Core/Store.cpp
  test/Analysis/casts.cpp


Index: lib/StaticAnalyzer/Core/Store.cpp
===
--- lib/StaticAnalyzer/Core/Store.cpp
+++ lib/StaticAnalyzer/Core/Store.cpp
@@ -375,8 +375,18 @@
 MR = Uncasted;
   }
 
+  // If we're casting a symbolic base pointer to a derived class, use
+  // CXXDerivedObjectRegion to represent the cast. If it's a pointer to an
+  // unrelated type, it must be a weird reinterpret_cast and we have to
+  // be fine with ElementRegion. TODO: Should we instead make
+  // Derived{TargetClass, Element{SourceClass, SR}}?
   if (const auto *SR = dyn_cast(MR)) {
-return loc::MemRegionVal(MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+QualType T = SR->getSymbol()->getType();
+const CXXRecordDecl *SourceClass = T->getPointeeCXXRecordDecl();
+if (TargetClass && SourceClass && TargetClass->isDerivedFrom(SourceClass))
+  return loc::MemRegionVal(
+  MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+return loc::MemRegionVal(GetElementZeroRegion(SR, TargetType));
   }
 
   // We failed if the region we ended up with has perfect type info.
Index: test/Analysis/casts.cpp
===
--- test/Analysis/casts.cpp
+++ test/Analysis/casts.cpp
@@ -70,5 +70,35 @@
   clang_analyzer_eval(c->x); // expected-warning{{UNKNOWN}}
   clang_analyzer_eval(c->y); // expected-warning{{TRUE}}
 }
+} // namespace base_to_derived_double_inheritance
+
+namespace base_to_derived_opaque_class {
+class NotInt {
+public:
+  operator int() { return !x; } // no-crash
+  int x;
+};
+
+typedef struct Opaque *OpaqueRef;
+typedef void *VeryOpaqueRef;
+
+class Transparent {
+public:
+  int getNotInt() { return NI; }
+  NotInt NI;
+};
+
+class SubTransparent : public Transparent {};
+
+SubTransparent *castToDerived(Transparent *TRef) {
+  return (SubTransparent *)TRef;
 }
 
+void foo(OpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
+}
+
+void foo(VeryOpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
+}
+} // namespace base_to_derived_opaque_class


Index: lib/StaticAnalyzer/Core/Store.cpp
===
--- lib/StaticAnalyzer/Core/Store.cpp
+++ lib/StaticAnalyzer/Core/Store.cpp
@@ -375,8 +375,18 @@
 MR = Uncasted;
   }
 
+  // If we're casting a symbolic base pointer to a derived class, use
+  // CXXDerivedObjectRegion to represent the cast. If it's a pointer to an
+  // unrelated type, it must be a weird reinterpret_cast and we have to
+  // be fine with ElementRegion. TODO: Should we instead make
+  // Derived{TargetClass, Element{SourceClass, SR}}?
   if (const auto *SR = dyn_cast(MR)) {
-return loc::MemRegionVal(MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+QualType T = SR->getSymbol()->getType();
+const CXXRecordDecl *SourceClass = T->getPointeeCXXRecordDecl();
+if (TargetClass && SourceClass && TargetClass->isDerivedFrom(SourceClass))
+  return loc::MemRegionVal(
+  MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+return loc::MemRegionVal(GetElementZeroRegion(SR, TargetType));
   }
 
   // We failed if the region we ended up with has perfect type info.
Index: test/Analysis/casts.cpp
===
--- test/Analysis/casts.cpp
+++ test/Analysis/casts.cpp
@@ -70,5 +70,35 @@
   clang_analyzer_eval(c->x); // expected-warning{{UNKNOWN}}
   clang_analyzer_eval(c->y); // expected-warning{{TRUE}}
 }
+} // namespace base_to_derived_double_inheritance
+
+namespace base_to_derived_opaque_class {
+class NotInt {
+public:
+  operator int() { return !x; } // no-crash
+  int x;
+};
+
+typedef struct Opaque *OpaqueRef;
+typedef void *VeryOpaqueRef;
+
+class Transparent {
+public:
+  int getNotInt() { return NI; }
+  NotInt NI;
+};
+
+class SubTransparent : public Transparent {};
+
+SubTransparent *castToDerived(Transparent *TRef) {
+  return (SubTransparent *)TRef;
 }
 
+void foo(OpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
+}
+
+void foo(VeryOpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
+}
+} // namespace base_to_derived_opaque_class
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52189: [analyzer] Fix a crash regression on casting opaque symbolic pointers from unrelated base classes to derived classes.

2018-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343051: [analyzer] Fix a crash on casting symbolic pointers 
to derived classes. (authored by dergachev, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52189?vs=165854=167031#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52189

Files:
  cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
  cfe/trunk/test/Analysis/casts.cpp


Index: cfe/trunk/test/Analysis/casts.cpp
===
--- cfe/trunk/test/Analysis/casts.cpp
+++ cfe/trunk/test/Analysis/casts.cpp
@@ -70,5 +70,35 @@
   clang_analyzer_eval(c->x); // expected-warning{{UNKNOWN}}
   clang_analyzer_eval(c->y); // expected-warning{{TRUE}}
 }
+} // namespace base_to_derived_double_inheritance
+
+namespace base_to_derived_opaque_class {
+class NotInt {
+public:
+  operator int() { return !x; } // no-crash
+  int x;
+};
+
+typedef struct Opaque *OpaqueRef;
+typedef void *VeryOpaqueRef;
+
+class Transparent {
+public:
+  int getNotInt() { return NI; }
+  NotInt NI;
+};
+
+class SubTransparent : public Transparent {};
+
+SubTransparent *castToDerived(Transparent *TRef) {
+  return (SubTransparent *)TRef;
 }
 
+void foo(OpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
+}
+
+void foo(VeryOpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
+}
+} // namespace base_to_derived_opaque_class
Index: cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
@@ -375,8 +375,18 @@
 MR = Uncasted;
   }
 
+  // If we're casting a symbolic base pointer to a derived class, use
+  // CXXDerivedObjectRegion to represent the cast. If it's a pointer to an
+  // unrelated type, it must be a weird reinterpret_cast and we have to
+  // be fine with ElementRegion. TODO: Should we instead make
+  // Derived{TargetClass, Element{SourceClass, SR}}?
   if (const auto *SR = dyn_cast(MR)) {
-return loc::MemRegionVal(MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+QualType T = SR->getSymbol()->getType();
+const CXXRecordDecl *SourceClass = T->getPointeeCXXRecordDecl();
+if (TargetClass && SourceClass && TargetClass->isDerivedFrom(SourceClass))
+  return loc::MemRegionVal(
+  MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+return loc::MemRegionVal(GetElementZeroRegion(SR, TargetType));
   }
 
   // We failed if the region we ended up with has perfect type info.


Index: cfe/trunk/test/Analysis/casts.cpp
===
--- cfe/trunk/test/Analysis/casts.cpp
+++ cfe/trunk/test/Analysis/casts.cpp
@@ -70,5 +70,35 @@
   clang_analyzer_eval(c->x); // expected-warning{{UNKNOWN}}
   clang_analyzer_eval(c->y); // expected-warning{{TRUE}}
 }
+} // namespace base_to_derived_double_inheritance
+
+namespace base_to_derived_opaque_class {
+class NotInt {
+public:
+  operator int() { return !x; } // no-crash
+  int x;
+};
+
+typedef struct Opaque *OpaqueRef;
+typedef void *VeryOpaqueRef;
+
+class Transparent {
+public:
+  int getNotInt() { return NI; }
+  NotInt NI;
+};
+
+class SubTransparent : public Transparent {};
+
+SubTransparent *castToDerived(Transparent *TRef) {
+  return (SubTransparent *)TRef;
 }
 
+void foo(OpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
+}
+
+void foo(VeryOpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
+}
+} // namespace base_to_derived_opaque_class
Index: cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
@@ -375,8 +375,18 @@
 MR = Uncasted;
   }
 
+  // If we're casting a symbolic base pointer to a derived class, use
+  // CXXDerivedObjectRegion to represent the cast. If it's a pointer to an
+  // unrelated type, it must be a weird reinterpret_cast and we have to
+  // be fine with ElementRegion. TODO: Should we instead make
+  // Derived{TargetClass, Element{SourceClass, SR}}?
   if (const auto *SR = dyn_cast(MR)) {
-return loc::MemRegionVal(MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+QualType T = SR->getSymbol()->getType();
+const CXXRecordDecl *SourceClass = T->getPointeeCXXRecordDecl();
+if (TargetClass && SourceClass && TargetClass->isDerivedFrom(SourceClass))
+  return loc::MemRegionVal(
+  MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+return loc::MemRegionVal(GetElementZeroRegion(SR, TargetType));
   }
 
   // We failed if the region we ended up with has perfect type info.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org

r343051 - [analyzer] Fix a crash on casting symbolic pointers to derived classes.

2018-09-25 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Tue Sep 25 17:17:14 2018
New Revision: 343051

URL: http://llvm.org/viewvc/llvm-project?rev=343051=rev
Log:
[analyzer] Fix a crash on casting symbolic pointers to derived classes.

Commit r340984 causes a crash when a pointer to a completely unrelated type
UnrelatedT (eg., opaque struct pattern) is being casted from base class BaseT to
derived class DerivedT, which results in an ill-formed region
Derived{SymRegion{$}, DerivedT}.

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

Modified:
cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
cfe/trunk/test/Analysis/casts.cpp

Modified: cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp?rev=343051=343050=343051=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/Store.cpp Tue Sep 25 17:17:14 2018
@@ -375,8 +375,18 @@ SVal StoreManager::attemptDownCast(SVal
 MR = Uncasted;
   }
 
+  // If we're casting a symbolic base pointer to a derived class, use
+  // CXXDerivedObjectRegion to represent the cast. If it's a pointer to an
+  // unrelated type, it must be a weird reinterpret_cast and we have to
+  // be fine with ElementRegion. TODO: Should we instead make
+  // Derived{TargetClass, Element{SourceClass, SR}}?
   if (const auto *SR = dyn_cast(MR)) {
-return loc::MemRegionVal(MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+QualType T = SR->getSymbol()->getType();
+const CXXRecordDecl *SourceClass = T->getPointeeCXXRecordDecl();
+if (TargetClass && SourceClass && TargetClass->isDerivedFrom(SourceClass))
+  return loc::MemRegionVal(
+  MRMgr.getCXXDerivedObjectRegion(TargetClass, SR));
+return loc::MemRegionVal(GetElementZeroRegion(SR, TargetType));
   }
 
   // We failed if the region we ended up with has perfect type info.

Modified: cfe/trunk/test/Analysis/casts.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Analysis/casts.cpp?rev=343051=343050=343051=diff
==
--- cfe/trunk/test/Analysis/casts.cpp (original)
+++ cfe/trunk/test/Analysis/casts.cpp Tue Sep 25 17:17:14 2018
@@ -70,5 +70,35 @@ void foo(B *b) {
   clang_analyzer_eval(c->x); // expected-warning{{UNKNOWN}}
   clang_analyzer_eval(c->y); // expected-warning{{TRUE}}
 }
+} // namespace base_to_derived_double_inheritance
+
+namespace base_to_derived_opaque_class {
+class NotInt {
+public:
+  operator int() { return !x; } // no-crash
+  int x;
+};
+
+typedef struct Opaque *OpaqueRef;
+typedef void *VeryOpaqueRef;
+
+class Transparent {
+public:
+  int getNotInt() { return NI; }
+  NotInt NI;
+};
+
+class SubTransparent : public Transparent {};
+
+SubTransparent *castToDerived(Transparent *TRef) {
+  return (SubTransparent *)TRef;
+}
+
+void foo(OpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
 }
 
+void foo(VeryOpaqueRef ORef) {
+  castToDerived(reinterpret_cast(ORef))->getNotInt();
+}
+} // namespace base_to_derived_opaque_class


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


[PATCH] D52133: [analyzer] A testing facility for testing relationships between symbols.

2018-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343048: [analyzer] Add a testing facility for testing 
relationships between symbols. (authored by dergachev, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52133?vs=165810=167029#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52133

Files:
  cfe/trunk/docs/analyzer/DebugChecks.rst
  cfe/trunk/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  cfe/trunk/test/Analysis/expr-inspection.cpp
  cfe/trunk/test/Analysis/svalbuilder-rearrange-comparisons.c

Index: cfe/trunk/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
===
--- cfe/trunk/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
@@ -43,6 +43,8 @@
   void analyzerPrintState(const CallExpr *CE, CheckerContext ) const;
   void analyzerGetExtent(const CallExpr *CE, CheckerContext ) const;
   void analyzerHashDump(const CallExpr *CE, CheckerContext ) const;
+  void analyzerDenote(const CallExpr *CE, CheckerContext ) const;
+  void analyzerExpress(const CallExpr *CE, CheckerContext ) const;
 
   typedef void (ExprInspectionChecker::*FnCheck)(const CallExpr *,
  CheckerContext ) const;
@@ -60,6 +62,7 @@
 }
 
 REGISTER_SET_WITH_PROGRAMSTATE(MarkedSymbols, SymbolRef)
+REGISTER_MAP_WITH_PROGRAMSTATE(DenotedSymbols, SymbolRef, const StringLiteral *)
 
 bool ExprInspectionChecker::evalCall(const CallExpr *CE,
  CheckerContext ) const {
@@ -82,6 +85,8 @@
 .Case("clang_analyzer_numTimesReached",
   ::analyzerNumTimesReached)
 .Case("clang_analyzer_hashDump", ::analyzerHashDump)
+.Case("clang_analyzer_denote", ::analyzerDenote)
+.Case("clang_analyzer_express", ::analyzerExpress)
 .Default(nullptr);
 
   if (!Handler)
@@ -264,6 +269,13 @@
   N = BugNode;
 State = State->remove(Sym);
   }
+
+  for (auto I : State->get()) {
+SymbolRef Sym = I.first;
+if (!SymReaper.isLive(Sym))
+  State = State->remove(Sym);
+  }
+
   C.addTransition(State, N);
 }
 
@@ -295,6 +307,92 @@
   reportBug(HashContent, C);
 }
 
+void ExprInspectionChecker::analyzerDenote(const CallExpr *CE,
+   CheckerContext ) const {
+  if (CE->getNumArgs() < 2) {
+reportBug("clang_analyzer_denote() requires a symbol and a string literal",
+  C);
+return;
+  }
+
+  SymbolRef Sym = C.getSVal(CE->getArg(0)).getAsSymbol();
+  if (!Sym) {
+reportBug("Not a symbol", C);
+return;
+  }
+
+  if (!isa(Sym)) {
+reportBug("Not an atomic symbol", C);
+return;
+  }
+
+  const auto *E = dyn_cast(CE->getArg(1)->IgnoreParenCasts());
+  if (!E) {
+reportBug("Not a string literal", C);
+return;
+  }
+
+  ProgramStateRef State = C.getState();
+
+  C.addTransition(C.getState()->set(Sym, E));
+}
+
+class SymbolExpressor
+: public SymExprVisitor> {
+  ProgramStateRef State;
+
+public:
+  SymbolExpressor(ProgramStateRef State) : State(State) {}
+
+  Optional VisitSymExpr(const SymExpr *S) {
+if (const StringLiteral *const *SLPtr = State->get(S)) {
+  const StringLiteral *SL = *SLPtr;
+  return std::string(SL->getBytes());
+}
+return None;
+  }
+
+  Optional VisitSymIntExpr(const SymIntExpr *S) {
+if (auto Str = Visit(S->getLHS()))
+  return (*Str + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) + " " +
+  std::to_string(S->getRHS().getLimitedValue()) +
+  (S->getRHS().isUnsigned() ? "U" : ""))
+  .str();
+return None;
+  }
+
+  Optional VisitSymSymExpr(const SymSymExpr *S) {
+if (auto Str1 = Visit(S->getLHS()))
+  if (auto Str2 = Visit(S->getRHS()))
+return (*Str1 + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) +
+" " + *Str2).str();
+return None;
+  }
+};
+
+void ExprInspectionChecker::analyzerExpress(const CallExpr *CE,
+CheckerContext ) const {
+  if (CE->getNumArgs() == 0) {
+reportBug("clang_analyzer_express() requires a symbol", C);
+return;
+  }
+
+  SymbolRef Sym = C.getSVal(CE->getArg(0)).getAsSymbol();
+  if (!Sym) {
+reportBug("Not a symbol", C);
+return;
+  }
+
+  SymbolExpressor V(C.getState());
+  auto Str = V.Visit(Sym);
+  if (!Str) {
+reportBug("Unable to express", C);
+return;
+  }
+
+  reportBug(*Str, C);
+}
+
 void ento::registerExprInspectionChecker(CheckerManager ) {
   Mgr.registerChecker();
 }
Index: cfe/trunk/docs/analyzer/DebugChecks.rst
===
--- cfe/trunk/docs/analyzer/DebugChecks.rst
+++ cfe/trunk/docs/analyzer/DebugChecks.rst
@@ -255,6 +255,23 @@
   clang_analyzer_hashDump(x); // expected-warning{{hashed string for x}}
 }
 
+- ``void 

r343050 - Fix a bot failure from r343042.

2018-09-25 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Tue Sep 25 16:52:29 2018
New Revision: 343050

URL: http://llvm.org/viewvc/llvm-project?rev=343050=rev
Log:
Fix a bot failure from r343042.

Modified:
cfe/trunk/test/Sema/warn-duplicate-enum.c

Modified: cfe/trunk/test/Sema/warn-duplicate-enum.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-duplicate-enum.c?rev=343050=343049=343050=diff
==
--- cfe/trunk/test/Sema/warn-duplicate-enum.c (original)
+++ cfe/trunk/test/Sema/warn-duplicate-enum.c Tue Sep 25 16:52:29 2018
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 %s -fsyntax-only -verify -Wduplicate-enum
-// RUN: %clang_cc1 %s -x c++ -DCPP -fsyntax-only -verify -Wduplicate-enum
+// RUN: %clang_cc1 -triple x86_64-apple-darwin %s -x c++ -DCPP -fsyntax-only 
-verify -Wduplicate-enum
 enum A {
   A1 = 0,  // expected-note {{element 'A1' also has value 0}}
   A2 = -1,
@@ -104,6 +104,6 @@ enum enum2 {
 #ifdef CPP
 enum BigEnumerators : long {
   e1,
-  e2 = 9223372036854775807L,
+  e2 = __LONG_MAX__,
 };
 #endif


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


[PATCH] D52133: [analyzer] A testing facility for testing relationships between symbols.

2018-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC343048: [analyzer] Add a testing facility for testing 
relationships between symbols. (authored by dergachev, committed by ).

Repository:
  rL LLVM

https://reviews.llvm.org/D52133

Files:
  docs/analyzer/DebugChecks.rst
  lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
  test/Analysis/expr-inspection.cpp
  test/Analysis/svalbuilder-rearrange-comparisons.c

Index: docs/analyzer/DebugChecks.rst
===
--- docs/analyzer/DebugChecks.rst
+++ docs/analyzer/DebugChecks.rst
@@ -255,6 +255,23 @@
   clang_analyzer_hashDump(x); // expected-warning{{hashed string for x}}
 }
 
+- ``void clang_analyzer_denote(int, const char *);``
+
+  Denotes symbols with strings. A subsequent call to clang_analyzer_express()
+  will expresses another symbol in terms of these string. Useful for testing
+  relationships between different symbols.
+
+  Example usage::
+
+void foo(int x) {
+  clang_analyzer_denote(x, "$x");
+  clang_analyzer_express(x + 1); // expected-warning{{$x + 1}}
+}
+
+- ``void clang_analyzer_express(int);``
+
+  See clang_analyzer_denote().
+
 Statistics
 ==
 
Index: test/Analysis/svalbuilder-rearrange-comparisons.c
===
--- test/Analysis/svalbuilder-rearrange-comparisons.c
+++ test/Analysis/svalbuilder-rearrange-comparisons.c
@@ -1,10 +1,8 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=debug.ExprInspection,core.builtin -analyzer-config aggressive-binary-operation-simplification=true -verify -analyzer-config eagerly-assume=false %s
 
-// Temporary xfailing, as debug printing functionality has changed.
-// XFAIL: *
-
-void clang_analyzer_dump(int x);
 void clang_analyzer_eval(int x);
+void clang_analyzer_denote(int x, const char *literal);
+void clang_analyzer_express(int x);
 
 void exit(int);
 
@@ -29,907 +27,951 @@
 
 void compare_different_symbol_equal() {
   int x = f(), y = f();
-  clang_analyzer_dump(x); // expected-warning{{conj_$2{int}}}
-  clang_analyzer_dump(y); // expected-warning{{conj_$9{int}}}
-  clang_analyzer_dump(x == y);
-  // expected-warning@-1{{((conj_$2{int}) - (conj_$9{int})) == 0}}
+  clang_analyzer_denote(x, "$x");
+  clang_analyzer_denote(y, "$y");
+  clang_analyzer_express(x == y); // expected-warning {{$x - $y == 0}}
 }
 
 void compare_different_symbol_plus_left_int_equal() {
-  int x = f()+1, y = f();
-  clang_analyzer_dump(x); // expected-warning{{(conj_$2{int}) + 1}}
-  clang_analyzer_dump(y); // expected-warning{{conj_$9{int}}}
-  clang_analyzer_dump(x == y);
-  // expected-warning@-1{{((conj_$9{int}) - (conj_$2{int})) == 1}}
+  int x = f(), y = f();
+  clang_analyzer_denote(x, "$x");
+  clang_analyzer_denote(y, "$y");
+  x += 1;
+  clang_analyzer_express(x == y); // expected-warning {{$y - $x == 1}}
 }
 
 void compare_different_symbol_minus_left_int_equal() {
-  int x = f()-1, y = f();
-  clang_analyzer_dump(x); // expected-warning{{(conj_$2{int}) - 1}}
-  clang_analyzer_dump(y); // expected-warning{{conj_$9{int}}}
-  clang_analyzer_dump(x == y);
-  // expected-warning@-1{{((conj_$2{int}) - (conj_$9{int})) == 1}}
+  int x = f(), y = f();
+  clang_analyzer_denote(x, "$x");
+  clang_analyzer_denote(y, "$y");
+  x -= 1;
+  clang_analyzer_express(x == y); // expected-warning {{$x - $y == 1}}
 }
 
 void compare_different_symbol_plus_right_int_equal() {
-  int x = f(), y = f()+2;
-  clang_analyzer_dump(x); // expected-warning{{conj_$2{int}}}
-  clang_analyzer_dump(y); // expected-warning{{(conj_$9{int}) + 2}}
-  clang_analyzer_dump(x == y);
-  // expected-warning@-1{{((conj_$2{int}) - (conj_$9{int})) == 2}}
+  int x = f(), y = f();
+  clang_analyzer_denote(x, "$x");
+  clang_analyzer_denote(y, "$y");
+  y += 2;
+  clang_analyzer_express(y); // expected-warning {{$y + 2}}
+  clang_analyzer_express(x == y); // expected-warning {{$x - $y == 2}}
 }
 
 void compare_different_symbol_minus_right_int_equal() {
-  int x = f(), y = f()-2;
-  clang_analyzer_dump(x); // expected-warning{{conj_$2{int}}}
-  clang_analyzer_dump(y); // expected-warning{{(conj_$9{int}) - 2}}
-  clang_analyzer_dump(x == y);
-  // expected-warning@-1{{((conj_$9{int}) - (conj_$2{int})) == 2}}
+  int x = f(), y = f();
+  clang_analyzer_denote(x, "$x");
+  clang_analyzer_denote(y, "$y");
+  y -= 2;
+  clang_analyzer_express(y); // expected-warning {{$y - 2}}
+  clang_analyzer_express(x == y); // expected-warning {{$y - $x == 2}}
 }
 
 void compare_different_symbol_plus_left_plus_right_int_equal() {
-  int x = f()+2, y = f()+1;
-  clang_analyzer_dump(x); // expected-warning{{(conj_$2{int}) + 2}}
-  clang_analyzer_dump(y); // expected-warning{{(conj_$9{int}) + 1}}
-  clang_analyzer_dump(x == y);
-  // expected-warning@-1{{((conj_$9{int}) - (conj_$2{int})) == 1}}
+  int x = f(), y = f();
+  clang_analyzer_denote(x, "$x");
+  clang_analyzer_denote(y, "$y");
+  x += 2;
+  y 

r343048 - [analyzer] Add a testing facility for testing relationships between symbols.

2018-09-25 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Tue Sep 25 16:50:53 2018
New Revision: 343048

URL: http://llvm.org/viewvc/llvm-project?rev=343048=rev
Log:
[analyzer] Add a testing facility for testing relationships between symbols.

Tests introduced in r329780 was disabled in r342317 because these tests
were accidentally testing dump infrastructure, when all they cared about was
how symbols relate to each other. So when dump infrastructure changed,
tests became annoying to maintain.

Add a new feature to ExprInspection: clang_analyzer_denote() and
clang_analyzer_explain(). The former adds a notation to a symbol, the latter
expresses another symbol in terms of previously denoted symbols.

It's currently a bit wonky - doesn't print parentheses and only supports
denoting atomic symbols. But it's even more readable that way.

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

Added:
cfe/trunk/test/Analysis/expr-inspection.cpp
Modified:
cfe/trunk/docs/analyzer/DebugChecks.rst
cfe/trunk/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
cfe/trunk/test/Analysis/svalbuilder-rearrange-comparisons.c

Modified: cfe/trunk/docs/analyzer/DebugChecks.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/analyzer/DebugChecks.rst?rev=343048=343047=343048=diff
==
--- cfe/trunk/docs/analyzer/DebugChecks.rst (original)
+++ cfe/trunk/docs/analyzer/DebugChecks.rst Tue Sep 25 16:50:53 2018
@@ -255,6 +255,23 @@ ExprInspection checks
   clang_analyzer_hashDump(x); // expected-warning{{hashed string for x}}
 }
 
+- ``void clang_analyzer_denote(int, const char *);``
+
+  Denotes symbols with strings. A subsequent call to clang_analyzer_express()
+  will expresses another symbol in terms of these string. Useful for testing
+  relationships between different symbols.
+
+  Example usage::
+
+void foo(int x) {
+  clang_analyzer_denote(x, "$x");
+  clang_analyzer_express(x + 1); // expected-warning{{$x + 1}}
+}
+
+- ``void clang_analyzer_express(int);``
+
+  See clang_analyzer_denote().
+
 Statistics
 ==
 

Modified: cfe/trunk/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp?rev=343048=343047=343048=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp Tue Sep 25 
16:50:53 2018
@@ -43,6 +43,8 @@ class ExprInspectionChecker : public Che
   void analyzerPrintState(const CallExpr *CE, CheckerContext ) const;
   void analyzerGetExtent(const CallExpr *CE, CheckerContext ) const;
   void analyzerHashDump(const CallExpr *CE, CheckerContext ) const;
+  void analyzerDenote(const CallExpr *CE, CheckerContext ) const;
+  void analyzerExpress(const CallExpr *CE, CheckerContext ) const;
 
   typedef void (ExprInspectionChecker::*FnCheck)(const CallExpr *,
  CheckerContext ) const;
@@ -60,6 +62,7 @@ public:
 }
 
 REGISTER_SET_WITH_PROGRAMSTATE(MarkedSymbols, SymbolRef)
+REGISTER_MAP_WITH_PROGRAMSTATE(DenotedSymbols, SymbolRef, const StringLiteral 
*)
 
 bool ExprInspectionChecker::evalCall(const CallExpr *CE,
  CheckerContext ) const {
@@ -82,6 +85,8 @@ bool ExprInspectionChecker::evalCall(con
 .Case("clang_analyzer_numTimesReached",
   ::analyzerNumTimesReached)
 .Case("clang_analyzer_hashDump", ::analyzerHashDump)
+.Case("clang_analyzer_denote", ::analyzerDenote)
+.Case("clang_analyzer_express", ::analyzerExpress)
 .Default(nullptr);
 
   if (!Handler)
@@ -264,6 +269,13 @@ void ExprInspectionChecker::checkDeadSym
   N = BugNode;
 State = State->remove(Sym);
   }
+
+  for (auto I : State->get()) {
+SymbolRef Sym = I.first;
+if (!SymReaper.isLive(Sym))
+  State = State->remove(Sym);
+  }
+
   C.addTransition(State, N);
 }
 
@@ -295,6 +307,92 @@ void ExprInspectionChecker::analyzerHash
   reportBug(HashContent, C);
 }
 
+void ExprInspectionChecker::analyzerDenote(const CallExpr *CE,
+   CheckerContext ) const {
+  if (CE->getNumArgs() < 2) {
+reportBug("clang_analyzer_denote() requires a symbol and a string literal",
+  C);
+return;
+  }
+
+  SymbolRef Sym = C.getSVal(CE->getArg(0)).getAsSymbol();
+  if (!Sym) {
+reportBug("Not a symbol", C);
+return;
+  }
+
+  if (!isa(Sym)) {
+reportBug("Not an atomic symbol", C);
+return;
+  }
+
+  const auto *E = dyn_cast(CE->getArg(1)->IgnoreParenCasts());
+  if (!E) {
+reportBug("Not a string literal", C);
+return;
+  }
+
+  ProgramStateRef State = C.getState();
+
+  C.addTransition(C.getState()->set(Sym, E));
+}
+
+class SymbolExpressor
+: public SymExprVisitor> {
+  ProgramStateRef State;
+

r343044 - [clang-check-codegen][cfstring] Accept either @ or % for progbits to make ppc64be bots happy.

2018-09-25 Thread Kristina Brooks via cfe-commits
Author: kristina
Date: Tue Sep 25 16:17:09 2018
New Revision: 343044

URL: http://llvm.org/viewvc/llvm-project?rev=343044=rev
Log:
[clang-check-codegen][cfstring] Accept either @ or % for progbits to make 
ppc64be bots happy.

PPC64BE bots use % instead of @ for directives like progbits. Since CFString 
tests also
check asm output, they fail on the following:

  cfstring3.c:44:19: error: CHECK-ASM-ELF: expected string not found in input
  // CHECK-ASM-ELF: .section cfstring,"aw",@progbits
  :30:2: note: possible intended match here
  .section cfstring,"aw",%progbits

Updating that check with a {{[@%]}}progbits regex to make those bots happy.
 

Modified:
cfe/trunk/test/CodeGen/cfstring3.c

Modified: cfe/trunk/test/CodeGen/cfstring3.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/CodeGen/cfstring3.c?rev=343044=343043=343044=diff
==
--- cfe/trunk/test/CodeGen/cfstring3.c (original)
+++ cfe/trunk/test/CodeGen/cfstring3.c Tue Sep 25 16:17:09 2018
@@ -41,5 +41,5 @@ const CFStringRef two = (CFStringRef)__b
 // CHECK-MACHO64: @_unnamed_cfstring_.2 = private global 
%struct.__NSConstantString_tag { i32* getelementptr inbounds ([0 x i32], [0 x 
i32]* @__CFConstantStringClassReference, i32 0, i32 0), i32 2000, i8* bitcast 
([7 x i16]* @.str.1 to i8*), i64 6 }, section "__DATA,__cfstring", align 8
 
 // CHECK-ASM-COFF: .section cfstring,"dw"
-// CHECK-ASM-ELF: .section cfstring,"aw",@progbits
+// CHECK-ASM-ELF: .section cfstring,"aw",{{[@%]}}progbits
 // CHECK-ASM-MACHO: .section __DATA,__cfstring


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


[PATCH] D52524: Add -Wno-poison-system-directories flag

2018-09-25 Thread Yunlian Jiang via Phabricator via cfe-commits
yunlian created this revision.
Herald added a subscriber: cfe-commits.

When using clang as a cross-compiler, we should not use system headers or 
libraries to do the compilation. This CL creates a new warning flag
-Wpoison-system-directories support to emit warnings if --sysroot is set and 
headers or libraries from common host system location are used.


Repository:
  rC Clang

https://reviews.llvm.org/D52524

Files:
  include/clang/Basic/DiagnosticCommonKinds.td
  include/clang/Basic/DiagnosticGroups.td
  include/clang/Frontend/Utils.h
  lib/Frontend/CompilerInstance.cpp
  lib/Frontend/InitHeaderSearch.cpp


Index: lib/Frontend/InitHeaderSearch.cpp
===
--- lib/Frontend/InitHeaderSearch.cpp
+++ lib/Frontend/InitHeaderSearch.cpp
@@ -45,12 +45,13 @@
   HeaderSearch 
   bool Verbose;
   std::string IncludeSysroot;
+  DiagnosticsEngine 
   bool HasSysroot;
 
 public:
 
-  InitHeaderSearch(HeaderSearch , bool verbose, StringRef sysroot)
-: Headers(HS), Verbose(verbose), IncludeSysroot(sysroot),
+  InitHeaderSearch(HeaderSearch , bool verbose, StringRef sysroot, 
DiagnosticsEngine )
+: Headers(HS), Verbose(verbose), IncludeSysroot(sysroot), Diag(Diag),
   HasSysroot(!(sysroot.empty() || sysroot == "/")) {
   }
 
@@ -138,6 +139,17 @@
   SmallString<256> MappedPathStorage;
   StringRef MappedPathStr = Path.toStringRef(MappedPathStorage);
 
+  // If use system headers/libraries while cross-compiling,
+  // emit the warning.
+  if (HasSysroot) {
+if(MappedPathStr.startswith("/usr/include") ||
+   MappedPathStr.startswith("/usr/local/include") ||
+   MappedPathStr.startswith("/lib") ||
+   MappedPathStr.startswith("/usr/local/lib") {
+ Diag.Report(diag::warn_poison_system_directories) << 
MappedPathStr.str();
+   }
+  }
+
   // Compute the DirectoryLookup type.
   SrcMgr::CharacteristicKind Type;
   if (Group == Quoted || Group == Angled || Group == IndexHeaderMap) {
@@ -663,8 +675,9 @@
 void clang::ApplyHeaderSearchOptions(HeaderSearch ,
  const HeaderSearchOptions ,
  const LangOptions ,
+ DiagnosticsEngine ,
  const llvm::Triple ) {
-  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot);
+  InitHeaderSearch Init(HS, HSOpts.Verbose, HSOpts.Sysroot, Diag);
 
   // Add the user defined entries.
   for (unsigned i = 0, e = HSOpts.UserEntries.size(); i != e; ++i) {
Index: lib/Frontend/CompilerInstance.cpp
===
--- lib/Frontend/CompilerInstance.cpp
+++ lib/Frontend/CompilerInstance.cpp
@@ -416,7 +416,7 @@
 HeaderSearchTriple = >getAuxTargetInfo()->getTriple();
 
   ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
-   PP->getLangOpts(), *HeaderSearchTriple);
+   PP->getLangOpts(), PP->getDiagnostics(), 
*HeaderSearchTriple);
 
   PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
 
Index: include/clang/Frontend/Utils.h
===
--- include/clang/Frontend/Utils.h
+++ include/clang/Frontend/Utils.h
@@ -63,6 +63,7 @@
 void ApplyHeaderSearchOptions(HeaderSearch ,
   const HeaderSearchOptions ,
   const LangOptions ,
+  DiagnosticsEngine ,
   const llvm::Triple );
 
 /// InitializePreprocessor - Initialize the preprocessor getting it and the
Index: include/clang/Basic/DiagnosticGroups.td
===
--- include/clang/Basic/DiagnosticGroups.td
+++ include/clang/Basic/DiagnosticGroups.td
@@ -1031,3 +1031,7 @@
 // A warning group specifically for warnings related to function
 // multiversioning.
 def FunctionMultiVersioning : DiagGroup<"function-multiversion">;
+
+// A warning group for warnings about including system headers when
+// cross-compiling.
+def PoisonSystemDirectories : DiagGroup<"poison-system-directories">;
Index: include/clang/Basic/DiagnosticCommonKinds.td
===
--- include/clang/Basic/DiagnosticCommonKinds.td
+++ include/clang/Basic/DiagnosticCommonKinds.td
@@ -248,4 +248,7 @@
 // OpenMP
 def err_omp_more_one_clause : Error<
   "directive '#pragma omp %0' cannot contain more than one '%1' 
clause%select{| with '%3' name modifier| with 'source' dependence}2">;
+
+// Poison system directories.
+def warn_poison_system_directories : Warning <"include location '%0' is unsafe 
for cross-compilation">, InGroup;
 }


Index: lib/Frontend/InitHeaderSearch.cpp
===
--- lib/Frontend/InitHeaderSearch.cpp
+++ lib/Frontend/InitHeaderSearch.cpp
@@ -45,12 +45,13 @@
   HeaderSearch 

r343042 - [Sema] Use a more civilized hash map to implement -Wduplicate-enum.

2018-09-25 Thread Erik Pilkington via cfe-commits
Author: epilk
Date: Tue Sep 25 15:53:06 2018
New Revision: 343042

URL: http://llvm.org/viewvc/llvm-project?rev=343042=rev
Log:
[Sema] Use a more civilized hash map to implement -Wduplicate-enum.

DenseMap used LONG_MAX as a tombstone, so it asserts
when you try to insert it!

rdar://44774672

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

Modified: cfe/trunk/lib/Sema/SemaDecl.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDecl.cpp?rev=343042=343041=343042=diff
==
--- cfe/trunk/lib/Sema/SemaDecl.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDecl.cpp Tue Sep 25 15:53:06 2018
@@ -16402,7 +16402,7 @@ static void CheckForDuplicateEnumValues(
   typedef SmallVector, 3> DuplicatesVector;
 
   typedef llvm::PointerUnion DeclOrVector;
-  typedef llvm::DenseMap ValueToVectorMap;
+  typedef std::unordered_map ValueToVectorMap;
 
   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
   auto EnumConstantToKey = [](const EnumConstantDecl *D) {

Modified: cfe/trunk/test/Sema/warn-duplicate-enum.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Sema/warn-duplicate-enum.c?rev=343042=343041=343042=diff
==
--- cfe/trunk/test/Sema/warn-duplicate-enum.c (original)
+++ cfe/trunk/test/Sema/warn-duplicate-enum.c Tue Sep 25 15:53:06 2018
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 %s -fsyntax-only -verify -Wduplicate-enum
-// RUN: %clang_cc1 %s -x c++ -fsyntax-only -verify -Wduplicate-enum
+// RUN: %clang_cc1 %s -x c++ -DCPP -fsyntax-only -verify -Wduplicate-enum
 enum A {
   A1 = 0,  // expected-note {{element 'A1' also has value 0}}
   A2 = -1,
@@ -99,3 +99,11 @@ enum enum1 {
 enum enum2 {
   VALUE // expected-error{{redefinition of enumerator 'VALUE'}}
 };
+
+// rdar://44774672
+#ifdef CPP
+enum BigEnumerators : long {
+  e1,
+  e2 = 9223372036854775807L,
+};
+#endif


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


r343040 - Don't emit "will be treated as an identifier character" warning for

2018-09-25 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Tue Sep 25 15:34:45 2018
New Revision: 343040

URL: http://llvm.org/viewvc/llvm-project?rev=343040=rev
Log:
Don't emit "will be treated as an identifier character" warning for
UTF-8 characters that aren't identifier characters in the current
language mode.

Modified:
cfe/trunk/lib/Lex/Lexer.cpp
cfe/trunk/test/Lexer/unicode.c

Modified: cfe/trunk/lib/Lex/Lexer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Lex/Lexer.cpp?rev=343040=343039=343040=diff
==
--- cfe/trunk/lib/Lex/Lexer.cpp (original)
+++ cfe/trunk/lib/Lex/Lexer.cpp Tue Sep 25 15:34:45 2018
@@ -3085,6 +3085,8 @@ bool Lexer::LexUnicode(Token , ui
   maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
 makeCharRange(*this, BufferPtr, CurPtr),
 /*IsFirst=*/true);
+  maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), C,
+ makeCharRange(*this, BufferPtr, CurPtr));
 }
 
 MIOpt.ReadToken();
@@ -3879,7 +3881,6 @@ LexNextToken:
 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
 // an escaped newline.
 --CurPtr;
-const char *UTF8StartPtr = CurPtr;
 llvm::ConversionResult Status =
 llvm::convertUTF8Sequence((const llvm::UTF8 **),
   (const llvm::UTF8 *)BufferEnd,
@@ -3894,9 +3895,6 @@ LexNextToken:
 // (We manually eliminate the tail call to avoid recursion.)
 goto LexNextToken;
   }
-  if (!isLexingRawMode())
-maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
-   makeCharRange(*this, UTF8StartPtr, CurPtr));
   return LexUnicode(Result, CodePoint, CurPtr);
 }
 

Modified: cfe/trunk/test/Lexer/unicode.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Lexer/unicode.c?rev=343040=343039=343040=diff
==
--- cfe/trunk/test/Lexer/unicode.c (original)
+++ cfe/trunk/test/Lexer/unicode.c Tue Sep 25 15:34:45 2018
@@ -45,3 +45,8 @@ int ⁠xx‍;
 // expected-warning@-3 {{identifier contains Unicode character  that 
is invisible in some environments}}
 int foo​bar = 0; // expected-warning {{identifier contains Unicode character 
 that is invisible in some environments}}
 int x = foobar; // expected-error {{undeclared identifier}}
+
+int ∣foo; // expected-error {{non-ASCII character}}
+#ifndef PP_ONLY
+#define ∶ x // expected-error {{macro name must be an identifier}}
+#endif


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


[clang-tools-extra] r343039 - [clangd] Remove unused using-declaration testing::AllOf

2018-09-25 Thread Fangrui Song via cfe-commits
Author: maskray
Date: Tue Sep 25 15:32:11 2018
New Revision: 343039

URL: http://llvm.org/viewvc/llvm-project?rev=343039=rev
Log:
[clangd] Remove unused using-declaration testing::AllOf

Modified:
clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp

Modified: clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp?rev=343039=343038=343039=diff
==
--- clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp (original)
+++ clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp Tue Sep 25 
15:32:11 2018
@@ -13,7 +13,6 @@
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
-using testing::AllOf;
 using testing::UnorderedElementsAre;
 using testing::UnorderedElementsAreArray;
 namespace clang {


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


[PATCH] D52344: [Clang][CodeGen][ObjC]: Fix non-bridged CoreFoundation builds on ELF targets that use `-fconstant-cfstrings`.

2018-09-25 Thread Kristina Brooks via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343038: Reland [Clang][CodeGen][ObjC]: Fix 
CoreFoundation on ELF with `-fconstant… (authored by kristina, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52344?vs=166996=167011#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52344

Files:
  cfe/trunk/lib/CodeGen/CodeGenModule.cpp
  cfe/trunk/test/CodeGen/CFStrings.c
  cfe/trunk/test/CodeGen/cfstring-elf-cfbuild-x86_64.c
  cfe/trunk/test/CodeGen/cfstring-elf-sections-x86_64.c
  cfe/trunk/test/CodeGen/cfstring3.c

Index: cfe/trunk/test/CodeGen/cfstring-elf-sections-x86_64.c
===
--- cfe/trunk/test/CodeGen/cfstring-elf-sections-x86_64.c
+++ cfe/trunk/test/CodeGen/cfstring-elf-sections-x86_64.c
@@ -0,0 +1,23 @@
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-elf -S %s -o - | FileCheck %s -check-prefix CHECK-ELF-DATA-SECTION
+
+typedef struct __CFString *CFStringRef;
+const CFStringRef one = (CFStringRef)__builtin___CFStringMakeConstantString("one");
+const CFStringRef two = (CFStringRef)__builtin___CFStringMakeConstantString("\xef\xbf\xbd\x74\xef\xbf\xbd\x77\xef\xbf\xbd\x6f");
+
+// CHECK-ELF-DATA-SECTION: .type .L.str,@object
+// CHECK-ELF-DATA-SECTION: .section .rodata,"a",@progbits
+// CHECK-ELF-DATA-SECTION: .L.str:
+// CHECK-ELF-DATA-SECTION: .asciz "one"
+
+// CHECK-ELF-DATA-SECTION: .type .L.str.1,@object
+// CHECK-ELF-DATA-SECTION: .section .rodata,"a",@progbits
+// CHECK-ELF-DATA-SECTION: .L.str.1:
+// CHECK-ELF-DATA-SECTION: .short 65533
+// CHECK-ELF-DATA-SECTION: .short 116
+// CHECK-ELF-DATA-SECTION: .short 65533
+// CHECK-ELF-DATA-SECTION: .short 119
+// CHECK-ELF-DATA-SECTION: .short 65533
+// CHECK-ELF-DATA-SECTION: .short 111
+// CHECK-ELF-DATA-SECTION: .short 0
Index: cfe/trunk/test/CodeGen/cfstring-elf-cfbuild-x86_64.c
===
--- cfe/trunk/test/CodeGen/cfstring-elf-cfbuild-x86_64.c
+++ cfe/trunk/test/CodeGen/cfstring-elf-cfbuild-x86_64.c
@@ -0,0 +1,36 @@
+// REQUIRES: x86-registered-target
+
+// RUN: %clang_cc1 -triple x86_64-elf -DCF_BUILDING_CF -DDECL -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-CF-IN-CF-DECL
+// RUN: %clang_cc1 -triple x86_64-elf -DCF_BUILDING_CF -DDEFN -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-CF-IN-CF-DEFN
+// RUN: %clang_cc1 -triple x86_64-elf -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-CF
+// RUN: %clang_cc1 -triple x86_64-elf -DEXTERN -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-CF-EXTERN
+
+// RUN: %clang_cc1 -Os -triple x86_64-elf -DCF_BUILDING_CF -DDECL -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-CF-IN-CF-DECL
+// RUN: %clang_cc1 -Os -triple x86_64-elf -DCF_BUILDING_CF -DDEFN -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-CF-IN-CF-DEFN
+// RUN: %clang_cc1 -Os -triple x86_64-elf -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-CF
+// RUN: %clang_cc1 -Os -triple x86_64-elf -DEXTERN -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-CF-EXTERN
+
+
+#if defined(CF_BUILDING_CF)
+#if defined(DECL)
+extern long __CFConstantStringClassReference[];
+#elif defined(DEFN)
+long __CFConstantStringClassReference[32];
+#endif
+#else
+#if defined(EXTERN)
+extern long __CFConstantStringClassReference[];
+#else
+long __CFConstantStringClassReference[];
+#endif
+#endif
+
+typedef struct __CFString *CFStringRef;
+const CFStringRef string = (CFStringRef)__builtin___CFStringMakeConstantString("string");
+
+
+// CHECK-CF-IN-CF-DECL: @__CFConstantStringClassReference = external global [0 x i32]
+// CHECK-CF-IN-CF-DEFN: @__CFConstantStringClassReference = common global [32 x i64] zeroinitializer, align 16
+// CHECK-CF: @__CFConstantStringClassReference = common global [1 x i64] zeroinitializer, align 8
+// CHECK-CF-EXTERN: @__CFConstantStringClassReference = external global [0 x i32]
+// CHECK-CF-EXTERN: @.str = private unnamed_addr constant [7 x i8] c"string\00", section ".rodata", align 1
Index: cfe/trunk/test/CodeGen/cfstring3.c
===
--- cfe/trunk/test/CodeGen/cfstring3.c
+++ cfe/trunk/test/CodeGen/cfstring3.c
@@ -0,0 +1,45 @@
+// REQUIRES: arm-registered-target,x86-registered-target
+
+// RUN: %clang_cc1 -triple thumbv7-windows -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-COFF
+// RUN: %clang_cc1 -triple i686-windows -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-COFF
+// RUN: %clang_cc1 -triple x86_64-windows -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-COFF
+
+// RUN: %clang_cc1 -triple armv7-elf -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-ELF -check-prefix CHECK-ELF32
+// RUN: %clang_cc1 -triple i686-elf -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-ELF -check-prefix CHECK-ELF32
+// RUN: %clang_cc1 -triple x86_64-elf -S 

r343038 - Reland "[Clang][CodeGen][ObjC]: Fix CoreFoundation on ELF with `-fconstant-cfstrings`"

2018-09-25 Thread Kristina Brooks via cfe-commits
Author: kristina
Date: Tue Sep 25 15:27:40 2018
New Revision: 343038

URL: http://llvm.org/viewvc/llvm-project?rev=343038=rev
Log:
Reland "[Clang][CodeGen][ObjC]: Fix CoreFoundation on ELF with 
`-fconstant-cfstrings`"

Relanding rL342883 with more fragmented tests to test ELF-specific
section emission separately from broad-scope CFString tests. Now this
tests the following separately

1). CoreFoundation builds and linkage for ELF while building it.
2). CFString ELF section emission outside CF in assembly output.
3). Broad scope `cfstring3.c` tests which cover all object formats at
bitcode level and assembly level (including ELF). 

This fixes non-bridged CoreFoundation builds on ELF targets
that use -fconstant-cfstrings. The original changes from differential 
for a similar patch to PE/COFF (https://reviews.llvm.org/D44491) did not
check for an edge case where the global could be a constant which surfaced
as an issue when building for ELF because of different linkage semantics.

This patch addresses several issues with crashes related to CF builds on ELF
as well as improves data layout by ensuring string literals that back
the actual CFConstStrings end up in .rodata in line with Mach-O.

Change itself tested with CoreFoundation on Linux x86_64 but should be valid
for BSD-like systems as well that use ELF as the native object format.

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


Added:
cfe/trunk/test/CodeGen/cfstring-elf-cfbuild-x86_64.c
cfe/trunk/test/CodeGen/cfstring-elf-sections-x86_64.c
cfe/trunk/test/CodeGen/cfstring3.c
Removed:
cfe/trunk/test/CodeGen/CFStrings.c
Modified:
cfe/trunk/lib/CodeGen/CodeGenModule.cpp

Modified: cfe/trunk/lib/CodeGen/CodeGenModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/CodeGen/CodeGenModule.cpp?rev=343038=343037=343038=diff
==
--- cfe/trunk/lib/CodeGen/CodeGenModule.cpp (original)
+++ cfe/trunk/lib/CodeGen/CodeGenModule.cpp Tue Sep 25 15:27:40 2018
@@ -4109,37 +4109,48 @@ CodeGenModule::GetAddrOfConstantCFString
 
   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
   llvm::Constant *Zeros[] = { Zero, Zero };
-
+  
   // If we don't already have it, get __CFConstantStringClassReference.
   if (!CFConstantStringClassRef) {
 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
 Ty = llvm::ArrayType::get(Ty, 0);
-llvm::GlobalValue *GV = cast(
-CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"));
-
-if (getTriple().isOSBinFormatCOFF()) {
-  IdentifierInfo  = getContext().Idents.get(GV->getName());
-  TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
-  DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
-
-  const VarDecl *VD = nullptr;
-  for (const auto  : DC->lookup())
-if ((VD = dyn_cast(Result)))
-  break;
-
-  if (!VD || !VD->hasAttr()) {
-GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
-GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
-  } else {
-GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
-GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
+llvm::Constant *C =
+CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
+
+if (getTriple().isOSBinFormatELF() || getTriple().isOSBinFormatCOFF()) {
+  llvm::GlobalValue *GV = nullptr;
+  
+  if ((GV = dyn_cast(C))) {
+IdentifierInfo  = getContext().Idents.get(GV->getName());
+TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
+DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
+
+const VarDecl *VD = nullptr;
+for (const auto  : DC->lookup())
+  if ((VD = dyn_cast(Result)))
+break;
+  
+if (getTriple().isOSBinFormatELF()) {
+  if (!VD)
+GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
+}
+else {
+  if (!VD || !VD->hasAttr()) {
+GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
+GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
+  } else {
+GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
+GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
+  }
+}
+
+setDSOLocal(GV);
   }
 }
-setDSOLocal(GV);
-
+  
 // Decay array -> ptr
 CFConstantStringClassRef =
-llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
+llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
   }
 
   QualType CFTy = getContext().getCFConstantStringType();
@@ -4185,7 +4196,11 @@ CodeGenModule::GetAddrOfConstantCFString
   if (getTriple().isOSBinFormatMachO())
 GV->setSection(isUTF16 ? "__TEXT,__ustring"
: "__TEXT,__cstring,cstring_literals");
-
+  // 

[PATCH] D51390: [analyzer] CallDescription: Improve array management.

2018-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC343037: [analyzer] NFC: CallDescription: Improve array 
management. (authored by dergachev, committed by ).

Repository:
  rC Clang

https://reviews.llvm.org/D51390

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


Index: include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -82,37 +82,26 @@
   mutable bool IsLookupDone = false;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
-  std::vector QualifiedName;
+  std::vector QualifiedName;
   unsigned RequiredArgs;
 
 public:
   const static unsigned NoArgRequirement = 
std::numeric_limits::max();
 
   /// Constructs a CallDescription object.
   ///
-  /// @param QualifiedName The list of the qualified names of the function that
-  /// will be matched. It does not require the user to provide the full list of
-  /// the qualified name. The more details provided, the more accurate the
-  /// matching.
+  /// @param QualifiedName The list of the name qualifiers of the function that
+  /// will be matched. The user is allowed to skip any of the qualifiers.
+  /// For example, {"std", "basic_string", "c_str"} would match both
+  /// std::basic_string<...>::c_str() and std::__1::basic_string<...>::c_str().
   ///
   /// @param RequiredArgs The number of arguments that is expected to match a
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
-  CallDescription(std::vector QualifiedName,
+  CallDescription(ArrayRef QualifiedName,
   unsigned RequiredArgs = NoArgRequirement)
   : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs) {}
 
-  /// Constructs a CallDescription object.
-  ///
-  /// @param FuncName The name of the function that will be matched.
-  ///
-  /// @param RequiredArgs The number of arguments that is expected to match a
-  /// call. Omit this parameter to match every occurrence of call with a given
-  /// name regardless the number of arguments.
-  CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
-  : CallDescription(std::vector({FuncName}), NoArgRequirement) {
-  }
-
   /// Get the name of the function that this object matches.
   StringRef getFunctionName() const { return QualifiedName.back(); }
 };
Index: lib/StaticAnalyzer/Core/CallEvent.cpp
===
--- lib/StaticAnalyzer/Core/CallEvent.cpp
+++ lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -371,23 +371,26 @@
   // accuracy.
   if (CD.QualifiedName.size() > 1 && D) {
 const DeclContext *Ctx = D->getDeclContext();
-std::vector QualifiedName = CD.QualifiedName;
-QualifiedName.pop_back();
+// See if we'll be able to match them all.
+size_t NumUnmatched = CD.QualifiedName.size() - 1;
 for (; Ctx && isa(Ctx); Ctx = Ctx->getParent()) {
+  if (NumUnmatched == 0)
+break;
+
   if (const auto *ND = dyn_cast(Ctx)) {
-if (!QualifiedName.empty() && ND->getName() == QualifiedName.back())
-  QualifiedName.pop_back();
+if (ND->getName() == CD.QualifiedName[NumUnmatched - 1])
+  --NumUnmatched;
 continue;
   }
 
   if (const auto *RD = dyn_cast(Ctx)) {
-if (!QualifiedName.empty() && RD->getName() == QualifiedName.back())
-  QualifiedName.pop_back();
+if (RD->getName() == CD.QualifiedName[NumUnmatched - 1])
+  --NumUnmatched;
 continue;
   }
 }
 
-if (!QualifiedName.empty())
+if (NumUnmatched > 0)
   return false;
   }
 


Index: include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
===
--- include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
+++ include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
@@ -82,37 +82,26 @@
   mutable bool IsLookupDone = false;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
-  std::vector QualifiedName;
+  std::vector QualifiedName;
   unsigned RequiredArgs;
 
 public:
   const static unsigned NoArgRequirement = std::numeric_limits::max();
 
   /// Constructs a CallDescription object.
   ///
-  /// @param QualifiedName The list of the qualified names of the function that
-  /// will be matched. It does not require the user to provide the full list of
-  /// the qualified name. The more details provided, the more accurate the
-  /// matching.
+  /// @param QualifiedName The list of the name qualifiers of the function that
+  /// 

r343037 - [analyzer] NFC: CallDescription: Improve array management.

2018-09-25 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Tue Sep 25 15:13:31 2018
New Revision: 343037

URL: http://llvm.org/viewvc/llvm-project?rev=343037=rev
Log:
[analyzer] NFC: CallDescription: Improve array management.

Combine the two constructor overrides into a single ArrayRef constructor
to allow easier brace initializations and simplify how the respective field
is used internally.

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp

Modified: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h?rev=343037=343036=343037=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h Tue 
Sep 25 15:13:31 2018
@@ -82,7 +82,7 @@ class CallDescription {
   mutable bool IsLookupDone = false;
   // The list of the qualified names used to identify the specified CallEvent,
   // e.g. "{a, b}" represent the qualified names, like "a::b".
-  std::vector QualifiedName;
+  std::vector QualifiedName;
   unsigned RequiredArgs;
 
 public:
@@ -90,29 +90,18 @@ public:
 
   /// Constructs a CallDescription object.
   ///
-  /// @param QualifiedName The list of the qualified names of the function that
-  /// will be matched. It does not require the user to provide the full list of
-  /// the qualified name. The more details provided, the more accurate the
-  /// matching.
+  /// @param QualifiedName The list of the name qualifiers of the function that
+  /// will be matched. The user is allowed to skip any of the qualifiers.
+  /// For example, {"std", "basic_string", "c_str"} would match both
+  /// std::basic_string<...>::c_str() and std::__1::basic_string<...>::c_str().
   ///
   /// @param RequiredArgs The number of arguments that is expected to match a
   /// call. Omit this parameter to match every occurrence of call with a given
   /// name regardless the number of arguments.
-  CallDescription(std::vector QualifiedName,
+  CallDescription(ArrayRef QualifiedName,
   unsigned RequiredArgs = NoArgRequirement)
   : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs) {}
 
-  /// Constructs a CallDescription object.
-  ///
-  /// @param FuncName The name of the function that will be matched.
-  ///
-  /// @param RequiredArgs The number of arguments that is expected to match a
-  /// call. Omit this parameter to match every occurrence of call with a given
-  /// name regardless the number of arguments.
-  CallDescription(StringRef FuncName, unsigned RequiredArgs = NoArgRequirement)
-  : CallDescription(std::vector({FuncName}), NoArgRequirement) {
-  }
-
   /// Get the name of the function that this object matches.
   StringRef getFunctionName() const { return QualifiedName.back(); }
 };

Modified: cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp?rev=343037=343036=343037=diff
==
--- cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp (original)
+++ cfe/trunk/lib/StaticAnalyzer/Core/CallEvent.cpp Tue Sep 25 15:13:31 2018
@@ -371,23 +371,26 @@ bool CallEvent::isCalled(const CallDescr
   // accuracy.
   if (CD.QualifiedName.size() > 1 && D) {
 const DeclContext *Ctx = D->getDeclContext();
-std::vector QualifiedName = CD.QualifiedName;
-QualifiedName.pop_back();
+// See if we'll be able to match them all.
+size_t NumUnmatched = CD.QualifiedName.size() - 1;
 for (; Ctx && isa(Ctx); Ctx = Ctx->getParent()) {
+  if (NumUnmatched == 0)
+break;
+
   if (const auto *ND = dyn_cast(Ctx)) {
-if (!QualifiedName.empty() && ND->getName() == QualifiedName.back())
-  QualifiedName.pop_back();
+if (ND->getName() == CD.QualifiedName[NumUnmatched - 1])
+  --NumUnmatched;
 continue;
   }
 
   if (const auto *RD = dyn_cast(Ctx)) {
-if (!QualifiedName.empty() && RD->getName() == QualifiedName.back())
-  QualifiedName.pop_back();
+if (RD->getName() == CD.QualifiedName[NumUnmatched - 1])
+  --NumUnmatched;
 continue;
   }
 }
 
-if (!QualifiedName.empty())
+if (NumUnmatched > 0)
   return false;
   }
 


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


r343036 - P0969R0: allow structured binding of accessible members, not only public members.

2018-09-25 Thread Richard Smith via cfe-commits
Author: rsmith
Date: Tue Sep 25 15:12:44 2018
New Revision: 343036

URL: http://llvm.org/viewvc/llvm-project?rev=343036=rev
Log:
P0969R0: allow structured binding of accessible members, not only public 
members.

Modified:
cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
cfe/trunk/include/clang/Sema/Sema.h
cfe/trunk/lib/Sema/SemaAccess.cpp
cfe/trunk/lib/Sema/SemaDeclAttr.cpp
cfe/trunk/lib/Sema/SemaDeclCXX.cpp
cfe/trunk/test/CXX/dcl.decl/dcl.decomp/p4.cpp
cfe/trunk/www/cxx_status.html

Modified: cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?rev=343036=343035=343036=diff
==
--- cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td (original)
+++ cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td Tue Sep 25 15:12:44 
2018
@@ -452,10 +452,12 @@ def err_decomp_decl_multiple_bases_with_
   "have non-static data members">;
 def err_decomp_decl_ambiguous_base : Error<
   "cannot decompose members of ambiguous base class %1 of %0:%2">;
-def err_decomp_decl_non_public_base : Error<
-  "cannot decompose members of non-public base class %1 of %0">;
-def err_decomp_decl_non_public_member : Error<
-  "cannot decompose non-public member %0 of %1">;
+def err_decomp_decl_inaccessible_base : Error<
+  "cannot decompose members of inaccessible base class %1 of %0">,
+  AccessControl;
+def err_decomp_decl_inaccessible_field : Error<
+  "cannot decompose %select{private|protected}0 member %1 of %3">,
+  AccessControl;
 def err_decomp_decl_anon_union_member : Error<
   "cannot decompose class type %0 because it has an anonymous "
   "%select{struct|union}1 member">;

Modified: cfe/trunk/include/clang/Sema/Sema.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/Sema.h?rev=343036=343035=343036=diff
==
--- cfe/trunk/include/clang/Sema/Sema.h (original)
+++ cfe/trunk/include/clang/Sema/Sema.h Tue Sep 25 15:12:44 2018
@@ -6036,6 +6036,10 @@ public:
   AccessResult CheckMemberAccess(SourceLocation UseLoc,
  CXXRecordDecl *NamingClass,
  DeclAccessPair Found);
+  AccessResult
+  CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
+ CXXRecordDecl *DecomposedClass,
+ DeclAccessPair Field);
   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
  Expr *ObjectExpr,
  Expr *ArgExpr,

Modified: cfe/trunk/lib/Sema/SemaAccess.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaAccess.cpp?rev=343036=343035=343036=diff
==
--- cfe/trunk/lib/Sema/SemaAccess.cpp (original)
+++ cfe/trunk/lib/Sema/SemaAccess.cpp Tue Sep 25 15:12:44 2018
@@ -1728,6 +1728,22 @@ Sema::AccessResult Sema::CheckMemberAcce
   return CheckAccess(*this, UseLoc, Entity);
 }
 
+/// Checks implicit access to a member in a structured binding.
+Sema::AccessResult
+Sema::CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
+ CXXRecordDecl *DecomposedClass,
+ DeclAccessPair Field) {
+  if (!getLangOpts().AccessControl ||
+  Field.getAccess() == AS_public)
+return AR_accessible;
+
+  AccessTarget Entity(Context, AccessTarget::Member, DecomposedClass, Field,
+  Context.getRecordType(DecomposedClass));
+  Entity.setDiag(diag::err_decomp_decl_inaccessible_field);
+
+  return CheckAccess(*this, UseLoc, Entity);
+}
+
 /// Checks access to an overloaded member operator, including
 /// conversion operators.
 Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,

Modified: cfe/trunk/lib/Sema/SemaDeclAttr.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?rev=343036=343035=343036=diff
==
--- cfe/trunk/lib/Sema/SemaDeclAttr.cpp (original)
+++ cfe/trunk/lib/Sema/SemaDeclAttr.cpp Tue Sep 25 15:12:44 2018
@@ -7514,6 +7514,7 @@ void Sema::PopParsingDeclaration(Parsing
   // for each of the different declarations.
   const DelayedDiagnosticPool *pool = 
   do {
+bool AnyAccessFailures = false;
 for (DelayedDiagnosticPool::pool_iterator
i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
   // This const_cast is a bit lame.  Really, Triggered should be mutable.
@@ -7530,7 +7531,14 @@ void Sema::PopParsingDeclaration(Parsing
 break;
 
   case DelayedDiagnostic::Access:
+// Only produce one access control diagnostic for a structured binding
+// declaration: we don't need to tell the 

[PATCH] D51388: [analyzer] NFC: Legalize state manager factory injection.

2018-09-25 Thread Phabricator via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343035: [analyzer] NFC: Legalize state manager factory 
injection. (authored by dergachev, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D51388?vs=162968=167003#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D51388

Files:
  cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
  cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
  cfe/trunk/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
  cfe/trunk/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
  cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp

Index: cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
===
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
@@ -30,8 +30,7 @@
 
   /// Declares a program state trait for type \p Type called \p Name, and
   /// introduce a type named \c NameTy.
-  /// The macro should not be used inside namespaces, or for traits that must
-  /// be accessible from more than one translation unit.
+  /// The macro should not be used inside namespaces.
   #define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type) \
 namespace { \
   class Name {}; \
@@ -47,6 +46,102 @@
 } \
 }
 
+  /// Declares a factory for objects of type \p Type in the program state
+  /// manager. The type must provide a ::Factory sub-class. Commonly used for
+  /// ImmutableMap, ImmutableSet, ImmutableList. The macro should not be used
+  /// inside namespaces.
+  #define REGISTER_FACTORY_WITH_PROGRAMSTATE(Type) \
+namespace clang { \
+namespace ento { \
+  template <> \
+  struct ProgramStateTrait \
+: public ProgramStatePartialTrait { \
+static void *GDMIndex() { static int Index; return  } \
+  }; \
+} \
+}
+
+  /// Helper for registering a map trait.
+  ///
+  /// If the map type were written directly in the invocation of
+  /// REGISTER_TRAIT_WITH_PROGRAMSTATE, the comma in the template arguments
+  /// would be treated as a macro argument separator, which is wrong.
+  /// This allows the user to specify a map type in a way that the preprocessor
+  /// can deal with.
+  #define CLANG_ENTO_PROGRAMSTATE_MAP(Key, Value) llvm::ImmutableMap
+
+  /// Declares an immutable map of type \p NameTy, suitable for placement into
+  /// the ProgramState. This is implementing using llvm::ImmutableMap.
+  ///
+  /// \code
+  /// State = State->set(K, V);
+  /// const Value *V = State->get(K); // Returns NULL if not in the map.
+  /// State = State->remove(K);
+  /// NameTy Map = State->get();
+  /// \endcode
+  ///
+  /// The macro should not be used inside namespaces, or for traits that must
+  /// be accessible from more than one translation unit.
+  #define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value) \
+REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, \
+ CLANG_ENTO_PROGRAMSTATE_MAP(Key, Value))
+
+  /// Declares an immutable map type \p Name and registers the factory
+  /// for such maps in the program state, but does not add the map itself
+  /// to the program state. Useful for managing lifetime of maps that are used
+  /// as elements of other program state data structures.
+  #define REGISTER_MAP_FACTORY_WITH_PROGRAMSTATE(Name, Key, Value) \
+using Name = llvm::ImmutableMap; \
+REGISTER_FACTORY_WITH_PROGRAMSTATE(Name)
+
+
+  /// Declares an immutable set of type \p NameTy, suitable for placement into
+  /// the ProgramState. This is implementing using llvm::ImmutableSet.
+  ///
+  /// \code
+  /// State = State->add(E);
+  /// State = State->remove(E);
+  /// bool Present = State->contains(E);
+  /// NameTy Set = State->get();
+  /// \endcode
+  ///
+  /// The macro should not be used inside namespaces, or for traits that must
+  /// be accessible from more than one translation unit.
+  #define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem) \
+REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableSet)
+
+  /// Declares an immutable set type \p Name and registers the factory
+  /// for such sets in the program state, but does not add the set itself
+  /// to the program state. Useful for managing lifetime of sets that are used
+  /// as elements of other program state data structures.
+  #define REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(Name, Elem) \
+using Name = llvm::ImmutableSet; \
+REGISTER_FACTORY_WITH_PROGRAMSTATE(Name)
+
+
+  /// Declares an immutable list type \p NameTy, suitable for placement into
+  /// the ProgramState. This is implementing using llvm::ImmutableList.
+  ///
+  /// \code
+  /// State = State->add(E); // Adds to the /end/ of the list.
+  /// bool Present = State->contains(E);
+  /// NameTy List = 

r343035 - [analyzer] NFC: Legalize state manager factory injection.

2018-09-25 Thread Artem Dergachev via cfe-commits
Author: dergachev
Date: Tue Sep 25 15:10:12 2018
New Revision: 343035

URL: http://llvm.org/viewvc/llvm-project?rev=343035=rev
Log:
[analyzer] NFC: Legalize state manager factory injection.

When a checker maintains a program state trait that isn't a simple 
list/set/map, but is a combination of multiple lists/sets/maps (eg., a multimap 
- which may be implemented as a map from something to set of something), 
ProgramStateManager only contains the factory for the trait itself. All 
auxiliary lists/sets/maps need a factory to be provided by the checker, which 
is annoying.

So far two checkers wanted a multimap, and both decided to trick the
ProgramStateManager into keeping the auxiliary factory within itself
by pretending that it's some sort of trait they're interested in,
but then never using this trait but only using the factory.

Make this trick legal. Define a convenient macro.

One thing that becomes apparent once all pieces are put together is that
these two checkers are in fact using the same factory, because the type that
identifies it, ImmutableMap>,
is the same. This situation is different from two checkers registering similar
primitive traits.

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

Modified:
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h

cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
cfe/trunk/lib/StaticAnalyzer/Checkers/CheckObjCDealloc.cpp
cfe/trunk/lib/StaticAnalyzer/Checkers/InnerPointerChecker.cpp
cfe/trunk/lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h?rev=343035=343034=343035=diff
==
--- cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h 
(original)
+++ cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h 
Tue Sep 25 15:10:12 2018
@@ -21,52 +21,6 @@
 namespace clang {
 namespace ento {
 
-  /// Declares an immutable map of type \p NameTy, suitable for placement into
-  /// the ProgramState. This is implementing using llvm::ImmutableMap.
-  ///
-  /// \code
-  /// State = State->set(K, V);
-  /// const Value *V = State->get(K); // Returns NULL if not in the map.
-  /// State = State->remove(K);
-  /// NameTy Map = State->get();
-  /// \endcode
-  ///
-  /// The macro should not be used inside namespaces, or for traits that must
-  /// be accessible from more than one translation unit.
-  #define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value) \
-REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, \
- CLANG_ENTO_PROGRAMSTATE_MAP(Key, Value))
-
-  /// Declares an immutable set of type \p NameTy, suitable for placement into
-  /// the ProgramState. This is implementing using llvm::ImmutableSet.
-  ///
-  /// \code
-  /// State = State->add(E);
-  /// State = State->remove(E);
-  /// bool Present = State->contains(E);
-  /// NameTy Set = State->get();
-  /// \endcode
-  ///
-  /// The macro should not be used inside namespaces, or for traits that must
-  /// be accessible from more than one translation unit.
-  #define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem) \
-REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableSet)
-
-  /// Declares an immutable list of type \p NameTy, suitable for placement into
-  /// the ProgramState. This is implementing using llvm::ImmutableList.
-  ///
-  /// \code
-  /// State = State->add(E); // Adds to the /end/ of the list.
-  /// bool Present = State->contains(E);
-  /// NameTy List = State->get();
-  /// \endcode
-  ///
-  /// The macro should not be used inside namespaces, or for traits that must
-  /// be accessible from more than one translation unit.
-  #define REGISTER_LIST_WITH_PROGRAMSTATE(Name, Elem) \
-REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, llvm::ImmutableList)
-
-
 class CheckerContext {
   ExprEngine 
   /// The current exploded(symbolic execution) graph node.

Modified: 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h?rev=343035=343034=343035=diff
==
--- 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h 
(original)
+++ 
cfe/trunk/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h 
Tue Sep 25 15:10:12 2018
@@ -30,8 +30,7 @@ namespace ento {
 
   /// Declares a program state trait for type \p Type called \p Name, and
   /// introduce a type named \c NameTy.
-  /// The macro should not be used inside namespaces, or for traits that must
-  /// be accessible from more than one translation unit.
+  /// The macro should not be 

[PATCH] D52521: [Sema] DR727: Ensure we pick up enclosing template instantiation arguments for a class-scope explicit specialization.

2018-09-25 Thread Erik Pilkington via Phabricator via cfe-commits
erik.pilkington added inline comments.



Comment at: clang/lib/Sema/SemaTemplateInstantiate.cpp:143
   TSK_ExplicitSpecialization &&
!Function->getClassScopeSpecializationPattern()))
 break;

It looks like theres a bug here too:
```
template  struct S {
  template  void f() {}
  template <> void f() {}
};
```
Will lead to a depth-2 MultiLevelTemplateArgumentList for f, but I believe 
there should only be 1 level. I don't think theres any way to observe this 
though.



Comment at: clang/test/SemaCXX/member-spec-dr727.cpp:35
+  static_assert(is_same::value);
+  static_assert(is_same::value);
+};

This fails on TOT because clang substitutes `int` for `Ap`!


Repository:
  rC Clang

https://reviews.llvm.org/D52521



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


[PATCH] D52344: [Clang][CodeGen][ObjC]: Fix non-bridged CoreFoundation builds on ELF targets that use `-fconstant-cfstrings`.

2018-09-25 Thread Kristina Brooks via Phabricator via cfe-commits
kristina updated this revision to Diff 166996.
kristina added a comment.

Split up the tests for ELF into tests 1). Checking whether CF can be built and 
linked correctly 2). Asm section tests originally from `CFStrings.c` as they 
had additional ELF-related cruft that should have been a separate test. Renamed 
`CFStrings.c` to `cfstring3.c` for consistency, which now tests ELF/COFF/MachO 
in a consistent fashion versus having a hunk of out of place ELF-specific tests.


Repository:
  rC Clang

https://reviews.llvm.org/D52344

Files:
  lib/CodeGen/CodeGenModule.cpp
  test/CodeGen/CFStrings.c
  test/CodeGen/cfstring-elf-cfbuild-x86_64.c
  test/CodeGen/cfstring-elf-sections-x86_64.c
  test/CodeGen/cfstring3.c

Index: test/CodeGen/cfstring3.c
===
--- test/CodeGen/cfstring3.c
+++ test/CodeGen/cfstring3.c
@@ -0,0 +1,45 @@
+// REQUIRES: arm-registered-target,x86-registered-target
+
+// RUN: %clang_cc1 -triple thumbv7-windows -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-COFF
+// RUN: %clang_cc1 -triple i686-windows -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-COFF
+// RUN: %clang_cc1 -triple x86_64-windows -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-COFF
+
+// RUN: %clang_cc1 -triple armv7-elf -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-ELF -check-prefix CHECK-ELF32
+// RUN: %clang_cc1 -triple i686-elf -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-ELF -check-prefix CHECK-ELF32
+// RUN: %clang_cc1 -triple x86_64-elf -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-ELF -check-prefix CHECK-ELF64
+
+// RUN: %clang_cc1 -triple armv7-macho -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-MACHO -check-prefix CHECK-MACHO32
+// RUN: %clang_cc1 -triple i386-apple-macosx -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-MACHO -check-prefix CHECK-MACHO32
+// RUN: %clang_cc1 -triple x86_64-macho -S -emit-llvm %s -o - | FileCheck %s -check-prefix CHECK-MACHO -check-prefix CHECK-MACHO64
+
+// RUN: %clang_cc1 -triple thumbv7-windows -S %s -o - | FileCheck %s -check-prefix CHECK-ASM-COFF
+// RUN: %clang_cc1 -triple thumbv7-elf -S %s -o - | FileCheck %s -check-prefix CHECK-ASM-ELF
+// RUN: %clang_cc1 -triple thumbv7-macho -S %s -o - | FileCheck %s -check-prefix CHECK-ASM-MACHO
+
+typedef struct __CFString *CFStringRef;
+const CFStringRef one = (CFStringRef)__builtin___CFStringMakeConstantString("one");
+const CFStringRef two = (CFStringRef)__builtin___CFStringMakeConstantString("\xef\xbf\xbd\x74\xef\xbf\xbd\x77\xef\xbf\xbd\x6f");
+
+// CHECK-COFF: @.str = private unnamed_addr constant [4 x i8] c"one\00", align 1
+// CHECK-ELF: @.str = private unnamed_addr constant [4 x i8] c"one\00", section ".rodata", align 1
+// CHECK-MACHO: @.str = private unnamed_addr constant [4 x i8] c"one\00", section "__TEXT,__cstring,cstring_literals", align 1
+
+// CHECK-COFF: @_unnamed_cfstring_ = private global %struct.__NSConstantString_tag { i32* getelementptr inbounds ([0 x i32], [0 x i32]* @__CFConstantStringClassReference, i32 0, i32 0), i32 1992, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i32 3 }, section "cfstring", align {{[48]}}
+// CHECK-ELF32: @_unnamed_cfstring_ = private global %struct.__NSConstantString_tag { i32* getelementptr inbounds ([0 x i32], [0 x i32]* @__CFConstantStringClassReference, i32 0, i32 0), i32 1992, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i32 3 }, section "cfstring", align 4
+// CHECK-ELF64: @_unnamed_cfstring_ = private global %struct.__NSConstantString_tag { i32* getelementptr inbounds ([0 x i32], [0 x i32]* @__CFConstantStringClassReference, i32 0, i32 0), i32 1992, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i64 3 }, section "cfstring", align 8
+// CHECK-MACHO32: @_unnamed_cfstring_ = private global %struct.__NSConstantString_tag { i32* getelementptr inbounds ([0 x i32], [0 x i32]* @__CFConstantStringClassReference, i32 0, i32 0), i32 1992, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i32 3 }, section "__DATA,__cfstring", align 4
+// CHECK-MACHO64: @_unnamed_cfstring_ = private global %struct.__NSConstantString_tag { i32* getelementptr inbounds ([0 x i32], [0 x i32]* @__CFConstantStringClassReference, i32 0, i32 0), i32 1992, i8* getelementptr inbounds ([4 x i8], [4 x i8]* @.str, i32 0, i32 0), i64 3 }, section "__DATA,__cfstring", align 8
+
+// CHECK-COFF: @.str.1 = private unnamed_addr constant [7 x i16] [i16 -3, i16 116, i16 -3, i16 119, i16 -3, i16 111, i16 0], align 2
+// CHECK-ELF: @.str.1 = private unnamed_addr constant [7 x i16] [i16 -3, i16 116, i16 -3, i16 119, i16 -3, i16 111, i16 0], section ".rodata", align 2
+// CHECK-MACHO: @.str.1 = private unnamed_addr constant [7 x i16] [i16 -3, i16 116, i16 -3, i16 119, i16 -3, i16 111, i16 0], section "__TEXT,__ustring", align 2
+
+// CHECK-COFF: @_unnamed_cfstring_.2 = private global 

[PATCH] D52517: [clangd] clangd-indexer: Drop support for MR-via-YAML

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 167000.
sammccall added a comment.

Remove unused function.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52517

Files:
  clangd/index/Serialization.h
  clangd/index/YAMLSerialization.cpp
  clangd/indexer/IndexerMain.cpp

Index: clangd/indexer/IndexerMain.cpp
===
--- clangd/indexer/IndexerMain.cpp
+++ clangd/indexer/IndexerMain.cpp
@@ -12,26 +12,17 @@
 //
 //===--===//
 
-#include "RIFF.h"
-#include "index/CanonicalIncludes.h"
 #include "index/Index.h"
 #include "index/IndexAction.h"
 #include "index/Merge.h"
 #include "index/Serialization.h"
 #include "index/SymbolCollector.h"
-#include "clang/Frontend/CompilerInstance.h"
-#include "clang/Frontend/FrontendActions.h"
-#include "clang/Index/IndexDataConsumer.h"
-#include "clang/Index/IndexingAction.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Execution.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/Support/CommandLine.h"
-#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Signals.h"
-#include "llvm/Support/ThreadPool.h"
-#include "llvm/Support/YAMLTraits.h"
 
 using namespace llvm;
 using namespace clang::tooling;
@@ -50,107 +41,44 @@
"not given, such headers will have relative paths."),
 llvm::cl::init(""));
 
-static llvm::cl::opt MergeOnTheFly(
-"merge-on-the-fly",
-llvm::cl::desc(
-"Merges symbols for each processed translation unit as soon "
-"they become available. This results in a smaller memory "
-"usage and an almost instant reduce stage. Optimal for running as a "
-"standalone tool, but cannot be used with multi-process executors like "
-"MapReduce."),
-llvm::cl::init(true), llvm::cl::Hidden);
-
 static llvm::cl::opt
 Format("format", llvm::cl::desc("Format of the index to be written"),
llvm::cl::values(clEnumValN(IndexFileFormat::YAML, "yaml",
"human-readable YAML format"),
 clEnumValN(IndexFileFormat::RIFF, "binary",
"binary RIFF format")),
llvm::cl::init(IndexFileFormat::YAML));
 
-/// Responsible for aggregating symbols from each processed file and producing
-/// the final results. All methods in this class must be thread-safe,
-/// 'consumeSymbols' may be called from multiple threads.
-class SymbolsConsumer {
-public:
-  virtual ~SymbolsConsumer() = default;
-
-  /// Consume a SymbolSlab build for a file.
-  virtual void consumeSymbols(SymbolSlab Symbols) = 0;
-  /// Produce a resulting symbol slab, by combining  occurrences of the same
-  /// symbols across translation units.
-  virtual SymbolSlab mergeResults() = 0;
-};
-
-class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
+class IndexActionFactory : public tooling::FrontendActionFactory {
 public:
-  SymbolIndexActionFactory(SymbolsConsumer ) : Consumer(Consumer) {}
+  IndexActionFactory(IndexFileIn ) : Result(Result) {}
 
   clang::FrontendAction *create() override {
-auto CollectorOpts = SymbolCollector::Options();
-CollectorOpts.FallbackDir = AssumedHeaderDir;
+SymbolCollector::Options Opts;
+Opts.FallbackDir = AssumedHeaderDir;
 return createStaticIndexingAction(
-   CollectorOpts,
-   [&](SymbolSlab S) { Consumer.consumeSymbols(std::move(S)); })
+   Opts,
+   [&](SymbolSlab S) {
+ // Merge as we go.
+ std::lock_guard Lock(SymbolsMu);
+ for (const auto  : S) {
+   if (const auto *Existing = Symbols.find(Sym.ID))
+ Symbols.insert(mergeSymbol(*Existing, Sym));
+   else
+ Symbols.insert(Sym);
+ }
+   })
 .release();
   }
 
-  SymbolsConsumer 
-};
-
-/// Stashes per-file results inside ExecutionContext, merges all of them at the
-/// end. Useful for running on MapReduce infrastructure to avoid keeping symbols
-/// from multiple files in memory.
-class ToolExecutorConsumer : public SymbolsConsumer {
-public:
-  ToolExecutorConsumer(ToolExecutor ) : Executor(Executor) {}
-
-  void consumeSymbols(SymbolSlab Symbols) override {
-for (const auto  : Symbols)
-  Executor.getExecutionContext()->reportResult(Sym.ID.str(), toYAML(Sym));
-  }
-
-  SymbolSlab mergeResults() override {
-SymbolSlab::Builder UniqueSymbols;
-Executor.getToolResults()->forEachResult(
-[&](llvm::StringRef Key, llvm::StringRef Value) {
-  llvm::yaml::Input Yin(Value);
-  auto Sym = cantFail(clang::clangd::symbolFromYAML(Yin));
-  auto ID = cantFail(clang::clangd::SymbolID::fromStr(Key));
-  if (const auto *Existing = UniqueSymbols.find(ID))
-

[PATCH] D52521: [Sema] DR727: Ensure we pick up enclosing template instantiation arguments for a class-scope explicit specialization.

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

Previously, we stopped early on a class-scope explicit specialization, leading 
us to lose enclosing levels of template arguments. I'm not entirely convinced 
that this is the right fix, so any insight here would be greatly appreciated!

llvm.org/PR39031

Thanks!
Erik


Repository:
  rC Clang

https://reviews.llvm.org/D52521

Files:
  clang/include/clang/AST/DeclTemplate.h
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/SemaCXX/member-spec-dr727.cpp

Index: clang/test/SemaCXX/member-spec-dr727.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/member-spec-dr727.cpp
@@ -0,0 +1,52 @@
+// RUN: %clang_cc1 -std=c++17 -verify %s -emit-llvm -o -
+
+// expected-no-diagnostics
+
+namespace PR39031 {
+template 
+struct S {
+  template 
+  struct Wrapper;
+
+  template <>
+  struct Wrapper {
+template 
+void f(T) {
+  T x;
+}
+  };
+};
+
+void Run() {
+  S::Wrapper().f(1);
+}
+} // namespace PR39031
+
+template  struct is_same { static constexpr bool value = false; };
+template  struct is_same { static constexpr bool value = true; };
+
+namespace t1 {
+template  struct A {
+  template  struct B;
+
+  template <> struct B {
+template  struct C {
+  static_assert(is_same::value);
+  static_assert(is_same::value);
+};
+  };
+};
+
+A::B::C x;
+}
+
+namespace t2 {
+template 
+struct A {
+  template  static constexpr int p = 0;
+  template <> static constexpr int p = 1;
+};
+
+// FIXME: why aren't we selecting the specialization here?
+static_assert(A::p == 0);
+}
Index: clang/lib/Serialization/ASTWriterDecl.cpp
===
--- clang/lib/Serialization/ASTWriterDecl.cpp
+++ clang/lib/Serialization/ASTWriterDecl.cpp
@@ -1452,6 +1452,7 @@
   Record.AddTemplateArgumentList(>getTemplateArgs());
   Record.AddSourceLocation(D->getPointOfInstantiation());
   Record.push_back(D->getSpecializationKind());
+  Record.push_back(D->isSpecializedMember());
   Record.push_back(D->isCanonicalDecl());
 
   if (D->isCanonicalDecl()) {
@@ -1519,6 +1520,7 @@
   Record.AddSourceLocation(D->getPointOfInstantiation());
   Record.push_back(D->getSpecializationKind());
   Record.push_back(D->IsCompleteDefinition);
+  Record.push_back(D->isSpecializedMember());
   Record.push_back(D->isCanonicalDecl());
 
   if (D->isCanonicalDecl()) {
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -2177,6 +2177,7 @@
   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
   D->PointOfInstantiation = ReadSourceLocation();
   D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
+  D->IsSpecializedMember = Record.readInt();
 
   bool writtenAsCanonicalDecl = Record.readInt();
   if (writtenAsCanonicalDecl) {
@@ -2298,6 +2299,7 @@
   D->PointOfInstantiation = ReadSourceLocation();
   D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
   D->IsCompleteDefinition = Record.readInt();
+  D->IsSpecializedMember = Record.readInt();
 
   bool writtenAsCanonicalDecl = Record.readInt();
   if (writtenAsCanonicalDecl) {
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2982,6 +2982,7 @@
   InstD->setTypeAsWritten(WrittenTy);
   InstD->setExternLoc(D->getExternLoc());
   InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
+  InstD->setIsSpecializedMember(D->isSpecializedMember());
 
   Owner->addDecl(InstD);
 
Index: clang/lib/Sema/SemaTemplateInstantiate.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -70,27 +70,27 @@
 if (VarTemplateSpecializationDecl *Spec =
 dyn_cast(D)) {
   // We're done when we hit an explicit specialization.
-  if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
-  !isa(Spec))
+  if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization ||
+  isa(Spec)) {
+Result.addOuterTemplateArguments(>getTemplateInstantiationArgs());
+
+// If this variable template specialization was instantiated from a
+// specialized member that is a variable template, we're done.
+assert(Spec->getSpecializedTemplate() && "No variable template?");
+llvm::PointerUnion Specialized
+  

[PATCH] D52364: [clangd] Initial supoprt for cross-namespace global code completion.

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This is really cool!
From reading the code this behaves exactly how I'd expect.
Ranking will be the real test.

Main comment is I'd like to tweak the interface on FuzzyFindRequest, rest is 
basically nits.




Comment at: clangd/CodeComplete.cpp:367
 if (C.IndexResult) {
-  Completion.Origin |= C.IndexResult->Origin;
+  const auto  = *C.IndexResult;
+  Completion.Origin |= Sym.Origin;

FWIW, I find "C.IndexResult" clearer than "Sym" here, the "index" part is 
relevant



Comment at: clangd/CodeComplete.cpp:375
+Completion.Name = Sym.Name;
+  // To avoid inserting unnecessary qualifiers (e.g. no need for qualifier
+  // when symbol is accessed via using shadow like "using ns::X;"), only

Consider inverting this comment, I found it a bit hard to unpack:
```
// If the completion was visible to Sema, no qualifier is needed.
// This avoids unneeded qualifiers in cases like with `using ns::X`.
```



Comment at: clangd/CodeComplete.cpp:378
+  // insert qualifier if the symbol is not already available form Sema.
+  // FIXME(ioeric): find a better way to avoid inserting redundant
+  // qualifiers.

I'm not sure this FIXME is important enough to ever get fixed, consider 
removing it.



Comment at: clangd/CodeComplete.h:105
+
+  /// Whether to include index symbols that are not defined in the scopes
+  /// visible from the code completion point (e.g. enclosing namespaces). Such

This comment should also mention that this applies in contexts without explicit 
scope qualifiers.



Comment at: clangd/CodeComplete.h:106
+  /// Whether to include index symbols that are not defined in the scopes
+  /// visible from the code completion point (e.g. enclosing namespaces). Such
+  /// completions can insert scope qualifiers.

nit: I'd remove the parenthetical, it's a little ambiguous whether it applies 
to the clause inside the "not" or outside it.



Comment at: clangd/CodeComplete.h:108
+  /// completions can insert scope qualifiers.
+  bool IncludeIndexSymbolsFromAllScopes = false;
 };

what about just calling this `AllScopes`?



Comment at: clangd/index/Index.h:430
   ///
-  /// The global scope is "", a top level scope is "foo::", etc.
+  /// The global scope is "", a top level scope is "foo::", etc. "*" is
+  /// wildcard.

I'm not a big fan of this magic value, it seems too easy to forget to handle.
Especially since we have a lot of existing code that touches this interface, 
and we may forget to check some of it.

I suggest making this a separate boolean field `AnyScope`, with a comment that 
scopes explicitly listed will be ranked higher.
We can probably also remove the "If this is empty" special case from `Scopes` 
now too, as the old behavior can be achieved by setting `Scopes = {}; AnyScope 
= true;`



Comment at: clangd/index/Index.h:432
+  /// wildcard.
+  /// FIXME: support assigning different weight to each scope.
   std::vector Scopes;

May not want a heavyweight API with explicit weights...

I think what we really **need** here is the ability to weight `clang::clangd::` 
> `clang::` > `` when you're in the scope of namespace clangd.

We could just say something like "the primary scope should come first" and do 
some FileDistance-like penalizing of the others...



Comment at: clangd/index/dex/Dex.cpp:161
+if (Scope == "*") {
+  ScopeIterators.push_back(createTrue(Symbols.size()));
+  continue;

wrap in a `createBoost(..., 0.1)` or so?



Comment at: clangd/tool/ClangdMain.cpp:139
 
+static llvm::cl::opt CrossNamespaceCompletion(
+"cross-namespace-completion",

It's a little confusing to give these different internal vs external names - do 
we have a strong reason not to call this "all-scopes-completion" or so?



Comment at: clangd/tool/ClangdMain.cpp:142
+llvm::cl::desc(
+"This is an experimental feature. If set to true, code completion will 
"
+"include index symbols that are not defined in the scopes (e.g. "

I'm not sure whether putting "experimental" in every flag description is 
worthwhile - maybe hidden is enough?



Comment at: unittests/clangd/CodeCompleteTests.cpp:2043
 
+TEST(CompletionTest, CrossNamespaceCompletion) {
+  clangd::CodeCompleteOptions Opts = {};

also verify that `na::Clangd^` only gets one result?



Comment at: unittests/clangd/CodeCompleteTests.cpp:2059
+   AllOf(Qualifier("ny::"), Named("Clangd2")),
+   AllOf(Qualifier(""), Named("Clangd3")),
+   AllOf(Qualifier("nb::"), 

[PATCH] D52315: [clang-tidy] Fix for performance-unnecessary-value-param, performance-unnecessary-copy-initialization and performance-for-range-copy

2018-09-25 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

"The three checks mentioned in the Title are two noisy if the code uses 
intrusive smart (reference counting) pointers. LLVM/Clang is such a code, it 
has lots of such types, e.g. StringRef, SymbolRef or ProgramStateRef, all of 
them based llvm::IntrusiveRefCntPtr. Every time such a type is passed as 
parameter, used for initialization or in a range-based for loop a false 
positive warning is issued together with an (unnecessary) fix."

I'm not quite following this comment - StringRef doesn't appear to have any 
connection to IntrusiveRefCntPtr so far as I can see? (I don't see anything in 
SymbolRef either. ProgramStateRef is an IntrusiveRefCntPtr, for sure - and has 
a non-trivial copy ctor  - yeah, if you pass that by value unnecessarily, I 
think that's a real/reasonable warning?

The reason these things are passed by value a lot is when passing ownership - 
if the callee is moving the IntrusiveRefCntPtr into something that exceeds the 
duration of the function call (eg: moving it into a member function from a 
setter) - so the warning should take that into account. But it shouldn't rely 
on the sizeof of the type - that's not really a good signal here, I think.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52315



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


[PATCH] D52281: [clang-tidy] Add modernize check to use std::invoke in generic code

2018-09-25 Thread Borsik Gábor via Phabricator via cfe-commits
boga95 updated this revision to Diff 166994.
boga95 marked 12 inline comments as done.

https://reviews.llvm.org/D52281

Files:
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tidy/modernize/ReplaceGenericFunctorCallCheck.cpp
  clang-tidy/modernize/ReplaceGenericFunctorCallCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-replace-generic-functor-call.rst
  test/clang-tidy/modernize-replace-generic-functor-call.cpp

Index: test/clang-tidy/modernize-replace-generic-functor-call.cpp
===
--- /dev/null
+++ test/clang-tidy/modernize-replace-generic-functor-call.cpp
@@ -0,0 +1,56 @@
+// RUN: %check_clang_tidy %s modernize-replace-generic-functor-call %t -- -- -std=c++17
+
+namespace std {
+
+template 
+T max(T a, T b) {
+  return a < b ? b : a;
+}
+
+struct function {
+  void operator()();
+};
+
+} // namespace std
+
+struct Foo {
+  static void print_() {}
+  void print() const {}
+  int num_;
+};
+
+// Something that triggers the check
+template 
+void func2(T func) {
+  func(1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use ::std::invoke to invoke type dependent callable objects. [modernize-replace-generic-functor-call]
+  // CHECK-FIXES: ::std::invoke(func, 1);
+  func();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use ::std::invoke to invoke type dependent callable objects. [modernize-replace-generic-functor-call]
+  // CHECK-FIXES: ::std::invoke(func);
+
+  Foo foo;
+  (foo.*func)(1);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use ::std::invoke to invoke type dependent callable objects. [modernize-replace-generic-functor-call]
+  // CHECK-FIXES: ::std::invoke(foo, func, 1);
+  (foo.*func)();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use ::std::invoke to invoke type dependent callable objects. [modernize-replace-generic-functor-call]
+  // CHECK-FIXES: ::std::invoke(foo, func);
+  (Foo().*func)(1, 2);
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: Use ::std::invoke to invoke type dependent callable objects. [modernize-replace-generic-functor-call]
+  // CHECK-FIXES: ::std::invoke(Foo(), func, 1, 2);
+}
+
+// Something that doesn't triggers the check
+void func3() {}
+
+void g(std::function func, int (*fp)(int), void (Foo::*mfp)(int)) {
+  func3();// Regular function call
+  std::max(1, 2); // Template function call
+  Foo::print_();  // Static function call
+  []() {}();  // Lambda call
+  func(); // Call through std::function
+  fp(3);  // Call through function pointer
+  Foo foo;
+  (foo.*(mfp))(1); // Call through member function pointer
+}
Index: docs/clang-tidy/checks/modernize-replace-generic-functor-call.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/modernize-replace-generic-functor-call.rst
@@ -0,0 +1,39 @@
+.. title:: clang-tidy - modernize-replace-generic-functor-call
+
+modernize-replace-generic-functor-call
+==
+
+Replaces type dependent functor, function pointer and pointer to member call
+to the proper ``std::invoke()`` in C++17 or newer codebases.
+  
+Examples:
+
+.. code-block:: c++
+
+  template
+  void f(T1 functionPointer, T2 memberFunctionPointer) {
+functionPointer(2); // Replace to ::std::invoke(functionPointer, 2)
+
+Foo foo;
+(foo.*memberFunctionPointer)(1, 2); // Replace to ::std::invoke(foo, memberFunctionPointer, 1, 2)
+
+(Foo().*memberFunctionPointer)(3); // Replace to ::std::invoke(Foo(), memberFunctionPointer, 3)
+  }
+
+  // Neither of them is type dependent, no diagnose
+  void g(std::function func, int (*functionPointer)(int), void (Foo::*memberFunctionPointer)(int)) {
+freeFunction();
+
+std::max(1,2);
+
+Foo::print_();
+
+[](){}();
+
+func();
+
+functionPointer(3);
+
+Foo foo;
+(foo.*(memberFunctionPointer))(1);
+  }
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -171,6 +171,7 @@
modernize-raw-string-literal
modernize-redundant-void-arg
modernize-replace-auto-ptr
+   modernize-replace-generic-functor-call
modernize-replace-random-shuffle
modernize-return-braced-init-list
modernize-shrink-to-fit
Index: docs/ReleaseNotes.rst
===
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -142,6 +142,12 @@
 
   Checks on ``switch`` and ``if`` - ``else if`` constructs that do not cover all possible code paths.
 
+- New :doc:`modernize-replace-generic-functor-call
+  ` check.
+
+  Replaces type dependent functor, function pointer and pointer to member call
+  to the proper ``std::invoke()`` in C++17 or newer codebases.
+  
 - New :doc:`modernize-use-uncaught-exceptions
   ` check.
 
Index: 

[PATCH] D46919: [libclang] Deprecate CXPrintingPolicy_IncludeTagDefinition

2018-09-25 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny updated this revision to Diff 166992.
jdenny set the repository for this revision to rC Clang.
jdenny added a comment.

Ping.  Rebased.  This patch intends to perform cleanup that @rsmith suggested 
while reviewing another patch from me.  If there's no more interest, it's fine 
with me to abandon.  I'll wait at least one more week.


Repository:
  rC Clang

https://reviews.llvm.org/D46919

Files:
  clang/include/clang-c/Index.h
  clang/include/clang/AST/PrettyPrinter.h
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/TypePrinter.cpp
  clang/tools/c-index-test/c-index-test.c

Index: clang/tools/c-index-test/c-index-test.c
===
--- clang/tools/c-index-test/c-index-test.c
+++ clang/tools/c-index-test/c-index-test.c
@@ -103,8 +103,6 @@
CXPrintingPolicy_SuppressSpecifiers},
   {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSTAGKEYWORD",
CXPrintingPolicy_SuppressTagKeyword},
-  {"CINDEXTEST_PRINTINGPOLICY_INCLUDETAGDEFINITION",
-   CXPrintingPolicy_IncludeTagDefinition},
   {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSCOPE",
CXPrintingPolicy_SuppressScope},
   {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSUNWRITTENSCOPE",
Index: clang/lib/AST/TypePrinter.cpp
===
--- clang/lib/AST/TypePrinter.cpp
+++ clang/lib/AST/TypePrinter.cpp
@@ -455,7 +455,7 @@
 OS << '(';
 
   PrintingPolicy InnerPolicy(Policy);
-  InnerPolicy.IncludeTagDefinition = false;
+  InnerPolicy.State.PrintOwnedTagDecl = false;
   TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
 
   OS << "::*";
@@ -1103,9 +1103,9 @@
 }
 
 void TypePrinter::printTag(TagDecl *D, raw_ostream ) {
-  if (Policy.IncludeTagDefinition) {
+  if (Policy.State.PrintOwnedTagDecl) {
 PrintingPolicy SubPolicy = Policy;
-SubPolicy.IncludeTagDefinition = false;
+SubPolicy.State.PrintOwnedTagDecl = false;
 D->print(OS, SubPolicy, Indentation);
 spaceBeforePlaceHolder(OS);
 return;
@@ -1258,20 +1258,19 @@
 
 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
 raw_ostream ) {
-  if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) {
+  if (Policy.State.PrintOwnedTagDecl && T->getOwnedTagDecl()) {
 TagDecl *OwnedTagDecl = T->getOwnedTagDecl();
 assert(OwnedTagDecl->getTypeForDecl() == T->getNamedType().getTypePtr() &&
"OwnedTagDecl expected to be a declaration for the type");
 PrintingPolicy SubPolicy = Policy;
-SubPolicy.IncludeTagDefinition = false;
+SubPolicy.State.PrintOwnedTagDecl = false;
 OwnedTagDecl->print(OS, SubPolicy, Indentation);
 spaceBeforePlaceHolder(OS);
 return;
   }
 
   // The tag definition will take care of these.
-  if (!Policy.IncludeTagDefinition)
-  {
+  if (!Policy.State.PrintOwnedTagDecl) {
 OS << TypeWithKeyword::getKeywordName(T->getKeyword());
 if (T->getKeyword() != ETK_None)
   OS << " ";
@@ -1286,7 +1285,7 @@
 
 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
 raw_ostream ) {
-  if (Policy.IncludeTagDefinition && T->getOwnedTagDecl())
+  if (Policy.State.PrintOwnedTagDecl && T->getOwnedTagDecl())
 return;
   ElaboratedTypePolicyRAII PolicyRAII(Policy);
   printAfter(T->getNamedType(), OS);
Index: clang/lib/AST/DeclPrinter.cpp
===
--- clang/lib/AST/DeclPrinter.cpp
+++ clang/lib/AST/DeclPrinter.cpp
@@ -178,12 +178,12 @@
   for ( ; Begin != End; ++Begin) {
 if (isFirst) {
   if(TD)
-SubPolicy.IncludeTagDefinition = true;
+SubPolicy.State.PrintOwnedTagDecl = true;
   SubPolicy.SuppressSpecifiers = false;
   isFirst = false;
 } else {
   if (!isFirst) Out << ", ";
-  SubPolicy.IncludeTagDefinition = false;
+  SubPolicy.State.PrintOwnedTagDecl = false;
   SubPolicy.SuppressSpecifiers = true;
 }
 
@@ -849,7 +849,7 @@
   }
   PrintingPolicy SubPolicy(Policy);
   SubPolicy.SuppressSpecifiers = false;
-  SubPolicy.IncludeTagDefinition = false;
+  SubPolicy.State.PrintOwnedTagDecl = false;
   Init->printPretty(Out, nullptr, SubPolicy, Indentation);
   if ((D->getInitStyle() == VarDecl::CallInit) && !isa(Init))
 Out << ")";
Index: clang/include/clang/AST/PrettyPrinter.h
===
--- clang/include/clang/AST/PrettyPrinter.h
+++ clang/include/clang/AST/PrettyPrinter.h
@@ -93,14 +93,7 @@
   /// \endcode
   unsigned SuppressTagKeyword : 1;
 
-  /// When true, include the body of a tag definition.
-  ///
-  /// This is used to place the definition of a struct
-  /// in the middle of another declaration as with:
-  ///
-  /// \code
-  /// typedef struct { int x, y; } Point;
-  /// \endcode
+  /// This flag is deprecated and no longer has any effect.
   unsigned IncludeTagDefinition : 

Re: r342827 - Fix modules build with shared library.

2018-09-25 Thread David Blaikie via cfe-commits
+Shuai Wang

On Tue, Sep 25, 2018 at 2:14 PM David Blaikie  wrote:

> Hey Eric - thanks for the fix - but could you explain the issue here in a
> bit more detail, as I'm a bit confused (& really interested in
> understanding any layering problems in LLVM - and fixing them/making sure
> they're fixed/holding the line/etc)
>
> What do you mean by "pull all of the AST matchers library into clang" -
> how does including a header ever add a link dependency?
>
> - Dave
>
>
> On Sat, Sep 22, 2018 at 5:49 PM Eric Fiselier via cfe-commits <
> cfe-commits@lists.llvm.org> wrote:
>
>> Author: ericwf
>> Date: Sat Sep 22 17:48:05 2018
>> New Revision: 342827
>>
>> URL: http://llvm.org/viewvc/llvm-project?rev=342827=rev
>> Log:
>> Fix modules build with shared library.
>>
>> r341994 caused clangAnalysis to pull all of the AST matchers
>> library into clang. Due to inline key functions in the headers,
>> importing the AST matchers library gives a link dependency on the
>> AST matchers (and thus the AST), which clang should not
>> have.
>>
>> This patch works around the issues by excluding the offending
>> libclangAnalysis header in the modulemap.
>>
>> Modified:
>> cfe/trunk/include/clang/module.modulemap
>>
>> Modified: cfe/trunk/include/clang/module.modulemap
>> URL:
>> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/module.modulemap?rev=342827=342826=342827=diff
>>
>> ==
>> --- cfe/trunk/include/clang/module.modulemap (original)
>> +++ cfe/trunk/include/clang/module.modulemap Sat Sep 22 17:48:05 2018
>> @@ -5,6 +5,12 @@ module Clang_Analysis {
>>textual header "Analysis/Analyses/ThreadSafetyOps.def"
>>
>>module * { export * }
>> +
>> +  // FIXME: Exclude these headers to avoid pulling all of the AST
>> matchers
>> +  // library into clang. Due to inline key functions in the headers,
>> +  // importing the AST matchers library gives a link dependency on the
>> AST
>> +  // matchers (and thus the AST), which clang-format should not have.
>> +  exclude header "Analysis/Analyses/ExprMutationAnalyzer.h"
>>  }
>>
>>  module Clang_AST {
>>
>>
>> ___
>> cfe-commits mailing list
>> cfe-commits@lists.llvm.org
>> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r342827 - Fix modules build with shared library.

2018-09-25 Thread David Blaikie via cfe-commits
Hey Eric - thanks for the fix - but could you explain the issue here in a
bit more detail, as I'm a bit confused (& really interested in
understanding any layering problems in LLVM - and fixing them/making sure
they're fixed/holding the line/etc)

What do you mean by "pull all of the AST matchers library into clang" - how
does including a header ever add a link dependency?

- Dave

On Sat, Sep 22, 2018 at 5:49 PM Eric Fiselier via cfe-commits <
cfe-commits@lists.llvm.org> wrote:

> Author: ericwf
> Date: Sat Sep 22 17:48:05 2018
> New Revision: 342827
>
> URL: http://llvm.org/viewvc/llvm-project?rev=342827=rev
> Log:
> Fix modules build with shared library.
>
> r341994 caused clangAnalysis to pull all of the AST matchers
> library into clang. Due to inline key functions in the headers,
> importing the AST matchers library gives a link dependency on the
> AST matchers (and thus the AST), which clang should not
> have.
>
> This patch works around the issues by excluding the offending
> libclangAnalysis header in the modulemap.
>
> Modified:
> cfe/trunk/include/clang/module.modulemap
>
> Modified: cfe/trunk/include/clang/module.modulemap
> URL:
> http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/module.modulemap?rev=342827=342826=342827=diff
>
> ==
> --- cfe/trunk/include/clang/module.modulemap (original)
> +++ cfe/trunk/include/clang/module.modulemap Sat Sep 22 17:48:05 2018
> @@ -5,6 +5,12 @@ module Clang_Analysis {
>textual header "Analysis/Analyses/ThreadSafetyOps.def"
>
>module * { export * }
> +
> +  // FIXME: Exclude these headers to avoid pulling all of the AST matchers
> +  // library into clang. Due to inline key functions in the headers,
> +  // importing the AST matchers library gives a link dependency on the AST
> +  // matchers (and thus the AST), which clang-format should not have.
> +  exclude header "Analysis/Analyses/ExprMutationAnalyzer.h"
>  }
>
>  module Clang_AST {
>
>
> ___
> cfe-commits mailing list
> cfe-commits@lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52419: [clangd] Cache FS stat() calls when building preamble.

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Generally LG. A few things I'm unsure about.




Comment at: clangd/CodeComplete.cpp:1028
 
+  IntrusiveRefCntPtr VFS = Input.VFS;
+  if (Input.PreambleStatCache)

ioeric wrote:
> ilya-biryukov wrote:
> > It feels like we could apply this caching one level higher, on the 
> > TUScheduler level when creating the filesystem. It makes sense not only for 
> > code completion, but also for all other features, including rebuilds of 
> > ASTs that were washed out of the cache.
> > WDYT?
> It sounds like a reasonable thing to do. I took a quick look, and it seemed 
> that this would probably require some refactoring/redesign on TUScheduler - 
> it doesn't know about the VFS?
> 
> I think it shouldn't be hard to do this case by case. For example, code 
> completion and signature help will be covered in this patch. And it should be 
> pretty easy to make AST rebuild use the cache as well?
> It sounds like a reasonable thing to do. I took a quick look, and it seemed 
> that this would probably require some refactoring/redesign on TUScheduler - 
> it doesn't know about the VFS?

Right, this is a bit of a mess...
Currently there are features that access the FS "directly". This includes 
CodeComplete which runs its own compile action, as well as things like 
switchSourceHeader or format. These invoke FSProvider.
Then there are features that build an AST (which may need file accesses), and 
then may implicitly read files by querying the AST (the FS is attached to the 
FileManager or something). These use the FS obtained from the FSProvider **in 
the relevant addDocument call**.
There's no fundamental reason we can't have both (access FS directly and use 
the AST) in which case we'll be using both filesystems together...

In the near term, making the TUScheduler-managed AST rebuild use the cache 
stored in the preamble seems like a nice win. (As you alluded to I don't think 
this change is in TUScheduler itself, rather buildAST?)



Comment at: clangd/FS.cpp:1
+//===--- FS.cpp - File system related utils --*- 
C++-*-===//
+//

Can we have unit tests for these?
It should be pretty straightforward, as you can inspect/seed the cache state 
directly.



Comment at: clangd/FS.cpp:29
+PreambleFileStatusCache::lookup(llvm::StringRef File) const {
+  auto I = StatCache.find(File);
+  if (I != StatCache.end())

lock



Comment at: clangd/FS.cpp:48
+return File;
+  if (auto S = File->get()->status())
+StatCache.update(getUnderlyingFS(), std::move(*S));

I'm not sure I get this: AFAICT (at least on linux) the status is never 
available on a newly opened file, so this will always be a stat() call, so 
we're just doing the work eagerly and caching it for later. Isn't this just 
moving the work around?

I'm sure you've verified this is important somehow, but a comment explaining 
how would be much appreciated :-)



Comment at: clangd/FS.h:20
+/// Caches `stat()` calls during preamble build, which can be used to avoid
+/// re-`stat`s header files when preamble is re-used (e.g. in code completion).
+/// Note that the cache is only valid whene reusing preamble.

can you give a little more colour on *why* code completion tends to stat a 
bunch of the same files over again?
(One might assume it's to validate the preamble, but it shouldn't be, because 
we don't do that for other reasons)



Comment at: clangd/FS.h:21
+/// re-`stat`s header files when preamble is re-used (e.g. in code completion).
+/// Note that the cache is only valid whene reusing preamble.
+///

whene -> when



Comment at: unittests/clangd/ClangdTests.cpp:966
 
+TEST(ClangdTests, PreambleVFSStatCache) {
+  class ListenStatsFSProvider : public FileSystemProvider {

it's not obvious what this test does (without the rest of the patch as context).
Maybe a high-level comment: `Check that running code completion doesn't stat() 
a bunch of files from the preamble again. (They should be using the preamble's 
stat-cache)`



Comment at: unittests/clangd/ClangdTests.cpp:980
+llvm::ErrorOr status(const Twine ) override {
+  auto I =
+  CountStats.try_emplace(llvm::sys::path::filename(Path.str()), 1);

just ++CountStats[...]?
life is too short :-)



Comment at: unittests/clangd/ClangdTests.cpp:984
+I.first->second += 1;
+  return getUnderlyingFS().status(Path);
+}

or just `return ProxyFileSystem::status(Path);` which is *slightly* less coupled



Comment at: unittests/clangd/ClangdTests.cpp:1018
+
+  unsigned Before = CountStats["foo.h"];
+  auto Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),

I think this would be 

[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen(), size() or equal length

2018-09-25 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:37
+
+enum class LengthHandleKind { LHK_Increase, LHK_Decrease };
+

Please drop the `LHK_` prefix -- the enum class name is sufficient as a prefix.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:44
+// therefore we have to inject '+ 1UL' instead.
+static bool IsInjectUL = false;
+static std::map MacroDefinedMap;

This seems like it should be a parameter threaded through the function calls 
from check() rather than a static data member.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:55
+// The destination array is where the result of the function call will be 
stored
+static const Expr *getDestExpr(const MatchFinder::MatchResult ) {
+  return Result.Nodes.getNodeAs(DestExprName);

These functions don't really add much benefit given that they're one-liners 
where the implementation is shorter than the declaration.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:75
+
+// Length is could be an IntegerLiteral or length of a StringLiteral
+static int getLength(const Expr *E, const MatchFinder::MatchResult );

Length is could -> Length could



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:93
+
+// If the capacity of the destination array is not known it denoted as unknown
+static bool isKnownDest(const MatchFinder::MatchResult ) {

it denoted as unknown -> it is denoted as unknown.

(Be sure to add the full stop at the end of the sentence.)



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:101
+// Note: If the capacity and the given length is equal then the new function
+// is a simple 'cpy()' and because it returns true it prevents to increase
+// the given length.

prevents to increase -> prevents increasing



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:106
+
+// If we write/read from the same array it should be already null-terminated
+static bool isDestAndSrcEquals(const MatchFinder::MatchResult );

Missing the full stop at the end of the sentence.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:110
+// We catch integers as a given length so we have to see if the length of the
+// source array is the same length and that is not null-terminated
+static bool isNoWrongLength(const MatchFinder::MatchResult );

that is not -> that it is not

Missing the full stop at the end of the sentence.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:111
+// source array is the same length and that is not null-terminated
+static bool isNoWrongLength(const MatchFinder::MatchResult );
+

isNoWrongLength should probably be named isNotWrongLength() or perhaps reverse 
the logic to isCorrectLength().



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:118
+
+static bool isGivenLengthEQToSrcLength(const MatchFinder::MatchResult );
+

EQ -> Equal, but perhaps "lenEquaSrcLen()" is more succinct?



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:131
+
+// Increase or decrease by one an expression
+static void lengthExprHandle(LengthHandleKind LengthHandle,

Reorder the words and add a full stop: Increase or decrease an integral 
expression by one.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:137
+
+// Increase or decrease by one a passed argument by its position
+static void lengthArgHandle(LengthHandleKind LengthHandle, int ArgPos,

Similar: Increase or decrease the passed integral argument by one.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:143
+// If the destination array is the same length as the given length we have to
+// increase the capacity by one to create space for the the null terminator
+static bool destCapacityFix(const MatchFinder::MatchResult ,

Missing full stop.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:196
+  const Expr *SimpleNode = 
+  SimpleNode = SimpleNode->IgnoreParenCasts()->IgnoreImpCasts();
+

You can call `IgnoreParenImpCasts()` instead.



Comment at: clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp:201
+
+  const auto DREHasInit = ignoringImpCasts(
+  
declRefExpr(to(varDecl(hasInitializer(ignoringImpCasts(InnerMatcher));

You can remove the local `const` qualifications here (we don't typically use 
that for local unless the qualified type is a pointer or a reference).

Same elsewhere in the patch.



Comment at: 

[PATCH] D52517: [clangd] clangd-indexer: Drop support for MR-via-YAML

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This was previously in https://reviews.llvm.org/D52465, but I reduced the scope 
of that patch to make it easier to land.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52517



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


[PATCH] D52517: [clangd] clangd-indexer: Drop support for MR-via-YAML

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: kadircet.
Herald added subscribers: cfe-commits, arphaman, jkorous, MaskRay, ioeric, 
ilya-biryukov.

It's slow, and the open-source reduce implementation doesn't scale properly.
While here, tidy up some dead headers and comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52517

Files:
  clangd/indexer/IndexerMain.cpp

Index: clangd/indexer/IndexerMain.cpp
===
--- clangd/indexer/IndexerMain.cpp
+++ clangd/indexer/IndexerMain.cpp
@@ -12,26 +12,17 @@
 //
 //===--===//
 
-#include "RIFF.h"
-#include "index/CanonicalIncludes.h"
 #include "index/Index.h"
 #include "index/IndexAction.h"
 #include "index/Merge.h"
 #include "index/Serialization.h"
 #include "index/SymbolCollector.h"
-#include "clang/Frontend/CompilerInstance.h"
-#include "clang/Frontend/FrontendActions.h"
-#include "clang/Index/IndexDataConsumer.h"
-#include "clang/Index/IndexingAction.h"
 #include "clang/Tooling/CommonOptionsParser.h"
 #include "clang/Tooling/Execution.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/Support/CommandLine.h"
-#include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Signals.h"
-#include "llvm/Support/ThreadPool.h"
-#include "llvm/Support/YAMLTraits.h"
 
 using namespace llvm;
 using namespace clang::tooling;
@@ -50,107 +41,44 @@
"not given, such headers will have relative paths."),
 llvm::cl::init(""));
 
-static llvm::cl::opt MergeOnTheFly(
-"merge-on-the-fly",
-llvm::cl::desc(
-"Merges symbols for each processed translation unit as soon "
-"they become available. This results in a smaller memory "
-"usage and an almost instant reduce stage. Optimal for running as a "
-"standalone tool, but cannot be used with multi-process executors like "
-"MapReduce."),
-llvm::cl::init(true), llvm::cl::Hidden);
-
 static llvm::cl::opt
 Format("format", llvm::cl::desc("Format of the index to be written"),
llvm::cl::values(clEnumValN(IndexFileFormat::YAML, "yaml",
"human-readable YAML format"),
 clEnumValN(IndexFileFormat::RIFF, "binary",
"binary RIFF format")),
llvm::cl::init(IndexFileFormat::YAML));
 
-/// Responsible for aggregating symbols from each processed file and producing
-/// the final results. All methods in this class must be thread-safe,
-/// 'consumeSymbols' may be called from multiple threads.
-class SymbolsConsumer {
-public:
-  virtual ~SymbolsConsumer() = default;
-
-  /// Consume a SymbolSlab build for a file.
-  virtual void consumeSymbols(SymbolSlab Symbols) = 0;
-  /// Produce a resulting symbol slab, by combining  occurrences of the same
-  /// symbols across translation units.
-  virtual SymbolSlab mergeResults() = 0;
-};
-
-class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
+class IndexActionFactory : public tooling::FrontendActionFactory {
 public:
-  SymbolIndexActionFactory(SymbolsConsumer ) : Consumer(Consumer) {}
+  IndexActionFactory(IndexFileIn ) : Result(Result) {}
 
   clang::FrontendAction *create() override {
-auto CollectorOpts = SymbolCollector::Options();
-CollectorOpts.FallbackDir = AssumedHeaderDir;
+SymbolCollector::Options Opts;
+Opts.FallbackDir = AssumedHeaderDir;
 return createStaticIndexingAction(
-   CollectorOpts,
-   [&](SymbolSlab S) { Consumer.consumeSymbols(std::move(S)); })
+   Opts,
+   [&](SymbolSlab S) {
+ // Merge as we go.
+ std::lock_guard Lock(SymbolsMu);
+ for (const auto  : S) {
+   if (const auto *Existing = Symbols.find(Sym.ID))
+ Symbols.insert(mergeSymbol(*Existing, Sym));
+   else
+ Symbols.insert(Sym);
+ }
+   })
 .release();
   }
 
-  SymbolsConsumer 
-};
-
-/// Stashes per-file results inside ExecutionContext, merges all of them at the
-/// end. Useful for running on MapReduce infrastructure to avoid keeping symbols
-/// from multiple files in memory.
-class ToolExecutorConsumer : public SymbolsConsumer {
-public:
-  ToolExecutorConsumer(ToolExecutor ) : Executor(Executor) {}
-
-  void consumeSymbols(SymbolSlab Symbols) override {
-for (const auto  : Symbols)
-  Executor.getExecutionContext()->reportResult(Sym.ID.str(), toYAML(Sym));
-  }
-
-  SymbolSlab mergeResults() override {
-SymbolSlab::Builder UniqueSymbols;
-Executor.getToolResults()->forEachResult(
-[&](llvm::StringRef Key, llvm::StringRef Value) {
-  llvm::yaml::Input Yin(Value);
-  auto Sym = cantFail(clang::clangd::symbolFromYAML(Yin));
-  auto 

[PATCH] D52465: [clangd] Extract mapper logic from clangd-indexer into a library.

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343019: [clangd] Extract mapper logic from clangd-indexer 
into a library. (authored by sammccall, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D52465

Files:
  clang-tools-extra/trunk/clangd/CMakeLists.txt
  clang-tools-extra/trunk/clangd/index/IndexAction.cpp
  clang-tools-extra/trunk/clangd/index/IndexAction.h
  clang-tools-extra/trunk/clangd/index/Serialization.h
  clang-tools-extra/trunk/clangd/index/SymbolCollector.h
  clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp

Index: clang-tools-extra/trunk/clangd/CMakeLists.txt
===
--- clang-tools-extra/trunk/clangd/CMakeLists.txt
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt
@@ -40,6 +40,7 @@
   index/CanonicalIncludes.cpp
   index/FileIndex.cpp
   index/Index.cpp
+  index/IndexAction.cpp
   index/MemIndex.cpp
   index/Merge.cpp
   index/Serialization.cpp
Index: clang-tools-extra/trunk/clangd/index/Serialization.h
===
--- clang-tools-extra/trunk/clangd/index/Serialization.h
+++ clang-tools-extra/trunk/clangd/index/Serialization.h
@@ -40,23 +40,26 @@
   YAML, // Human-readable format, suitable for experiments and debugging.
 };
 
+// Holds the contents of an index file that was read.
+struct IndexFileIn {
+  llvm::Optional Symbols;
+};
+// Parse an index file. The input must be a RIFF container chunk.
+llvm::Expected readIndexFile(llvm::StringRef);
+
 // Specifies the contents of an index file to be written.
 struct IndexFileOut {
   const SymbolSlab *Symbols;
   // TODO: Support serializing symbol occurrences.
   // TODO: Support serializing Dex posting lists.
   IndexFileFormat Format = IndexFileFormat::RIFF;
-};
-// Serializes an index file. (This is a RIFF container chunk).
-llvm::raw_ostream <<(llvm::raw_ostream , const IndexFileOut );
 
-// Holds the contents of an index file that was read.
-struct IndexFileIn {
-  llvm::Optional Symbols;
-  IndexFileFormat Format;
+  IndexFileOut() = default;
+  IndexFileOut(const IndexFileIn )
+  : Symbols(I.Symbols ? I.Symbols.getPointer() : nullptr) {}
 };
-// Parse an index file. The input must be a RIFF container chunk.
-llvm::Expected readIndexFile(llvm::StringRef);
+// Serializes an index file.
+llvm::raw_ostream <<(llvm::raw_ostream , const IndexFileOut );
 
 std::string toYAML(const Symbol &);
 // Returned symbol is backed by the YAML input.
Index: clang-tools-extra/trunk/clangd/index/SymbolCollector.h
===
--- clang-tools-extra/trunk/clangd/index/SymbolCollector.h
+++ clang-tools-extra/trunk/clangd/index/SymbolCollector.h
@@ -6,6 +6,8 @@
 // License. See LICENSE.TXT for details.
 //
 //===--===//
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOL_COLLECTOR_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOL_COLLECTOR_H
 
 #include "CanonicalIncludes.h"
 #include "Index.h"
@@ -122,3 +124,4 @@
 
 } // namespace clangd
 } // namespace clang
+#endif
Index: clang-tools-extra/trunk/clangd/index/IndexAction.h
===
--- clang-tools-extra/trunk/clangd/index/IndexAction.h
+++ clang-tools-extra/trunk/clangd/index/IndexAction.h
@@ -0,0 +1,32 @@
+//===--- IndexAction.h - Run the indexer as a frontend action *- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_ACTION_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_INDEX_ACTION_H
+#include "SymbolCollector.h"
+#include "clang/Frontend/FrontendActions.h"
+
+namespace clang {
+namespace clangd {
+
+// Creates an action that indexes translation units and delivers the results
+// for SymbolsCallback (each slab corresponds to one TU).
+//
+// Only a subset of SymbolCollector::Options are respected:
+//   - include paths are always collected, and canonicalized appropriately
+//   - references are always counted
+//   - the symbol origin is always Static
+std::unique_ptr
+createStaticIndexingAction(SymbolCollector::Options Opts,
+   std::function SymbolsCallback);
+
+} // namespace clangd
+} // namespace clang
+
+#endif
Index: clang-tools-extra/trunk/clangd/index/IndexAction.cpp
===
--- clang-tools-extra/trunk/clangd/index/IndexAction.cpp
+++ clang-tools-extra/trunk/clangd/index/IndexAction.cpp
@@ -0,0 +1,73 @@
+#include "IndexAction.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Index/IndexDataConsumer.h"

[clang-tools-extra] r343019 - [clangd] Extract mapper logic from clangd-indexer into a library.

2018-09-25 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Tue Sep 25 13:02:36 2018
New Revision: 343019

URL: http://llvm.org/viewvc/llvm-project?rev=343019=rev
Log:
[clangd] Extract mapper logic from clangd-indexer into a library.

Summary: Soon we can drop support for MR-via-YAML.
I need to modify some out-of-tree versions to use the library, first.

Reviewers: kadircet

Subscribers: mgorny, ilya-biryukov, ioeric, MaskRay, jkorous, arphaman, 
cfe-commits

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

Added:
clang-tools-extra/trunk/clangd/index/IndexAction.cpp
clang-tools-extra/trunk/clangd/index/IndexAction.h
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/index/Serialization.h
clang-tools-extra/trunk/clangd/index/SymbolCollector.h
clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=343019=343018=343019=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Tue Sep 25 13:02:36 2018
@@ -40,6 +40,7 @@ add_clang_library(clangDaemon
   index/CanonicalIncludes.cpp
   index/FileIndex.cpp
   index/Index.cpp
+  index/IndexAction.cpp
   index/MemIndex.cpp
   index/Merge.cpp
   index/Serialization.cpp

Added: clang-tools-extra/trunk/clangd/index/IndexAction.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/IndexAction.cpp?rev=343019=auto
==
--- clang-tools-extra/trunk/clangd/index/IndexAction.cpp (added)
+++ clang-tools-extra/trunk/clangd/index/IndexAction.cpp Tue Sep 25 13:02:36 
2018
@@ -0,0 +1,73 @@
+#include "IndexAction.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Index/IndexDataConsumer.h"
+#include "clang/Index/IndexingAction.h"
+#include "clang/Tooling/Tooling.h"
+namespace clang {
+namespace clangd {
+namespace {
+
+// Wraps the index action and reports index data after each translation unit.
+class IndexAction : public WrapperFrontendAction {
+public:
+  IndexAction(std::shared_ptr C,
+  std::unique_ptr Includes,
+  const index::IndexingOptions ,
+  std::function )
+  : WrapperFrontendAction(index::createIndexingAction(C, Opts, nullptr)),
+SymbolsCallback(SymbolsCallback), Collector(C),
+Includes(std::move(Includes)),
+PragmaHandler(collectIWYUHeaderMaps(this->Includes.get())) {}
+
+  std::unique_ptr CreateASTConsumer(CompilerInstance ,
+ StringRef InFile) override {
+CI.getPreprocessor().addCommentHandler(PragmaHandler.get());
+return WrapperFrontendAction::CreateASTConsumer(CI, InFile);
+  }
+
+  bool BeginInvocation(CompilerInstance ) override {
+// We want all comments, not just the doxygen ones.
+CI.getLangOpts().CommentOpts.ParseAllComments = true;
+return WrapperFrontendAction::BeginInvocation(CI);
+  }
+
+  void EndSourceFileAction() override {
+WrapperFrontendAction::EndSourceFileAction();
+
+const auto  = getCompilerInstance();
+if (CI.hasDiagnostics() &&
+CI.getDiagnostics().hasUncompilableErrorOccurred()) {
+  llvm::errs() << "Skipping TU due to uncompilable errors\n";
+  return;
+}
+SymbolsCallback(Collector->takeSymbols());
+  }
+
+private:
+  std::function SymbolsCallback;
+  std::shared_ptr Collector;
+  std::unique_ptr Includes;
+  std::unique_ptr PragmaHandler;
+};
+
+} // namespace
+
+std::unique_ptr
+createStaticIndexingAction(SymbolCollector::Options Opts,
+   std::function SymbolsCallback) {
+  index::IndexingOptions IndexOpts;
+  IndexOpts.SystemSymbolFilter =
+  index::IndexingOptions::SystemSymbolFilterKind::All;
+  Opts.CollectIncludePath = true;
+  Opts.CountReferences = true;
+  Opts.Origin = SymbolOrigin::Static;
+  auto Includes = llvm::make_unique();
+  addSystemHeadersMapping(Includes.get());
+  Opts.Includes = Includes.get();
+  return llvm::make_unique(
+  std::make_shared(std::move(Opts)), std::move(Includes),
+  IndexOpts, SymbolsCallback);
+};
+
+} // namespace clangd
+} // namespace clang

Added: clang-tools-extra/trunk/clangd/index/IndexAction.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/IndexAction.h?rev=343019=auto
==
--- clang-tools-extra/trunk/clangd/index/IndexAction.h (added)
+++ clang-tools-extra/trunk/clangd/index/IndexAction.h Tue Sep 25 13:02:36 2018
@@ -0,0 +1,32 @@
+//===--- IndexAction.h - Run the indexer as a frontend action *- 
C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// 

Re: [PATCH] D50294: [Driver] Use -gdwarf-3 by default for FreeBSD

2018-09-25 Thread Fāng-ruì Sòng via cfe-commits


On 2018-09-25, Ed Maste via Phabricator wrote:

emaste added a comment.

I'm using this change: 
https://github.com/emaste/freebsd/commit/1c3deab6d518feb1a7e88de5b342a139e4022a21

In FreeBSD 12 and later we use Clang, lld, and ELF Tool Chain. (We still have 
gas and objdump from the outdated binutils 2.17.50.)


Repository:
 rC Clang

https://reviews.llvm.org/D50294


Your change should be upstreamed then
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r343017 - [clangd] Fix reversed RIFF/YAML serialization

2018-09-25 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Tue Sep 25 12:53:33 2018
New Revision: 343017

URL: http://llvm.org/viewvc/llvm-project?rev=343017=rev
Log:
[clangd] Fix reversed RIFF/YAML serialization

Modified:
clang-tools-extra/trunk/clangd/index/Serialization.cpp

Modified: clang-tools-extra/trunk/clangd/index/Serialization.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Serialization.cpp?rev=343017=343016=343017=diff
==
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp Tue Sep 25 12:53:33 
2018
@@ -389,10 +389,10 @@ Expected readYAML(StringRef
 llvm::raw_ostream <<(llvm::raw_ostream , const IndexFileOut ) {
   switch (O.Format) {
   case IndexFileFormat::RIFF:
-writeYAML(O, OS);
+writeRIFF(O, OS);
 break;
   case IndexFileFormat::YAML:
-writeRIFF(O, OS);
+writeYAML(O, OS);
 break;
   }
   return OS;


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


[PATCH] D52344: [Clang][CodeGen][ObjC]: Fix non-bridged CoreFoundation builds on ELF targets that use `-fconstant-cfstrings`.

2018-09-25 Thread Kristina Brooks via Phabricator via cfe-commits
kristina added a comment.

Turns out test didn't execute as there are two tests named `CFString.c` and 
`cfstring.c` which usually shouldn't matter unless LLVM source checkout is done 
into a case insensitive filesystem in which case the failing test is skipped, 
this seems like a bug, going to rename `CFString.c` to `CFString3.c` and revise 
it to adjust backing stores for actual literals to quote `.rodata` like in the 
other test. Pretty silly issue and why test suite ran just fine locally but 
failed when ran on case-sensitive buildbots.


Repository:
  rC Clang

https://reviews.llvm.org/D52344



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


[PATCH] D52465: [clangd] Extract mapper logic from clangd-indexer into a library.

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

On second thoughts, let's just leave the MR functionality in place for now so 
this can be landed.
Then the out-of-tree stuff can migrate to the library, and we can rip out the 
MR stuff soon.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52465



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


[PATCH] D52058: Add Parameters to DW_AT_name Attribute of Template Variables

2018-09-25 Thread Matthew Voss via Phabricator via cfe-commits
ormris added a comment.

//Ping//


Repository:
  rC Clang

https://reviews.llvm.org/D52058



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


[PATCH] D52465: [clangd] Extract mapper logic from clangd-indexer into a library.

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 166970.
sammccall added a comment.

Leave functionality of clangd-indexer unchanged, to make this easier to land.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52465

Files:
  clangd/CMakeLists.txt
  clangd/index/IndexAction.cpp
  clangd/index/IndexAction.h
  clangd/index/Serialization.h
  clangd/index/SymbolCollector.h
  clangd/indexer/IndexerMain.cpp

Index: clangd/indexer/IndexerMain.cpp
===
--- clangd/indexer/IndexerMain.cpp
+++ clangd/indexer/IndexerMain.cpp
@@ -15,6 +15,7 @@
 #include "RIFF.h"
 #include "index/CanonicalIncludes.h"
 #include "index/Index.h"
+#include "index/IndexAction.h"
 #include "index/Merge.h"
 #include "index/Serialization.h"
 #include "index/SymbolCollector.h"
@@ -86,68 +87,12 @@
   SymbolIndexActionFactory(SymbolsConsumer ) : Consumer(Consumer) {}
 
   clang::FrontendAction *create() override {
-// Wraps the index action and reports collected symbols to the execution
-// context at the end of each translation unit.
-class WrappedIndexAction : public WrapperFrontendAction {
-public:
-  WrappedIndexAction(std::shared_ptr C,
- std::unique_ptr Includes,
- const index::IndexingOptions ,
- SymbolsConsumer )
-  : WrapperFrontendAction(
-index::createIndexingAction(C, Opts, nullptr)),
-Consumer(Consumer), Collector(C), Includes(std::move(Includes)),
-PragmaHandler(collectIWYUHeaderMaps(this->Includes.get())) {}
-
-  std::unique_ptr
-  CreateASTConsumer(CompilerInstance , StringRef InFile) override {
-CI.getPreprocessor().addCommentHandler(PragmaHandler.get());
-return WrapperFrontendAction::CreateASTConsumer(CI, InFile);
-  }
-
-  bool BeginInvocation(CompilerInstance ) override {
-// We want all comments, not just the doxygen ones.
-CI.getLangOpts().CommentOpts.ParseAllComments = true;
-return WrapperFrontendAction::BeginInvocation(CI);
-  }
-
-  void EndSourceFileAction() override {
-WrapperFrontendAction::EndSourceFileAction();
-
-const auto  = getCompilerInstance();
-if (CI.hasDiagnostics() &&
-CI.getDiagnostics().hasUncompilableErrorOccurred()) {
-  llvm::errs()
-  << "Found uncompilable errors in the translation unit. Igoring "
- "collected symbols...\n";
-  return;
-}
-
-Consumer.consumeSymbols(Collector->takeSymbols());
-  }
-
-private:
-  SymbolsConsumer 
-  std::shared_ptr Collector;
-  std::unique_ptr Includes;
-  std::unique_ptr PragmaHandler;
-};
-
-index::IndexingOptions IndexOpts;
-IndexOpts.SystemSymbolFilter =
-index::IndexingOptions::SystemSymbolFilterKind::All;
-IndexOpts.IndexFunctionLocals = false;
 auto CollectorOpts = SymbolCollector::Options();
 CollectorOpts.FallbackDir = AssumedHeaderDir;
-CollectorOpts.CollectIncludePath = true;
-CollectorOpts.CountReferences = true;
-CollectorOpts.Origin = SymbolOrigin::Static;
-auto Includes = llvm::make_unique();
-addSystemHeadersMapping(Includes.get());
-CollectorOpts.Includes = Includes.get();
-return new WrappedIndexAction(
-std::make_shared(std::move(CollectorOpts)),
-std::move(Includes), IndexOpts, Consumer);
+return createStaticIndexingAction(
+   CollectorOpts,
+   [&](SymbolSlab S) { Consumer.consumeSymbols(std::move(S)); })
+.release();
   }
 
   SymbolsConsumer 
Index: clangd/index/SymbolCollector.h
===
--- clangd/index/SymbolCollector.h
+++ clangd/index/SymbolCollector.h
@@ -6,6 +6,8 @@
 // License. See LICENSE.TXT for details.
 //
 //===--===//
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOL_COLLECTOR_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOL_COLLECTOR_H
 
 #include "CanonicalIncludes.h"
 #include "Index.h"
@@ -122,3 +124,4 @@
 
 } // namespace clangd
 } // namespace clang
+#endif
Index: clangd/index/Serialization.h
===
--- clangd/index/Serialization.h
+++ clangd/index/Serialization.h
@@ -40,23 +40,26 @@
   YAML, // Human-readable format, suitable for experiments and debugging.
 };
 
+// Holds the contents of an index file that was read.
+struct IndexFileIn {
+  llvm::Optional Symbols;
+};
+// Parse an index file. The input must be a RIFF container chunk.
+llvm::Expected readIndexFile(llvm::StringRef);
+
 // Specifies the contents of an index file to be written.
 struct IndexFileOut {
   const SymbolSlab *Symbols;
   // TODO: Support serializing symbol occurrences.
   // TODO: Support serializing Dex posting lists.
   IndexFileFormat Format = 

[PATCH] D52465: [clangd] Extract mapper logic from clangd-indexer into a library.

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 166968.
sammccall marked an inline comment as done.
sammccall added a comment.

Rebase and address comments.


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52465

Files:
  clangd/CMakeLists.txt
  clangd/index/IndexAction.cpp
  clangd/index/IndexAction.h
  clangd/index/Serialization.h
  clangd/index/SymbolCollector.h
  clangd/indexer/IndexerMain.cpp

Index: clangd/indexer/IndexerMain.cpp
===
--- clangd/indexer/IndexerMain.cpp
+++ clangd/indexer/IndexerMain.cpp
@@ -15,6 +15,7 @@
 #include "RIFF.h"
 #include "index/CanonicalIncludes.h"
 #include "index/Index.h"
+#include "index/IndexAction.h"
 #include "index/Merge.h"
 #include "index/Serialization.h"
 #include "index/SymbolCollector.h"
@@ -49,163 +50,44 @@
"not given, such headers will have relative paths."),
 llvm::cl::init(""));
 
-static llvm::cl::opt MergeOnTheFly(
-"merge-on-the-fly",
-llvm::cl::desc(
-"Merges symbols for each processed translation unit as soon "
-"they become available. This results in a smaller memory "
-"usage and an almost instant reduce stage. Optimal for running as a "
-"standalone tool, but cannot be used with multi-process executors like "
-"MapReduce."),
-llvm::cl::init(true), llvm::cl::Hidden);
-
 static llvm::cl::opt
 Format("format", llvm::cl::desc("Format of the index to be written"),
llvm::cl::values(clEnumValN(IndexFileFormat::YAML, "yaml",
"human-readable YAML format"),
 clEnumValN(IndexFileFormat::RIFF, "binary",
"binary RIFF format")),
llvm::cl::init(IndexFileFormat::YAML));
 
-/// Responsible for aggregating symbols from each processed file and producing
-/// the final results. All methods in this class must be thread-safe,
-/// 'consumeSymbols' may be called from multiple threads.
-class SymbolsConsumer {
-public:
-  virtual ~SymbolsConsumer() = default;
-
-  /// Consume a SymbolSlab build for a file.
-  virtual void consumeSymbols(SymbolSlab Symbols) = 0;
-  /// Produce a resulting symbol slab, by combining  occurrences of the same
-  /// symbols across translation units.
-  virtual SymbolSlab mergeResults() = 0;
-};
-
-class SymbolIndexActionFactory : public tooling::FrontendActionFactory {
+class IndexActionFactory : public tooling::FrontendActionFactory {
 public:
-  SymbolIndexActionFactory(SymbolsConsumer ) : Consumer(Consumer) {}
+  IndexActionFactory(IndexFileIn ) : Result(Result) {}
 
   clang::FrontendAction *create() override {
-// Wraps the index action and reports collected symbols to the execution
-// context at the end of each translation unit.
-class WrappedIndexAction : public WrapperFrontendAction {
-public:
-  WrappedIndexAction(std::shared_ptr C,
- std::unique_ptr Includes,
- const index::IndexingOptions ,
- SymbolsConsumer )
-  : WrapperFrontendAction(
-index::createIndexingAction(C, Opts, nullptr)),
-Consumer(Consumer), Collector(C), Includes(std::move(Includes)),
-PragmaHandler(collectIWYUHeaderMaps(this->Includes.get())) {}
-
-  std::unique_ptr
-  CreateASTConsumer(CompilerInstance , StringRef InFile) override {
-CI.getPreprocessor().addCommentHandler(PragmaHandler.get());
-return WrapperFrontendAction::CreateASTConsumer(CI, InFile);
-  }
-
-  bool BeginInvocation(CompilerInstance ) override {
-// We want all comments, not just the doxygen ones.
-CI.getLangOpts().CommentOpts.ParseAllComments = true;
-return WrapperFrontendAction::BeginInvocation(CI);
-  }
-
-  void EndSourceFileAction() override {
-WrapperFrontendAction::EndSourceFileAction();
-
-const auto  = getCompilerInstance();
-if (CI.hasDiagnostics() &&
-CI.getDiagnostics().hasUncompilableErrorOccurred()) {
-  llvm::errs()
-  << "Found uncompilable errors in the translation unit. Igoring "
- "collected symbols...\n";
-  return;
-}
-
-Consumer.consumeSymbols(Collector->takeSymbols());
-  }
-
-private:
-  SymbolsConsumer 
-  std::shared_ptr Collector;
-  std::unique_ptr Includes;
-  std::unique_ptr PragmaHandler;
-};
-
-index::IndexingOptions IndexOpts;
-IndexOpts.SystemSymbolFilter =
-index::IndexingOptions::SystemSymbolFilterKind::All;
-IndexOpts.IndexFunctionLocals = false;
-auto CollectorOpts = SymbolCollector::Options();
-CollectorOpts.FallbackDir = AssumedHeaderDir;
-CollectorOpts.CollectIncludePath = true;
-CollectorOpts.CountReferences = true;
-CollectorOpts.Origin = SymbolOrigin::Static;
-auto Includes = llvm::make_unique();
-

[PATCH] D52248: [SEMA] ignore duplicate declaration specifiers from typeof exprs

2018-09-25 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

The right way to produce diagnostics under pedantic mode is to model them as 
Extension or ExtWarn in the .td file, not by checking the Pedantic diagnostic 
option directly. If this is an intentional GNU extension too, that makes things 
a bit more complex (one approach would be to have two diagnostics, one for 
"this is ill-formed" and another for "this is a GNU extension").


Repository:
  rC Clang

https://reviews.llvm.org/D52248



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


[PATCH] D52465: [clangd] Extract mapper logic from clangd-indexer into a library.

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall marked 3 inline comments as done.
sammccall added a comment.

Thanks!
Will land in a day or two, we maintain some out-of-tree mapreduce patches to 
this file that I need to turn into a real fork.




Comment at: clangd/index/IndexAction.h:24
+//   - references are always counted
+//   - (all) references ane provided if RefsCallback is non-null
+//   - the symbol origin is always Static

kadircet wrote:
> s/ane/are/
> 
> What is RefsCallback?
Oops, I considered adding refs collection in this patch and then decided 
against it (add later instead)


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52465



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


[PATCH] D52513: [Modules] Do not emit file modification error when -fno-validate-pch is set

2018-09-25 Thread Yuka Takahashi via Phabricator via cfe-commits
yamaguchi created this revision.
yamaguchi added reviewers: rsmith, v.g.vassilev.

This is a follow-up patch of
https://reviews.llvm.org/rL338503: [Modules] Do not emit relocation error when 
-fno-validate-pch is set

File modification with modules is also fine for our usecase as we
want to reuse pcms. This enables us to use the same build directory
again without deleting pcm directory.


https://reviews.llvm.org/D52513

Files:
  clang/lib/Serialization/ASTReader.cpp
  clang/test/Modules/module-file-novalidate.c


Index: clang/test/Modules/module-file-novalidate.c
===
--- /dev/null
+++ clang/test/Modules/module-file-novalidate.c
@@ -0,0 +1,11 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo 'int foo = 0;' > %t/a.h
+// RUN: echo 'module A { header "a.h" }' > %t/m.modulemap
+// RUN: %clang_cc1 -fmodules -emit-module -fmodule-name=A -x c %t/m.modulemap 
-o %t/m.pcm
+// RUN: echo 'int bar;' > %t/a.h
+// RUN: not %clang_cc1 -fmodules -fmodule-file=%t/m.pcm 
-fmodule-map-file=%t/m.modulemap -fno-validate-pch -x c %s -I%t -fsyntax-only 
2>&1 | FileCheck %s
+#include "a.h"
+int foo = 0; // redefinition of 'foo'
+// CHECK-NOT: fatal error: file {{.*}} has been modified since the module file 
{{.*}} was built
+// REQUIRES: shell
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2175,7 +2175,8 @@
   bool IsOutOfDate = false;
 
   // For an overridden file, there is nothing to validate.
-  if (!Overridden && //
+  // Don't emit file modification error if we have -fno-validate-pch
+  if (!Overridden && !PP.getPreprocessorOpts().DisablePCHValidation &&
   (StoredSize != File->getSize() ||
(StoredTime && StoredTime != File->getModificationTime() &&
 !DisableValidation)


Index: clang/test/Modules/module-file-novalidate.c
===
--- /dev/null
+++ clang/test/Modules/module-file-novalidate.c
@@ -0,0 +1,11 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: echo 'int foo = 0;' > %t/a.h
+// RUN: echo 'module A { header "a.h" }' > %t/m.modulemap
+// RUN: %clang_cc1 -fmodules -emit-module -fmodule-name=A -x c %t/m.modulemap -o %t/m.pcm
+// RUN: echo 'int bar;' > %t/a.h
+// RUN: not %clang_cc1 -fmodules -fmodule-file=%t/m.pcm -fmodule-map-file=%t/m.modulemap -fno-validate-pch -x c %s -I%t -fsyntax-only 2>&1 | FileCheck %s
+#include "a.h"
+int foo = 0; // redefinition of 'foo'
+// CHECK-NOT: fatal error: file {{.*}} has been modified since the module file {{.*}} was built
+// REQUIRES: shell
Index: clang/lib/Serialization/ASTReader.cpp
===
--- clang/lib/Serialization/ASTReader.cpp
+++ clang/lib/Serialization/ASTReader.cpp
@@ -2175,7 +2175,8 @@
   bool IsOutOfDate = false;
 
   // For an overridden file, there is nothing to validate.
-  if (!Overridden && //
+  // Don't emit file modification error if we have -fno-validate-pch
+  if (!Overridden && !PP.getPreprocessorOpts().DisablePCHValidation &&
   (StoredSize != File->getSize() ||
(StoredTime && StoredTime != File->getModificationTime() &&
 !DisableValidation)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r343002 - Revert "[DRIVER][OFFLOAD] Do not invoke unbundler on unsupported file

2018-09-25 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Sep 25 11:31:56 2018
New Revision: 343002

URL: http://llvm.org/viewvc/llvm-project?rev=343002=rev
Log:
Revert "[DRIVER][OFFLOAD] Do not invoke unbundler on unsupported file
types."

It reverts commit r342991 + several other commits intended to fix the
tests. Still have some failed tests, need to investigate it.

Removed:
cfe/trunk/test/Driver/Inputs/in.so
Modified:
cfe/trunk/lib/Driver/Driver.cpp
cfe/trunk/test/Driver/openmp-offload-gpu.c
cfe/trunk/test/Driver/openmp-offload.c

Modified: cfe/trunk/lib/Driver/Driver.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/Driver.cpp?rev=343002=343001=343002=diff
==
--- cfe/trunk/lib/Driver/Driver.cpp (original)
+++ cfe/trunk/lib/Driver/Driver.cpp Tue Sep 25 11:31:56 2018
@@ -2559,8 +2559,6 @@ class OffloadingActionBuilder final {
 getDeviceDependences(OffloadAction::DeviceDependences ,
  phases::ID CurPhase, phases::ID FinalPhase,
  PhasesTy ) override {
-  if (OpenMPDeviceActions.empty())
-return ABRT_Inactive;
 
   // We should always have an action for each input.
   assert(OpenMPDeviceActions.size() == ToolChains.size() &&
@@ -2819,16 +2817,6 @@ public:
 if (CanUseBundler && isa(HostAction) &&
 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
 !types::isSrcFile(HostAction->getType())) {
-  StringRef FileName = InputArg->getAsString(C.getArgs());
-  // Check if the type of the file is the same as the action. Do not
-  // unbundle it if it is not. Do not unbundle .so files, for example, 
which
-  // are not object files.
-  if (HostAction->getType() == types::TY_Object &&
-  llvm::sys::path::has_extension(FileName) &&
-  types::lookupTypeForExtension(
-  llvm::sys::path::extension(FileName).drop_front()) !=
-  HostAction->getType())
-return false;
   auto UnbundlingHostAction =
   C.MakeAction(HostAction);
   UnbundlingHostAction->registerDependentActionInfo(

Removed: cfe/trunk/test/Driver/Inputs/in.so
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/Inputs/in.so?rev=343001=auto
==
--- cfe/trunk/test/Driver/Inputs/in.so (original)
+++ cfe/trunk/test/Driver/Inputs/in.so (removed)
@@ -1 +0,0 @@
-

Modified: cfe/trunk/test/Driver/openmp-offload-gpu.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/openmp-offload-gpu.c?rev=343002=343001=343002=diff
==
--- cfe/trunk/test/Driver/openmp-offload-gpu.c (original)
+++ cfe/trunk/test/Driver/openmp-offload-gpu.c Tue Sep 25 11:31:56 2018
@@ -73,15 +73,13 @@
 /// Check cubin file unbundling and usage by nvlink
 // RUN:   touch %t.o
 // RUN:   %clang -### -target powerpc64le-unknown-linux-gnu -fopenmp=libomp 
-fopenmp-targets=nvptx64-nvidia-cuda \
-// RUN:  -no-canonical-prefixes -save-temps %t.o %S/Inputs/in.so 2>&1 \
+// RUN:  -no-canonical-prefixes -save-temps %t.o 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-CUBIN-UNBUNDLING-NVLINK %s
 
 /// Use DAG to ensure that cubin file has been unbundled.
-// CHK-CUBIN-UNBUNDLING-NVLINK-NOT: clang-offload-bundler{{.*}}" 
"-type=o"{{.*}}in.so
 // CHK-CUBIN-UNBUNDLING-NVLINK-DAG: nvlink{{.*}}" {{.*}}"[[CUBIN:.*\.cubin]]"
 // CHK-CUBIN-UNBUNDLING-NVLINK-DAG: clang-offload-bundler{{.*}}" "-type=o" 
{{.*}}"-outputs={{.*}}[[CUBIN]]
 // CHK-CUBIN-UNBUNDLING-NVLINK-DAG-SAME: "-unbundle"
-// CHK-CUBIN-UNBUNDLING-NVLINK-NOT: clang-offload-bundler{{.*}}" 
"-type=o"{{.*}}in.so
 
 /// ###
 

Modified: cfe/trunk/test/Driver/openmp-offload.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/openmp-offload.c?rev=343002=343001=343002=diff
==
--- cfe/trunk/test/Driver/openmp-offload.c (original)
+++ cfe/trunk/test/Driver/openmp-offload.c Tue Sep 25 11:31:56 2018
@@ -358,7 +358,7 @@
 /// ###
 
 /// Check separate compilation with offloading - bundling actions
-// RUN:   %clang -### -ccc-print-phases -fopenmp=libomp -c -o %t.o  
%S/Input/in.so -lsomelib -target powerpc64le-linux 
-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s 
-no-canonical-prefixes 2>&1 \
+// RUN:   %clang -### -ccc-print-phases -fopenmp=libomp -c -o %t.o -lsomelib 
-target powerpc64le-linux 
-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s 
-no-canonical-prefixes 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-BUACTIONS %s
 
 // CHK-BUACTIONS: 0: input, "[[INPUT:.+\.c]]", c, (host-openmp)


___

[PATCH] D52499: [clang-cl] Make /Gs imply default stack probes, not /Gs0 (PR39074)

2018-09-25 Thread David Majnemer via Phabricator via cfe-commits
majnemer accepted this revision.
majnemer added a comment.
This revision is now accepted and ready to land.

FWIW, Microsoft's newest documentation does not say that `/O2` and `/O1` imply 
`/Gs`: 
https://docs.microsoft.com/en-us/cpp/build/reference/o1-o2-minimize-size-maximize-speed?view=vs-2017


https://reviews.llvm.org/D52499



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


[PATCH] D52230: [clang-tidy] use CHECK-NOTES in tests for bugprone-macro-repeated-side-effects

2018-09-25 Thread Jonas Toth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE343001: [clang-tidy] use CHECK-NOTES in tests for 
bugprone-macro-repeated-side-effects (authored by JonasToth, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52230?vs=165942=166961#toc

Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52230

Files:
  test/clang-tidy/bugprone-macro-repeated-side-effects.c

Index: test/clang-tidy/bugprone-macro-repeated-side-effects.c
===
--- test/clang-tidy/bugprone-macro-repeated-side-effects.c
+++ test/clang-tidy/bugprone-macro-repeated-side-effects.c
@@ -3,45 +3,59 @@
 #define badA(x,y)  ((x)+((x)+(y))+(y))
 void bad(int ret, int a, int b) {
   ret = badA(a++, b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x' are repeated in macro expansion [bugprone-macro-repeated-side-effects]
+  // CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x' are repeated in macro expansion [bugprone-macro-repeated-side-effects]
+  // CHECK-NOTES: :[[@LINE-4]]:9: note: macro 'badA' defined here
   ret = badA(++a, b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x'
+  // CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x'
+  // CHECK-NOTES: :[[@LINE-7]]:9: note: macro 'badA' defined here
   ret = badA(a--, b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x'
+  // CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x'
+  // CHECK-NOTES: :[[@LINE-10]]:9: note: macro 'badA' defined here
   ret = badA(--a, b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x'
+  // CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x'
+  // CHECK-NOTES: :[[@LINE-13]]:9: note: macro 'badA' defined here
   ret = badA(a, b++);
-  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
+  // CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
+  // CHECK-NOTES: :[[@LINE-16]]:9: note: macro 'badA' defined here
   ret = badA(a, ++b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
+  // CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
+  // CHECK-NOTES: :[[@LINE-19]]:9: note: macro 'badA' defined here
   ret = badA(a, b--);
-  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
+  // CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
+  // CHECK-NOTES: :[[@LINE-22]]:9: note: macro 'badA' defined here
   ret = badA(a, --b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
+  // CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y'
+  // CHECK-NOTES: :[[@LINE-25]]:9: note: macro 'badA' defined here
 }
 
 
 #define MIN(A,B) ((A) < (B) ? (A) : (B))// single ?:
 #define LIMIT(X,A,B) ((X) < (A) ? (A) : ((X) > (B) ? (B) : (X)))// two ?:
 void question(int x) {
   MIN(x++, 12);
-  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: side effects in the 1st macro argument 'A'
+  // CHECK-NOTES: :[[@LINE-1]]:7: warning: side effects in the 1st macro argument 'A'
+  // CHECK-NOTES: :[[@LINE-5]]:9: note: macro 'MIN' defined here
   MIN(34, x++);
-  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: side effects in the 2nd macro argument 'B'
+  // CHECK-NOTES: :[[@LINE-1]]:11: warning: side effects in the 2nd macro argument 'B'
+  // CHECK-NOTES: :[[@LINE-8]]:9: note: macro 'MIN' defined here
   LIMIT(x++, 0, 100);
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: side effects in the 1st macro argument 'X'
+  // CHECK-NOTES: :[[@LINE-1]]:9: warning: side effects in the 1st macro argument 'X'
+  // CHECK-NOTES: :[[@LINE-10]]:9: note: macro 'LIMIT' defined here
   LIMIT(20, x++, 100);
-  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: side effects in the 2nd macro argument 'A'
+  // CHECK-NOTES: :[[@LINE-1]]:13: warning: side effects in the 2nd macro argument 'A'
+  // CHECK-NOTES: :[[@LINE-13]]:9: note: macro 'LIMIT' defined here
   LIMIT(20, 0, x++);
-  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: side effects in the 3rd macro argument 'B'
+  // CHECK-NOTES: :[[@LINE-1]]:16: warning: side effects in the 3rd macro argument 'B'
+  // CHECK-NOTES: :[[@LINE-16]]:9: note: macro 'LIMIT' defined here
 }
 
 // False positive: Repeated side effects is intentional.
 // It is hard to know when it's done by intention so right now we warn.
 #define UNROLL(A){A A}
 void fp1(int i) {
   UNROLL({ i++; });
-  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: side effects in the 1st macro argument 'A'
+  // CHECK-NOTES: :[[@LINE-1]]:10: warning: side effects in the 1st macro argument 'A'
+  // 

[clang-tools-extra] r343001 - [clang-tidy] use CHECK-NOTES in tests for bugprone-macro-repeated-side-effects

2018-09-25 Thread Jonas Toth via cfe-commits
Author: jonastoth
Date: Tue Sep 25 11:15:52 2018
New Revision: 343001

URL: http://llvm.org/viewvc/llvm-project?rev=343001=rev
Log:
[clang-tidy] use CHECK-NOTES in tests for bugprone-macro-repeated-side-effects

Reviewers: alexfh, aaron.ballman, hokein

Reviewed By: alexfh

Subscribers: xazax.hun, cfe-commits

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

Modified:

clang-tools-extra/trunk/test/clang-tidy/bugprone-macro-repeated-side-effects.c

Modified: 
clang-tools-extra/trunk/test/clang-tidy/bugprone-macro-repeated-side-effects.c
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/bugprone-macro-repeated-side-effects.c?rev=343001=343000=343001=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/bugprone-macro-repeated-side-effects.c 
(original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/bugprone-macro-repeated-side-effects.c 
Tue Sep 25 11:15:52 2018
@@ -3,21 +3,29 @@
 #define badA(x,y)  ((x)+((x)+(y))+(y))
 void bad(int ret, int a, int b) {
   ret = badA(a++, b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: side effects in the 1st macro 
argument 'x' are repeated in macro expansion 
[bugprone-macro-repeated-side-effects]
+  // CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro 
argument 'x' are repeated in macro expansion 
[bugprone-macro-repeated-side-effects]
+  // CHECK-NOTES: :[[@LINE-4]]:9: note: macro 'badA' defined here
   ret = badA(++a, b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: side effects in the 1st macro 
argument 'x'
+  // CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro 
argument 'x'
+  // CHECK-NOTES: :[[@LINE-7]]:9: note: macro 'badA' defined here
   ret = badA(a--, b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: side effects in the 1st macro 
argument 'x'
+  // CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro 
argument 'x'
+  // CHECK-NOTES: :[[@LINE-10]]:9: note: macro 'badA' defined here
   ret = badA(--a, b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: side effects in the 1st macro 
argument 'x'
+  // CHECK-NOTES: :[[@LINE-1]]:14: warning: side effects in the 1st macro 
argument 'x'
+  // CHECK-NOTES: :[[@LINE-13]]:9: note: macro 'badA' defined here
   ret = badA(a, b++);
-  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro 
argument 'y'
+  // CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro 
argument 'y'
+  // CHECK-NOTES: :[[@LINE-16]]:9: note: macro 'badA' defined here
   ret = badA(a, ++b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro 
argument 'y'
+  // CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro 
argument 'y'
+  // CHECK-NOTES: :[[@LINE-19]]:9: note: macro 'badA' defined here
   ret = badA(a, b--);
-  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro 
argument 'y'
+  // CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro 
argument 'y'
+  // CHECK-NOTES: :[[@LINE-22]]:9: note: macro 'badA' defined here
   ret = badA(a, --b);
-  // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro 
argument 'y'
+  // CHECK-NOTES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro 
argument 'y'
+  // CHECK-NOTES: :[[@LINE-25]]:9: note: macro 'badA' defined here
 }
 
 
@@ -25,15 +33,20 @@ void bad(int ret, int a, int b) {
 #define LIMIT(X,A,B) ((X) < (A) ? (A) : ((X) > (B) ? (B) : (X)))// two ?:
 void question(int x) {
   MIN(x++, 12);
-  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: side effects in the 1st macro 
argument 'A'
+  // CHECK-NOTES: :[[@LINE-1]]:7: warning: side effects in the 1st macro 
argument 'A'
+  // CHECK-NOTES: :[[@LINE-5]]:9: note: macro 'MIN' defined here
   MIN(34, x++);
-  // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: side effects in the 2nd macro 
argument 'B'
+  // CHECK-NOTES: :[[@LINE-1]]:11: warning: side effects in the 2nd macro 
argument 'B'
+  // CHECK-NOTES: :[[@LINE-8]]:9: note: macro 'MIN' defined here
   LIMIT(x++, 0, 100);
-  // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: side effects in the 1st macro 
argument 'X'
+  // CHECK-NOTES: :[[@LINE-1]]:9: warning: side effects in the 1st macro 
argument 'X'
+  // CHECK-NOTES: :[[@LINE-10]]:9: note: macro 'LIMIT' defined here
   LIMIT(20, x++, 100);
-  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: side effects in the 2nd macro 
argument 'A'
+  // CHECK-NOTES: :[[@LINE-1]]:13: warning: side effects in the 2nd macro 
argument 'A'
+  // CHECK-NOTES: :[[@LINE-13]]:9: note: macro 'LIMIT' defined here
   LIMIT(20, 0, x++);
-  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: side effects in the 3rd macro 
argument 'B'
+  // CHECK-NOTES: :[[@LINE-1]]:16: warning: side effects in the 3rd macro 
argument 'B'
+  // CHECK-NOTES: :[[@LINE-16]]:9: note: macro 'LIMIT' defined here
 }
 
 // False positive: Repeated side effects is intentional.
@@ -41,7 +54,8 @@ void 

[PATCH] D52136: [clang-tidy] Add modernize-concat-nested-namespaces check

2018-09-25 Thread Jonas Toth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL343000: [clang-tidy] Add modernize-concat-nested-namespaces 
check (authored by JonasToth, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52136?vs=166945=166959#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52136

Files:
  clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
  clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
  clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.h
  clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
  clang-tools-extra/trunk/docs/ReleaseNotes.rst
  clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-concat-nested-namespaces.rst
  clang-tools-extra/trunk/test/clang-tidy/modernize-concat-nested-namespaces.cpp

Index: clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
===
--- clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
+++ clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
@@ -0,0 +1,113 @@
+//===--- ConcatNestedNamespacesCheck.cpp - clang-tidy--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "ConcatNestedNamespacesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include 
+#include 
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+static bool locationsInSameFile(const SourceManager ,
+SourceLocation Loc1, SourceLocation Loc2) {
+  return Loc1.isFileID() && Loc2.isFileID() &&
+ Sources.getFileID(Loc1) == Sources.getFileID(Loc2);
+}
+
+static bool anonymousOrInlineNamespace(const NamespaceDecl ) {
+  return ND.isAnonymousNamespace() || ND.isInlineNamespace();
+}
+
+static bool singleNamedNamespaceChild(const NamespaceDecl ) {
+  NamespaceDecl::decl_range Decls = ND.decls();
+  if (std::distance(Decls.begin(), Decls.end()) != 1)
+return false;
+
+  const auto *ChildNamespace = dyn_cast(*Decls.begin());
+  return ChildNamespace && !anonymousOrInlineNamespace(*ChildNamespace);
+}
+
+static bool alreadyConcatenated(std::size_t NumCandidates,
+const SourceRange ,
+const SourceManager ,
+const LangOptions ) {
+  CharSourceRange TextRange =
+  Lexer::getAsCharRange(ReplacementRange, Sources, LangOpts);
+  StringRef CurrentNamespacesText =
+  Lexer::getSourceText(TextRange, Sources, LangOpts);
+  return CurrentNamespacesText.count(':') == (NumCandidates - 1) * 2;
+}
+
+ConcatNestedNamespacesCheck::NamespaceString
+ConcatNestedNamespacesCheck::concatNamespaces() {
+  NamespaceString Result("namespace ");
+  Result.append(Namespaces.front()->getName());
+
+  std::for_each(std::next(Namespaces.begin()), Namespaces.end(),
+[](const NamespaceDecl *ND) {
+  Result.append("::");
+  Result.append(ND->getName());
+});
+
+  return Result;
+}
+
+void ConcatNestedNamespacesCheck::registerMatchers(
+ast_matchers::MatchFinder *Finder) {
+  if (!getLangOpts().CPlusPlus17)
+return;
+
+  Finder->addMatcher(ast_matchers::namespaceDecl().bind("namespace"), this);
+}
+
+void ConcatNestedNamespacesCheck::reportDiagnostic(
+const SourceRange , const SourceRange ) {
+  diag(Namespaces.front()->getBeginLoc(),
+   "nested namespaces can be concatenated", DiagnosticIDs::Warning)
+  << FixItHint::CreateReplacement(FrontReplacement, concatNamespaces())
+  << FixItHint::CreateReplacement(BackReplacement, "}");
+}
+
+void ConcatNestedNamespacesCheck::check(
+const ast_matchers::MatchFinder::MatchResult ) {
+  const NamespaceDecl  = *Result.Nodes.getNodeAs("namespace");
+  const SourceManager  = *Result.SourceManager;
+
+  if (!locationsInSameFile(Sources, ND.getBeginLoc(), ND.getRBraceLoc()))
+return;
+
+  if (!Sources.isInMainFile(ND.getBeginLoc()))
+return;
+
+  if (anonymousOrInlineNamespace(ND))
+return;
+
+  Namespaces.push_back();
+
+  if (singleNamedNamespaceChild(ND))
+return;
+
+  SourceRange FrontReplacement(Namespaces.front()->getBeginLoc(),
+   Namespaces.back()->getLocation());
+  SourceRange BackReplacement(Namespaces.back()->getRBraceLoc(),
+  Namespaces.front()->getRBraceLoc());
+
+  if (!alreadyConcatenated(Namespaces.size(), FrontReplacement, Sources,
+   getLangOpts()))
+reportDiagnostic(FrontReplacement, 

[PATCH] D52136: [clang-tidy] Add modernize-concat-nested-namespaces check

2018-09-25 Thread Jonas Toth via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE343000: [clang-tidy] Add 
modernize-concat-nested-namespaces check (authored by JonasToth, committed by ).

Repository:
  rL LLVM

https://reviews.llvm.org/D52136

Files:
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
  clang-tidy/modernize/ConcatNestedNamespacesCheck.h
  clang-tidy/modernize/ModernizeTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-concat-nested-namespaces.rst
  test/clang-tidy/modernize-concat-nested-namespaces.cpp

Index: test/clang-tidy/modernize-concat-nested-namespaces.cpp
===
--- test/clang-tidy/modernize-concat-nested-namespaces.cpp
+++ test/clang-tidy/modernize-concat-nested-namespaces.cpp
@@ -0,0 +1,161 @@
+// RUN: %check_clang_tidy %s modernize-concat-nested-namespaces %t -- -- -std=c++17
+
+namespace n1 {}
+
+namespace n2 {
+namespace n3 {
+void t();
+}
+namespace n4 {
+void t();
+}
+} // namespace n2
+
+namespace n5 {
+inline namespace n6 {
+void t();
+}
+} // namespace n5
+
+namespace n7 {
+void t();
+
+namespace n8 {
+void t();
+}
+} // namespace n7
+
+namespace n9 {
+namespace n10 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n9::n10
+void t();
+} // namespace n10
+} // namespace n9
+// CHECK-FIXES: }
+
+namespace n11 {
+namespace n12 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n11::n12
+namespace n13 {
+void t();
+}
+namespace n14 {
+void t();
+}
+} // namespace n12
+} // namespace n11
+// CHECK-FIXES: }
+
+namespace n15 {
+namespace n16 {
+void t();
+}
+
+inline namespace n17 {
+void t();
+}
+
+namespace n18 {
+namespace n19 {
+namespace n20 {
+// CHECK-MESSAGES: :[[@LINE-3]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n18::n19::n20
+void t();
+} // namespace n20
+} // namespace n19
+} // namespace n18
+// CHECK-FIXES: }
+
+namespace n21 {
+void t();
+}
+} // namespace n15
+
+namespace n22 {
+namespace {
+void t();
+}
+} // namespace n22
+
+namespace n23 {
+namespace {
+namespace n24 {
+namespace n25 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n24::n25
+void t();
+} // namespace n25
+} // namespace n24
+// CHECK-FIXES: }
+} // namespace
+} // namespace n23
+
+namespace n26::n27 {
+namespace n28 {
+namespace n29::n30 {
+// CHECK-MESSAGES: :[[@LINE-3]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n26::n27::n28::n29::n30
+void t() {}
+} // namespace n29::n30
+} // namespace n28
+} // namespace n26::n27
+// CHECK-FIXES: }
+
+namespace n31 {
+namespace n32 {}
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+} // namespace n31
+// CHECK-FIXES-EMPTY
+
+namespace n33 {
+namespace n34 {
+namespace n35 {}
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+} // namespace n34
+// CHECK-FIXES-EMPTY
+namespace n36 {
+void t();
+}
+} // namespace n33
+
+namespace n37::n38 {
+void t();
+}
+
+#define IEXIST
+namespace n39 {
+namespace n40 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n39::n40
+#ifdef IEXIST
+void t() {}
+#endif
+} // namespace n40
+} // namespace n39
+// CHECK-FIXES: }
+
+namespace n41 {
+namespace n42 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n41::n42
+#ifdef IDONTEXIST
+void t() {}
+#endif
+} // namespace n42
+} // namespace n41
+// CHECK-FIXES: }
+
+int main() {
+  n26::n27::n28::n29::n30::t();
+#ifdef IEXIST
+  n39::n40::t();
+#endif
+
+#ifdef IDONTEXIST
+  n41::n42::t();
+#endif
+
+  return 0;
+}
Index: clang-tidy/modernize/CMakeLists.txt
===
--- clang-tidy/modernize/CMakeLists.txt
+++ clang-tidy/modernize/CMakeLists.txt
@@ -2,6 +2,7 @@
 
 add_clang_library(clangTidyModernizeModule
   AvoidBindCheck.cpp
+  ConcatNestedNamespacesCheck.cpp
   DeprecatedHeadersCheck.cpp
   LoopConvertCheck.cpp
   LoopConvertUtils.cpp
Index: clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
===
--- clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
+++ clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
@@ -0,0 +1,113 @@
+//===--- ConcatNestedNamespacesCheck.cpp - clang-tidy--===//
+//

[PATCH] D52136: [clang-tidy] Add modernize-concat-nested-namespaces check

2018-09-25 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth added a comment.

Commited for you.


https://reviews.llvm.org/D52136



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


[clang-tools-extra] r343000 - [clang-tidy] Add modernize-concat-nested-namespaces check

2018-09-25 Thread Jonas Toth via cfe-commits
Author: jonastoth
Date: Tue Sep 25 11:12:28 2018
New Revision: 343000

URL: http://llvm.org/viewvc/llvm-project?rev=343000=rev
Log:
[clang-tidy] Add modernize-concat-nested-namespaces check

Summary:
Finds instances of namespaces concatenated using explicit syntax, such as 
`namespace a { namespace b { [...] }}` and offers fix to glue it to `namespace 
a::b { [...] }`.

Properly handles `inline` and unnamed namespaces. ~~Also, detects empty blocks 
in nested namespaces and offers to remove them.~~

Test with common use cases included.
I ran the check against entire llvm repository. Except for expected `nested 
namespace definitions only available with -std=c++17 or -std=gnu++17` warnings 
I noticed no issues when the check was performed.

Example:
```
namespace a { namespace b {
void test();
}}

```
can become
```
namespace a::b {
void test();
}
```

Patch by wgml!

Reviewers: alexfh, aaron.ballman, hokein

Reviewed By: aaron.ballman

Subscribers: JonasToth, Eugene.Zelenko, lebedev.ri, mgorny, xazax.hun, 
cfe-commits

Tags: #clang-tools-extra

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

Added:
clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.h

clang-tools-extra/trunk/docs/clang-tidy/checks/modernize-concat-nested-namespaces.rst

clang-tools-extra/trunk/test/clang-tidy/modernize-concat-nested-namespaces.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/modernize/ModernizeTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt?rev=343000=342999=343000=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/CMakeLists.txt Tue Sep 25 
11:12:28 2018
@@ -2,6 +2,7 @@ set(LLVM_LINK_COMPONENTS support)
 
 add_clang_library(clangTidyModernizeModule
   AvoidBindCheck.cpp
+  ConcatNestedNamespacesCheck.cpp
   DeprecatedHeadersCheck.cpp
   LoopConvertCheck.cpp
   LoopConvertUtils.cpp

Added: 
clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp?rev=343000=auto
==
--- 
clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp 
(added)
+++ 
clang-tools-extra/trunk/clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp 
Tue Sep 25 11:12:28 2018
@@ -0,0 +1,113 @@
+//===--- ConcatNestedNamespacesCheck.cpp - 
clang-tidy--===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "ConcatNestedNamespacesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include 
+#include 
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+static bool locationsInSameFile(const SourceManager ,
+SourceLocation Loc1, SourceLocation Loc2) {
+  return Loc1.isFileID() && Loc2.isFileID() &&
+ Sources.getFileID(Loc1) == Sources.getFileID(Loc2);
+}
+
+static bool anonymousOrInlineNamespace(const NamespaceDecl ) {
+  return ND.isAnonymousNamespace() || ND.isInlineNamespace();
+}
+
+static bool singleNamedNamespaceChild(const NamespaceDecl ) {
+  NamespaceDecl::decl_range Decls = ND.decls();
+  if (std::distance(Decls.begin(), Decls.end()) != 1)
+return false;
+
+  const auto *ChildNamespace = dyn_cast(*Decls.begin());
+  return ChildNamespace && !anonymousOrInlineNamespace(*ChildNamespace);
+}
+
+static bool alreadyConcatenated(std::size_t NumCandidates,
+const SourceRange ,
+const SourceManager ,
+const LangOptions ) {
+  CharSourceRange TextRange =
+  Lexer::getAsCharRange(ReplacementRange, Sources, LangOpts);
+  StringRef CurrentNamespacesText =
+  Lexer::getSourceText(TextRange, Sources, LangOpts);
+  return CurrentNamespacesText.count(':') == (NumCandidates - 1) * 2;
+}
+
+ConcatNestedNamespacesCheck::NamespaceString
+ConcatNestedNamespacesCheck::concatNamespaces() {
+  NamespaceString Result("namespace ");
+  Result.append(Namespaces.front()->getName());
+
+  std::for_each(std::next(Namespaces.begin()), Namespaces.end(),
+[](const NamespaceDecl *ND) {
+  

[PATCH] D52503: [clangd] More precise index memory usage estimate

2018-09-25 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clang-tools-extra/clangd/index/dex/Dex.cpp:251
   Bytes += InvertedIndex.getMemorySize();
-  for (const auto  : InvertedIndex)
-Bytes += P.second.bytes();
+  for (const auto  : InvertedIndex)
+Bytes += TokenToPostingList.first.Data.size() +

kbobyrev wrote:
> ioeric wrote:
> > Would `InvertedIndex.getMemorySize()` be a better estimate?
> IIUC this is only precise for the objects which do not make any allocations 
> (e.g. `std::vector` and `std::string` memory estimate would not be "correct").
> 
> From the documentation
> 
> > This is just the raw memory used by DenseMap. If entries are pointers to 
> > objects, the size of the referenced objects are not included.
> 
> I also have `Bytes += InvertedIndex.getMemorySize();` above, so the purpose 
> of this code would be to take into account the size of these "reference 
> objects".
> 
> However, since `PostingList::bytes()` also returns underlying `std::vector` 
> size, this code will probably add these `std::vector` objects size twice (the 
> first one was in `InvertedIndex.getMemorySize()`). I should fix that.
> `If entries are pointers to objects, the size of the referenced objects are 
> not included.`
This applies to *pointers* to objects, but the `PostingList`s in InvertedList 
are not pointerd? So it seems to me that `InvertedIndex.getMemorySize()` covers 
everything in the `InvertedIndex`. One way to verify is probably check the size 
calculated with loop against `InvertedIndex.getMemorySize()`.


https://reviews.llvm.org/D52503



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


[PATCH] D52453: [clangd] Merge binary + YAML serialization behind a (mostly) common interface.

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rCTE342999: [clangd] Merge binary + YAML serialization behind 
a (mostly) common interface. (authored by sammccall, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52453?vs=166828=166956#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52453

Files:
  clangd/CMakeLists.txt
  clangd/benchmarks/IndexBenchmark.cpp
  clangd/index/Serialization.cpp
  clangd/index/Serialization.h
  clangd/index/SymbolYAML.cpp
  clangd/index/SymbolYAML.h
  clangd/index/YAMLSerialization.cpp
  clangd/index/dex/dexp/Dexp.cpp
  clangd/indexer/IndexerMain.cpp
  clangd/tool/ClangdMain.cpp
  unittests/clangd/SerializationTests.cpp
  unittests/clangd/SymbolCollectorTests.cpp

Index: clangd/CMakeLists.txt
===
--- clangd/CMakeLists.txt
+++ clangd/CMakeLists.txt
@@ -44,7 +44,7 @@
   index/Merge.cpp
   index/Serialization.cpp
   index/SymbolCollector.cpp
-  index/SymbolYAML.cpp
+  index/YAMLSerialization.cpp
 
   index/dex/Dex.cpp
   index/dex/Iterator.cpp
Index: clangd/index/YAMLSerialization.cpp
===
--- clangd/index/YAMLSerialization.cpp
+++ clangd/index/YAMLSerialization.cpp
@@ -0,0 +1,230 @@
+//===--- SymbolYAML.cpp --*- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "Index.h"
+#include "Serialization.h"
+#include "Trace.h"
+#include "dex/Dex.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Errc.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/YAMLTraits.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+
+LLVM_YAML_IS_SEQUENCE_VECTOR(clang::clangd::Symbol::IncludeHeaderWithReferences)
+
+namespace llvm {
+namespace yaml {
+
+using clang::clangd::Symbol;
+using clang::clangd::SymbolID;
+using clang::clangd::SymbolLocation;
+using clang::clangd::SymbolOrigin;
+using clang::index::SymbolInfo;
+using clang::index::SymbolKind;
+using clang::index::SymbolLanguage;
+
+// Helper to (de)serialize the SymbolID. We serialize it as a hex string.
+struct NormalizedSymbolID {
+  NormalizedSymbolID(IO &) {}
+  NormalizedSymbolID(IO &, const SymbolID ) {
+llvm::raw_string_ostream OS(HexString);
+OS << ID;
+  }
+
+  SymbolID denormalize(IO ) {
+auto ID = SymbolID::fromStr(HexString);
+if (!ID) {
+  I.setError(llvm::toString(ID.takeError()));
+  return SymbolID();
+}
+return *ID;
+  }
+
+  std::string HexString;
+};
+
+struct NormalizedSymbolFlag {
+  NormalizedSymbolFlag(IO &) {}
+  NormalizedSymbolFlag(IO &, Symbol::SymbolFlag F) {
+Flag = static_cast(F);
+  }
+
+  Symbol::SymbolFlag denormalize(IO &) {
+return static_cast(Flag);
+  }
+
+  uint8_t Flag = 0;
+};
+
+struct NormalizedSymbolOrigin {
+  NormalizedSymbolOrigin(IO &) {}
+  NormalizedSymbolOrigin(IO &, SymbolOrigin O) {
+Origin = static_cast(O);
+  }
+
+  SymbolOrigin denormalize(IO &) { return static_cast(Origin); }
+
+  uint8_t Origin = 0;
+};
+
+template <> struct MappingTraits {
+  static void mapping(IO , SymbolLocation::Position ) {
+IO.mapRequired("Line", Value.Line);
+IO.mapRequired("Column", Value.Column);
+  }
+};
+
+template <> struct MappingTraits {
+  static void mapping(IO , SymbolLocation ) {
+IO.mapRequired("FileURI", Value.FileURI);
+IO.mapRequired("Start", Value.Start);
+IO.mapRequired("End", Value.End);
+  }
+};
+
+template <> struct MappingTraits {
+  static void mapping(IO , SymbolInfo ) {
+// FIXME: expose other fields?
+io.mapRequired("Kind", SymInfo.Kind);
+io.mapRequired("Lang", SymInfo.Lang);
+  }
+};
+
+template <>
+struct MappingTraits {
+  static void mapping(IO ,
+  clang::clangd::Symbol::IncludeHeaderWithReferences ) {
+io.mapRequired("Header", Inc.IncludeHeader);
+io.mapRequired("References", Inc.References);
+  }
+};
+
+template <> struct MappingTraits {
+  static void mapping(IO , Symbol ) {
+MappingNormalization NSymbolID(IO, Sym.ID);
+MappingNormalization NSymbolFlag(
+IO, Sym.Flags);
+MappingNormalization NSymbolOrigin(
+IO, Sym.Origin);
+IO.mapRequired("ID", NSymbolID->HexString);
+IO.mapRequired("Name", Sym.Name);
+IO.mapRequired("Scope", Sym.Scope);
+IO.mapRequired("SymInfo", Sym.SymInfo);
+IO.mapOptional("CanonicalDeclaration", Sym.CanonicalDeclaration,
+   SymbolLocation());
+IO.mapOptional("Definition", Sym.Definition, SymbolLocation());
+IO.mapOptional("References", Sym.References, 0u);
+IO.mapOptional("Origin", NSymbolOrigin->Origin);
+IO.mapOptional("Flags", NSymbolFlag->Flag);
+   

[PATCH] D50294: [Driver] Use -gdwarf-3 by default for FreeBSD

2018-09-25 Thread Ed Maste via Phabricator via cfe-commits
emaste added a comment.

I'm using this change: 
https://github.com/emaste/freebsd/commit/1c3deab6d518feb1a7e88de5b342a139e4022a21

In FreeBSD 12 and later we use Clang, lld, and ELF Tool Chain. (We still have 
gas and objdump from the outdated binutils 2.17.50.)


Repository:
  rC Clang

https://reviews.llvm.org/D50294



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


[PATCH] D52453: [clangd] Merge binary + YAML serialization behind a (mostly) common interface.

2018-09-25 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL342999: [clangd] Merge binary + YAML serialization behind a 
(mostly) common interface. (authored by sammccall, committed by ).
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D52453?vs=166828=166957#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D52453

Files:
  clang-tools-extra/trunk/clangd/CMakeLists.txt
  clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp
  clang-tools-extra/trunk/clangd/index/Serialization.cpp
  clang-tools-extra/trunk/clangd/index/Serialization.h
  clang-tools-extra/trunk/clangd/index/SymbolYAML.cpp
  clang-tools-extra/trunk/clangd/index/SymbolYAML.h
  clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
  clang-tools-extra/trunk/clangd/index/dex/dexp/Dexp.cpp
  clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp
  clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
  clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
  clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp

Index: clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
===
--- clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
+++ clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
@@ -9,18 +9,18 @@
 
 #include "index/Index.h"
 #include "index/Serialization.h"
-#include "index/SymbolYAML.h"
 #include "llvm/Support/ScopedPrinter.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
+using testing::AllOf;
 using testing::UnorderedElementsAre;
 using testing::UnorderedElementsAreArray;
 namespace clang {
 namespace clangd {
 namespace {
 
-const char *YAML1 = R"(
+const char *YAML = R"(
 ---
 ID: 057557CEBF6E6B2DD437FBF60CC58F352D1DF856
 Name:   'Foo1'
@@ -46,9 +46,6 @@
   - Header:'include2'
 References:3
 ...
-)";
-
-const char *YAML2 = R"(
 ---
 ID: 057557CEBF6E6B2DD437FBF60CC58F352D1DF858
 Name:   'Foo2'
@@ -70,15 +67,29 @@
 ...
 )";
 
+MATCHER_P(ID, I, "") { return arg.ID == cantFail(SymbolID::fromStr(I)); }
 MATCHER_P(QName, Name, "") { return (arg.Scope + arg.Name).str() == Name; }
 MATCHER_P2(IncludeHeaderWithRef, IncludeHeader, References, "") {
   return (arg.IncludeHeader == IncludeHeader) && (arg.References == References);
 }
 
 TEST(SerializationTest, YAMLConversions) {
-  auto Symbols1 = symbolsFromYAML(YAML1);
-  ASSERT_EQ(Symbols1.size(), 1u);
-  const auto  = *Symbols1.begin();
+  auto In = readIndexFile(YAML);
+  EXPECT_TRUE(bool(In)) << In.takeError();
+
+  auto ParsedYAML = readIndexFile(YAML);
+  ASSERT_TRUE(bool(ParsedYAML)) << ParsedYAML.takeError();
+  ASSERT_TRUE(bool(ParsedYAML->Symbols));
+  EXPECT_THAT(
+  *ParsedYAML->Symbols,
+  UnorderedElementsAre(ID("057557CEBF6E6B2DD437FBF60CC58F352D1DF856"),
+   ID("057557CEBF6E6B2DD437FBF60CC58F352D1DF858")));
+
+  auto Sym1 = *ParsedYAML->Symbols->find(
+  cantFail(SymbolID::fromStr("057557CEBF6E6B2DD437FBF60CC58F352D1DF856")));
+  auto Sym2 = *ParsedYAML->Symbols->find(
+  cantFail(SymbolID::fromStr("057557CEBF6E6B2DD437FBF60CC58F352D1DF858")));
+
   EXPECT_THAT(Sym1, QName("clang::Foo1"));
   EXPECT_EQ(Sym1.Signature, "");
   EXPECT_EQ(Sym1.Documentation, "Foo doc");
@@ -91,51 +102,38 @@
   UnorderedElementsAre(IncludeHeaderWithRef("include1", 7u),
IncludeHeaderWithRef("include2", 3u)));
 
-  auto Symbols2 = symbolsFromYAML(YAML2);
-  ASSERT_EQ(Symbols2.size(), 1u);
-  const auto  = *Symbols2.begin();
   EXPECT_THAT(Sym2, QName("clang::Foo2"));
   EXPECT_EQ(Sym2.Signature, "-sig");
   EXPECT_EQ(Sym2.ReturnType, "");
   EXPECT_EQ(Sym2.CanonicalDeclaration.FileURI, "file:///path/bar.h");
   EXPECT_FALSE(Sym2.Flags & Symbol::IndexedForCodeCompletion);
   EXPECT_TRUE(Sym2.Flags & Symbol::Deprecated);
-
-  std::string ConcatenatedYAML;
-  {
-llvm::raw_string_ostream OS(ConcatenatedYAML);
-SymbolsToYAML(Symbols1, OS);
-SymbolsToYAML(Symbols2, OS);
-  }
-  auto ConcatenatedSymbols = symbolsFromYAML(ConcatenatedYAML);
-  EXPECT_THAT(ConcatenatedSymbols,
-  UnorderedElementsAre(QName("clang::Foo1"), QName("clang::Foo2")));
 }
 
 std::vector YAMLFromSymbols(const SymbolSlab ) {
   std::vector Result;
   for (const auto  : Slab)
-Result.push_back(SymbolToYAML(Sym));
+Result.push_back(toYAML(Sym));
   return Result;
 }
 
 TEST(SerializationTest, BinaryConversions) {
-  // We reuse the test symbols from YAML.
-  auto Slab = symbolsFromYAML(std::string(YAML1) + YAML2);
-  ASSERT_EQ(Slab.size(), 2u);
+  auto In = readIndexFile(YAML);
+  EXPECT_TRUE(bool(In)) << In.takeError();
 
   // Write to binary format, and parse again.
   IndexFileOut Out;
-  Out.Symbols = 
+  Out.Symbols = In->Symbols.getPointer();
+  Out.Format = IndexFileFormat::RIFF;
   std::string Serialized = llvm::to_string(Out);
 
-  auto In = readIndexFile(Serialized);
-  

[clang-tools-extra] r342999 - [clangd] Merge binary + YAML serialization behind a (mostly) common interface.

2018-09-25 Thread Sam McCall via cfe-commits
Author: sammccall
Date: Tue Sep 25 11:06:43 2018
New Revision: 342999

URL: http://llvm.org/viewvc/llvm-project?rev=342999=rev
Log:
[clangd] Merge binary + YAML serialization behind a (mostly) common interface.

Summary:
Interface is in one file, implementation in two as they have little in common.
A couple of ad-hoc YAML functions left exposed:
 - symbol -> YAML I expect to keep for tools like dexp
 - YAML -> symbol is used for the MR-style indexer, I think we can eliminate
   this (merge-on-the-fly, else use a different serialization)

Reviewers: kbobyrev

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

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

Added:
clang-tools-extra/trunk/clangd/index/YAMLSerialization.cpp
  - copied, changed from r342974, 
clang-tools-extra/trunk/clangd/index/SymbolYAML.cpp
Removed:
clang-tools-extra/trunk/clangd/index/SymbolYAML.cpp
clang-tools-extra/trunk/clangd/index/SymbolYAML.h
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp
clang-tools-extra/trunk/clangd/index/Serialization.cpp
clang-tools-extra/trunk/clangd/index/Serialization.h
clang-tools-extra/trunk/clangd/index/dex/dexp/Dexp.cpp
clang-tools-extra/trunk/clangd/indexer/IndexerMain.cpp
clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
clang-tools-extra/trunk/unittests/clangd/SymbolCollectorTests.cpp

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=342999=342998=342999=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Tue Sep 25 11:06:43 2018
@@ -44,7 +44,7 @@ add_clang_library(clangDaemon
   index/Merge.cpp
   index/Serialization.cpp
   index/SymbolCollector.cpp
-  index/SymbolYAML.cpp
+  index/YAMLSerialization.cpp
 
   index/dex/Dex.cpp
   index/dex/Iterator.cpp

Modified: clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp?rev=342999=342998=342999=diff
==
--- clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp (original)
+++ clang-tools-extra/trunk/clangd/benchmarks/IndexBenchmark.cpp Tue Sep 25 
11:06:43 2018
@@ -7,7 +7,7 @@
 //
 
//===--===//
 
-#include "../index/SymbolYAML.h"
+#include "../index/Serialization.h"
 #include "../index/dex/Dex.h"
 #include "benchmark/benchmark.h"
 #include "llvm/ADT/SmallVector.h"

Modified: clang-tools-extra/trunk/clangd/index/Serialization.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Serialization.cpp?rev=342999=342998=342999=diff
==
--- clang-tools-extra/trunk/clangd/index/Serialization.cpp (original)
+++ clang-tools-extra/trunk/clangd/index/Serialization.cpp Tue Sep 25 11:06:43 
2018
@@ -9,6 +9,8 @@
 #include "Serialization.h"
 #include "Index.h"
 #include "RIFF.h"
+#include "Trace.h"
+#include "dex/Dex.h"
 #include "llvm/Support/Compression.h"
 #include "llvm/Support/Endian.h"
 #include "llvm/Support/Error.h"
@@ -294,8 +296,6 @@ Symbol readSymbol(Reader , ArrayRef
   return Sym;
 }
 
-} // namespace
-
 // FILE ENCODING
 // A file is a RIFF chunk with type 'CdIx'.
 // It contains the sections:
@@ -308,7 +308,7 @@ Symbol readSymbol(Reader , ArrayRef
 // data. Later we may want to support some backward compatibility.
 constexpr static uint32_t Version = 4;
 
-Expected readIndexFile(StringRef Data) {
+Expected readRIFF(StringRef Data) {
   auto RIFF = riff::readFile(Data);
   if (!RIFF)
 return RIFF.takeError();
@@ -343,7 +343,7 @@ Expected readIndexFile(Stri
   return std::move(Result);
 }
 
-raw_ostream <<(raw_ostream , const IndexFileOut ) {
+void writeRIFF(const IndexFileOut , raw_ostream ) {
   assert(Data.Symbols && "An index file without symbols makes no sense!");
   riff::File RIFF;
   RIFF.Type = riff::fourCC("CdIx");
@@ -377,7 +377,64 @@ raw_ostream <<(raw_ostream ,
   }
   RIFF.Chunks.push_back({riff::fourCC("symb"), SymbolSection});
 
-  return OS << RIFF;
+  OS << RIFF;
+}
+
+} // namespace
+
+// Defined in YAMLSerialization.cpp.
+void writeYAML(const IndexFileOut &, raw_ostream &);
+Expected readYAML(StringRef);
+
+llvm::raw_ostream <<(llvm::raw_ostream , const IndexFileOut ) {
+  switch (O.Format) {
+  case IndexFileFormat::RIFF:
+writeYAML(O, OS);
+break;
+  case IndexFileFormat::YAML:
+writeRIFF(O, OS);
+break;
+  }
+  return OS;
+}
+
+Expected readIndexFile(StringRef Data) {
+  if 

[PATCH] D52286: [Intrinsic] Signed Saturation Intirnsic

2018-09-25 Thread Leonard Chan via Phabricator via cfe-commits
leonardchan added inline comments.



Comment at: lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:1119
+  case ISD::SSAT:
+// Target legalization checked here?
+Action = TargetLowering::Expand;

ebevhan wrote:
> leonardchan wrote:
> > ebevhan wrote:
> > > leonardchan wrote:
> > > > @ebevhan Do you know if this is where checking if this intrinsic is 
> > > > supported by the target should be? 
> > > Yes, this would be it. For nodes like ssat and fixed-point ops, you could 
> > > ask a custom target hook, maybe `TLI.getScaledOperationAction(, 
> > > , )` to determine the legality of a given node.
> > > 
> > > When type-legalizing you also need to handle things for specific nodes as 
> > > well, since things behave differently when you legalize operands/results 
> > > on different nodes.
> > > 
> > > (Of course, this all depends on whether we do the legalization here or in 
> > > IR instead.)
> > Made the default action `Expand` for this in `TargetLoweringBase` and 
> > targets can override this themselves.
> > 
> > I think ssat may not need a custom hook since I don't think it requires 
> > anything extra like fixsmul if it has to be expanded. But I see what you 
> > mean now by how different nodes may require different steps for 
> > legalization.
> You don't need an extra hook to determine anything extra for expansion, but 
> you do need the hook to determine if it's legal in the first place. As I 
> mentioned in another comment, an i16 ssat with a saturating width of 8 might 
> be legal, but an i16 ssat with saturating width 12 might not. The former must 
> not be expanded, but the latter must.
Got it. Just to clarify though, legalizations regarding the scale would only 
apply for our mul/div intrinsics right? Operations like saturation and sat 
add/sub which don't care about the scale do not need this hook right, since it 
would also be useful for these operations to work on regular integers?


Repository:
  rL LLVM

https://reviews.llvm.org/D52286



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


r342996 - [OPENMP] Fix the test, NFC.

2018-09-25 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Sep 25 10:58:08 2018
New Revision: 342996

URL: http://llvm.org/viewvc/llvm-project?rev=342996=rev
Log:
[OPENMP] Fix the test, NFC.

Fixed test to pacify buildbot.

Modified:
cfe/trunk/test/Driver/openmp-offload.c

Modified: cfe/trunk/test/Driver/openmp-offload.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/openmp-offload.c?rev=342996=342995=342996=diff
==
--- cfe/trunk/test/Driver/openmp-offload.c (original)
+++ cfe/trunk/test/Driver/openmp-offload.c Tue Sep 25 10:58:08 2018
@@ -358,7 +358,7 @@
 /// ###
 
 /// Check separate compilation with offloading - bundling actions
-// RUN:   %clang -### -ccc-print-phases -fopenmp=libomp -c -o %t.o  
Input/in.so -lsomelib -target powerpc64le-linux 
-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s 
-no-canonical-prefixes 2>&1 \
+// RUN:   %clang -### -ccc-print-phases -fopenmp=libomp -c -o %t.o  
%S/Input/in.so -lsomelib -target powerpc64le-linux 
-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s 
-no-canonical-prefixes 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-BUACTIONS %s
 
 // CHK-BUACTIONS: 0: input, "[[INPUT:.+\.c]]", c, (host-openmp)
@@ -500,7 +500,7 @@
 // RUN:   touch %t.o
 // RUN:   %clang -###  -fopenmp=libomp -o %t.out -lsomelib -target 
powerpc64le-linux 
-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.o 
-no-canonical-prefixes 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-UBJOBS2 %s
-// RUN:   %clang -### -fopenmp=libomp -o %t.out -lsomelib -target 
powerpc64le-linux 
-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.o 
%S/Inputs/in.so -save-temps -no-canonical-prefixes 2>&1 \
+// RUN:   %clang -### -fopenmp=libomp -o %t.out -lsomelib -target 
powerpc64le-linux 
-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %t.o -save-temps 
-no-canonical-prefixes 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-UBJOBS2-ST %s
 
 // Unbundle and create host BC.
@@ -579,7 +579,6 @@
 // CHK-UBJOBS2-ST-SAME: [[HOSTOBJ:[^\\/,]+\.o]],
 // CHK-UBJOBS2-ST-SAME: [[T1OBJ:[^\\/,]+\.o]],
 // CHK-UBJOBS2-ST-SAME: [[T2OBJ:[^\\/,]+\.o]]" "-unbundle"
-// CHK-UBJOBS2-ST-NOT: clang-offload-bundler{{.*}}in.so
 // CHK-UBJOBS2-ST: ld{{(\.exe)?}}" {{.*}}"-o" "
 // CHK-UBJOBS2-ST-SAME: 
[[T1BIN:[^\\/]+\.out-openmp-powerpc64le-ibm-linux-gnu]]" {{.*}}"{{.*}}[[T1OBJ]]"
 // CHK-UBJOBS2-ST: ld{{(\.exe)?}}" {{.*}}"-o" "


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


[PATCH] D52419: [clangd] Cache FS stat() calls when building preamble.

2018-09-25 Thread Eric Liu via Phabricator via cfe-commits
ioeric added a comment.

Thanks for the reviews!




Comment at: clangd/ClangdUnit.cpp:155
+auto S = FS->status(Path);
+if (S)
+  cacheStatus(*S);

sammccall wrote:
> why are you only caching success?
I had a comment in `openFileForRead`:
```
// Only cache stats for files that exist because, unlike building preamble,
// we only care about existing files when reusing preamble.
```

Another reason is that we are using the file name in the Status as the cache 
key.



Comment at: clangd/ClangdUnit.cpp:339
+llvm::ErrorOr status(const Twine ) override {
+  auto I = StatCache.find(Path.str());
+  return (I != StatCache.end()) ? I->getValue() : FS->status(Path);

ilya-biryukov wrote:
> We store absolute paths, but Path can be relative here.
This is because preamble stores absolute paths. `Path` should be an path from 
preamble. Added documentation.



Comment at: clangd/CodeComplete.cpp:1028
 
+  IntrusiveRefCntPtr VFS = Input.VFS;
+  if (Input.PreambleStatCache)

ilya-biryukov wrote:
> It feels like we could apply this caching one level higher, on the 
> TUScheduler level when creating the filesystem. It makes sense not only for 
> code completion, but also for all other features, including rebuilds of ASTs 
> that were washed out of the cache.
> WDYT?
It sounds like a reasonable thing to do. I took a quick look, and it seemed 
that this would probably require some refactoring/redesign on TUScheduler - it 
doesn't know about the VFS?

I think it shouldn't be hard to do this case by case. For example, code 
completion and signature help will be covered in this patch. And it should be 
pretty easy to make AST rebuild use the cache as well?



Comment at: clangd/CodeComplete.h:217
+CodeCompleteResult codeComplete(PathRef FileName, Position Pos,
+const InputsAndPreamble ,
 IntrusiveRefCntPtr VFS,

sammccall wrote:
> ilya-biryukov wrote:
> > We should not be depending `TUScheduler.h`, I suggest to pass 
> > `PreambleData`instead of `PrecompiledPreamble` instead.
> > 
> > Depending on `TUScheduler.h` our layering  in clangd: low-level 
> > implementation of features should not depend on higher-level building 
> > blocks like TUScheduler.
> +1. We're maybe not doing the best job of header encapsulation here, but 
> InputsAndPreamble is an implementation detail of ClangdServer.
I thought `InputsAndPreamble` was a pretty natural fit here, but I guess I 
hadn't understand the abstractions well enough. Thanks for the explanation!


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52419



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


[PATCH] D52419: [clangd] Cache FS stat() calls when building preamble.

2018-09-25 Thread Eric Liu via Phabricator via cfe-commits
ioeric updated this revision to Diff 166951.
ioeric marked 10 inline comments as done.
ioeric added a comment.
Herald added a subscriber: mgorny.

- Address review comments


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52419

Files:
  clangd/CMakeLists.txt
  clangd/ClangdServer.cpp
  clangd/ClangdUnit.cpp
  clangd/ClangdUnit.h
  clangd/CodeComplete.cpp
  clangd/CodeComplete.h
  clangd/FS.cpp
  clangd/FS.h
  unittests/clangd/ClangdTests.cpp

Index: unittests/clangd/ClangdTests.cpp
===
--- unittests/clangd/ClangdTests.cpp
+++ unittests/clangd/ClangdTests.cpp
@@ -963,6 +963,67 @@
Field(::Name, "baz")));
 }
 
+TEST(ClangdTests, PreambleVFSStatCache) {
+  class ListenStatsFSProvider : public FileSystemProvider {
+  public:
+ListenStatsFSProvider(llvm::StringMap )
+: CountStats(CountStats) {}
+
+IntrusiveRefCntPtr getFileSystem() override {
+  class ListenStatVFS : public vfs::ProxyFileSystem {
+  public:
+ListenStatVFS(IntrusiveRefCntPtr FS,
+  llvm::StringMap )
+: ProxyFileSystem(std::move(FS)), CountStats(CountStats) {}
+
+llvm::ErrorOr status(const Twine ) override {
+  auto I =
+  CountStats.try_emplace(llvm::sys::path::filename(Path.str()), 1);
+  if (!I.second)
+I.first->second += 1;
+  return getUnderlyingFS().status(Path);
+}
+
+  private:
+llvm::StringMap 
+  };
+
+  return IntrusiveRefCntPtr(
+  new ListenStatVFS(buildTestFS(Files), CountStats));
+}
+
+// If relative paths are used, they are resolved with testPath().
+llvm::StringMap Files;
+llvm::StringMap 
+  };
+
+  llvm::StringMap CountStats;
+  ListenStatsFSProvider FS(CountStats);
+  ErrorCheckingDiagConsumer DiagConsumer;
+  MockCompilationDatabase CDB;
+  ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest());
+
+  auto SourcePath = testPath("foo.cpp");
+  auto HeaderPath = testPath("foo.h");
+  FS.Files[HeaderPath] = "struct TestSym {};";
+  Annotations Code(R"cpp(
+#include "foo.h"
+
+int main() {
+  TestSy^
+})cpp");
+
+  runAddDocument(Server, SourcePath, Code.code());
+
+  unsigned Before = CountStats["foo.h"];
+  auto Completions = cantFail(runCodeComplete(Server, SourcePath, Code.point(),
+  clangd::CodeCompleteOptions()))
+ .Completions;
+  EXPECT_EQ(CountStats["foo.h"], Before);
+  EXPECT_THAT(Completions,
+  ElementsAre(Field(::Name, "TestSym")));
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clangd/FS.h
===
--- /dev/null
+++ clangd/FS.h
@@ -0,0 +1,55 @@
+//===--- FS.h - File system related utils *- C++-*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_FS_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_FS_H
+
+#include "clang/Basic/VirtualFileSystem.h"
+#include "llvm/ADT/Optional.h"
+#include 
+namespace clang {
+namespace clangd {
+
+/// Caches `stat()` calls during preamble build, which can be used to avoid
+/// re-`stat`s header files when preamble is re-used (e.g. in code completion).
+/// Note that the cache is only valid whene reusing preamble.
+///
+/// The cache is keyed by absolute path of file name in cached status, as this
+/// is what preamble stores.
+class PreambleFileStatusCache {
+public:
+  void update(const vfs::FileSystem , vfs::Status S);
+  /// \p Path is a path stored in preamble.
+  llvm::Optional lookup(llvm::StringRef Path) const;
+
+  /// Returns a VFS that collects file status.
+  /// Only cache stats for files that exist because
+  ///   1) we only care about existing files when reusing preamble, unlike
+  ///   building preamble.
+  ///   2) we use the file name in the Status as the cache key.
+  ///
+  /// Note that the returned VFS should not outlive the cache.
+  IntrusiveRefCntPtr
+  getProducingFS(IntrusiveRefCntPtr FS);
+
+  /// Returns a VFS that uses the cache collected.
+  ///
+  /// Note that the returned VFS should not outlive the cache.
+  IntrusiveRefCntPtr
+  getConsumingFS(IntrusiveRefCntPtr FS) const;
+
+private:
+  llvm::StringMap StatCache;
+  mutable std::mutex Mutex;
+};
+
+} // namespace clangd
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANGD_FS_H
Index: clangd/FS.cpp
===
--- /dev/null
+++ clangd/FS.cpp
@@ -0,0 +1,87 @@
+//===--- FS.cpp - File system related utils --*- C++-*-===//
+//
+// The LLVM 

Re: r342925 - P0962R1: only use the member form of 'begin' and 'end' in a range-based

2018-09-25 Thread Vitaly Buka via cfe-commits
http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-fast/builds/24083

FAIL: Clang :: CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp (1692 of 13357)
 TEST 'Clang ::
CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp' FAILED

Script:
--
: 'RUN: at line 1';
/b/sanitizer-x86_64-linux-fast/build/llvm_build_ubsan/bin/clang -cc1
-internal-isystem
/b/sanitizer-x86_64-linux-fast/build/llvm_build_ubsan/lib/clang/8.0.0/include
-nostdsysteminc -std=c++11 -fsyntax-only -verify
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
: 'RUN: at line 2';
/b/sanitizer-x86_64-linux-fast/build/llvm_build_ubsan/bin/clang -cc1
-internal-isystem
/b/sanitizer-x86_64-linux-fast/build/llvm_build_ubsan/lib/clang/8.0.0/include
-nostdsysteminc -std=c++14 -fsyntax-only -verify
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
: 'RUN: at line 3';
/b/sanitizer-x86_64-linux-fast/build/llvm_build_ubsan/bin/clang -cc1
-internal-isystem
/b/sanitizer-x86_64-linux-fast/build/llvm_build_ubsan/lib/clang/8.0.0/include
-nostdsysteminc -std=c++17 -fsyntax-only -verify
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/test/CXX/stmt.stmt/stmt.iter/stmt.ranged/p1.cpp
--
Exit Code: 1

Command Output (stderr):
--
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/Sema/Lookup.h:185:19:
runtime error: load of value 32764, which is not a valid value for
type 'typename std::remove_reference::type' (aka
'clang::LookupResult::AmbiguityKind')
#0 0x49b97ec in
clang::LookupResult::LookupResult(clang::LookupResult&&)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/include/clang/Sema/Lookup.h:185:19
#1 0x49b8a2b in BuildNonArrayForRange(clang::Sema&, clang::Expr*,
clang::Expr*, clang::QualType, clang::VarDecl*, clang::VarDecl*,
clang::SourceLocation, clang::SourceLocation,
clang::OverloadCandidateSet*, clang::ActionResult*, clang::ActionResult*, (anonymous
namespace)::BeginEndFunction*)::$_3::operator()((anonymous
namespace)::BeginEndFunction, clang::LookupResult&,
llvm::function_ref,
llvm::function_ref) const
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Sema/SemaStmt.cpp:2225:33
#2 0x49a5ed0 in BuildNonArrayForRange
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Sema/SemaStmt.cpp
#3 0x49a5ed0 in
clang::Sema::BuildCXXForRangeStmt(clang::SourceLocation,
clang::SourceLocation, clang::SourceLocation, clang::Stmt*,
clang::Stmt*, clang::Stmt*, clang::Expr*, clang::Expr*, clang::Stmt*,
clang::SourceLocation, clang::Sema::BuildForRangeKind)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Sema/SemaStmt.cpp:2497
#4 0x49a49df in clang::Sema::ActOnCXXForRangeStmt(clang::Scope*,
clang::SourceLocation, clang::SourceLocation, clang::Stmt*,
clang::SourceLocation, clang::Expr*, clang::SourceLocation,
clang::Sema::BuildForRangeKind)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Sema/SemaStmt.cpp:2122:10
#5 0x41a3301 in
clang::Parser::ParseForStatement(clang::SourceLocation*)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Parse/ParseStmt.cpp:1762:28
#6 0x419fe76 in
clang::Parser::ParseStatementOrDeclarationAfterAttributes(llvm::SmallVector&, clang::Parser::AllowedConstructsKind, clang::SourceLocation*,
clang::Parser::ParsedAttributesWithRange&)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Parse/ParseStmt.cpp:251:12
#7 0x419f496 in
clang::Parser::ParseStatementOrDeclaration(llvm::SmallVector&, clang::Parser::AllowedConstructsKind, clang::SourceLocation*)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Parse/ParseStmt.cpp:110:20
#8 0x41a563b in clang::Parser::ParseCompoundStatementBody(bool)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Parse/ParseStmt.cpp:997:11
#9 0x41a61c8 in
clang::Parser::ParseFunctionStatementBody(clang::Decl*,
clang::Parser::ParseScope&)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Parse/ParseStmt.cpp:1971:21
#10 0x410fde8 in
clang::Parser::ParseFunctionDefinition(clang::ParsingDeclarator&,
clang::Parser::ParsedTemplateInfo const&,
clang::Parser::LateParsedAttrList*)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Parse/Parser.cpp:1246:10
#11 0x412cc1c in
clang::Parser::ParseDeclGroup(clang::ParsingDeclSpec&,
clang::DeclaratorContext, clang::SourceLocation*,
clang::Parser::ForRangeInit*)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Parse/ParseDecl.cpp:1968:11
#12 0x410e9ab in
clang::Parser::ParseDeclOrFunctionDefInternal(clang::Parser::ParsedAttributesWithRange&,
clang::ParsingDeclSpec&, clang::AccessSpecifier)
/b/sanitizer-x86_64-linux-fast/build/llvm/tools/clang/lib/Parse/Parser.cpp:1015:10
#13 0x410e167 in
clang::Parser::ParseDeclarationOrFunctionDefinition(clang::Parser::ParsedAttributesWithRange&,
clang::ParsingDeclSpec*, clang::AccessSpecifier)

r342995 - [OPENMP] Fix failed test, NFC.

2018-09-25 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Sep 25 10:47:53 2018
New Revision: 342995

URL: http://llvm.org/viewvc/llvm-project?rev=342995=rev
Log:
[OPENMP] Fix failed test, NFC.

Modified:
cfe/trunk/test/Driver/openmp-offload.c

Modified: cfe/trunk/test/Driver/openmp-offload.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/openmp-offload.c?rev=342995=342994=342995=diff
==
--- cfe/trunk/test/Driver/openmp-offload.c (original)
+++ cfe/trunk/test/Driver/openmp-offload.c Tue Sep 25 10:47:53 2018
@@ -574,7 +574,6 @@
 // CHK-UBJOBS2: ld{{(\.exe)?}}" {{.*}}"-o" "
 // CHK-UBJOBS2-SAME: [[HOSTBIN:[^\\/]+\.out]]" {{.*}}"{{.*}}[[HOSTOBJ]]" 
{{.*}}"-T" "
 // CHK-UBJOBS2-SAME: [[LKS:[^\\/]+\.lk]]"
-// CHK-UBJOBS2-ST-NOT: clang-offload-bundler{{.*}}in.so
 // CHK-UBJOBS2-ST: clang-offload-bundler{{.*}}" "-type=o" 
"-targets=host-powerpc64le-unknown-linux,openmp-powerpc64le-ibm-linux-gnu,openmp-x86_64-pc-linux-gnu"
 "-inputs=
 // CHK-UBJOBS2-ST-SAME: [[INPUT:[^\\/]+\.o]]" "-outputs=
 // CHK-UBJOBS2-ST-SAME: [[HOSTOBJ:[^\\/,]+\.o]],


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


[PATCH] D51741: [coro]Pass rvalue reference for named local variable to return_value

2018-09-25 Thread Tanoy Sinha via Phabricator via cfe-commits
tks2103 added a comment.

ping @GorNishanov SAVE ME GOR! YOU'RE MY ONLY HOPE!


Repository:
  rC Clang

https://reviews.llvm.org/D51741



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


[PATCH] D52136: [clang-tidy] Add modernize-concat-nested-namespaces check

2018-09-25 Thread Wojtek Gumuła via Phabricator via cfe-commits
wgml added a comment.

Thanks you all for your participation in the review process. I guess it is done 
now.
I don't have write access to the repositories, @aaron.ballman, could you apply 
the patch on my behalf?




Comment at: clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp:31
+static bool singleNamedNamespaceChild(const NamespaceDecl ) {
+  const NamespaceDecl::decl_range Decls = ND.decls();
+  if (std::distance(Decls.begin(), Decls.end()) != 1)

aaron.ballman wrote:
> wgml wrote:
> > aaron.ballman wrote:
> > > We usually only const-qualify local declarations when they're 
> > > pointers/references, so you can drop the `const` here (and in several 
> > > other places). It's not a hard and fast rule, but the clutter is not 
> > > useful in such small functions.
> > From my perspective, `const` is a easy way of declaring that my intention 
> > is only to name given declaration only for reading and to improve code 
> > readability. 
> I wasn't making a value judgement about the coding style so much as pointing 
> out that this is novel to the code base and we tend to avoid novel constructs 
> unless there's a good reason to deviate. I don't see a strong justification 
> here, so I'd prefer them to be removed for consistency.
Okay then, adjusted.


https://reviews.llvm.org/D52136



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


[PATCH] D52219: [analyzer] (1/n) Support pointee mutation analysis in ExprMutationAnalyzer.

2018-09-25 Thread Shuai Wang via Phabricator via cfe-commits
shuaiwang updated this revision to Diff 166947.
shuaiwang marked 6 inline comments as done.
shuaiwang added a comment.

Addressed review comments.


Repository:
  rC Clang

https://reviews.llvm.org/D52219

Files:
  include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
  lib/Analysis/ExprMutationAnalyzer.cpp
  unittests/Analysis/ExprMutationAnalyzerTest.cpp

Index: unittests/Analysis/ExprMutationAnalyzerTest.cpp
===
--- unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -50,13 +50,23 @@
 }
 
 bool isMutated(const SmallVectorImpl , ASTUnit *AST) {
-  const auto *const S = selectFirst("stmt", Results);
-  const auto *const E = selectFirst("expr", Results);
+  const auto *S = selectFirst("stmt", Results);
+  const auto *E = selectFirst("expr", Results);
+  assert(S && E);
   return ExprMutationAnalyzer(*S, AST->getASTContext()).isMutated(E);
 }
 
+bool isPointeeMutated(const SmallVectorImpl ,
+  ASTUnit *AST) {
+  const auto *S = selectFirst("stmt", Results);
+  const auto *E = selectFirst("expr", Results);
+  assert(S && E);
+  return ExprMutationAnalyzer(*S, AST->getASTContext()).isPointeeMutated(E);
+}
+
 SmallVector
 mutatedBy(const SmallVectorImpl , ASTUnit *AST) {
+  EXPECT_TRUE(isMutated(Results, AST));
   const auto *const S = selectFirst("stmt", Results);
   SmallVector Chain;
   ExprMutationAnalyzer Analyzer(*S, AST->getASTContext());
@@ -71,6 +81,19 @@
   return Chain;
 }
 
+std::string pointeeMutatedBy(const SmallVectorImpl ,
+ ASTUnit *AST) {
+  EXPECT_TRUE(isPointeeMutated(Results, AST));
+  const auto *const S = selectFirst("stmt", Results);
+  const auto *const E = selectFirst("expr", Results);
+  ExprMutationAnalyzer Analyzer(*S, AST->getASTContext());
+  std::string buffer;
+  llvm::raw_string_ostream stream(buffer);
+  const Stmt *By = Analyzer.findPointeeMutation(E);
+  By->printPretty(stream, nullptr, AST->getASTContext().getPrintingPolicy());
+  return StringRef(stream.str()).trim().str();
+}
+
 std::string removeSpace(std::string s) {
   s.erase(std::remove_if(s.begin(), s.end(),
  [](char c) { return std::isspace(c); }),
@@ -100,10 +123,14 @@
 } // namespace
 
 TEST(ExprMutationAnalyzerTest, Trivial) {
-  const auto AST = buildASTFromCode("void f() { int x; x; }");
-  const auto Results =
+  auto AST = buildASTFromCode("void f() { int x; x; }");
+  auto Results =
   match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
   EXPECT_FALSE(isMutated(Results, AST.get()));
+
+  AST = buildASTFromCode("void f() { const int x = 0; x; }");
+  Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
+  EXPECT_FALSE(isMutated(Results, AST.get()));
 }
 
 class AssignmentTest : public ::testing::TestWithParam {};
@@ -134,41 +161,111 @@
 Values("++x", "--x", "x++", "x--"), );
 
 TEST(ExprMutationAnalyzerTest, NonConstMemberFunc) {
-  const auto AST = buildASTFromCode(
+  auto AST = buildASTFromCode(
   "void f() { struct Foo { void mf(); }; Foo x; x.mf(); }");
-  const auto Results =
+  auto Results =
   match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
   EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.mf()"));
+  EXPECT_FALSE(isPointeeMutated(Results, AST.get()));
+
+  AST = buildASTFromCode(
+  "void f() { struct Foo { void mf(); }; Foo *p; p->mf(); }");
+  Results = match(withEnclosingCompound(declRefTo("p")), AST->getASTContext());
+  EXPECT_FALSE(isMutated(Results, AST.get()));
+  EXPECT_EQ(pointeeMutatedBy(Results, AST.get()), "p->mf()");
+
+  AST = buildASTFromCode(
+  "void f() { struct Foo { void mf(); }; Foo *x; Foo * = x; p->mf(); }");
+  Results = match(withEnclosingCompound(declRefTo("p")), AST->getASTContext());
+  EXPECT_FALSE(isMutated(Results, AST.get()));
+  EXPECT_EQ(pointeeMutatedBy(Results, AST.get()), "p->mf()");
 }
 
 TEST(ExprMutationAnalyzerTest, AssumedNonConstMemberFunc) {
   auto AST = buildASTFromCodeWithArgs(
   "struct X { template  void mf(); };"
-  "template  void f() { X x; x.mf(); }",
+  "template  void f() { X x; x.mf(); }"
+  "template  void g() { X *p; p->mf(); }",
   {"-fno-delayed-template-parsing"});
   auto Results =
   match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
   EXPECT_THAT(mutatedBy(Results, AST.get()), ElementsAre("x.mf()"));
+  Results = match(withEnclosingCompound(declRefTo("p")), AST->getASTContext());
+  EXPECT_FALSE(isMutated(Results, AST.get()));
+  EXPECT_EQ(pointeeMutatedBy(Results, AST.get()), "p->mf()");
 
-  AST = buildASTFromCodeWithArgs("template  void f() { T x; x.mf(); }",
- {"-fno-delayed-template-parsing"});
+  AST =
+  buildASTFromCodeWithArgs("template  void f() { T x; x.mf(); }"
+   "template  void g() { T *p; p->mf(); }",
+ 

[PATCH] D52136: [clang-tidy] Add modernize-concat-nested-namespaces check

2018-09-25 Thread Wojtek Gumuła via Phabricator via cfe-commits
wgml updated this revision to Diff 166945.
wgml marked 10 inline comments as done.
wgml added a comment.

Dropped a few consts, updated doc text.


https://reviews.llvm.org/D52136

Files:
  clang-tidy/modernize/CMakeLists.txt
  clang-tidy/modernize/ConcatNestedNamespacesCheck.cpp
  clang-tidy/modernize/ConcatNestedNamespacesCheck.h
  clang-tidy/modernize/ModernizeTidyModule.cpp
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/modernize-concat-nested-namespaces.rst
  test/clang-tidy/modernize-concat-nested-namespaces.cpp

Index: test/clang-tidy/modernize-concat-nested-namespaces.cpp
===
--- /dev/null
+++ test/clang-tidy/modernize-concat-nested-namespaces.cpp
@@ -0,0 +1,161 @@
+// RUN: %check_clang_tidy %s modernize-concat-nested-namespaces %t -- -- -std=c++17
+
+namespace n1 {}
+
+namespace n2 {
+namespace n3 {
+void t();
+}
+namespace n4 {
+void t();
+}
+} // namespace n2
+
+namespace n5 {
+inline namespace n6 {
+void t();
+}
+} // namespace n5
+
+namespace n7 {
+void t();
+
+namespace n8 {
+void t();
+}
+} // namespace n7
+
+namespace n9 {
+namespace n10 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n9::n10
+void t();
+} // namespace n10
+} // namespace n9
+// CHECK-FIXES: }
+
+namespace n11 {
+namespace n12 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n11::n12
+namespace n13 {
+void t();
+}
+namespace n14 {
+void t();
+}
+} // namespace n12
+} // namespace n11
+// CHECK-FIXES: }
+
+namespace n15 {
+namespace n16 {
+void t();
+}
+
+inline namespace n17 {
+void t();
+}
+
+namespace n18 {
+namespace n19 {
+namespace n20 {
+// CHECK-MESSAGES: :[[@LINE-3]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n18::n19::n20
+void t();
+} // namespace n20
+} // namespace n19
+} // namespace n18
+// CHECK-FIXES: }
+
+namespace n21 {
+void t();
+}
+} // namespace n15
+
+namespace n22 {
+namespace {
+void t();
+}
+} // namespace n22
+
+namespace n23 {
+namespace {
+namespace n24 {
+namespace n25 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n24::n25
+void t();
+} // namespace n25
+} // namespace n24
+// CHECK-FIXES: }
+} // namespace
+} // namespace n23
+
+namespace n26::n27 {
+namespace n28 {
+namespace n29::n30 {
+// CHECK-MESSAGES: :[[@LINE-3]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n26::n27::n28::n29::n30
+void t() {}
+} // namespace n29::n30
+} // namespace n28
+} // namespace n26::n27
+// CHECK-FIXES: }
+
+namespace n31 {
+namespace n32 {}
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+} // namespace n31
+// CHECK-FIXES-EMPTY
+
+namespace n33 {
+namespace n34 {
+namespace n35 {}
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+} // namespace n34
+// CHECK-FIXES-EMPTY
+namespace n36 {
+void t();
+}
+} // namespace n33
+
+namespace n37::n38 {
+void t();
+}
+
+#define IEXIST
+namespace n39 {
+namespace n40 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n39::n40
+#ifdef IEXIST
+void t() {}
+#endif
+} // namespace n40
+} // namespace n39
+// CHECK-FIXES: }
+
+namespace n41 {
+namespace n42 {
+// CHECK-MESSAGES: :[[@LINE-2]]:1: warning: nested namespaces can be concatenated [modernize-concat-nested-namespaces]
+// CHECK-FIXES: namespace n41::n42
+#ifdef IDONTEXIST
+void t() {}
+#endif
+} // namespace n42
+} // namespace n41
+// CHECK-FIXES: }
+
+int main() {
+  n26::n27::n28::n29::n30::t();
+#ifdef IEXIST
+  n39::n40::t();
+#endif
+
+#ifdef IDONTEXIST
+  n41::n42::t();
+#endif
+
+  return 0;
+}
Index: docs/clang-tidy/checks/modernize-concat-nested-namespaces.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/modernize-concat-nested-namespaces.rst
@@ -0,0 +1,49 @@
+.. title:: clang-tidy - modernize-concat-nested-namespaces
+
+modernize-concat-nested-namespaces
+==
+
+Checks for use of nested namespaces such as ``namespace a { namespace b { ... } }``
+and suggests changing to the more concise syntax introduced in C++17: ``namespace a::b { ... }``.
+Inline namespaces are not modified.
+
+For example:
+
+.. code-block:: c++
+
+  namespace n1 {
+  namespace n2 {
+  void t();
+  }
+  }
+
+  namespace n3 {
+  namespace n4 {
+  namespace n5 {
+  void t();
+  }
+  }
+  namespace n6 {
+  namespace n7 {
+  void t();
+  }
+  }
+  }
+
+Will be modified to:
+

[PATCH] D52503: [clangd] More precise index memory usage estimate

2018-09-25 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang-tools-extra/clangd/index/dex/Dex.cpp:251
   Bytes += InvertedIndex.getMemorySize();
-  for (const auto  : InvertedIndex)
-Bytes += P.second.bytes();
+  for (const auto  : InvertedIndex)
+Bytes += TokenToPostingList.first.Data.size() +

ioeric wrote:
> Would `InvertedIndex.getMemorySize()` be a better estimate?
IIUC this is only precise for the objects which do not make any allocations 
(e.g. `std::vector` and `std::string` memory estimate would not be "correct").

From the documentation

> This is just the raw memory used by DenseMap. If entries are pointers to 
> objects, the size of the referenced objects are not included.

I also have `Bytes += InvertedIndex.getMemorySize();` above, so the purpose of 
this code would be to take into account the size of these "reference objects".

However, since `PostingList::bytes()` also returns underlying `std::vector` 
size, this code will probably add these `std::vector` objects size twice (the 
first one was in `InvertedIndex.getMemorySize()`). I should fix that.


https://reviews.llvm.org/D52503



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


[PATCH] D52434: [OpenMP] Make default schedules for NVPTX target regions in SPMD mode achieve coalescing

2018-09-25 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: lib/CodeGen/CGStmtOpenMP.cpp:2304
+  const auto *C = S.getSingleClause();
+  if (C) {
+// If schedule clause is present.

Restore original code here



Comment at: lib/CodeGen/CGStmtOpenMP.cpp:2317
+// When schedule clause is absent we choose sensible defaults.
+CGM.getOpenMPRuntime().chooseDefaultSchedule();
+Chunk = CGM.getOpenMPRuntime().getDefaultChunkValue(

Why you don't want to have only one function for the default scheduling/chunk? 
Also, you should change `DistSchedule` code, not `Schedule`



Comment at: lib/CodeGen/CGStmtOpenMP.cpp:3337
   }
+
   const unsigned IVSize = getContext().getTypeSize(IVExpr->getType());

Restore original


Repository:
  rC Clang

https://reviews.llvm.org/D52434



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


[PATCH] D52248: [SEMA] ignore duplicate declaration specifiers from typeof exprs

2018-09-25 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

> Should GCC instead warn for the typedef case for -std=c89 (non pedantic), 
> according to C90 6.5.3?

Seems like yes: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80868#c6
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87435
But let's wait a bit to see what the GCC folks say.  If the newer bug doesn't 
get closed, then I need to rework this patch.


Repository:
  rC Clang

https://reviews.llvm.org/D52248



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


[PATCH] D52503: [clangd] More precise index memory usage estimate

2018-09-25 Thread Eric Liu via Phabricator via cfe-commits
ioeric added inline comments.



Comment at: clang-tools-extra/clangd/index/dex/Dex.cpp:251
   Bytes += InvertedIndex.getMemorySize();
-  for (const auto  : InvertedIndex)
-Bytes += P.second.bytes();
+  for (const auto  : InvertedIndex)
+Bytes += TokenToPostingList.first.Data.size() +

Would `InvertedIndex.getMemorySize()` be a better estimate?


https://reviews.llvm.org/D52503



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


r342991 - [DRIVER][OFFLOAD] Do not invoke unbundler on unsupported file types.

2018-09-25 Thread Alexey Bataev via cfe-commits
Author: abataev
Date: Tue Sep 25 10:09:17 2018
New Revision: 342991

URL: http://llvm.org/viewvc/llvm-project?rev=342991=rev
Log:
[DRIVER][OFFLOAD] Do not invoke unbundler on unsupported file types.

clang-offload-bundler should not be invoked with the unbundling action
when the input file type does not match the action type. For example,
.so files should be unbundled during linking phase and should be linked
only with the host code.

Added:
cfe/trunk/test/Driver/Inputs/in.so
Modified:
cfe/trunk/lib/Driver/Driver.cpp
cfe/trunk/test/Driver/openmp-offload-gpu.c
cfe/trunk/test/Driver/openmp-offload.c

Modified: cfe/trunk/lib/Driver/Driver.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/Driver.cpp?rev=342991=342990=342991=diff
==
--- cfe/trunk/lib/Driver/Driver.cpp (original)
+++ cfe/trunk/lib/Driver/Driver.cpp Tue Sep 25 10:09:17 2018
@@ -2559,6 +2559,8 @@ class OffloadingActionBuilder final {
 getDeviceDependences(OffloadAction::DeviceDependences ,
  phases::ID CurPhase, phases::ID FinalPhase,
  PhasesTy ) override {
+  if (OpenMPDeviceActions.empty())
+return ABRT_Inactive;
 
   // We should always have an action for each input.
   assert(OpenMPDeviceActions.size() == ToolChains.size() &&
@@ -2817,6 +2819,16 @@ public:
 if (CanUseBundler && isa(HostAction) &&
 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
 !types::isSrcFile(HostAction->getType())) {
+  StringRef FileName = InputArg->getAsString(C.getArgs());
+  // Check if the type of the file is the same as the action. Do not
+  // unbundle it if it is not. Do not unbundle .so files, for example, 
which
+  // are not object files.
+  if (HostAction->getType() == types::TY_Object &&
+  llvm::sys::path::has_extension(FileName) &&
+  types::lookupTypeForExtension(
+  llvm::sys::path::extension(FileName).drop_front()) !=
+  HostAction->getType())
+return false;
   auto UnbundlingHostAction =
   C.MakeAction(HostAction);
   UnbundlingHostAction->registerDependentActionInfo(

Added: cfe/trunk/test/Driver/Inputs/in.so
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/Inputs/in.so?rev=342991=auto
==
--- cfe/trunk/test/Driver/Inputs/in.so (added)
+++ cfe/trunk/test/Driver/Inputs/in.so Tue Sep 25 10:09:17 2018
@@ -0,0 +1 @@
+

Modified: cfe/trunk/test/Driver/openmp-offload-gpu.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/openmp-offload-gpu.c?rev=342991=342990=342991=diff
==
--- cfe/trunk/test/Driver/openmp-offload-gpu.c (original)
+++ cfe/trunk/test/Driver/openmp-offload-gpu.c Tue Sep 25 10:09:17 2018
@@ -73,13 +73,15 @@
 /// Check cubin file unbundling and usage by nvlink
 // RUN:   touch %t.o
 // RUN:   %clang -### -target powerpc64le-unknown-linux-gnu -fopenmp=libomp 
-fopenmp-targets=nvptx64-nvidia-cuda \
-// RUN:  -no-canonical-prefixes -save-temps %t.o 2>&1 \
+// RUN:  -no-canonical-prefixes -save-temps %t.o %S/Inputs/in.so 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-CUBIN-UNBUNDLING-NVLINK %s
 
 /// Use DAG to ensure that cubin file has been unbundled.
+// CHK-CUBIN-UNBUNDLING-NVLINK-NOT: clang-offload-bundler{{.*}}" 
"-type=o"{{.*}}in.so
 // CHK-CUBIN-UNBUNDLING-NVLINK-DAG: nvlink{{.*}}" {{.*}}"[[CUBIN:.*\.cubin]]"
 // CHK-CUBIN-UNBUNDLING-NVLINK-DAG: clang-offload-bundler{{.*}}" "-type=o" 
{{.*}}"-outputs={{.*}}[[CUBIN]]
 // CHK-CUBIN-UNBUNDLING-NVLINK-DAG-SAME: "-unbundle"
+// CHK-CUBIN-UNBUNDLING-NVLINK-NOT: clang-offload-bundler{{.*}}" 
"-type=o"{{.*}}in.so
 
 /// ###
 

Modified: cfe/trunk/test/Driver/openmp-offload.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/openmp-offload.c?rev=342991=342990=342991=diff
==
--- cfe/trunk/test/Driver/openmp-offload.c (original)
+++ cfe/trunk/test/Driver/openmp-offload.c Tue Sep 25 10:09:17 2018
@@ -358,7 +358,7 @@
 /// ###
 
 /// Check separate compilation with offloading - bundling actions
-// RUN:   %clang -### -ccc-print-phases -fopenmp=libomp -c -o %t.o -lsomelib 
-target powerpc64le-linux 
-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s 
-no-canonical-prefixes 2>&1 \
+// RUN:   %clang -### -ccc-print-phases -fopenmp=libomp -c -o %t.o  
Input/in.so -lsomelib -target powerpc64le-linux 
-fopenmp-targets=powerpc64le-ibm-linux-gnu,x86_64-pc-linux-gnu %s 
-no-canonical-prefixes 2>&1 \
 // RUN:   | FileCheck -check-prefix=CHK-BUACTIONS %s
 
 // CHK-BUACTIONS: 

Re: [clang-tools-extra] r342730 - [clangd] Remember to serialize symbol origin in YAML.

2018-09-25 Thread Ilya Biryukov via cfe-commits
Eric Liu  schrieb am Di., 25. Sep. 2018, 01:22:

> On Tue, Sep 25, 2018 at 6:34 AM Ilya Biryukov 
> wrote:
>
>> Why would we want to serialize the origin?
>>
> We only serialize and deserialize for the static index, it does not seem
>> to be useful to serialize origin in that scenario.
>>
> We serialize Origin because it's a property of Symbol? The origin for the
> current YAML symbols is defaulted to "unknown".
>
My view would be that it's a property of a symbol living in memory, but not
the serialized one. E.g. all symbols read from the yaml index should have
the static origin. If we store an origin, we allow loading symbols with
non-static origin, it's hard to see how that would be useful.




> It's true that we *currently* only serialize symbols from static index,
> but there is nothing preventing us from doing it for other indexes with
> different origins. You could probably override origins when loading static
> index, but that doesn't seem to work in general.
>
The origin seems to be exactly the field that is set and manipulated by
index implementations, but they all have the knowledge on what their origin
is or how to combine origins of subindexes.

Again, it seems there are two classes hiding in symbol. All other fields
provide useful information about C++ semantics of the symbol, while origin
provides some traceability when combining indexes. The former is something
we need to serialize, the latter is something we can infer when
deserializing.

If we will have a use case for serializing the latter entity(with origin)
for any reason, we might add that separately.

Not sure if it's worth the trouble changing it, just wanted to point out
that storing the  origin for each symbol in the yaml index for the purpose
of indicating that the symbol is in the yaml index seems to be a bit off.



> I checked this in without review as I thought this was a trivial fix. The
> binary serialization also serializes the Origin field.
>
LG to be consistent with binary serialization, the same question applies to
binary serialization.

Again, the change itself seems fine, just nitpicking on whether putting
origin into a symbol at that level makes sense.



>> Am I missing something?
>>
>
>> On Fri, Sep 21, 2018 at 3:06 PM Eric Liu via cfe-commits <
>> cfe-commits@lists.llvm.org> wrote:
>>
>>> Author: ioeric
>>> Date: Fri Sep 21 06:04:57 2018
>>> New Revision: 342730
>>>
>>> URL: http://llvm.org/viewvc/llvm-project?rev=342730=rev
>>> Log:
>>> [clangd] Remember to serialize symbol origin in YAML.
>>>
>>> Modified:
>>> clang-tools-extra/trunk/clangd/index/SymbolYAML.cpp
>>> clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
>>>
>>> Modified: clang-tools-extra/trunk/clangd/index/SymbolYAML.cpp
>>> URL:
>>> http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/SymbolYAML.cpp?rev=342730=342729=342730=diff
>>>
>>> ==
>>> --- clang-tools-extra/trunk/clangd/index/SymbolYAML.cpp (original)
>>> +++ clang-tools-extra/trunk/clangd/index/SymbolYAML.cpp Fri Sep 21
>>> 06:04:57 2018
>>> @@ -27,6 +27,7 @@ namespace yaml {
>>>
>>>  using clang::clangd::Symbol;
>>>  using clang::clangd::SymbolID;
>>> +using clang::clangd::SymbolOrigin;
>>>  using clang::clangd::SymbolLocation;
>>>  using clang::index::SymbolInfo;
>>>  using clang::index::SymbolKind;
>>> @@ -65,6 +66,17 @@ struct NormalizedSymbolFlag {
>>>uint8_t Flag = 0;
>>>  };
>>>
>>> +struct NormalizedSymbolOrigin {
>>> +  NormalizedSymbolOrigin(IO &) {}
>>> +  NormalizedSymbolOrigin(IO &, SymbolOrigin O) {
>>> +Origin = static_cast(O);
>>> +  }
>>> +
>>> +  SymbolOrigin denormalize(IO &) { return
>>> static_cast(Origin); }
>>> +
>>> +  uint8_t Origin = 0;
>>> +};
>>> +
>>>  template <> struct MappingTraits {
>>>static void mapping(IO , SymbolLocation::Position ) {
>>>  IO.mapRequired("Line", Value.Line);
>>> @@ -102,6 +114,8 @@ template <> struct MappingTraits
>>>  MappingNormalization NSymbolID(IO,
>>> Sym.ID);
>>>  MappingNormalization
>>> NSymbolFlag(
>>>  IO, Sym.Flags);
>>> +MappingNormalization
>>> NSymbolOrigin(
>>> +IO, Sym.Origin);
>>>  IO.mapRequired("ID", NSymbolID->HexString);
>>>  IO.mapRequired("Name", Sym.Name);
>>>  IO.mapRequired("Scope", Sym.Scope);
>>> @@ -110,6 +124,7 @@ template <> struct MappingTraits
>>> SymbolLocation());
>>>  IO.mapOptional("Definition", Sym.Definition, SymbolLocation());
>>>  IO.mapOptional("References", Sym.References, 0u);
>>> +IO.mapOptional("Origin", NSymbolOrigin->Origin);
>>>  IO.mapOptional("Flags", NSymbolFlag->Flag);
>>>  IO.mapOptional("Signature", Sym.Signature);
>>>  IO.mapOptional("CompletionSnippetSuffix",
>>> Sym.CompletionSnippetSuffix);
>>>
>>> Modified: clang-tools-extra/trunk/unittests/clangd/SerializationTests.cpp
>>> URL:
>>> 

[PATCH] D52399: [AArch64] Support adding X[8-15, 18] registers as CSRs.

2018-09-25 Thread Tri Vo via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rC342990: [AArch64] Support adding X[8-15,18] registers as 
CSRs. (authored by trong, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D52399?vs=166722=166940#toc

Repository:
  rC Clang

https://reviews.llvm.org/D52399

Files:
  docs/ClangCommandLineReference.rst
  include/clang/Driver/Options.td
  lib/Driver/ToolChains/Arch/AArch64.cpp
  test/Driver/aarch64-call-saved-x-register.c
  test/Driver/aarch64-fixed-call-saved-x-register.c

Index: docs/ClangCommandLineReference.rst
===
--- docs/ClangCommandLineReference.rst
+++ docs/ClangCommandLineReference.rst
@@ -2334,6 +2334,42 @@
 
 Reserve the x20 register (AArch64 only)
 
+.. option:: -fcall-saved-x8
+
+Make the x8 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x9
+
+Make the x9 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x10
+
+Make the x10 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x11
+
+Make the x11 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x12
+
+Make the x12 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x13
+
+Make the x13 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x14
+
+Make the x14 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x15
+
+Make the x15 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x18
+
+Make the x18 register call-saved (AArch64 only)
+
 .. option:: -mfix-cortex-a53-835769, -mno-fix-cortex-a53-835769
 
 Workaround Cortex-A53 erratum 835769 (AArch64 only)
Index: include/clang/Driver/Options.td
===
--- include/clang/Driver/Options.td
+++ include/clang/Driver/Options.td
@@ -2054,6 +2054,10 @@
   def ffixed_x#i : Flag<["-"], "ffixed-x"#i>, Group,
 HelpText<"Reserve the "#i#" register (AArch64 only)">;
 
+foreach i = {8-15,18} in
+  def fcall_saved_x#i : Flag<["-"], "fcall-saved-x"#i>, Group,
+HelpText<"Make the x"#i#" register call-saved (AArch64 only)">;
+
 def msign_return_address : Joined<["-"], "msign-return-address=">,
   Flags<[CC1Option]>, Group,
   HelpText<"Select return address signing scope">, Values<"none,all,non-leaf">;
Index: test/Driver/aarch64-call-saved-x-register.c
===
--- test/Driver/aarch64-call-saved-x-register.c
+++ test/Driver/aarch64-call-saved-x-register.c
@@ -0,0 +1,58 @@
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x8 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X8 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x9 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X9 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x10 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X10 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x11 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X11 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x12 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X12 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x13 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X13 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x14 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X14 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x15 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X15 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x18 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X18 %s
+
+// Test all call-saved-x# options together.
+// RUN: %clang -target aarch64-none-gnu \
+// RUN: -fcall-saved-x8 \
+// RUN: -fcall-saved-x9 \
+// RUN: -fcall-saved-x10 \
+// RUN: -fcall-saved-x11 \
+// RUN: -fcall-saved-x12 \
+// RUN: -fcall-saved-x13 \
+// RUN: -fcall-saved-x14 \
+// RUN: -fcall-saved-x15 \
+// RUN: -fcall-saved-x18 \
+// RUN: -### %s  2>&1 | FileCheck %s \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X8 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X9 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X10 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X11 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X12 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X13 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X14 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X15 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X18
+
+// CHECK-CALL-SAVED-X8: "-target-feature" "+call-saved-x8"
+// CHECK-CALL-SAVED-X9: "-target-feature" "+call-saved-x9"
+// CHECK-CALL-SAVED-X10: "-target-feature" "+call-saved-x10"
+// CHECK-CALL-SAVED-X11: "-target-feature" "+call-saved-x11"
+// CHECK-CALL-SAVED-X12: "-target-feature" "+call-saved-x12"
+// CHECK-CALL-SAVED-X13: "-target-feature" "+call-saved-x13"
+// CHECK-CALL-SAVED-X14: "-target-feature" 

[PATCH] D52399: [AArch64] Support adding X[8-15, 18] registers as CSRs.

2018-09-25 Thread Tri Vo via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL342990: [AArch64] Support adding X[8-15,18] registers as 
CSRs. (authored by trong, committed by ).
Herald added a subscriber: llvm-commits.

Repository:
  rL LLVM

https://reviews.llvm.org/D52399

Files:
  cfe/trunk/docs/ClangCommandLineReference.rst
  cfe/trunk/include/clang/Driver/Options.td
  cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp
  cfe/trunk/test/Driver/aarch64-call-saved-x-register.c
  cfe/trunk/test/Driver/aarch64-fixed-call-saved-x-register.c

Index: cfe/trunk/docs/ClangCommandLineReference.rst
===
--- cfe/trunk/docs/ClangCommandLineReference.rst
+++ cfe/trunk/docs/ClangCommandLineReference.rst
@@ -2334,6 +2334,42 @@
 
 Reserve the x20 register (AArch64 only)
 
+.. option:: -fcall-saved-x8
+
+Make the x8 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x9
+
+Make the x9 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x10
+
+Make the x10 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x11
+
+Make the x11 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x12
+
+Make the x12 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x13
+
+Make the x13 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x14
+
+Make the x14 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x15
+
+Make the x15 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x18
+
+Make the x18 register call-saved (AArch64 only)
+
 .. option:: -mfix-cortex-a53-835769, -mno-fix-cortex-a53-835769
 
 Workaround Cortex-A53 erratum 835769 (AArch64 only)
Index: cfe/trunk/include/clang/Driver/Options.td
===
--- cfe/trunk/include/clang/Driver/Options.td
+++ cfe/trunk/include/clang/Driver/Options.td
@@ -2054,6 +2054,10 @@
   def ffixed_x#i : Flag<["-"], "ffixed-x"#i>, Group,
 HelpText<"Reserve the "#i#" register (AArch64 only)">;
 
+foreach i = {8-15,18} in
+  def fcall_saved_x#i : Flag<["-"], "fcall-saved-x"#i>, Group,
+HelpText<"Make the x"#i#" register call-saved (AArch64 only)">;
+
 def msign_return_address : Joined<["-"], "msign-return-address=">,
   Flags<[CC1Option]>, Group,
   HelpText<"Select return address signing scope">, Values<"none,all,non-leaf">;
Index: cfe/trunk/test/Driver/aarch64-fixed-call-saved-x-register.c
===
--- cfe/trunk/test/Driver/aarch64-fixed-call-saved-x-register.c
+++ cfe/trunk/test/Driver/aarch64-fixed-call-saved-x-register.c
@@ -0,0 +1,8 @@
+// Check that -ffixed and -fcall-saved flags work correctly together.
+// RUN: %clang -target aarch64-none-gnu \
+// RUN: -ffixed-x18 \
+// RUN: -fcall-saved-x18 \
+// RUN: -### %s  2>&1 | FileCheck %s
+
+// CHECK: "-target-feature" "+reserve-x18"
+// CHECK: "-target-feature" "+call-saved-x18"
Index: cfe/trunk/test/Driver/aarch64-call-saved-x-register.c
===
--- cfe/trunk/test/Driver/aarch64-call-saved-x-register.c
+++ cfe/trunk/test/Driver/aarch64-call-saved-x-register.c
@@ -0,0 +1,58 @@
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x8 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X8 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x9 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X9 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x10 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X10 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x11 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X11 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x12 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X12 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x13 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X13 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x14 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X14 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x15 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X15 %s
+
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x18 -### %s  2>&1  \
+// RUN: | FileCheck --check-prefix=CHECK-CALL-SAVED-X18 %s
+
+// Test all call-saved-x# options together.
+// RUN: %clang -target aarch64-none-gnu \
+// RUN: -fcall-saved-x8 \
+// RUN: -fcall-saved-x9 \
+// RUN: -fcall-saved-x10 \
+// RUN: -fcall-saved-x11 \
+// RUN: -fcall-saved-x12 \
+// RUN: -fcall-saved-x13 \
+// RUN: -fcall-saved-x14 \
+// RUN: -fcall-saved-x15 \
+// RUN: -fcall-saved-x18 \
+// RUN: -### %s  2>&1 | FileCheck %s \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X8 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X9 \
+// RUN: --check-prefix=CHECK-CALL-SAVED-X10 \
+// RUN: 

[PATCH] D52465: [clangd] Extract mapper logic from clangd-indexer into a library.

2018-09-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

LGTM, thanks for factoring out this to a library.




Comment at: clangd/index/IndexAction.cpp:41
+  llvm::errs()
+  << "Found uncompilable errors in the translation unit. Igoring "
+ "collected symbols...\n";

s/Igoring/Ignoring/



Comment at: clangd/index/IndexAction.cpp:63
+  index::IndexingOptions::SystemSymbolFilterKind::All;
+  IndexOpts.IndexFunctionLocals = false;
+  Opts.CollectIncludePath = true;

nit: this is false by default.



Comment at: clangd/index/IndexAction.h:24
+//   - references are always counted
+//   - (all) references ane provided if RefsCallback is non-null
+//   - the symbol origin is always Static

s/ane/are/

What is RefsCallback?


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D52465



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


r342990 - [AArch64] Support adding X[8-15,18] registers as CSRs.

2018-09-25 Thread Tri Vo via cfe-commits
Author: trong
Date: Tue Sep 25 09:48:40 2018
New Revision: 342990

URL: http://llvm.org/viewvc/llvm-project?rev=342990=rev
Log:
[AArch64] Support adding X[8-15,18] registers as CSRs.

Summary:
Making X[8-15,18] registers call-saved is used to support
CONFIG_ARM64_LSE_ATOMICS in Linux kernel.

Signed-off-by: Tri Vo 

Reviewers: srhines, nickdesaulniers, javed.absar

Reviewed By: nickdesaulniers

Subscribers: kristof.beyls, jfb, cfe-commits

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

Added:
cfe/trunk/test/Driver/aarch64-call-saved-x-register.c
cfe/trunk/test/Driver/aarch64-fixed-call-saved-x-register.c
Modified:
cfe/trunk/docs/ClangCommandLineReference.rst
cfe/trunk/include/clang/Driver/Options.td
cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp

Modified: cfe/trunk/docs/ClangCommandLineReference.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangCommandLineReference.rst?rev=342990=342989=342990=diff
==
--- cfe/trunk/docs/ClangCommandLineReference.rst (original)
+++ cfe/trunk/docs/ClangCommandLineReference.rst Tue Sep 25 09:48:40 2018
@@ -2334,6 +2334,42 @@ Reserve the x18 register (AArch64 only)
 
 Reserve the x20 register (AArch64 only)
 
+.. option:: -fcall-saved-x8
+
+Make the x8 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x9
+
+Make the x9 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x10
+
+Make the x10 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x11
+
+Make the x11 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x12
+
+Make the x12 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x13
+
+Make the x13 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x14
+
+Make the x14 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x15
+
+Make the x15 register call-saved (AArch64 only)
+
+.. option:: -fcall-saved-x18
+
+Make the x18 register call-saved (AArch64 only)
+
 .. option:: -mfix-cortex-a53-835769, -mno-fix-cortex-a53-835769
 
 Workaround Cortex-A53 erratum 835769 (AArch64 only)

Modified: cfe/trunk/include/clang/Driver/Options.td
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Driver/Options.td?rev=342990=342989=342990=diff
==
--- cfe/trunk/include/clang/Driver/Options.td (original)
+++ cfe/trunk/include/clang/Driver/Options.td Tue Sep 25 09:48:40 2018
@@ -2054,6 +2054,10 @@ foreach i = {1-7,18,20} in
   def ffixed_x#i : Flag<["-"], "ffixed-x"#i>, Group,
 HelpText<"Reserve the "#i#" register (AArch64 only)">;
 
+foreach i = {8-15,18} in
+  def fcall_saved_x#i : Flag<["-"], "fcall-saved-x"#i>, 
Group,
+HelpText<"Make the x"#i#" register call-saved (AArch64 only)">;
+
 def msign_return_address : Joined<["-"], "msign-return-address=">,
   Flags<[CC1Option]>, Group,
   HelpText<"Select return address signing scope">, Values<"none,all,non-leaf">;

Modified: cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp?rev=342990=342989=342990=diff
==
--- cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp (original)
+++ cfe/trunk/lib/Driver/ToolChains/Arch/AArch64.cpp Tue Sep 25 09:48:40 2018
@@ -251,6 +251,33 @@ fp16_fml_fallthrough:
   if (Args.hasArg(options::OPT_ffixed_x20))
 Features.push_back("+reserve-x20");
 
+  if (Args.hasArg(options::OPT_fcall_saved_x8))
+Features.push_back("+call-saved-x8");
+
+  if (Args.hasArg(options::OPT_fcall_saved_x9))
+Features.push_back("+call-saved-x9");
+
+  if (Args.hasArg(options::OPT_fcall_saved_x10))
+Features.push_back("+call-saved-x10");
+
+  if (Args.hasArg(options::OPT_fcall_saved_x11))
+Features.push_back("+call-saved-x11");
+
+  if (Args.hasArg(options::OPT_fcall_saved_x12))
+Features.push_back("+call-saved-x12");
+
+  if (Args.hasArg(options::OPT_fcall_saved_x13))
+Features.push_back("+call-saved-x13");
+
+  if (Args.hasArg(options::OPT_fcall_saved_x14))
+Features.push_back("+call-saved-x14");
+
+  if (Args.hasArg(options::OPT_fcall_saved_x15))
+Features.push_back("+call-saved-x15");
+
+  if (Args.hasArg(options::OPT_fcall_saved_x18))
+Features.push_back("+call-saved-x18");
+
   if (Args.hasArg(options::OPT_mno_neg_immediates))
 Features.push_back("+no-neg-immediates");
 }

Added: cfe/trunk/test/Driver/aarch64-call-saved-x-register.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/aarch64-call-saved-x-register.c?rev=342990=auto
==
--- cfe/trunk/test/Driver/aarch64-call-saved-x-register.c (added)
+++ cfe/trunk/test/Driver/aarch64-call-saved-x-register.c Tue Sep 25 09:48:40 
2018
@@ -0,0 +1,58 @@
+// RUN: %clang -target aarch64-none-gnu -fcall-saved-x8 

[PATCH] D52259: [CUDA] Fix two failed test cases using --cuda-path-ignore-env

2018-09-25 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra added a comment.
This revision is now accepted and ready to land.

It's unfortunate that lit does not scrub the environment in order to make tests 
hermetic.


Repository:
  rC Clang

https://reviews.llvm.org/D52259



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


[PATCH] D52491: [ARM/AArch64][v8.5A] Add Armv8.5-A target

2018-09-25 Thread Sjoerd Meijer via Phabricator via cfe-commits
SjoerdMeijer accepted this revision.
SjoerdMeijer added a comment.
This revision is now accepted and ready to land.

Looks okay to me




Comment at: test/Driver/arm-cortex-cpus.c:338
+
+// RUN: %clang -target armv8a-linux-eabi -march=armv8.5-a+fp16 -### -c %s 2>&1 
| FileCheck --check-prefix CHECK-V85A-FP16 %s
+// CHECK-V85A-FP16: "-cc1"{{.*}} "-triple" "armv8.5{{.*}}" "-target-cpu" 
"generic" {{.*}}"-target-feature" "+fullfp16"

nit: perhaps move this to below, where we have the other fp16 checks?



Comment at: test/Preprocessor/arm-target-features.c:746
+
+// RUN: %clang -target armv8.4a-none-none-eabi -x c -E -dM %s -o - | FileCheck 
-match-full-lines --check-prefix=CHECK-V84A %s
+// CHECK-V84A: #define __ARM_ARCH 8

thanks for upstreaming a little bit of v8.3 and v8.4 too :-)


Repository:
  rC Clang

https://reviews.llvm.org/D52491



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


[PATCH] D52502: [Lex] TokenConcatenation now takes const Preprocessor

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

Thanks!

> any particular motivation for this?

I'm currently trying to include macro expansions in the Static Analyzer's plist 
output, and I only managed to make this happen by some `Token` handling 
hackery, including printing them. I saw this trick in 
`lib/Rewrite/HTMLRewrite.cpp`.


Repository:
  rC Clang

https://reviews.llvm.org/D52502



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


[PATCH] D52503: [clangd] More precise index memory usage estimate

2018-09-25 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added reviewers: ioeric, sammccall.
kbobyrev added a project: clang-tools-extra.
Herald added subscribers: kadircet, arphaman, jkorous, MaskRay.

This patch adds `Token`'s string data to the memory estimation. While it is 
only responsible for a couple of extra megabytes of symbol index (out of ~150 
MB) it still makes the estimate more precise.


https://reviews.llvm.org/D52503

Files:
  clang-tools-extra/clangd/index/dex/Dex.cpp


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -248,8 +248,9 @@
   Bytes += SymbolQuality.size() * sizeof(float);
   Bytes += LookupTable.getMemorySize();
   Bytes += InvertedIndex.getMemorySize();
-  for (const auto  : InvertedIndex)
-Bytes += P.second.bytes();
+  for (const auto  : InvertedIndex)
+Bytes += TokenToPostingList.first.Data.size() +
+ TokenToPostingList.second.bytes();
   return Bytes + BackingDataSize;
 }
 


Index: clang-tools-extra/clangd/index/dex/Dex.cpp
===
--- clang-tools-extra/clangd/index/dex/Dex.cpp
+++ clang-tools-extra/clangd/index/dex/Dex.cpp
@@ -248,8 +248,9 @@
   Bytes += SymbolQuality.size() * sizeof(float);
   Bytes += LookupTable.getMemorySize();
   Bytes += InvertedIndex.getMemorySize();
-  for (const auto  : InvertedIndex)
-Bytes += P.second.bytes();
+  for (const auto  : InvertedIndex)
+Bytes += TokenToPostingList.first.Data.size() +
+ TokenToPostingList.second.bytes();
   return Bytes + BackingDataSize;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D52290: [driver][mips] Adjust target triple accordingly to provided ABI name

2018-09-25 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

Should `--target=mipsZZZ -mabi=n64` be meaningful? What does `clang 
--target=i686-linux-gnu -m64` do? If this matches that, then let's do it.

I think each listed reviewer is currently at CppCon, hence the delay.


Repository:
  rC Clang

https://reviews.llvm.org/D52290



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


[PATCH] D52502: [Lex] TokenConcatenation now takes const Preprocessor

2018-09-25 Thread David Blaikie via Phabricator via cfe-commits
dblaikie accepted this revision.
dblaikie added a comment.
This revision is now accepted and ready to land.

any particular motivation for this? But looks fine to me in any case.


Repository:
  rC Clang

https://reviews.llvm.org/D52502



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


[PATCH] D52502: [Lex] TokenConcatenation now takes const Preprocessor

2018-09-25 Thread Umann Kristóf via Phabricator via cfe-commits
Szelethus created this revision.
Szelethus added a reviewer: dblaikie.
Herald added a subscriber: cfe-commits.

Repository:
  rC Clang

https://reviews.llvm.org/D52502

Files:
  include/clang/Lex/TokenConcatenation.h
  lib/Lex/TokenConcatenation.cpp


Index: lib/Lex/TokenConcatenation.cpp
===
--- lib/Lex/TokenConcatenation.cpp
+++ lib/Lex/TokenConcatenation.cpp
@@ -67,7 +67,7 @@
   return IsStringPrefix(StringRef(PP.getSpelling(Tok)), LangOpts.CPlusPlus11);
 }
 
-TokenConcatenation::TokenConcatenation(Preprocessor ) : PP(pp) {
+TokenConcatenation::TokenConcatenation(const Preprocessor ) : PP(pp) {
   memset(TokenInfo, 0, sizeof(TokenInfo));
 
   // These tokens have custom code in AvoidConcat.
@@ -126,7 +126,7 @@
 
 /// GetFirstChar - Get the first character of the token \arg Tok,
 /// avoiding calls to getSpelling where possible.
-static char GetFirstChar(Preprocessor , const Token ) {
+static char GetFirstChar(const Preprocessor , const Token ) {
   if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
 // Avoid spelling identifiers, the most common form of token.
 return II->getNameStart()[0];
Index: include/clang/Lex/TokenConcatenation.h
===
--- include/clang/Lex/TokenConcatenation.h
+++ include/clang/Lex/TokenConcatenation.h
@@ -29,7 +29,7 @@
   /// and ")" next to each other is safe.
   ///
   class TokenConcatenation {
-Preprocessor 
+const Preprocessor 
 
 enum AvoidConcatInfo {
   /// By default, a token never needs to avoid concatenation.  Most tokens
@@ -56,7 +56,7 @@
 /// method.
 char TokenInfo[tok::NUM_TOKENS];
   public:
-TokenConcatenation(Preprocessor );
+TokenConcatenation(const Preprocessor );
 
 bool AvoidConcat(const Token ,
  const Token ,


Index: lib/Lex/TokenConcatenation.cpp
===
--- lib/Lex/TokenConcatenation.cpp
+++ lib/Lex/TokenConcatenation.cpp
@@ -67,7 +67,7 @@
   return IsStringPrefix(StringRef(PP.getSpelling(Tok)), LangOpts.CPlusPlus11);
 }
 
-TokenConcatenation::TokenConcatenation(Preprocessor ) : PP(pp) {
+TokenConcatenation::TokenConcatenation(const Preprocessor ) : PP(pp) {
   memset(TokenInfo, 0, sizeof(TokenInfo));
 
   // These tokens have custom code in AvoidConcat.
@@ -126,7 +126,7 @@
 
 /// GetFirstChar - Get the first character of the token \arg Tok,
 /// avoiding calls to getSpelling where possible.
-static char GetFirstChar(Preprocessor , const Token ) {
+static char GetFirstChar(const Preprocessor , const Token ) {
   if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
 // Avoid spelling identifiers, the most common form of token.
 return II->getNameStart()[0];
Index: include/clang/Lex/TokenConcatenation.h
===
--- include/clang/Lex/TokenConcatenation.h
+++ include/clang/Lex/TokenConcatenation.h
@@ -29,7 +29,7 @@
   /// and ")" next to each other is safe.
   ///
   class TokenConcatenation {
-Preprocessor 
+const Preprocessor 
 
 enum AvoidConcatInfo {
   /// By default, a token never needs to avoid concatenation.  Most tokens
@@ -56,7 +56,7 @@
 /// method.
 char TokenInfo[tok::NUM_TOKENS];
   public:
-TokenConcatenation(Preprocessor );
+TokenConcatenation(const Preprocessor );
 
 bool AvoidConcat(const Token ,
  const Token ,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D51120: clang-format Additional Indent for class blocks

2018-09-25 Thread Darby Payne via Phabricator via cfe-commits
dpayne added a comment.

@djasper @klimek

Are there any comments here about this approach?


Repository:
  rC Clang

https://reviews.llvm.org/D51120



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


[PATCH] D45050: [clang-tidy] New checker for not null-terminated result caused by strlen(), size() or equal length

2018-09-25 Thread Whisperity via Phabricator via cfe-commits
whisperity added a comment.

I have checked the results, thank you for uploading them, they look solid to 
me, although I'm not exactly a developer for these projects, without full 
understanding of what and where allocates and true path-sensitive analysis and 
memory modelling, they look good. (E.g. one thing this check misses I think is 
when the allocator returns an explicitly zero-filled memory, because that way 
the write without the good size is //still// NUL-terminated... but this 
requires modelling we might just not be capable of, especially not in 
Clang-Tidy.)

With a bit of focused glancing, the check's code is also understandable, 
thanks. :)


https://reviews.llvm.org/D45050



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


[PATCH] D52499: [clang-cl] Make /Gs imply default stack probes, not /Gs0 (PR39074)

2018-09-25 Thread Hans Wennborg via Phabricator via cfe-commits
hans created this revision.
hans added reviewers: thakis, rnk.

Also remove text saying /https://reviews.llvm.org/owners/package/1/ and 
/https://reviews.llvm.org/owners/package/2/ implies /Gs. They don't seem to do 
that, at least with modern MSVC (see bug).


https://reviews.llvm.org/D52499

Files:
  include/clang/Driver/CLCompatOptions.td
  test/Driver/cl-options.c


Index: test/Driver/cl-options.c
===
--- test/Driver/cl-options.c
+++ test/Driver/cl-options.c
@@ -101,7 +101,7 @@
 // Gy_-NOT: -ffunction-sections
 
 // RUN: %clang_cl /Gs -### -- %s 2>&1 | FileCheck -check-prefix=Gs %s
-// Gs: "-mstack-probe-size=0"
+// Gs: "-mstack-probe-size=4096"
 // RUN: %clang_cl /Gs0 -### -- %s 2>&1 | FileCheck -check-prefix=Gs0 %s
 // Gs0: "-mstack-probe-size=0"
 // RUN: %clang_cl /Gs4096 -### -- %s 2>&1 | FileCheck -check-prefix=Gs4096 %s
Index: include/clang/Driver/CLCompatOptions.td
===
--- include/clang/Driver/CLCompatOptions.td
+++ include/clang/Driver/CLCompatOptions.td
@@ -90,8 +90,8 @@
   Alias;
 def _SLASH_GS : CLFlag<"GS">, HelpText<"Enable buffer security check 
(default)">;
 def _SLASH_GS_ : CLFlag<"GS-">, HelpText<"Disable buffer security check">;
-// FIXME: Not sure /Gs really means /Gs0 (see PR39074).
-def : CLFlag<"Gs">, HelpText<"Same as /Gs0">, Alias, 
AliasArgs<["0"]>;
+def : CLFlag<"Gs">, HelpText<"Use stack probes (default)">,
+  Alias, AliasArgs<["4096"]>;
 def _SLASH_Gs : CLJoined<"Gs">,
   HelpText<"Set stack probe size (default 4096)">, Alias;
 def _SLASH_Gy : CLFlag<"Gy">, HelpText<"Put each function in its own section">,
@@ -121,9 +121,9 @@
 // FIXME: Not sure why we have -O0 here; MSVC doesn't support that.
 def : CLFlag<"O0">, Alias, HelpText<"Disable optimization">;
 def : CLFlag<"O1">, Alias<_SLASH_O>, AliasArgs<["1"]>,
-  HelpText<"Optimize for size (equivalent to /Og /Os /Oy /Ob2 /Gs /GF /Gy)">;
+  HelpText<"Optimize for size (equivalent to /Og /Os /Oy /Ob2 /GF /Gy)">;
 def : CLFlag<"O2">, Alias<_SLASH_O>, AliasArgs<["2"]>,
-  HelpText<"Optimize for speed (equivalent to /Og /Oi /Ot /Oy /Ob2 /Gs /GF 
/Gy)">;
+  HelpText<"Optimize for speed (equivalent to /Og /Oi /Ot /Oy /Ob2 /GF /Gy)">;
 def : CLFlag<"Ob0">, Alias<_SLASH_O>, AliasArgs<["b0"]>,
   HelpText<"Disable function inlining">;
 def : CLFlag<"Ob1">, Alias<_SLASH_O>, AliasArgs<["b1"]>,


Index: test/Driver/cl-options.c
===
--- test/Driver/cl-options.c
+++ test/Driver/cl-options.c
@@ -101,7 +101,7 @@
 // Gy_-NOT: -ffunction-sections
 
 // RUN: %clang_cl /Gs -### -- %s 2>&1 | FileCheck -check-prefix=Gs %s
-// Gs: "-mstack-probe-size=0"
+// Gs: "-mstack-probe-size=4096"
 // RUN: %clang_cl /Gs0 -### -- %s 2>&1 | FileCheck -check-prefix=Gs0 %s
 // Gs0: "-mstack-probe-size=0"
 // RUN: %clang_cl /Gs4096 -### -- %s 2>&1 | FileCheck -check-prefix=Gs4096 %s
Index: include/clang/Driver/CLCompatOptions.td
===
--- include/clang/Driver/CLCompatOptions.td
+++ include/clang/Driver/CLCompatOptions.td
@@ -90,8 +90,8 @@
   Alias;
 def _SLASH_GS : CLFlag<"GS">, HelpText<"Enable buffer security check (default)">;
 def _SLASH_GS_ : CLFlag<"GS-">, HelpText<"Disable buffer security check">;
-// FIXME: Not sure /Gs really means /Gs0 (see PR39074).
-def : CLFlag<"Gs">, HelpText<"Same as /Gs0">, Alias, AliasArgs<["0"]>;
+def : CLFlag<"Gs">, HelpText<"Use stack probes (default)">,
+  Alias, AliasArgs<["4096"]>;
 def _SLASH_Gs : CLJoined<"Gs">,
   HelpText<"Set stack probe size (default 4096)">, Alias;
 def _SLASH_Gy : CLFlag<"Gy">, HelpText<"Put each function in its own section">,
@@ -121,9 +121,9 @@
 // FIXME: Not sure why we have -O0 here; MSVC doesn't support that.
 def : CLFlag<"O0">, Alias, HelpText<"Disable optimization">;
 def : CLFlag<"O1">, Alias<_SLASH_O>, AliasArgs<["1"]>,
-  HelpText<"Optimize for size (equivalent to /Og /Os /Oy /Ob2 /Gs /GF /Gy)">;
+  HelpText<"Optimize for size (equivalent to /Og /Os /Oy /Ob2 /GF /Gy)">;
 def : CLFlag<"O2">, Alias<_SLASH_O>, AliasArgs<["2"]>,
-  HelpText<"Optimize for speed (equivalent to /Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy)">;
+  HelpText<"Optimize for speed (equivalent to /Og /Oi /Ot /Oy /Ob2 /GF /Gy)">;
 def : CLFlag<"Ob0">, Alias<_SLASH_O>, AliasArgs<["b0"]>,
   HelpText<"Disable function inlining">;
 def : CLFlag<"Ob1">, Alias<_SLASH_O>, AliasArgs<["b1"]>,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >