[PATCH] D92039: [-Wcalled-once-parameter] Introduce 'called_once' attribute

2020-12-18 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D92039#2458392 , @aaron.ballman 
wrote:

> 



> There have been efforts to add cross-TU support to the static analyzer, so 
> I'm less worried about cross-TU inter-procedural bugs over the long term as I 
> would expect that situation to be improved.

I'm a bit less optimistic on that front, the whole model of how we do the 
analysis should be redesigned in order to get true cross-TU inter-procedural 
analysis.  Additionally, some checkers when essentially inter-procedural rely 
on function conventions to assume behavior of called functions, the same way it 
is done with this analysis.

> I think my concern is somewhat different. If the goal is for the semantics to 
> follow the parameter (which I also think is the correct behavior), then I 
> think adding this as a frontend analysis is the incorrect place for the check 
> to go because someday we're going to want the inter-procedural analysis and 
> that will require us to figure out what to do with the frontend bits vs the 
> static analyzer bits. If it starts off in the static analyzer, then the later 
> improvements to the analysis capabilities don't require the user to change 
> the way they interact with the toolchain.
>
> Or do you expect that this analysis is sufficient and you don't expect to 
> ever extend it to be inter-procedural?

As I noted above, in some sense it is already inter-procedural because usually 
called functions follow completion handler conventions as well.
So, we can actually make it inter-procedural if all involved functions follow 
conventions.  And we can warn people if they leak `called_once` parameter into 
a function that doesn't specify what it will do with that parameter.

It was a decision not to do this and to be more lenient in the first version.  
You can see that in a lot of cases during the analysis we assume that the user 
knows what they are doing.  And even in this model the number of reported 
warnings is pretty high.
We hope that this warning will help to change those cases and, maybe in the 
future, we can harden the analysis to be more demanding.




Comment at: clang/lib/Analysis/CalledOnceCheck.cpp:83
+//   1. for any Kind K: NoReturn | K == K
+//   2. for any Kind K: Reported | K == K
+//   3. for any Kind K: K | K == K




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92039

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


[PATCH] D93522: [WIP] [clangd] Extend heuristic resolution to support nested templates

2020-12-18 Thread Nathan Ridge via Phabricator via cfe-commits
nridge created this revision.
Herald added subscribers: usaxena95, kadircet, arphaman, javed.absar.
nridge requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

https://github.com/clangd/clangd/issues/451


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93522

Files:
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/FindTarget.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/ParsedAST.h
  clang-tools-extra/clangd/TUScheduler.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TestTU.h
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -1165,7 +1165,8 @@
   for (const auto *Case : Tests) {
 SCOPED_TRACE(Case);
 auto T = Annotations(Case);
-auto AST = TestTU::withCode(T.code()).build();
+TestTU TU = TestTU::withCode(T.code());
+auto AST = TU.build();
 EXPECT_THAT(locateSymbolAt(AST, T.point()),
 UnorderedPointwise(DeclRange(), T.ranges()));
   }
Index: clang-tools-extra/clangd/unittests/TestTU.h
===
--- clang-tools-extra/clangd/unittests/TestTU.h
+++ clang-tools-extra/clangd/unittests/TestTU.h
@@ -76,9 +76,10 @@
   // to eliminate this option some day.
   bool OverlayRealFileSystemForModules = false;
 
-  // This is used to add the ASTContext of the AST produced by build() to the
-  // clangd Context.
+  // This is used to add the ASTContext and Sema of the AST produced by build()
+  // to the clangd Context.
   mutable std::unique_ptr ASTCtx;
+  mutable std::unique_ptr SemaCtx;
 
   // By default, build() will report Error diagnostics as GTest errors.
   // Suppress this behavior by adding an 'error-ok' comment to the code.
Index: clang-tools-extra/clangd/unittests/TestTU.cpp
===
--- clang-tools-extra/clangd/unittests/TestTU.cpp
+++ clang-tools-extra/clangd/unittests/TestTU.cpp
@@ -141,6 +141,8 @@
   }
   ASTCtx = std::make_unique(ParsedAST::CurrentASTContext,
   &AST->getASTContext());
+  SemaCtx = std::make_unique(ParsedAST::CurrentSema,
+   &AST->getSema());
   return std::move(*AST);
 }
 
Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -227,7 +227,8 @@
   };
 )cpp";
   EXPECT_DECLS("UnresolvedUsingValueDecl", {"using Base::waldo", Rel::Alias},
-   {"void waldo()"});
+   {"void waldo()", Rel::TemplatePattern},
+   {"void waldo()", Rel::TemplateInstantiation});
 }
 
 TEST_F(TargetDeclTest, ConstructorInitList) {
@@ -737,6 +738,20 @@
   )cpp";
   EXPECT_DECLS("CXXDependentScopeMemberExpr",
"template  T convert() const");
+
+  Code = R"cpp(
+template 
+struct vector {
+  T front();
+};
+template 
+void foo(vector> c) {
+  c.front().[[front]]();
+}
+  )cpp";
+  EXPECT_DECLS("CXXDependentScopeMemberExpr",
+   {"T front()", Rel::TemplatePattern},
+   {"type-parameter-0-0 front()", Rel::TemplateInstantiation});
 }
 
 TEST_F(TargetDeclTest, DependentTypes) {
@@ -750,7 +765,8 @@
 template 
 void foo(typename A::[[B]]);
   )cpp";
-  EXPECT_DECLS("DependentNameTypeLoc", "struct B");
+  EXPECT_DECLS("DependentNameTypeLoc", {"struct B", Rel::TemplatePattern},
+   {"struct B", Rel::TemplateInstantiation});
 
   // Heuristic resolution of dependent type name which doesn't get a TypeLoc
   Code = R"cpp(
@@ -760,7 +776,8 @@
 template 
 void foo(typename A::[[B]]::C);
   )cpp";
-  EXPECT_DECLS("NestedNameSpecifierLoc", "struct B");
+  EXPECT_DECLS("NestedNameSpecifierLoc", {"struct B", Rel::TemplatePattern},
+   {"struct B", Rel::TemplateInstantiation});
 
   // Heuristic resolution of dependent type name whose qualifier is also
   // dependent
@@ -986,37 +1003,36 @@
 
 TEST_F(FindExplicitReferencesTest, All) {
   std::pair Cases[] =
-  {
-  // Simple expressions.
-  {R"cpp(
+  {// Simple expressions.
+   {R"cpp(
 int global;
 int func();
 void foo(int param) {
   $0^global = $1^param + $2^func();
 }
 )cpp",
-   "0: targets = {global}\n"
-   "1: targets = {param}\n"
-   "2: targets = {func}\n"},
-

[clang] f4511ae - [clang][cli] Port HeaderSearch simple string options to new option parsing system

2020-12-18 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2020-12-18T09:30:32+01:00
New Revision: f4511aec2bf482f2ae5bbd14138a229b72c41c80

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

LOG: [clang][cli] Port HeaderSearch simple string options to new option parsing 
system

Depends on D84669

Reviewed By: Bigcheese

Original patch by Daniel Grumberg.

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 9987143009d3..7275e84d7c53 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1797,7 +1797,8 @@ def fmodules_cache_path : Joined<["-"], 
"fmodules-cache-path=">, Group,
   HelpText<"Specify the module cache path">;
 def fmodules_user_build_path : Separate<["-"], "fmodules-user-build-path">, 
Group,
   Flags<[NoXarchOption, CC1Option]>, MetaVarName<"">,
-  HelpText<"Specify the module user build path">;
+  HelpText<"Specify the module user build path">,
+  MarshallingInfoString<"HeaderSearchOpts->ModuleUserBuildPath">;
 def fprebuilt_module_path : Joined<["-"], "fprebuilt-module-path=">, 
Group,
   Flags<[NoXarchOption, CC1Option]>, MetaVarName<"">,
   HelpText<"Specify the prebuilt module path">;
@@ -1806,16 +1807,19 @@ defm prebuilt_implicit_modules : 
OptInFFlag<"prebuilt-implicit-modules",
   [NoXarchOption, CC1Option], 
"HeaderSearchOpts->EnablePrebuiltImplicitModules">;
 def fmodules_prune_interval : Joined<["-"], "fmodules-prune-interval=">, 
Group,
   Flags<[CC1Option]>, MetaVarName<"">,
-  HelpText<"Specify the interval (in seconds) between attempts to prune the 
module cache">;
+  HelpText<"Specify the interval (in seconds) between attempts to prune the 
module cache">,
+  MarshallingInfoStringInt<"HeaderSearchOpts->ModuleCachePruneInterval", "7 * 
24 * 60 * 60">;
 def fmodules_prune_after : Joined<["-"], "fmodules-prune-after=">, 
Group,
   Flags<[CC1Option]>, MetaVarName<"">,
-  HelpText<"Specify the interval (in seconds) after which a module file will 
be considered unused">;
+  HelpText<"Specify the interval (in seconds) after which a module file will 
be considered unused">,
+  MarshallingInfoStringInt<"HeaderSearchOpts->ModuleCachePruneAfter", "31 * 24 
* 60 * 60">;
 def fmodules_search_all : Flag <["-"], "fmodules-search-all">, Group,
   Flags<[NoXarchOption, CC1Option]>,
   HelpText<"Search even non-imported modules to resolve references">;
 def fbuild_session_timestamp : Joined<["-"], "fbuild-session-timestamp=">,
   Group, Flags<[CC1Option]>, MetaVarName<"">,
-  HelpText<"Time when the current build session started">;
+  HelpText<"Time when the current build session started">,
+  MarshallingInfoStringInt<"HeaderSearchOpts->BuildSessionTimestamp">;
 def fbuild_session_file : Joined<["-"], "fbuild-session-file=">,
   Group, MetaVarName<"">,
   HelpText<"Use the last modification time of  as the build session 
timestamp">;
@@ -2602,7 +2606,8 @@ def iprefix : JoinedOrSeparate<["-"], "iprefix">, 
Group, Flags<[C
 def iquote : JoinedOrSeparate<["-"], "iquote">, Group, 
Flags<[CC1Option]>,
   HelpText<"Add directory to QUOTE include search path">, 
MetaVarName<"">;
 def isysroot : JoinedOrSeparate<["-"], "isysroot">, Group, 
Flags<[CC1Option]>,
-  HelpText<"Set the system root directory (usually /)">, MetaVarName<"">;
+  HelpText<"Set the system root directory (usually /)">, MetaVarName<"">,
+  MarshallingInfoString<"HeaderSearchOpts->Sysroot", [{"/"}]>;
 def isystem : JoinedOrSeparate<["-"], "isystem">, Group,
   Flags<[CC1Option]>,
   HelpText<"Add directory to SYSTEM include search path">, 
MetaVarName<"">;
@@ -3330,7 +3335,8 @@ def rewrite_legacy_objc : Flag<["-"], 
"rewrite-legacy-objc">, Flags<[NoXarchOpti
 def rdynamic : Flag<["-"], "rdynamic">, Group;
 def resource_dir : Separate<["-"], "resource-dir">,
   Flags<[NoXarchOption, CC1Option, CoreOption, HelpHidden]>,
-  HelpText<"The directory which holds the compiler resource files">;
+  HelpText<"The directory which holds the compiler resource files">,
+  MarshallingInfoString<"HeaderSearchOpts->ResourceDir">;
 def resource_dir_EQ : Joined<["-"], "resource-dir=">, Flags<[NoXarchOption, 
CoreOption]>,
   Alias;
 def rpath : Separate<["-"], "rpath">, Flags<[LinkerInput]>, Group;
@@ -4671,7 +4677,8 @@ def fmodules_debuginfo :
   MarshallingInfoFlag<"LangOpts->ModulesDebugInfo">;
 def fmodule_format_EQ : Joined<["-"], "fmodule-format=">,
   HelpText<"Select the container format for clang modules and PCH. "
-   "Supported options are 'raw' and 'obj'.">;
+   "Supported options are 'raw' and 'obj'.">,
+  MarshallingInfoString<"HeaderSearchOpts->ModuleFormat", [{"ra

[PATCH] D84670: [clang][cli] Port HeaderSearch simple string options to new option parsing system

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf4511aec2bf4: [clang][cli] Port HeaderSearch simple string 
options to new option parsing… (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D84670?vs=312176&id=312702#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84670

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2028,10 +2028,8 @@
 
 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
   const std::string &WorkingDir) {
-  Opts.Sysroot = std::string(Args.getLastArgValue(OPT_isysroot, "/"));
   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
-  Opts.ResourceDir = std::string(Args.getLastArgValue(OPT_resource_dir));
 
   // Canonicalize -fmodules-cache-path before storing it.
   SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
@@ -2044,8 +2042,6 @@
   llvm::sys::path::remove_dots(P);
   Opts.ModuleCachePath = std::string(P.str());
 
-  Opts.ModuleUserBuildPath =
-  std::string(Args.getLastArgValue(OPT_fmodules_user_build_path));
   // Only the -fmodule-file== form.
   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
 StringRef Val = A->getValue();
@@ -2057,14 +2053,6 @@
   }
   for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
 Opts.AddPrebuiltModulePath(A->getValue());
-  Opts.ModuleCachePruneInterval =
-  getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
-  Opts.ModuleCachePruneAfter =
-  getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
-  Opts.BuildSessionTimestamp =
-  getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
-  if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ))
-Opts.ModuleFormat = A->getValue();
 
   for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
 StringRef MacroDef = A->getValue();
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1797,7 +1797,8 @@
   HelpText<"Specify the module cache path">;
 def fmodules_user_build_path : Separate<["-"], "fmodules-user-build-path">, Group,
   Flags<[NoXarchOption, CC1Option]>, MetaVarName<"">,
-  HelpText<"Specify the module user build path">;
+  HelpText<"Specify the module user build path">,
+  MarshallingInfoString<"HeaderSearchOpts->ModuleUserBuildPath">;
 def fprebuilt_module_path : Joined<["-"], "fprebuilt-module-path=">, Group,
   Flags<[NoXarchOption, CC1Option]>, MetaVarName<"">,
   HelpText<"Specify the prebuilt module path">;
@@ -1806,16 +1807,19 @@
   [NoXarchOption, CC1Option], "HeaderSearchOpts->EnablePrebuiltImplicitModules">;
 def fmodules_prune_interval : Joined<["-"], "fmodules-prune-interval=">, Group,
   Flags<[CC1Option]>, MetaVarName<"">,
-  HelpText<"Specify the interval (in seconds) between attempts to prune the module cache">;
+  HelpText<"Specify the interval (in seconds) between attempts to prune the module cache">,
+  MarshallingInfoStringInt<"HeaderSearchOpts->ModuleCachePruneInterval", "7 * 24 * 60 * 60">;
 def fmodules_prune_after : Joined<["-"], "fmodules-prune-after=">, Group,
   Flags<[CC1Option]>, MetaVarName<"">,
-  HelpText<"Specify the interval (in seconds) after which a module file will be considered unused">;
+  HelpText<"Specify the interval (in seconds) after which a module file will be considered unused">,
+  MarshallingInfoStringInt<"HeaderSearchOpts->ModuleCachePruneAfter", "31 * 24 * 60 * 60">;
 def fmodules_search_all : Flag <["-"], "fmodules-search-all">, Group,
   Flags<[NoXarchOption, CC1Option]>,
   HelpText<"Search even non-imported modules to resolve references">;
 def fbuild_session_timestamp : Joined<["-"], "fbuild-session-timestamp=">,
   Group, Flags<[CC1Option]>, MetaVarName<"">,
-  HelpText<"Time when the current build session started">;
+  HelpText<"Time when the current build session started">,
+  MarshallingInfoStringInt<"HeaderSearchOpts->BuildSessionTimestamp">;
 def fbuild_session_file : Joined<["-"], "fbuild-session-file=">,
   Group, MetaVarName<"">,
   HelpText<"Use the last modification time of  as the build session timestamp">;
@@ -2602,7 +2606,8 @@
 def iquote : JoinedOrSeparate<["-"], "iquote">, Group, Flags<[CC1Option]>,
   HelpText<"Add directory to QUOTE include search path">, MetaVarName<"">;
 def isysroot : JoinedOrSeparate<["-"], "isysroot">, Group, Flags<[CC1Option]>,
-  HelpText<"Set the 

[PATCH] D84670: [clang][cli] Port HeaderSearch simple string options to new option parsing system

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

Committing with whitespace fix and with `std::string` constructors removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84670

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


[PATCH] D92290: [clangd] Use clangd's Context mechanism to make the ASTContext of the AST being operated on available everywhere

2020-12-18 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

In D92290#2460748 , @sammccall wrote:

> my manager was appalled when we added it...

:-)

> Does this enable some future work, or is it reasonable to evaluate this patch 
> in isolation?

I was inspired to do this by a work-in-progress patch I have to fix 
https://github.com/clangd/clangd/issues/451, for which I need to make `Sema` 
available in a similar way. That patch isn't quite ready for review (there are 
some crashes / assertion failures that I need to iron out), but I posted what I 
have so far at D93522  if you're curious.

> Here it's a mandatory input, and the alternative is cluttering a couple of 
> layers of purely-private interfaces, so this seems like a lot of magic to 
> avoid a fairly small amount of awkwardness.

I agree that there is no fundamental need to use `Context`, it just seemed 
convenient (and hey, `ASTContext` even has `Context` in its name :-)). I could 
just pass the `ASTContext` as a parameter to `targetDecl()` and other relevant 
functions.

Perhaps, with a view to eventually needing `Sema` as well, I should just pass 
`ParsedAST` instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92290

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


[PATCH] D93522: [WIP] [clangd] Extend heuristic resolution to support nested templates

2020-12-18 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

(This is not ready for review, I just posted it in case it helps inform 
discussion in D92290 .)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93522

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


[clang] ff4b76d - [clang][cli] Port TargetOpts simple string based options to new option parsing system

2020-12-18 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2020-12-18T09:40:56+01:00
New Revision: ff4b76d74f38a3816495c9914789e87a95525cf4

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

LOG: [clang][cli] Port TargetOpts simple string based options to new option 
parsing system

Depends on D84190

Reviewed By: Bigcheese

Original patch by Daniel Grumberg.

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 7275e84d7c53..b92244fd2f18 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2690,7 +2690,8 @@ def mwatchos_simulator_version_min_EQ : Joined<["-"], 
"mwatchos-simulator-versio
 def mwatchsimulator_version_min_EQ : Joined<["-"], 
"mwatchsimulator-version-min=">, Alias;
 def march_EQ : Joined<["-"], "march=">, Group, Flags<[CoreOption]>;
 def masm_EQ : Joined<["-"], "masm=">, Group, Flags<[NoXarchOption]>;
-def mcmodel_EQ : Joined<["-"], "mcmodel=">, Group, Flags<[CC1Option]>;
+def mcmodel_EQ : Joined<["-"], "mcmodel=">, Group, Flags<[CC1Option]>,
+  MarshallingInfoString<"TargetOpts->CodeModel", [{"default"}]>;
 def mtls_size_EQ : Joined<["-"], "mtls-size=">, Group, 
Flags<[NoXarchOption, CC1Option]>,
   HelpText<"Specify bit size of immediate TLS offsets (AArch64 ELF only): "
"12 (for 4KB) | 24 (for 16MB, default) | 32 (for 4GB) | 48 (for 
256TB, needs -mcmodel=large)">;
@@ -2760,7 +2761,10 @@ def mno_stack_arg_probe : Flag<["-"], 
"mno-stack-arg-probe">, Group, Fl
 def mthread_model : Separate<["-"], "mthread-model">, Group, 
Flags<[CC1Option]>,
   HelpText<"The thread model to use, e.g. posix, single (posix by default)">, 
Values<"posix,single">;
 def meabi : Separate<["-"], "meabi">, Group, Flags<[CC1Option]>,
-  HelpText<"Set EABI type, e.g. 4, 5 or gnu (default depends on triple)">, 
Values<"default,4,5,gnu">;
+  HelpText<"Set EABI type, e.g. 4, 5 or gnu (default depends on triple)">, 
Values<"default,4,5,gnu">,
+  MarshallingInfoString<"TargetOpts->EABIVersion", "Default">,
+  NormalizedValuesScope<"llvm::EABI">,
+  NormalizedValues<["Default", "EABI4", "EABI5", "GNU"]>, AutoNormalizeEnum;
 
 def mno_constant_cfstrings : Flag<["-"], "mno-constant-cfstrings">, 
Group;
 def mno_global_merge : Flag<["-"], "mno-global-merge">, Group, 
Flags<[CC1Option]>,
@@ -4052,9 +4056,11 @@ let Flags = [CC1Option, NoDriverOption] in {
 let Flags = [CC1Option, CC1AsOption, NoDriverOption] in {
 
 def target_cpu : Separate<["-"], "target-cpu">,
-  HelpText<"Target a specific cpu type">;
+  HelpText<"Target a specific cpu type">,
+  MarshallingInfoString<"TargetOpts->CPU">;
 def tune_cpu : Separate<["-"], "tune-cpu">,
-  HelpText<"Tune for a specific cpu type">;
+  HelpText<"Tune for a specific cpu type">,
+  MarshallingInfoString<"TargetOpts->TuneCPU">;
 def target_feature : Separate<["-"], "target-feature">,
   HelpText<"Target specific attributes">;
 def triple : Separate<["-"], "triple">,
@@ -4062,17 +4068,20 @@ def triple : Separate<["-"], "triple">,
   MarshallingInfoString<"TargetOpts->Triple", 
"llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple())">,
   AlwaysEmit, Normalizer<"normalizeTriple">;
 def target_abi : Separate<["-"], "target-abi">,
-  HelpText<"Target a particular ABI type">;
+  HelpText<"Target a particular ABI type">,
+  MarshallingInfoString<"TargetOpts->ABI">;
 def target_sdk_version_EQ : Joined<["-"], "target-sdk-version=">,
   HelpText<"The version of target SDK used for compilation">;
 
 }
 
 def target_linker_version : Separate<["-"], "target-linker-version">,
-  HelpText<"Target linker version">;
+  HelpText<"Target linker version">,
+  MarshallingInfoString<"TargetOpts->LinkerVersion">;
 def triple_EQ : Joined<["-"], "triple=">, Alias;
 def mfpmath : Separate<["-"], "mfpmath">,
-  HelpText<"Which unit to use for fp math">;
+  HelpText<"Which unit to use for fp math">,
+  MarshallingInfoString<"TargetOpts->FPMath">;
 
 def fpadding_on_unsigned_fixed_point : Flag<["-"], 
"fpadding-on-unsigned-fixed-point">,
   HelpText<"Force each unsigned fixed point type to have an extra bit of 
padding to align their scales with those of signed fixed point types">;

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index f7bb2308953f..ea0cc74217ff 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -244,10 +244,10 @@ static llvm::Optional 
normalizeSimpleEnum(OptSpecifier Opt,
   return None;
 }
 
-static void denormalizeSimpleEnum(SmallVectorImpl &Args,
-  const char *Spelling,
-   

[PATCH] D84668: [clang][cli] Port TargetOpts simple string based options to new option parsing system

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGff4b76d74f38: [clang][cli] Port TargetOpts simple string 
based options to new option parsing… (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D84668?vs=312171&id=312704#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84668

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -244,10 +244,10 @@
   return None;
 }
 
-static void denormalizeSimpleEnum(SmallVectorImpl &Args,
-  const char *Spelling,
-  CompilerInvocation::StringAllocator SA,
-  unsigned TableIndex, unsigned Value) {
+static void denormalizeSimpleEnumImpl(SmallVectorImpl &Args,
+  const char *Spelling,
+  CompilerInvocation::StringAllocator SA,
+  unsigned TableIndex, unsigned Value) {
   assert(TableIndex < SimpleEnumValueTablesSize);
   const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
   if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
@@ -259,6 +259,15 @@
   }
 }
 
+template 
+static void denormalizeSimpleEnum(SmallVectorImpl &Args,
+  const char *Spelling,
+  CompilerInvocation::StringAllocator SA,
+  unsigned TableIndex, T Value) {
+  return denormalizeSimpleEnumImpl(Args, Spelling, SA, TableIndex,
+   static_cast(Value));
+}
+
 static void denormalizeSimpleEnumJoined(SmallVectorImpl &Args,
 const char *Spelling,
 CompilerInvocation::StringAllocator SA,
@@ -3357,28 +3366,7 @@
 
 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
 DiagnosticsEngine &Diags) {
-  Opts.CodeModel = std::string(Args.getLastArgValue(OPT_mcmodel_EQ, "default"));
-  Opts.ABI = std::string(Args.getLastArgValue(OPT_target_abi));
-  if (Arg *A = Args.getLastArg(OPT_meabi)) {
-StringRef Value = A->getValue();
-llvm::EABI EABIVersion = llvm::StringSwitch(Value)
- .Case("default", llvm::EABI::Default)
- .Case("4", llvm::EABI::EABI4)
- .Case("5", llvm::EABI::EABI5)
- .Case("gnu", llvm::EABI::GNU)
- .Default(llvm::EABI::Unknown);
-if (EABIVersion == llvm::EABI::Unknown)
-  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
-<< Value;
-else
-  Opts.EABIVersion = EABIVersion;
-  }
-  Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));
-  Opts.TuneCPU = std::string(Args.getLastArgValue(OPT_tune_cpu));
-  Opts.FPMath = std::string(Args.getLastArgValue(OPT_mfpmath));
   Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
-  Opts.LinkerVersion =
-  std::string(Args.getLastArgValue(OPT_target_linker_version));
   Opts.OpenCLExtensionsAsWritten = Args.getAllArgValues(OPT_cl_ext_EQ);
   Opts.AllowAMDGPUUnsafeFPAtomics =
   Args.hasFlag(options::OPT_munsafe_fp_atomics,
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2690,7 +2690,8 @@
 def mwatchsimulator_version_min_EQ : Joined<["-"], "mwatchsimulator-version-min=">, Alias;
 def march_EQ : Joined<["-"], "march=">, Group, Flags<[CoreOption]>;
 def masm_EQ : Joined<["-"], "masm=">, Group, Flags<[NoXarchOption]>;
-def mcmodel_EQ : Joined<["-"], "mcmodel=">, Group, Flags<[CC1Option]>;
+def mcmodel_EQ : Joined<["-"], "mcmodel=">, Group, Flags<[CC1Option]>,
+  MarshallingInfoString<"TargetOpts->CodeModel", [{"default"}]>;
 def mtls_size_EQ : Joined<["-"], "mtls-size=">, Group, Flags<[NoXarchOption, CC1Option]>,
   HelpText<"Specify bit size of immediate TLS offsets (AArch64 ELF only): "
"12 (for 4KB) | 24 (for 16MB, default) | 32 (for 4GB) | 48 (for 256TB, needs -mcmodel=large)">;
@@ -2760,7 +2761,10 @@
 def mthread_model : Separate<["-"], "mthread-model">, Group, Flags<[CC1Option]>,
   HelpText<"The thread model to use, e.g. posix, single (posix by default)">, Values<"posix,single">;
 def meabi : Separate<["-"], "meabi">, Group, Flags<[CC1Option]>,
-  HelpText<"Set EABI type, e.g. 4, 5 or gnu (default depends

[clang] aec2991 - [clang][cli] Port LangOpts simple string based options to new option parsing system

2020-12-18 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2020-12-18T09:44:02+01:00
New Revision: aec2991d083a9c5b92f94d84a7b3a7bbed405af8

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

LOG: [clang][cli] Port LangOpts simple string based options to new option 
parsing system

Depends on D84670

Reviewed By: Bigcheese

Original patch by Daniel Grumberg.

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticFrontendKinds.td
clang/include/clang/Driver/Options.td
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index def189f65994..b9f8c78e43da 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -108,8 +108,6 @@ def err_fe_action_not_available : Error<
 "action %0 not compiled in">;
 def err_fe_invalid_alignment : Error<
 "invalid value '%1' in '%0'; alignment must be a power of 2">;
-def err_fe_invalid_wchar_type
-: Error<"invalid wchar_t type '%0'; must be one of 'char', 'short', 
'int'">;
 def err_fe_invalid_exception_model
: Error<"invalid exception model 
'%select{none|dwarf|sjlj|arm|seh|wasm|aix}0' for target '%1'">;
 def warn_fe_concepts_ts_flag : Warning<

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index b92244fd2f18..f7e3b298bccd 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -994,7 +994,8 @@ def interface_stub_version_EQ : JoinedOrSeparate<["-"], 
"interface-stub-version=
 def exported__symbols__list : Separate<["-"], "exported_symbols_list">;
 def e : JoinedOrSeparate<["-"], "e">, Flags<[LinkerInput]>, Group;
 def fmax_tokens_EQ : Joined<["-"], "fmax-tokens=">, Group, 
Flags<[CC1Option]>,
-  HelpText<"Max total number of preprocessed tokens for -Wmax-tokens.">;
+  HelpText<"Max total number of preprocessed tokens for -Wmax-tokens.">,
+  MarshallingInfoStringInt<"LangOpts->MaxTokens">;
 def fPIC : Flag<["-"], "fPIC">, Group;
 def fno_PIC : Flag<["-"], "fno-PIC">, Group;
 def fPIE : Flag<["-"], "fPIE">, Group;
@@ -1212,7 +1213,10 @@ defm complete_member_pointers : 
BoolOption<"complete-member-pointers",
 " would be significant under the Microsoft ABI">, "f">,
   Group;
 def fcf_runtime_abi_EQ : Joined<["-"], "fcf-runtime-abi=">, Group,
-Flags<[CC1Option]>;
+Flags<[CC1Option]>, 
Values<"unspecified,standalone,objc,swift,swift-5.0,swift-4.2,swift-4.1">,
+NormalizedValuesScope<"LangOptions::CoreFoundationABI">,
+NormalizedValues<["ObjectiveC", "ObjectiveC", "ObjectiveC", "Swift5_0", 
"Swift5_0", "Swift4_2", "Swift4_1"]>,
+MarshallingInfoString<"LangOpts->CFRuntime", "ObjectiveC">, 
AutoNormalizeEnum;
 defm constant_cfstrings : BoolFOption<"constant-cfstrings",
   "LangOpts->NoConstantCFStrings", DefaultsToFalse,
   ChangedBy,
@@ -1420,7 +1424,8 @@ defm sanitize_memory_use_after_dtor : 
BoolOption<"sanitize-memory-use-after-dtor
   Group;
 def fsanitize_address_field_padding : Joined<["-"], 
"fsanitize-address-field-padding=">,
 Group,
-HelpText<"Level of field padding for 
AddressSanitizer">;
+HelpText<"Level of field padding for 
AddressSanitizer">,
+
MarshallingInfoStringInt<"LangOpts->SanitizeAddressFieldPadding">;
 defm sanitize_address_use_after_scope : 
BoolOption<"sanitize-address-use-after-scope",
   "CodeGenOpts.SanitizeAddressUseAfterScope", DefaultsToFalse,
   ChangedBy, ResetBy,
@@ -1739,7 +1744,10 @@ defm experimental_relative_cxx_abi_vtables : 
BoolFOption<"experimental-relative-
 
 def flat__namespace : Flag<["-"], "flat_namespace">;
 def flax_vector_conversions_EQ : Joined<["-"], "flax-vector-conversions=">, 
Group,
-  HelpText<"Enable implicit vector bit-casts">, Values<"none,integer,all">, 
Flags<[CC1Option]>;
+  HelpText<"Enable implicit vector bit-casts">, Values<"none,integer,all">, 
Flags<[CC1Option]>,
+  NormalizedValuesScope<"LangOptions::LaxVectorConversionKind">,
+  NormalizedValues<["None", "Integer", "All"]>,
+  MarshallingInfoString<"LangOpts->LaxVectorConversions", "All">, 
AutoNormalizeEnum;
 def flax_vector_conversions : Flag<["-"], "flax-vector-conversions">, 
Group,
   Alias, AliasArgs<["integer"]>;
 def flimited_precision_EQ : Joined<["-"], "flimited-precision=">, 
Group;
@@ -1791,7 +1799,12 @@ defm delayed_template_parsing : 
BoolFOption<"delayed-template-parsing",
   ChangedBy,
   ResetBy,
   BothFlags<[CoreOption]>>;
-def fms_memptr_rep_EQ : Joined<["-"], "fms-memptr-rep=">, Group, 
Flags<[CC1Op

[PATCH] D84671: [clang][cli] Port LangOpts simple string based options to new option parsing system

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGaec2991d083a: [clang][cli] Port LangOpts simple string based 
options to new option parsing… (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84671

Files:
  clang/include/clang/Basic/DiagnosticFrontendKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -352,7 +352,8 @@
 }
 
 static void FixupInvocation(CompilerInvocation &Invocation,
-DiagnosticsEngine &Diags) {
+DiagnosticsEngine &Diags,
+InputArgList &Args) {
   LangOptions &LangOpts = *Invocation.getLangOpts();
   DiagnosticOptions &DiagOpts = Invocation.getDiagnosticOpts();
   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
@@ -366,10 +367,12 @@
 
   LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
   LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
+  LangOpts.CurrentModule = LangOpts.ModuleName;
 
   llvm::sys::Process::UseANSIEscapeCodes(DiagOpts.UseANSIEscapeCodes);
 
   llvm::Triple T(TargetOpts.Triple);
+  llvm::Triple::ArchType Arch = T.getArch();
 
   if (LangOpts.getExceptionHandling() != llvm::ExceptionHandling::None &&
   T.isWindowsMSVCEnvironment())
@@ -378,6 +381,28 @@
 
   if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
 Diags.Report(diag::warn_c_kext);
+
+  if (LangOpts.NewAlignOverride &&
+  !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
+Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
+Diags.Report(diag::err_fe_invalid_alignment)
+<< A->getAsString(Args) << A->getValue();
+LangOpts.NewAlignOverride = 0;
+  }
+
+  if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
+auto DefaultCC = LangOpts.getDefaultCallingConv();
+
+bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
+  DefaultCC == LangOptions::DCC_StdCall) &&
+ Arch != llvm::Triple::x86;
+emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
+  DefaultCC == LangOptions::DCC_RegCall) &&
+ !T.isX86();
+if (emitError)
+  Diags.Report(diag::err_drv_argument_not_allowed_with)
+  << A->getSpelling() << T.getTriple();
+  }
 }
 
 //===--===//
@@ -2605,24 +2630,6 @@
   Opts.GNUInline = 1;
   }
 
-  if (const auto *A = Args.getLastArg(OPT_fcf_runtime_abi_EQ))
-Opts.CFRuntime =
-llvm::StringSwitch(A->getValue())
-.Cases("unspecified", "standalone", "objc",
-   LangOptions::CoreFoundationABI::ObjectiveC)
-.Cases("swift", "swift-5.0",
-   LangOptions::CoreFoundationABI::Swift5_0)
-.Case("swift-4.2", LangOptions::CoreFoundationABI::Swift4_2)
-.Case("swift-4.1", LangOptions::CoreFoundationABI::Swift4_1)
-.Default(LangOptions::CoreFoundationABI::ObjectiveC);
-
-  // The value-visibility mode defaults to "default".
-  if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
-Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
-  } else {
-Opts.setValueVisibilityMode(DefaultVisibility);
-  }
-
   // The type-visibility mode defaults to the value-visibility mode.
   if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
@@ -2696,20 +2703,6 @@
   Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
OPT_fno_dollars_in_identifiers,
Opts.DollarIdents);
-  Opts.setVtorDispMode(
-  MSVtorDispMode(getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags)));
-  if (Arg *A = Args.getLastArg(OPT_flax_vector_conversions_EQ)) {
-using LaxKind = LangOptions::LaxVectorConversionKind;
-if (auto Kind = llvm::StringSwitch>(A->getValue())
-.Case("none", LaxKind::None)
-.Case("integer", LaxKind::Integer)
-.Case("all", LaxKind::All)
-.Default(llvm::None))
-  Opts.setLaxVectorConversions(*Kind);
-else
-  Diags.Report(diag::err_drv_invalid_value)
-  << A->getAsString(Args) << A->getValue();
-  }
 
   // -ffixed-point
   Opts.FixedPoint =
@@ -2752,15 +2745,6 @@
   Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
   Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
   Opts.Char8 = Args.hasFlag(OPT_fchar8__t, OPT_fno_char8__t, Op

[clang] d1b3f82 - [clang][cli] Port PreprocessorOpts simple string based options to new option parsing system

2020-12-18 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2020-12-18T09:52:20+01:00
New Revision: d1b3f82e51378dd9fb5a23806d8fa906151f5e7b

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

LOG: [clang][cli] Port PreprocessorOpts simple string based options to new 
option parsing system

Depends on D84671

Reviewed By: Bigcheese

Original patch by Daniel Grumberg.

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index f7e3b298bccd..01ee6f747e51 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2615,7 +2615,8 @@ def image__base : Separate<["-"], "image_base">;
 def include_ : JoinedOrSeparate<["-", "--"], "include">, Group, 
EnumName<"include">,
 MetaVarName<"">, HelpText<"Include file before parsing">, 
Flags<[CC1Option]>;
 def include_pch : Separate<["-"], "include-pch">, Group, 
Flags<[CC1Option]>,
-  HelpText<"Include precompiled header file">, MetaVarName<"">;
+  HelpText<"Include precompiled header file">, MetaVarName<"">,
+  MarshallingInfoString<"PreprocessorOpts->ImplicitPCHInclude">;
 def relocatable_pch : Flag<["-", "--"], "relocatable-pch">, Flags<[CC1Option]>,
   HelpText<"Whether to build a relocatable precompiled header">,
   MarshallingInfoFlag<"FrontendOpts.RelocatablePCH">;
@@ -4857,7 +4858,8 @@ def foverride_record_layout_EQ : Joined<["-"], 
"foverride-record-layout=">,
   HelpText<"Override record layouts with those in the given file">;
 def pch_through_header_EQ : Joined<["-"], "pch-through-header=">,
   HelpText<"Stop PCH generation after including this file.  When using a PCH, "
-   "skip tokens until after this file is included.">;
+   "skip tokens until after this file is included.">,
+  MarshallingInfoString<"PreprocessorOpts->PCHThroughHeader">;
 def pch_through_hdrstop_create : Flag<["-"], "pch-through-hdrstop-create">,
   HelpText<"When creating a PCH, stop PCH generation after #pragma hdrstop.">,
   MarshallingInfoFlag<"PreprocessorOpts->PCHWithHdrStopCreate">;
@@ -4904,7 +4906,9 @@ def fconstant_string_class : Separate<["-"], 
"fconstant-string-class">,
   HelpText<"Specify the class to use for constant Objective-C string 
objects.">,
   MarshallingInfoString<"LangOpts->ObjCConstantStringClass">;
 def fobjc_arc_cxxlib_EQ : Joined<["-"], "fobjc-arc-cxxlib=">,
-  HelpText<"Objective-C++ Automatic Reference Counting standard library 
kind">, Values<"libc++,libstdc++,none">;
+  HelpText<"Objective-C++ Automatic Reference Counting standard library 
kind">, Values<"libc++,libstdc++,none">,
+  NormalizedValues<["ARCXX_libcxx", "ARCXX_libstdcxx", "ARCXX_nolib"]>,
+  MarshallingInfoString<"PreprocessorOpts->ObjCXXARCStandardLibrary", 
"ARCXX_nolib">, AutoNormalizeEnum;
 def fobjc_runtime_has_weak : Flag<["-"], "fobjc-runtime-has-weak">,
   HelpText<"The target Objective-C runtime supports ARC weak operations">;
 def fobjc_dispatch_method_EQ : Joined<["-"], "fobjc-dispatch-method=">,

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 5eea882e502b..a2ff437208f6 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -3115,11 +3115,8 @@ static bool 
isStrictlyPreprocessorAction(frontend::ActionKind Action) {
 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
   DiagnosticsEngine &Diags,
   frontend::ActionKind Action) {
-  Opts.ImplicitPCHInclude = std::string(Args.getLastArgValue(OPT_include_pch));
   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
 Args.hasArg(OPT_pch_through_hdrstop_use);
-  Opts.PCHThroughHeader =
-  std::string(Args.getLastArgValue(OPT_pch_through_header_EQ));
   Opts.AllowPCHWithCompilerErrors =
   Args.hasArg(OPT_fallow_pch_with_errors, OPT_fallow_pcm_with_errors);
 
@@ -3187,19 +3184,6 @@ static void ParsePreprocessorArgs(PreprocessorOptions 
&Opts, ArgList &Args,
 Opts.addRemappedFile(Split.first, Split.second);
   }
 
-  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
-StringRef Name = A->getValue();
-unsigned Library = llvm::StringSwitch(Name)
-  .Case("libc++", ARCXX_libcxx)
-  .Case("libstdc++", ARCXX_libstdcxx)
-  .Case("none", ARCXX_nolib)
-  .Default(~0U);
-if (Library == ~0U)
-  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << 
Name;
-else
-  Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
-  }
-
   // Always avoid lexing editor placeh

[PATCH] D84672: [clang][cli] Port PreprocessorOpts simple string based options to new option parsing system

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd1b3f82e5137: [clang][cli] Port PreprocessorOpts simple 
string based options to new option… (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D84672?vs=312205&id=312709#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84672

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3115,11 +3115,8 @@
 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
   DiagnosticsEngine &Diags,
   frontend::ActionKind Action) {
-  Opts.ImplicitPCHInclude = std::string(Args.getLastArgValue(OPT_include_pch));
   Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
 Args.hasArg(OPT_pch_through_hdrstop_use);
-  Opts.PCHThroughHeader =
-  std::string(Args.getLastArgValue(OPT_pch_through_header_EQ));
   Opts.AllowPCHWithCompilerErrors =
   Args.hasArg(OPT_fallow_pch_with_errors, OPT_fallow_pcm_with_errors);
 
@@ -3187,19 +3184,6 @@
 Opts.addRemappedFile(Split.first, Split.second);
   }
 
-  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
-StringRef Name = A->getValue();
-unsigned Library = llvm::StringSwitch(Name)
-  .Case("libc++", ARCXX_libcxx)
-  .Case("libstdc++", ARCXX_libstdcxx)
-  .Case("none", ARCXX_nolib)
-  .Default(~0U);
-if (Library == ~0U)
-  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << 
Name;
-else
-  Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
-  }
-
   // Always avoid lexing editor placeholders when we're just running the
   // preprocessor as we never want to emit the
   // "editor placeholder in source file" error in PP only mode.
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2615,7 +2615,8 @@
 def include_ : JoinedOrSeparate<["-", "--"], "include">, Group, 
EnumName<"include">,
 MetaVarName<"">, HelpText<"Include file before parsing">, 
Flags<[CC1Option]>;
 def include_pch : Separate<["-"], "include-pch">, Group, 
Flags<[CC1Option]>,
-  HelpText<"Include precompiled header file">, MetaVarName<"">;
+  HelpText<"Include precompiled header file">, MetaVarName<"">,
+  MarshallingInfoString<"PreprocessorOpts->ImplicitPCHInclude">;
 def relocatable_pch : Flag<["-", "--"], "relocatable-pch">, Flags<[CC1Option]>,
   HelpText<"Whether to build a relocatable precompiled header">,
   MarshallingInfoFlag<"FrontendOpts.RelocatablePCH">;
@@ -4857,7 +4858,8 @@
   HelpText<"Override record layouts with those in the given file">;
 def pch_through_header_EQ : Joined<["-"], "pch-through-header=">,
   HelpText<"Stop PCH generation after including this file.  When using a PCH, "
-   "skip tokens until after this file is included.">;
+   "skip tokens until after this file is included.">,
+  MarshallingInfoString<"PreprocessorOpts->PCHThroughHeader">;
 def pch_through_hdrstop_create : Flag<["-"], "pch-through-hdrstop-create">,
   HelpText<"When creating a PCH, stop PCH generation after #pragma hdrstop.">,
   MarshallingInfoFlag<"PreprocessorOpts->PCHWithHdrStopCreate">;
@@ -4904,7 +4906,9 @@
   HelpText<"Specify the class to use for constant Objective-C string 
objects.">,
   MarshallingInfoString<"LangOpts->ObjCConstantStringClass">;
 def fobjc_arc_cxxlib_EQ : Joined<["-"], "fobjc-arc-cxxlib=">,
-  HelpText<"Objective-C++ Automatic Reference Counting standard library 
kind">, Values<"libc++,libstdc++,none">;
+  HelpText<"Objective-C++ Automatic Reference Counting standard library 
kind">, Values<"libc++,libstdc++,none">,
+  NormalizedValues<["ARCXX_libcxx", "ARCXX_libstdcxx", "ARCXX_nolib"]>,
+  MarshallingInfoString<"PreprocessorOpts->ObjCXXARCStandardLibrary", 
"ARCXX_nolib">, AutoNormalizeEnum;
 def fobjc_runtime_has_weak : Flag<["-"], "fobjc-runtime-has-weak">,
   HelpText<"The target Objective-C runtime supports ARC weak operations">;
 def fobjc_dispatch_method_EQ : Joined<["-"], "fobjc-dispatch-method=">,


Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3115,11 +3115,8 @@
 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
   DiagnosticsEngine &Diags,
   front

[clang] 333d41e - [clang][cli] Port FrontendOpts simple string based options to new option parsing system

2020-12-18 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2020-12-18T10:00:03+01:00
New Revision: 333d41e9eb8b5f6cd67d318e84ee8dba99b840cc

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

LOG: [clang][cli] Port FrontendOpts simple string based options to new option 
parsing system

Depends on D84189

Reviewed By: dexonsmith

Original patch by Daniel Grumberg.

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 01ee6f747e51..d143781d1d09 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -542,7 +542,8 @@ def ccc_arcmt_modify : Flag<["-"], "ccc-arcmt-modify">, 
InternalDriverOpt,
 def ccc_arcmt_migrate : Separate<["-"], "ccc-arcmt-migrate">, 
InternalDriverOpt,
   HelpText<"Apply modifications and produces temporary files that conform to 
ARC">;
 def arcmt_migrate_report_output : Separate<["-"], 
"arcmt-migrate-report-output">,
-  HelpText<"Output path for the plist report">,  Flags<[CC1Option]>;
+  HelpText<"Output path for the plist report">,  Flags<[CC1Option]>,
+  MarshallingInfoString<"FrontendOpts.ARCMTMigrateReportOut">;
 def arcmt_migrate_emit_arc_errors : Flag<["-"], "arcmt-migrate-emit-errors">,
   HelpText<"Emit ARC errors even if the migrator can fix them">, 
Flags<[CC1Option]>,
   MarshallingInfoFlag<"FrontendOpts.ARCMTMigrateEmitARCErrors">;
@@ -605,7 +606,8 @@ def objcmt_migrate_designated_init : Flag<["-"], 
"objcmt-migrate-designated-init
   MarshallingInfoBitfieldFlag<"FrontendOpts.ObjCMTAction", 
"FrontendOptions::ObjCMT_DesignatedInitializer">;
 
 def objcmt_whitelist_dir_path: Joined<["-"], "objcmt-whitelist-dir-path=">, 
Flags<[CC1Option]>,
-  HelpText<"Only modify files with a filename contained in the provided 
directory path">;
+  HelpText<"Only modify files with a filename contained in the provided 
directory path">,
+  MarshallingInfoString<"FrontendOpts.ObjCMTWhiteListPath">;
 // The misspelt "white-list" [sic] alias is due for removal.
 def : Joined<["-"], "objcmt-white-list-dir-path=">, Flags<[CC1Option]>,
 Alias;
@@ -2339,7 +2341,8 @@ can be analyzed with chrome://tracing or `Speedscope App
   MarshallingInfoFlag<"FrontendOpts.TimeTrace">;
 def ftime_trace_granularity_EQ : Joined<["-"], "ftime-trace-granularity=">, 
Group,
   HelpText<"Minimum time granularity (in microseconds) traced by time 
profiler">,
-  Flags<[CC1Option, CoreOption]>;
+  Flags<[CC1Option, CoreOption]>,
+  MarshallingInfoStringInt<"FrontendOpts.TimeTraceGranularity", "500u">;
 def fproc_stat_report : Joined<["-"], "fproc-stat-report">, Group,
   HelpText<"Print subprocess statistics">;
 def fproc_stat_report_EQ : Joined<["-"], "fproc-stat-report=">, Group,
@@ -3309,7 +3312,8 @@ def nostdlibxx : Flag<["-"], "nostdlib++">;
 def object : Flag<["-"], "object">;
 def o : JoinedOrSeparate<["-"], "o">, Flags<[NoXarchOption, RenderAsInput,
   CC1Option, CC1AsOption, FC1Option, FlangOption]>,
-  HelpText<"Write output to ">, MetaVarName<"">;
+  HelpText<"Write output to ">, MetaVarName<"">,
+  MarshallingInfoString<"FrontendOpts.OutputFile">;
 def pagezero__size : JoinedOrSeparate<["-"], "pagezero_size">;
 def pass_exit_codes : Flag<["-", "--"], "pass-exit-codes">, 
Flags<[Unsupported]>;
 def pedantic_errors : Flag<["-", "--"], "pedantic-errors">, 
Group, Flags<[CC1Option]>;
@@ -4626,7 +4630,8 @@ def aux_target_cpu : Separate<["-"], "aux-target-cpu">,
 def aux_target_feature : Separate<["-"], "aux-target-feature">,
   HelpText<"Target specific auxiliary attributes">;
 def aux_triple : Separate<["-"], "aux-triple">,
-  HelpText<"Auxiliary target triple.">;
+  HelpText<"Auxiliary target triple.">,
+  MarshallingInfoString<"FrontendOpts.AuxTriple">;
 def code_completion_at : Separate<["-"], "code-completion-at">,
   MetaVarName<"::">,
   HelpText<"Dump code-completion information at a location">;
@@ -4672,7 +4677,8 @@ def ast_dump_filter : Separate<["-"], "ast-dump-filter">,
   MetaVarName<"">,
   HelpText<"Use with -ast-dump or -ast-print to dump/print only AST 
declaration"
" nodes having a certain substring in a qualified name. Use"
-   " -ast-list to list all filterable declaration node names.">;
+   " -ast-list to list all filterable declaration node names.">,
+  MarshallingInfoString<"FrontendOpts.ASTDumpFilter">;
 def fno_modules_global_index : Flag<["-"], "fno-modules-global-index">,
   HelpText<"Do not automatically generate or update the global module index">,
   MarshallingInfoFlag<"FrontendOpts.UseGlobalModuleIndex", "true">, IsNegative;
@@ -4815,7 +4821,8 @@ defm emit_llvm_uselists : BoolOption<"emit-llvm-useli

[PATCH] D84190: [clang][cli] Port FrontendOpts simple string based options to new option parsing system

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG333d41e9eb8b: [clang][cli] Port FrontendOpts simple string 
based options to new option… (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D84190?vs=311865&id=312712#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84190

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp

Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -1922,15 +1922,11 @@
 << A->getAsString(Args) << A->getValue();
   }
 
-  Opts.OutputFile = std::string(Args.getLastArgValue(OPT_o));
   Opts.Plugins = Args.getAllArgValues(OPT_load);
-  Opts.TimeTraceGranularity = getLastArgIntValue(
-  Args, OPT_ftime_trace_granularity_EQ, Opts.TimeTraceGranularity, Diags);
   Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
   Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
-  Opts.ASTDumpFilter = std::string(Args.getLastArgValue(OPT_ast_dump_filter));
   Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file);
   // Only the -fmodule-file= form.
   for (const auto *A : Args.filtered(OPT_fmodule_file)) {
@@ -1945,22 +1941,10 @@
 Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
<< "-emit-module";
 
-  Opts.OverrideRecordLayoutsFile =
-  std::string(Args.getLastArgValue(OPT_foverride_record_layout_EQ));
-  Opts.AuxTriple = std::string(Args.getLastArgValue(OPT_aux_triple));
   if (Args.hasArg(OPT_aux_target_cpu))
 Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
   if (Args.hasArg(OPT_aux_target_feature))
 Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
-  Opts.StatsFile = std::string(Args.getLastArgValue(OPT_stats_file));
-
-  Opts.MTMigrateDir =
-  std::string(Args.getLastArgValue(OPT_mt_migrate_directory));
-  Opts.ARCMTMigrateReportOut =
-  std::string(Args.getLastArgValue(OPT_arcmt_migrate_report_output));
-
-  Opts.ObjCMTWhiteListPath =
-  std::string(Args.getLastArgValue(OPT_objcmt_whitelist_dir_path));
 
   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
   Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -542,7 +542,8 @@
 def ccc_arcmt_migrate : Separate<["-"], "ccc-arcmt-migrate">, InternalDriverOpt,
   HelpText<"Apply modifications and produces temporary files that conform to ARC">;
 def arcmt_migrate_report_output : Separate<["-"], "arcmt-migrate-report-output">,
-  HelpText<"Output path for the plist report">,  Flags<[CC1Option]>;
+  HelpText<"Output path for the plist report">,  Flags<[CC1Option]>,
+  MarshallingInfoString<"FrontendOpts.ARCMTMigrateReportOut">;
 def arcmt_migrate_emit_arc_errors : Flag<["-"], "arcmt-migrate-emit-errors">,
   HelpText<"Emit ARC errors even if the migrator can fix them">, Flags<[CC1Option]>,
   MarshallingInfoFlag<"FrontendOpts.ARCMTMigrateEmitARCErrors">;
@@ -605,7 +606,8 @@
   MarshallingInfoBitfieldFlag<"FrontendOpts.ObjCMTAction", "FrontendOptions::ObjCMT_DesignatedInitializer">;
 
 def objcmt_whitelist_dir_path: Joined<["-"], "objcmt-whitelist-dir-path=">, Flags<[CC1Option]>,
-  HelpText<"Only modify files with a filename contained in the provided directory path">;
+  HelpText<"Only modify files with a filename contained in the provided directory path">,
+  MarshallingInfoString<"FrontendOpts.ObjCMTWhiteListPath">;
 // The misspelt "white-list" [sic] alias is due for removal.
 def : Joined<["-"], "objcmt-white-list-dir-path=">, Flags<[CC1Option]>,
 Alias;
@@ -2339,7 +2341,8 @@
   MarshallingInfoFlag<"FrontendOpts.TimeTrace">;
 def ftime_trace_granularity_EQ : Joined<["-"], "ftime-trace-granularity=">, Group,
   HelpText<"Minimum time granularity (in microseconds) traced by time profiler">,
-  Flags<[CC1Option, CoreOption]>;
+  Flags<[CC1Option, CoreOption]>,
+  MarshallingInfoStringInt<"FrontendOpts.TimeTraceGranularity", "500u">;
 def fproc_stat_report : Joined<["-"], "fproc-stat-report">, Group,
   HelpText<"Print subprocess statistics">;
 def fproc_stat_report_EQ : Joined<["-"], "fproc-stat-report=">, Group,
@@ -3309,7 +3312,8 @@
 def object : Flag<["-"], "object">;
 def o : JoinedOrSeparate<["-"], "o">, Flags<[NoXarchOption, RenderAsInput,
   CC1Option, CC1AsOption, FC1Option, FlangOption]>,
-  Hel

[clang] 9e08e51 - [c++20] P1907R1: Support for generalized non-type template arguments of scalar type.

2020-12-18 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2020-12-18T01:08:41-08:00
New Revision: 9e08e51a20d0d2b1c5724bb17e969d036fced4cd

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

LOG: [c++20] P1907R1: Support for generalized non-type template arguments of 
scalar type.

Added: 
clang/test/CodeGenCXX/template-arguments.cpp

Modified: 
clang/include/clang/AST/PropertiesBase.td
clang/include/clang/AST/RecursiveASTVisitor.h
clang/include/clang/AST/TemplateArgumentVisitor.h
clang/include/clang/AST/TemplateBase.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/include/clang/Serialization/ASTRecordWriter.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/ASTStructuralEquivalence.cpp
clang/lib/AST/Decl.cpp
clang/lib/AST/ItaniumMangle.cpp
clang/lib/AST/MicrosoftMangle.cpp
clang/lib/AST/ODRHash.cpp
clang/lib/AST/StmtProfile.cpp
clang/lib/AST/TemplateBase.cpp
clang/lib/AST/TypeLoc.cpp
clang/lib/CodeGen/CGDebugInfo.cpp
clang/lib/CodeGen/CGExprConstant.cpp
clang/lib/Index/USRGeneration.cpp
clang/lib/Sema/SemaLookup.cpp
clang/lib/Sema/SemaOverload.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/SemaTemplateVariadic.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/test/CodeGenCXX/mangle-ms-templates.cpp
clang/test/CodeGenCXX/mangle-template.cpp
clang/test/SemaTemplate/temp_arg_nontype_cxx17.cpp
clang/test/SemaTemplate/temp_arg_nontype_cxx20.cpp
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/CXCursor.cpp

Removed: 




diff  --git a/clang/include/clang/AST/PropertiesBase.td 
b/clang/include/clang/AST/PropertiesBase.td
index ba0f237a3bc3..dbe75ab9de19 100644
--- a/clang/include/clang/AST/PropertiesBase.td
+++ b/clang/include/clang/AST/PropertiesBase.td
@@ -72,6 +72,7 @@ class CountPropertyType : 
PropertyType {
 
 def APInt : PropertyType<"llvm::APInt"> { let PassByReference = 1; }
 def APSInt : PropertyType<"llvm::APSInt"> { let PassByReference = 1; }
+def APValue : PropertyType { let PassByReference = 1; }
 def ArraySizeModifier : EnumPropertyType<"ArrayType::ArraySizeModifier">;
 def AttrKind : EnumPropertyType<"attr::Kind">;
 def AutoTypeKeyword : EnumPropertyType;
@@ -450,6 +451,17 @@ let Class = PropertyTypeCase 
in {
 return TemplateArgument(ctx, value, type);
   }]>;
 }
+let Class = PropertyTypeCase in {
+  def : Property<"value", APValue> {
+let Read = [{ node.getAsUncommonValue() }];
+  }
+  def : Property<"type", QualType> {
+let Read = [{ node.getUncommonValueType() }];
+  }
+  def : Creator<[{
+return TemplateArgument(ctx, type, value);
+  }]>;
+}
 let Class = PropertyTypeCase in {
   def : Property<"name", TemplateName> {
 let Read = [{ node.getAsTemplateOrTemplatePattern() }];

diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 96db0e439952..61e524793ec7 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -767,6 +767,7 @@ bool RecursiveASTVisitor::TraverseTemplateArgument(
   case TemplateArgument::Declaration:
   case TemplateArgument::Integral:
   case TemplateArgument::NullPtr:
+  case TemplateArgument::UncommonValue:
 return true;
 
   case TemplateArgument::Type:
@@ -800,6 +801,7 @@ bool 
RecursiveASTVisitor::TraverseTemplateArgumentLoc(
   case TemplateArgument::Declaration:
   case TemplateArgument::Integral:
   case TemplateArgument::NullPtr:
+  case TemplateArgument::UncommonValue:
 return true;
 
   case TemplateArgument::Type: {

diff  --git a/clang/include/clang/AST/TemplateArgumentVisitor.h 
b/clang/include/clang/AST/TemplateArgumentVisitor.h
index 190aa97adf45..8c0da70b25eb 100644
--- a/clang/include/clang/AST/TemplateArgumentVisitor.h
+++ b/clang/include/clang/AST/TemplateArgumentVisitor.h
@@ -37,6 +37,7 @@ class Base {
   DISPATCH(Declaration);
   DISPATCH(NullPtr);
   DISPATCH(Integral);
+  DISPATCH(UncommonValue);
   DISPATCH(Template);
   DISPATCH(TemplateExpansion);
   DISPATCH(Expression);
@@ -59,6 +60,7 @@ class Base {
   VISIT_METHOD(Declaration);
   VISIT_METHOD(NullPtr);
   VISIT_METHOD(Integral);
+  VISIT_METHOD(UncommonValue);
   VISIT_METHOD(Template);
   VISIT_METHOD(TemplateExpansion);
   VISIT_METHOD(Expression);

diff  --git a/clang/include/clang/AST/TemplateBase.h 
b/clang/include/clang/AST/TemplateBase.h
index abf873a7ee40..9968143e8761 100644
--- a/clang/include/clang/AST/TemplateBase.h
+++ b/clang/include/clang/AST/TemplateBase.h
@@

[clang] 569676c - Make Expr::HasSideEffect more precise for instantiation-dependent

2020-12-18 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2020-12-18T01:08:42-08:00
New Revision: 569676c05725d79909bd8a9224bc709bd621553c

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

LOG: Make Expr::HasSideEffect more precise for instantiation-dependent
expressions.

Fixes a regression in the clang-tidy test suite from making DeclRefExprs
referring to dependent declarations be instantiation-dependent.

Added: 


Modified: 
clang/lib/AST/Expr.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaType.cpp

Removed: 




diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index 0426b20a33a9..dafa7136ecb4 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -3242,9 +3242,6 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
   if (!IncludePossibleEffects && getExprLoc().isMacroID())
 return false;
 
-  if (isInstantiationDependent())
-return IncludePossibleEffects;
-
   switch (getStmtClass()) {
   case NoStmtClass:
   #define ABSTRACT_STMT(Type)
@@ -3264,7 +3261,8 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
   case TypoExprClass:
   case RecoveryExprClass:
   case CXXFoldExprClass:
-llvm_unreachable("shouldn't see dependent / unresolved nodes here");
+// Make a conservative assumption for dependent nodes.
+return IncludePossibleEffects;
 
   case DeclRefExprClass:
   case ObjCIvarRefExprClass:

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ca1939222cf0..3992a373f721 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -4135,7 +4135,11 @@ bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
 
   // The operand for sizeof and alignof is in an unevaluated expression 
context,
   // so side effects could result in unintended consequences.
+  // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
+  // used to build SFINAE gadgets.
+  // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
+  !E->isInstantiationDependent() &&
   E->HasSideEffects(Context, false))
 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
 

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 241b8f72c56e..05b28c11e5a5 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -7691,7 +7691,8 @@ ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation 
KeyLoc, Expr *Operand,
 
   Operand = R.get();
 
-  if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
+  if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
+  Operand->HasSideEffects(Context, false)) {
 // The expression operand for noexcept is in an unevaluated expression
 // context, so side effects could result in unintended consequences.
 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);

diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 6485bebc0e8e..00ec0c4a0cee 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -8993,9 +8993,11 @@ QualType Sema::BuildDecltypeType(Expr *E, SourceLocation 
Loc,
   assert(!E->hasPlaceholderType() && "unexpected placeholder");
 
   if (AsUnevaluated && CodeSynthesisContexts.empty() &&
-  E->HasSideEffects(Context, false)) {
+  !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
 // The expression operand for decltype is in an unevaluated expression
 // context, so side effects could result in unintended consequences.
+// Exclude instantiation-dependent expressions, because 'decltype' is often
+// used to build SFINAE gadgets.
 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
   }
 



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


[clang] 95d3cc6 - [clang][cli] Port CodeGenOpts simple string flags to new option parsing system

2020-12-18 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2020-12-18T10:28:48+01:00
New Revision: 95d3cc67caac04668ef808f65c30ced60ed14f5d

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

LOG: [clang][cli] Port CodeGenOpts simple string flags to new option parsing 
system

Depends on D84668

Reviewed By: Bigcheese

Original patch by Daniel Grumberg.

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

Added: 


Modified: 
clang/include/clang/Basic/CodeGenOptions.h
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Driver/Options.td
clang/lib/Frontend/CompilerInvocation.cpp
clang/test/Profile/c-generate.c

Removed: 




diff  --git a/clang/include/clang/Basic/CodeGenOptions.h 
b/clang/include/clang/Basic/CodeGenOptions.h
index 5c540812ed31..ef4fa31256cd 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -30,6 +30,8 @@ namespace clang {
 /// Bitfields of CodeGenOptions, split out from CodeGenOptions to ensure
 /// that this large collection of bitfields is a trivial class type.
 class CodeGenOptionsBase {
+  friend class CompilerInvocation;
+
 public:
 #define CODEGENOPT(Name, Bits, Default) unsigned Name : Bits;
 #define ENUM_CODEGENOPT(Name, Type, Bits, Default)

diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 0e85be8f058b..c67cce099a28 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -86,8 +86,6 @@ def err_drv_invalid_thread_model_for_target : Error<
   "invalid thread model '%0' in '%1' for this target">;
 def err_drv_invalid_linker_name : Error<
   "invalid linker name in argument '%0'">;
-def err_drv_invalid_pgo_instrumentor : Error<
-  "invalid PGO instrumentor in argument '%0'">;
 def err_drv_invalid_rtlib_name : Error<
   "invalid runtime library name in argument '%0'">;
 def err_drv_unsupported_rtlib_for_platform : Error<

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d143781d1d09..3e4fbf1fbb8f 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1053,7 +1053,10 @@ defm coroutines_ts : OptInFFlag<"coroutines-ts", "Enable 
support for the C++ Cor
 
 def fembed_bitcode_EQ : Joined<["-"], "fembed-bitcode=">,
 Group, Flags<[NoXarchOption, CC1Option, CC1AsOption]>, 
MetaVarName<"">,
-HelpText<"Embed LLVM bitcode (option: off, all, bitcode, marker)">;
+HelpText<"Embed LLVM bitcode (option: off, all, bitcode, marker)">,
+Values<"off,all,bitcode,marker">, NormalizedValuesScope<"CodeGenOptions">,
+NormalizedValues<["Embed_Off", "Embed_All", "Embed_Bitcode", 
"Embed_Marker"]>,
+MarshallingInfoString<"CodeGenOpts.EmbedBitcode", "Embed_Off">, 
AutoNormalizeEnum;
 def fembed_bitcode : Flag<["-"], "fembed-bitcode">, Group,
   Alias, AliasArgs<["all"]>,
   HelpText<"Embed LLVM IR bitcode as data">;
@@ -1070,7 +1073,8 @@ def fno_profile_sample_use : Flag<["-"], 
"fno-profile-sample-use">, Group;
 def fprofile_sample_use_EQ : Joined<["-"], "fprofile-sample-use=">,
 Group, Flags<[NoXarchOption, CC1Option]>,
-HelpText<"Enable sample-based profile guided optimizations">;
+HelpText<"Enable sample-based profile guided optimizations">,
+MarshallingInfoString<"CodeGenOpts.SampleProfileFile">;
 def fprofile_sample_accurate : Flag<["-"], "fprofile-sample-accurate">,
 Group, Flags<[NoXarchOption, CC1Option]>,
 HelpText<"Specifies that the sample profile is accurate">,
@@ -1093,7 +1097,8 @@ def fno_auto_profile_accurate : Flag<["-"], 
"fno-auto-profile-accurate">,
 Group, Alias;
 def fdebug_compilation_dir : Separate<["-"], "fdebug-compilation-dir">,
 Group, Flags<[CC1Option, CC1AsOption, CoreOption]>,
-HelpText<"The compilation directory to embed in the debug info.">;
+HelpText<"The compilation directory to embed in the debug info.">,
+MarshallingInfoString<"CodeGenOpts.DebugCompilationDir">;
 def fdebug_compilation_dir_EQ : Joined<["-"], "fdebug-compilation-dir=">,
 Group, Flags<[CC1Option, CC1AsOption, CoreOption]>,
 Alias;
@@ -1114,7 +1119,8 @@ def fprofile_instr_use_EQ : Joined<["-"], 
"fprofile-instr-use=">,
 HelpText<"Use instrumentation data for profile-guided optimization">;
 def fprofile_remapping_file_EQ : Joined<["-"], "fprofile-remapping-file=">,
 Group, Flags<[CC1Option, CoreOption]>, MetaVarName<"">,
-HelpText<"Use the remappings described in  to match the profile data 
against names in the program">;
+HelpText<"Use the remappings described in  to match the profile data 
against names in the program">,
+MarshallingInfoString<"CodeGenOpts.ProfileRemappingFile">;
 def fprofile_re

[PATCH] D84669: [clang][cli] Port CodeGenOpts simple string flags to new option parsing system

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG95d3cc67caac: [clang][cli] Port CodeGenOpts simple string 
flags to new option parsing system (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D84669?vs=311919&id=312719#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84669

Files:
  clang/include/clang/Basic/CodeGenOptions.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/Profile/c-generate.c

Index: clang/test/Profile/c-generate.c
===
--- clang/test/Profile/c-generate.c
+++ clang/test/Profile/c-generate.c
@@ -7,7 +7,7 @@
 //
 // PROF-INSTR-NONE-NOT: __llvm_prf
 //
-// PROF-INSTR-GARBAGE: invalid PGO instrumentor in argument '-fprofile-instrument=garbage'
+// PROF-INSTR-GARBAGE: invalid value 'garbage' in '-fprofile-instrument=garbage'
 
 int main(void) {
   return 0;
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -353,7 +353,7 @@
 
 static void FixupInvocation(CompilerInvocation &Invocation,
 DiagnosticsEngine &Diags,
-InputArgList &Args) {
+const InputArgList &Args) {
   LangOptions &LangOpts = *Invocation.getLangOpts();
   DiagnosticOptions &DiagOpts = Invocation.getDiagnosticOpts();
   CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
@@ -403,6 +403,11 @@
   Diags.Report(diag::err_drv_argument_not_allowed_with)
   << A->getSpelling() << T.getTriple();
   }
+
+  if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager)
+Diags.Report(diag::err_drv_argument_only_allowed_with)
+<< Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
+<< "-fno-legacy-pass-manager";
 }
 
 //===--===//
@@ -845,28 +850,6 @@
   }
 }
 
-// Set the profile kind for fprofile-instrument.
-static void setPGOInstrumentor(CodeGenOptions &Opts, ArgList &Args,
-   DiagnosticsEngine &Diags) {
-  Arg *A = Args.getLastArg(OPT_fprofile_instrument_EQ);
-  if (A == nullptr)
-return;
-  StringRef S = A->getValue();
-  unsigned I = llvm::StringSwitch(S)
-   .Case("none", CodeGenOptions::ProfileNone)
-   .Case("clang", CodeGenOptions::ProfileClangInstr)
-   .Case("llvm", CodeGenOptions::ProfileIRInstr)
-   .Case("csllvm", CodeGenOptions::ProfileCSIRInstr)
-   .Default(~0U);
-  if (I == ~0U) {
-Diags.Report(diag::err_drv_invalid_pgo_instrumentor) << A->getAsString(Args)
- << S;
-return;
-  }
-  auto Instrumentor = static_cast(I);
-  Opts.setProfileInstr(Instrumentor);
-}
-
 // Set the profile kind using fprofile-instrument-use-path.
 static void setPGOUseInstrumentor(CodeGenOptions &Opts,
   const Twine &ProfileName) {
@@ -928,61 +911,12 @@
 }
   }
 
-  if (Arg *A = Args.getLastArg(OPT_fveclib)) {
-StringRef Name = A->getValue();
-if (Name == "Accelerate")
-  Opts.setVecLib(CodeGenOptions::Accelerate);
-else if (Name == "libmvec")
-  Opts.setVecLib(CodeGenOptions::LIBMVEC);
-else if (Name == "MASSV")
-  Opts.setVecLib(CodeGenOptions::MASSV);
-else if (Name == "SVML")
-  Opts.setVecLib(CodeGenOptions::SVML);
-else if (Name == "none")
-  Opts.setVecLib(CodeGenOptions::NoLibrary);
-else
-  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
-  }
-
-  if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
-unsigned Val =
-llvm::StringSwitch(A->getValue())
-.Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
-.Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
-.Case("constructor", codegenoptions::DebugInfoConstructor)
-.Case("limited", codegenoptions::LimitedDebugInfo)
-.Case("standalone", codegenoptions::FullDebugInfo)
-.Case("unused-types", codegenoptions::UnusedTypeInfo)
-.Default(~0U);
-if (Val == ~0U)
-  Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
-<< A->getValue();
-else
-  Opts.setDebugInfo(static_cast(Val));
-  }
   // If -fuse-ctor-homing is set and limited debug info is already on, then use
   // constructor homing.
   if (Args.getLastArg(OPT_fuse_ctor_homing))
 if (Opts.getDebugInfo() 

[clang] 7d246cb - [flang][driver] Add support for `-fsyntax-only`

2020-12-18 Thread Andrzej Warzynski via cfe-commits

Author: Andrzej Warzynski
Date: 2020-12-18T09:35:02Z
New Revision: 7d246cb19db9fce65946fb4bac6e570787dbe78a

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

LOG: [flang][driver] Add support for `-fsyntax-only`

The behaviour triggered with this flag is consistent with `-fparse-only`
in `flang` (i.e. the throwaway driver). This new spelling is consistent
with Clang and gfortran, and was proposed and agreed on for the new
driver in [1].

This patch also adds some minimal logic to communicate whether the
semantic checks have failed or not. When semantic checks fail, a
frontend driver error is generated. The return code from the frontend
driver is then determined by checking the driver diagnostics - the
presence of driver errors means that the compilation has failed. This
logic is consistent with `clang -cc1`.

[1] http://lists.llvm.org/pipermail/flang-dev/2020-November/000588.html

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

Added: 
flang/test/Flang-Driver/syntax-only.f90

Modified: 
clang/include/clang/Driver/Options.td
flang/include/flang/Frontend/CompilerInstance.h
flang/include/flang/Frontend/FrontendActions.h
flang/include/flang/Frontend/FrontendOptions.h
flang/lib/Frontend/CMakeLists.txt
flang/lib/Frontend/CompilerInstance.cpp
flang/lib/Frontend/CompilerInvocation.cpp
flang/lib/Frontend/FrontendActions.cpp
flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
flang/unittests/Frontend/PrintPreprocessedTest.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 3e4fbf1fbb8f..63a5b5484f0f 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2287,7 +2287,7 @@ defm strict_vtable_pointers : 
BoolFOption<"strict-vtable-pointers",
   ResetBy>;
 def fstrict_overflow : Flag<["-"], "fstrict-overflow">, Group;
 def fsyntax_only : Flag<["-"], "fsyntax-only">,
-  Flags<[NoXarchOption,CoreOption,CC1Option]>, Group;
+  Flags<[NoXarchOption,CoreOption,CC1Option,FC1Option]>, Group;
 def ftabstop_EQ : Joined<["-"], "ftabstop=">, Group;
 def ftemplate_depth_EQ : Joined<["-"], "ftemplate-depth=">, Group;
 def ftemplate_depth_ : Joined<["-"], "ftemplate-depth-">, Group;

diff  --git a/flang/include/flang/Frontend/CompilerInstance.h 
b/flang/include/flang/Frontend/CompilerInstance.h
index 21ef9f0dcd47..b00b5cd4479a 100644
--- a/flang/include/flang/Frontend/CompilerInstance.h
+++ b/flang/include/flang/Frontend/CompilerInstance.h
@@ -12,6 +12,7 @@
 #include "flang/Frontend/FrontendAction.h"
 #include "flang/Parser/parsing.h"
 #include "flang/Parser/provenance.h"
+#include "flang/Semantics/semantics.h"
 #include "llvm/Support/raw_ostream.h"
 
 namespace Fortran::frontend {
@@ -28,6 +29,12 @@ class CompilerInstance {
 
   std::shared_ptr parsing_;
 
+  /// The stream for diagnostics from Semantics
+  llvm::raw_ostream *semaOutputStream_ = &llvm::errs();
+
+  /// The stream for diagnostics from Semantics if owned, otherwise nullptr.
+  std::unique_ptr ownedSemaOutputStream_;
+
   /// The diagnostics engine instance.
   llvm::IntrusiveRefCntPtr diagnostics_;
 
@@ -77,6 +84,11 @@ class CompilerInstance {
 
   bool HasAllSources() const { return allSources_ != nullptr; }
 
+  parser::AllCookedSources &allCookedSources() {
+assert(allCookedSources_ && "Compiler instance has no AllCookedSources!");
+return *allCookedSources_;
+  };
+
   /// }
   /// @name Parser Operations
   /// {
@@ -84,6 +96,19 @@ class CompilerInstance {
   /// Return parsing to be used by Actions.
   Fortran::parser::Parsing &parsing() const { return *parsing_; }
 
+  /// }
+  /// @name Semantic analysis
+  /// {
+
+  /// Replace the current stream for verbose output.
+  void set_semaOutputStream(llvm::raw_ostream &Value);
+
+  /// Replace the current stream for verbose output.
+  void set_semaOutputStream(std::unique_ptr Value);
+
+  /// Get the current stream for verbose output.
+  llvm::raw_ostream &semaOutputStream() { return *semaOutputStream_; }
+
   /// }
   /// @name High-Level Operations
   /// {

diff  --git a/flang/include/flang/Frontend/FrontendActions.h 
b/flang/include/flang/Frontend/FrontendActions.h
index db5afe4da7eb..3eea94b60bf5 100644
--- a/flang/include/flang/Frontend/FrontendActions.h
+++ b/flang/include/flang/Frontend/FrontendActions.h
@@ -25,6 +25,10 @@ class PrintPreprocessedAction : public FrontendAction {
   void ExecuteAction() override;
 };
 
+class ParseSyntaxOnlyAction : public FrontendAction {
+  void ExecuteAction() override;
+};
+
 } // namespace Fortran::frontend
 
 #endif // LLVM_FLANG_FRONTEND_FRONTENDACTIONS_H

diff  --git a/flang/include/flang/Frontend/FrontendOptions.h 
b/flang/include/flang/Frontend/FrontendOptions.h
index ac8f01d2a1

[PATCH] D92290: [clangd] Use clangd's Context mechanism to make the ASTContext of the AST being operated on available everywhere

2020-12-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

Ah, I suspected something like this was afoot! The patch looks... exciting :-) 
And I definitely agree we should remove the hacks if we're going to have access 
to ASTContext anyway.

I think an explicit parameter here is probably a good idea, it's a bit sad to 
lose targetDecl's simple signature but seems justified at this point.
But **I also think we should consider splitting out the heuristic resolution 
parts into a separate module**, maybe leading to a signature like:

`targetDecl(DynTypedNode N, HeuristicResolver * = nullptr)`

The HeuristicResolver object could provide primitives like finding the pointee 
type, template patterns etc. It would hold a reference to Sema/ASTContext.

There are a few reasons for this:

- isolating complexity: FindTargets is mostly fairly broad-but-simple (many 
cases, but mostly trivial AST traversal) while heuristic resolution is fairly 
narrow-but-complex. Having the complexity in the way hinders understanding for 
people who, say, want to improve basic handling of some ObjC nodes that we 
forgot.
- testing: Being able to test heuristic resolution primitives directly rather 
than through targetDecl seems valuable. Particularly for operations that 
involve sema and template instantiation, I expect we'll find crashes/problems 
and direct tests will expose them more clearly. Conversely the fallback 
heuristics can get in the way of testing the basic functionality (we've dealt 
with this a bit in xrefs).
- encapsulation: I don't love the idea of exposing the Sema god-object 
everywhere via ParsedAST. We've gotten a long way without this, it's a really 
big and complicated hammer, and my suspicion is most places we'd be tempted to 
use it are bad or at least risky. If we expose HeuristicResolver from ParsedAST 
instead of Sema directly, we keep the barrier high.
- reuse: might we also want to use the heuristic resolution for code completion 
at some point, e.g. LHS of MemberExpr? (We could abstract it via some 
callbacks, but I also suspect it's not coupled to clangd and could just be 
lifted up to clang at some point)

What do you think about this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92290

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


[PATCH] D92854: [flang][driver] Add support for `-fsyntax-only`

2020-12-18 Thread Andrzej Warzynski via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7d246cb19db9: [flang][driver] Add support for 
`-fsyntax-only` (authored by awarzynski).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92854

Files:
  clang/include/clang/Driver/Options.td
  flang/include/flang/Frontend/CompilerInstance.h
  flang/include/flang/Frontend/FrontendActions.h
  flang/include/flang/Frontend/FrontendOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInstance.cpp
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
  flang/test/Flang-Driver/syntax-only.f90
  flang/unittests/Frontend/PrintPreprocessedTest.cpp

Index: flang/unittests/Frontend/PrintPreprocessedTest.cpp
===
--- flang/unittests/Frontend/PrintPreprocessedTest.cpp
+++ flang/unittests/Frontend/PrintPreprocessedTest.cpp
@@ -76,4 +76,60 @@
   llvm::sys::fs::remove(inputFile);
   compInst.ClearOutputFiles(/*EraseFiles=*/true);
 }
+
+TEST(FrontendAction, ParseSyntaxOnly) {
+  std::string inputFile = "test-file.f";
+  std::error_code ec;
+
+  // 1. Create the input file for the file manager
+  // AllSources (which is used to manage files inside every compiler instance),
+  // works with paths. This means that it requires a physical file. Create one.
+  std::unique_ptr os{
+  new llvm::raw_fd_ostream(inputFile, ec, llvm::sys::fs::OF_None)};
+  if (ec)
+FAIL() << "Fail to create the file need by the test";
+
+  // Populate the input file with the pre-defined input and flush it.
+  *(os) << "! if_stmt.f90:\n"
+<< "IF (A > 0.0) IF (B < 0.0) A = LOG (A)\n"
+<< "END";
+  os.reset();
+
+  // Get the path of the input file
+  llvm::SmallString<64> cwd;
+  if (std::error_code ec = llvm::sys::fs::current_path(cwd))
+FAIL() << "Failed to obtain the current working directory";
+  std::string testFilePath(cwd.c_str());
+  testFilePath += "/" + inputFile;
+
+  // 2. Prepare the compiler (CompilerInvocation + CompilerInstance)
+  CompilerInstance compInst;
+  compInst.CreateDiagnostics();
+  auto invocation = std::make_shared();
+  invocation->frontendOpts().programAction_ = ParseSyntaxOnly;
+
+  compInst.set_invocation(std::move(invocation));
+  compInst.frontendOpts().inputs_.push_back(
+  FrontendInputFile(testFilePath, Language::Fortran));
+
+  // 3. Set-up the output stream for the semantic diagnostics.
+  llvm::SmallVector outputDiagBuffer;
+  std::unique_ptr outputStream(
+  new llvm::raw_svector_ostream(outputDiagBuffer));
+  compInst.set_semaOutputStream(std::move(outputStream));
+
+  // 4. Execute the ParseSyntaxOnly action
+  bool success = ExecuteCompilerInvocation(&compInst);
+
+  // 5. Validate the expected output
+  EXPECT_FALSE(success);
+  EXPECT_TRUE(!outputDiagBuffer.empty());
+  EXPECT_TRUE(
+  llvm::StringRef(outputDiagBuffer.data())
+  .startswith(
+  ":2:14: error: IF statement is not allowed in IF statement\n"));
+
+  // 6. Clear the input files.
+  llvm::sys::fs::remove(inputFile);
+}
 } // namespace
Index: flang/test/Flang-Driver/syntax-only.f90
===
--- /dev/null
+++ flang/test/Flang-Driver/syntax-only.f90
@@ -0,0 +1,9 @@
+! RUN: not %flang-new -fc1 -fsyntax-only %s 2>&1 | FileCheck %s
+! RUN: not %f18 -fparse-only %s 2>&1 | FileCheck %s
+
+! REQUIRES: new-flang-driver
+
+! CHECK: IF statement is not allowed in IF statement
+! CHECK: semantic errors in {{.*}}syntax-only.f90
+IF (A > 0.0) IF (B < 0.0) A = LOG (A)
+END
Index: flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
===
--- flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
+++ flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
@@ -32,6 +32,9 @@
   case PrintPreprocessedInput:
 return std::make_unique();
 break;
+  case ParseSyntaxOnly:
+return std::make_unique();
+break;
   default:
 break;
 // TODO:
Index: flang/lib/Frontend/FrontendActions.cpp
===
--- flang/lib/Frontend/FrontendActions.cpp
+++ flang/lib/Frontend/FrontendActions.cpp
@@ -7,10 +7,12 @@
 //===--===//
 
 #include "flang/Frontend/FrontendActions.h"
+#include "flang/Common/default-kinds.h"
 #include "flang/Frontend/CompilerInstance.h"
 #include "flang/Parser/parsing.h"
 #include "flang/Parser/provenance.h"
 #include "flang/Parser/source.h"
+#include "flang/Semantics/semantics.h"
 
 using namespace Fortran::frontend;
 
@@ -68,3 +70,33 @@
 return;
   }
 }
+
+void ParseSyntaxOnlyAction::ExecuteAction() {
+  CompilerInstance &ci = this->instance();
+

[PATCH] D93525: [OpenMP] Add unbundling of archives containing bundled object files into device specific archives

2020-12-18 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam created this revision.
saiislam added reviewers: grokos, hfinkel, jdoerfert, JonChesterfield, ronlieb, 
ABataev, mdtoguchi, kbobrovs, sdmitriev, gregrodgers, kkwli0, dreachem, Tyker, 
jsjodin.
saiislam requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch adds the file type "a", which together with the --unbundle flag, 
unbundles
an archive of bundled object files into an archive containing the 
device-specific code.
Example:
clang-offload-bundler --unbundle --inputs=libMyLib.a -type=a
 -outputs=libMyDeviceLib.a -targets=openmp-amdgcn-amdhsa-gfx906


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93525

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

Index: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
===
--- clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
+++ clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
@@ -22,6 +22,8 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Object/Archive.h"
+#include "llvm/Object/ArchiveWriter.h"
 #include "llvm/Object/Binary.h"
 #include "llvm/Object/ObjectFile.h"
 #include "llvm/Support/Casting.h"
@@ -30,6 +32,7 @@
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Host.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
@@ -81,6 +84,7 @@
"  bc  - llvm-bc\n"
"  s   - assembler\n"
"  o   - object\n"
+   "  a   - archive of objects\n"
"  gch - precompiled-header\n"
"  ast - clang AST file"),
   cl::cat(ClangOffloadBundlerCategory));
@@ -124,6 +128,22 @@
   return OffloadKind == "host";
 }
 
+static StringRef getTriple(StringRef Target) {
+  StringRef OffloadKind;
+  StringRef Triple;
+  getOffloadKindAndTriple(Target, OffloadKind, Triple);
+  return Triple;
+}
+
+static StringRef getDevice(StringRef Triple) {
+  if (Triple.contains("-")) {
+auto Split = Triple.rsplit('-');
+return Split.second;
+  } else {
+return Triple;
+  }
+}
+
 /// Generic file handler interface.
 class FileHandler {
 public:
@@ -145,7 +165,7 @@
   virtual Error ReadBundleEnd(MemoryBuffer &Input) = 0;
 
   /// Read the current bundle and write the result into the stream \a OS.
-  virtual Error ReadBundle(raw_fd_ostream &OS, MemoryBuffer &Input) = 0;
+  virtual Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) = 0;
 
   /// Write the header of the bundled file to \a OS based on the information
   /// gathered from \a Inputs.
@@ -317,7 +337,7 @@
 return Error::success();
   }
 
-  Error ReadBundle(raw_fd_ostream &OS, MemoryBuffer &Input) final {
+  Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) final {
 assert(CurBundleInfo != BundlesInfo.end() && "Invalid reader info!");
 StringRef FC = Input.getBuffer();
 OS.write(FC.data() + CurBundleInfo->second.Offset,
@@ -480,7 +500,7 @@
 
   Error ReadBundleEnd(MemoryBuffer &Input) final { return Error::success(); }
 
-  Error ReadBundle(raw_fd_ostream &OS, MemoryBuffer &Input) final {
+  Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) final {
 Expected ContentOrErr = CurrentSection->getContents();
 if (!ContentOrErr)
   return ContentOrErr.takeError();
@@ -674,7 +694,7 @@
 return Error::success();
   }
 
-  Error ReadBundle(raw_fd_ostream &OS, MemoryBuffer &Input) final {
+  Error ReadBundle(raw_ostream &OS, MemoryBuffer &Input) final {
 StringRef FC = Input.getBuffer();
 size_t BundleStart = ReadChars;
 
@@ -757,6 +777,8 @@
 return std::make_unique(/*Comment=*/"#");
   if (FilesType == "o")
 return CreateObjectFileHandler(FirstInput);
+  if (FilesType == "a")
+return CreateObjectFileHandler(FirstInput);
   if (FilesType == "gch")
 return std::make_unique();
   if (FilesType == "ast")
@@ -916,6 +938,152 @@
   return Error::success();
 }
 
+static Archive::Kind getDefaultArchiveKindForHost() {
+  return Triple(sys::getDefaultTargetTriple()).isOSDarwin() ? Archive::K_DARWIN
+: Archive::K_GNU;
+}
+
+/// Returns arch specific extension for device object files in the generated
+/// device specific archive in archive unbundling mode
+static StringRef getDeviceFileExtension(StringRef Device) {
+  if (Device.contains("gfx"))
+return ".bc";
+  if (Device.contains("sm_"))
+return ".cubin";
+  else {
+WithColor::warning() << "Could not determine extension for archive "
+"members, using \".o\"\n";
+return ".o";
+  }
+}
+
+static StringRef removeExtension(StringRef FileName) {
+  return (Fil

[PATCH] D92663: [clangd] Add hot-reload of compile_commands.json and compile_flags.txt

2020-12-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/GlobalCompilationDatabase.cpp:217
+  if (!Buf || (*Buf)->getBufferSize() != Stat->getSize()) {
+Size = NoFileCached;
+elog("Failed to read {0}: {1}", Path,

sammccall wrote:
> adamcz wrote:
> > Why throw away the information we have? Better keep the cached metadata 
> > around, transient error here could mean the build system is re-creating the 
> > file, but it may end up being identical to what we already read, it's just 
> > that someone re-run cmake or something.
> Good point, done.
> 
> Of course this relies on us getting "lucky" and seeing two different sizes 
> for the file between the calls. If it's being written then we could e.g. see 
> it with size 0 on both stat and read, and then we'll throw away the content.
> 
> The way around this would be to e.g. call an unparseable file a transient 
> error (reuse cached value), which requires some structural changes here I 
> think. What do you think about that? (I think this would help with 
> compile_commands.json but not compile_flags.txt)
> Another way would be to handle a size of 0 as a special case (presumed 
> invalid), which may catch the practical cases.
Decided not to do anything about this for now, the most common generator is 
cmake and it does atomic writes. Seems likely other build systems will too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92663

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


[PATCH] D93525: [OpenMP] Add unbundling of archives containing bundled object files into device specific archives

2020-12-18 Thread Saiyedul Islam via Phabricator via cfe-commits
saiislam added a comment.

Refer to D80816  for earlier review of this 
patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93525

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


[clang-tools-extra] 9899319 - [clangd] Add hot-reload of compile_commands.json and compile_flags.txt

2020-12-18 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2020-12-18T11:16:46+01:00
New Revision: 98993193e9037345ad13720a62974064a5f3d953

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

LOG: [clangd] Add hot-reload of compile_commands.json and compile_flags.txt

When querying the CDB, we stat the underlying file to check it hasn't changed.
We don't do this every time, but only if we didn't check within 5 seconds.

This behavior only exists for compile_commands.json and compile_flags.txt.
The CDB plugin system doesn't expose enough information to handle others.

Slight behavior change: we now only look for `build/compile_commands.json`
rather than trying every CDB strategy under `build` subdirectories.

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

Added: 


Modified: 
clang-tools-extra/clangd/ClangdLSPServer.cpp
clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
clang-tools-extra/clangd/GlobalCompilationDatabase.h
clang-tools-extra/clangd/tool/Check.cpp
clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 66dee68ec474..b32c9e13973b 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -496,8 +496,10 @@ void ClangdLSPServer::onInitialize(const InitializeParams 
&Params,
   if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
 Opts.CompileCommandsDir = Dir;
   if (Opts.UseDirBasedCDB) {
-BaseCDB = std::make_unique(
-Opts.CompileCommandsDir);
+DirectoryBasedGlobalCompilationDatabase::Options CDBOpts(TFS);
+CDBOpts.CompileCommandsDir = Opts.CompileCommandsDir;
+BaseCDB =
+std::make_unique(CDBOpts);
 BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
  std::move(BaseCDB));
   }
@@ -704,6 +706,10 @@ void ClangdLSPServer::onFileEvent(const 
DidChangeWatchedFilesParams &Params) {
   //  - this is useful e.g. when switching git branches, but we're likely to 
see
   //fresh headers but still have the old-branch main-file content
   Server->onFileEvent(Params);
+  // FIXME: observe config files, immediately expire time-based caches, 
reparse:
+  //  - compile_commands.json and compile_flags.txt
+  //  - .clang_format and .clang-tidy
+  //  - .clangd and clangd/config.yaml
 }
 
 void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,

diff  --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp 
b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
index add0eec4a2c8..41b549cefc7c 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -8,11 +8,15 @@
 
 #include "GlobalCompilationDatabase.h"
 #include "FS.h"
+#include "SourceCode.h"
 #include "support/Logger.h"
 #include "support/Path.h"
+#include "support/ThreadsafeFS.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Tooling/ArgumentsAdjusters.h"
 #include "clang/Tooling/CompilationDatabase.h"
+#include "clang/Tooling/CompilationDatabasePluginRegistry.h"
+#include "clang/Tooling/JSONCompilationDatabase.h"
 #include "llvm/ADT/None.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/STLExtras.h"
@@ -22,6 +26,7 @@
 #include "llvm/Support/FileUtilities.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
+#include "llvm/Support/VirtualFileSystem.h"
 #include 
 #include 
 #include 
@@ -85,33 +90,78 @@ GlobalCompilationDatabase::getFallbackCommand(PathRef File) 
const {
 //  - 1) determine all the paths that might be searched
 //  - 2) acquire the map lock and get-or-create all the DirectoryCache entries
 //  - 3) release the map lock and query the caches as desired
-//
-// FIXME: this should revalidate the cache sometimes
-// FIXME: IO should go through a VFS
 class DirectoryBasedGlobalCompilationDatabase::DirectoryCache {
-  // Absolute canonical path that we're the cache for. (Not case-folded).
-  const std::string Path;
-
-  // True if we've looked for a CDB here and found none.
-  // (This makes it possible for get() to return without taking a lock)
-  // FIXME: this should have an expiry time instead of lasting forever.
-  std::atomic FinalizedNoCDB = {false};
-
-  // Guards following cache state.
+  using stopwatch = std::chrono::steady_clock;
+
+  // CachedFile is used to read a CDB file on disk (e.g. 
compile_commands.json).
+  // It specializes in being able to quickly bail out if the file is unchanged,
+  // which is the common case.
+  // Internally, it stores file metadata so a stat() can verify it's unchanged.
+  // We don't actually cache the content as it's not needed -

[PATCH] D92663: [clangd] Add hot-reload of compile_commands.json and compile_flags.txt

2020-12-18 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG98993193e903: [clangd] Add hot-reload of 
compile_commands.json and compile_flags.txt (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D92663?vs=312193&id=312731#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92663

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
  clang-tools-extra/clangd/GlobalCompilationDatabase.h
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp

Index: clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
===
--- clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
+++ clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
@@ -11,8 +11,10 @@
 #include "Matchers.h"
 #include "TestFS.h"
 #include "support/Path.h"
+#include "support/ThreadsafeFS.h"
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
@@ -23,6 +25,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 #include 
 #include 
 
@@ -40,7 +43,8 @@
 using ::testing::UnorderedElementsAre;
 
 TEST(GlobalCompilationDatabaseTest, FallbackCommand) {
-  DirectoryBasedGlobalCompilationDatabase DB(None);
+  MockFS TFS;
+  DirectoryBasedGlobalCompilationDatabase DB(TFS);
   auto Cmd = DB.getFallbackCommand(testPath("foo/bar.cc"));
   EXPECT_EQ(Cmd.Directory, testPath("foo"));
   EXPECT_THAT(Cmd.CommandLine, ElementsAre("clang", testPath("foo/bar.cc")));
@@ -166,6 +170,7 @@
 }
 
 // Allows placement of files for tests and cleans them up after.
+// FIXME: GlobalCompilationDatabase is mostly VFS-clean now, switch to MockFS?
 class ScratchFS {
   llvm::SmallString<128> Root;
 
@@ -238,13 +243,14 @@
   ]
   )cdb";
   ScratchFS FS;
+  RealThreadsafeFS TFS;
   FS.write("compile_commands.json", CDBOuter);
   FS.write("build/compile_commands.json", CDBInner);
 
   // Note that gen2.cc goes missing with our following model, not sure this
   // happens in practice though.
   {
-DirectoryBasedGlobalCompilationDatabase DB(llvm::None);
+DirectoryBasedGlobalCompilationDatabase DB(TFS);
 std::vector DiscoveredFiles;
 auto Sub =
 DB.watch([&DiscoveredFiles](const std::vector Changes) {
@@ -262,7 +268,9 @@
 
   // With a custom compile commands dir.
   {
-DirectoryBasedGlobalCompilationDatabase DB(FS.root().str());
+DirectoryBasedGlobalCompilationDatabase::Options Opts(TFS);
+Opts.CompileCommandsDir = FS.root().str();
+DirectoryBasedGlobalCompilationDatabase DB(Opts);
 std::vector DiscoveredFiles;
 auto Sub =
 DB.watch([&DiscoveredFiles](const std::vector Changes) {
@@ -282,17 +290,34 @@
 
 TEST(GlobalCompilationDatabaseTest, BuildDir) {
   ScratchFS FS;
+  RealThreadsafeFS TFS;
   auto Command = [&](llvm::StringRef Relative) {
-return DirectoryBasedGlobalCompilationDatabase(llvm::None)
+DirectoryBasedGlobalCompilationDatabase::Options Opts(TFS);
+return DirectoryBasedGlobalCompilationDatabase(Opts)
 .getCompileCommand(FS.path(Relative))
 .getValueOr(tooling::CompileCommand())
 .CommandLine;
   };
   EXPECT_THAT(Command("x/foo.cc"), IsEmpty());
-  FS.write("x/build/compile_flags.txt", "-DXYZZY");
+  const char *const CDB =
+  R"cdb(
+  [
+{
+  "file": "{0}/x/foo.cc",
+  "command": "clang -DXYZZY {0}/x/foo.cc",
+  "directory": "{0}",
+},
+{
+  "file": "{0}/bar.cc",
+  "command": "clang -DXYZZY {0}/bar.cc",
+  "directory": "{0}",
+}
+  ]
+  )cdb";
+  FS.write("x/build/compile_commands.json", CDB);
   EXPECT_THAT(Command("x/foo.cc"), Contains("-DXYZZY"));
   EXPECT_THAT(Command("bar.cc"), IsEmpty())
-  << "x/build/compile_flags.txt only applicable to x/";
+  << "x/build/compile_flags.json only applicable to x/";
 }
 
 TEST(GlobalCompilationDatabaseTest, NonCanonicalFilenames) {
@@ -330,5 +355,108 @@
   EXPECT_EQ(DB.getProjectInfo(Header)->SourceRoot, testRoot());
 }
 } // namespace
+
+// Friend test has access to internals.
+class DirectoryBasedGlobalCompilationDatabaseCacheTest
+: public ::testing::Test {
+protected:
+  std::shared_ptr
+  lookupCDB(const DirectoryBasedGlobalCompilationDatabase &GDB,
+llvm::StringRef Path,
+std::chrono::steady_clock::time_point FreshTime) {
+DirectoryBasedGlobalCompilationDatabase::CDBLookupRequest Req;
+Req.FileName = Path;
+Req.FreshTime = Req.FreshTimeMissing = FreshTime;
+

[PATCH] D84189: Let denormalizer decide how to render the option based on the option class

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 commandeered this revision.
jansvoboda11 added a reviewer: dang.
jansvoboda11 added a comment.

Taking over this patch, as Daniel is no longer involved.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84189

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


[PATCH] D93528: [clang-format] Add basic support for formatting JSON

2020-12-18 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: curdeius, krasimir, klimek, sammccall, 
benhamilton.
MyDeveloperDay added projects: clang, clang-format.
Herald added a subscriber: mgorny.
MyDeveloperDay requested review of this revision.

I find as I develop I'm moving between many different languages 
C++,C#,JavaScript all the time. As I move between the file types I like to keep 
`clang-format` as my formatting tool of choice. (hence why I initially added C# 
support  in D58404: [clang-format] Add basic support for formatting C# files 
) I know those other languages have their own 
tools but I have to learn them all, and I have to work out how to configure 
them, and they may or may not have integration into my IDE or my source code 
integration.

I am increasingly finding that I'm editing additional JSON files as part of my 
daily work and my editor and git commit hooks are just not setup to go and run 
jq , So I tend to go to  JSON Formatter 
 and copy and paste back and forth. 
To get nicely formatted JSON. This is a painful process and I'd like a new one 
that causes me much less friction.

This has come up from time to time:

D10543: clang-format: [JS] recognize .ts and .json in git-clang-format. 

https://stackoverflow.com/questions/35856565/clang-format-a-json-file

I would like to stop having to do that and have formatting JSON as a first 
class clang-format support `Language` (even if it has minimal style settings at 
present).

This revision adds support for formatting JSON using the inbuilt JSON 
serialization library of LLVM, With limited control at present only over the 
indentation level

This adds an additional Language into the .clang-format file to separate the 
settings from your other supported languages.

  -- 
  Language: Json
  IndentWidth: 2

For example of it working, this snipped from the Wikipedia definition of JSON 
can be formatted as below without the need to trick clang-format into thinking 
this is javascript:

file.json

  { "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 27, 
"address": { "streetAddress": "21 2nd Street", "city": "New York", "state": 
"NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", 
"number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" } ], 
"children": [], "spouse": null }



  $ clang-format.exe file.json
  {
"address": {
  "city": "New York",
  "postalCode": "10021-3100",
  "state": "NY",
  "streetAddress": "21 2nd Street"
},
"age": 27,
"children": [],
"firstName": "John",
"isAlive": true,
"lastName": "Smith",
"phoneNumbers": [
  {
"number": "212 555-1234",
"type": "home"
  },
  {
"number": "646 555-4567",
"type": "office"
  }
],
"spouse": null
  }




Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93528

Files:
  clang/docs/ClangFormat.rst
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/tools/clang-format/ClangFormat.cpp
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/FormatTestJson.cpp

Index: clang/unittests/Format/FormatTestJson.cpp
===
--- /dev/null
+++ clang/unittests/Format/FormatTestJson.cpp
@@ -0,0 +1,120 @@
+//===- unittest/Format/FormatTestJson.cpp - Formatting tests for Json -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "FormatTestUtils.h"
+#include "clang/Format/Format.h"
+#include "llvm/Support/Debug.h"
+#include "gtest/gtest.h"
+
+#define DEBUG_TYPE "format-test"
+
+namespace clang {
+namespace format {
+
+class FormatTestJson : public ::testing::Test {
+protected:
+  static std::string format(llvm::StringRef Code, unsigned Offset,
+unsigned Length, const FormatStyle &Style) {
+LLVM_DEBUG(llvm::errs() << "---\n");
+LLVM_DEBUG(llvm::errs() << Code << "\n\n");
+std::vector Ranges(1, tooling::Range(Offset, Length));
+tooling::Replacements Replaces = reformat(Style, Code, Ranges);
+auto Result = applyAllReplacements(Code, Replaces);
+EXPECT_TRUE(static_cast(Result));
+LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
+return *Result;
+  }
+
+  static std::string
+  format(llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle(FormatStyle::LK_Json)) {
+return format(Code, 0, Code.size(), Style);
+  }
+
+  static FormatStyle getStyleWithColumns(unsigned ColumnLimit) {
+Form

[PATCH] D93452: [clangd] Trim memory after buildINdex

2020-12-18 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D93452#2460563 , @sammccall wrote:

> I think we should pass a nonzero `pad` to malloc_trim of several MB. It only 
> affects the main thread, but the main thread is constantly allocating small 
> short-lived objects (e.g. JSON encoding/decoding) and cutting it to the bone 
> only to have it sbrk again seems pointless.

It would require a lot of work, but JSON encoding/decoding is possible without 
lots of allocations.
If you want to really compress memory usage, losing the map like access, O(1), 
on json objects, in favour of storing them in a vector, O(n), would be 
beneficial. I don't think the jsons in clangd ever really have maps with large 
numbers of keys which are queried often.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93452

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


[PATCH] D92039: [-Wcalled-once-parameter] Introduce 'called_once' attribute

2020-12-18 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko updated this revision to Diff 312741.
vsavchenko added a comment.

Detect all conventions for captured parameters as well


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92039

Files:
  clang/include/clang/Analysis/Analyses/CalledOnceCheck.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Analysis/CMakeLists.txt
  clang/lib/Analysis/CalledOnceCheck.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/SemaObjC/attr-called-once.m
  clang/test/SemaObjC/warn-called-once.m

Index: clang/test/SemaObjC/warn-called-once.m
===
--- /dev/null
+++ clang/test/SemaObjC/warn-called-once.m
@@ -0,0 +1,1050 @@
+// RUN: %clang_cc1 -verify -fsyntax-only -fblocks -fobjc-exceptions -Wcompletion-handler %s
+
+#define NULL (void *)0
+#define nil (id)0
+#define CALLED_ONCE __attribute__((called_once))
+#define NORETURN __attribute__((noreturn))
+
+@protocol NSObject
+@end
+@interface NSObject 
+- (id)copy;
+- (id)class;
+- autorelease;
+@end
+
+typedef unsigned int NSUInteger;
+typedef struct {
+} NSFastEnumerationState;
+
+@interface NSArray <__covariant NSFastEnumeration>
+- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
+@end
+@interface NSMutableArray : NSArray 
+- addObject:anObject;
+@end
+@class NSString, Protocol;
+extern void NSLog(NSString *format, ...);
+
+void escape(void (^callback)(void));
+void escape_void(void *);
+void indirect_call(void (^callback)(void) CALLED_ONCE);
+void indirect_conv(void (^completionHandler)(void));
+void filler(void);
+void exit(int) NORETURN;
+
+void double_call_one_block(void (^callback)(void) CALLED_ONCE) {
+  callback(); // expected-note{{previous call is here}}
+  callback(); // expected-warning{{'callback' parameter marked 'called_once' is called twice}}
+}
+
+void double_call_one_block_parens(void (^callback)(void) CALLED_ONCE) {
+  (callback)(); // expected-note{{previous call is here}}
+  (callback)(); // expected-warning{{'callback' parameter marked 'called_once' is called twice}}
+}
+
+void double_call_one_block_ptr(void (*callback)(void) CALLED_ONCE) {
+  callback(); // expected-note{{previous call is here}}
+  callback(); // expected-warning{{'callback' parameter marked 'called_once' is called twice}}
+}
+
+void double_call_one_block_ptr_deref(void (*callback)(void) CALLED_ONCE) {
+  (*callback)(); // expected-note{{previous call is here}}
+  (*callback)(); // expected-warning{{'callback' parameter marked 'called_once' is called twice}}
+}
+
+void multiple_call_one_block(void (^callback)(void) CALLED_ONCE) {
+  // We don't really need to repeat the same warning for the same parameter.
+  callback(); // no-warning
+  callback(); // no-warning
+  callback(); // no-warning
+  callback(); // expected-note{{previous call is here}}
+  callback(); // expected-warning{{'callback' parameter marked 'called_once' is called twice}}
+}
+
+void double_call_branching_1(int cond, void (^callback)(void) CALLED_ONCE) {
+  if (cond) {
+callback(); // expected-note{{previous call is here}}
+  } else {
+cond += 42;
+  }
+  callback(); // expected-warning{{'callback' parameter marked 'called_once' is called twice}}
+}
+
+void double_call_branching_2(int cond, void (^callback)(void) CALLED_ONCE) {
+  callback();
+  // expected-note@-1{{previous call is here; set to nil to indicate it cannot be called afterwards}}
+
+  if (cond) {
+callback(); // expected-warning{{'callback' parameter marked 'called_once' is called twice}}
+  } else {
+cond += 42;
+  }
+}
+
+void double_call_branching_3(int cond, void (^callback)(void) CALLED_ONCE) {
+  if (cond) {
+callback();
+  } else {
+callback();
+  }
+  // no-warning
+}
+
+void double_call_branching_4(int cond1, int cond2, void (^callback)(void) CALLED_ONCE) {
+  if (cond1) {
+cond2 = !cond2;
+  } else {
+callback();
+// expected-note@-1{{previous call is here; set to nil to indicate it cannot be called afterwards}}
+  }
+
+  if (cond2) {
+callback(); // expected-warning{{'callback' parameter marked 'called_once' is called twice}}
+  }
+}
+
+void double_call_loop(int counter, void (^callback)(void) CALLED_ONCE) {
+  while (counter > 0) {
+counter--;
+// Both note and warning are on the same line, which is a common situation
+// in loops.
+callback(); // expected-note{{previous call is here}}
+// expected-warning@-1{{'callback' parameter marked 'called_once' is called twice}}
+  }
+}
+
+void never_called_trivial(void (^callback)(void) CALLED_ONCE) {
+  // expected-warning@-1{{'callback' parameter marked 'c

[PATCH] D93393: [clangd] Ignore the static index refs from the dynamic index files.

2020-12-18 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX updated this revision to Diff 312742.
ArcsinX added a comment.

Fix format
Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93393

Files:
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Index.h
  clang-tools-extra/clangd/index/MemIndex.cpp
  clang-tools-extra/clangd/index/MemIndex.h
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/index/Merge.h
  clang-tools-extra/clangd/index/ProjectAware.cpp
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/index/dex/Dex.h
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/DexTests.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp
  clang-tools-extra/clangd/unittests/TestFS.cpp

Index: clang-tools-extra/clangd/unittests/TestFS.cpp
===
--- clang-tools-extra/clangd/unittests/TestFS.cpp
+++ clang-tools-extra/clangd/unittests/TestFS.cpp
@@ -99,8 +99,9 @@
   llvm::Expected
   getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
   llvm::StringRef HintPath) const override {
-if (!HintPath.startswith(testRoot()))
-  return error("Hint path doesn't start with test root: {0}", HintPath);
+if (!HintPath.empty() && !HintPath.startswith(testRoot()))
+  return error("Hint path is not empty and doesn't start with {0}: {1}",
+   testRoot(), HintPath);
 if (!Body.consume_front("/"))
   return error("Body of an unittest: URI must start with '/'");
 llvm::SmallString<16> Path(Body.begin(), Body.end());
Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1237,6 +1237,12 @@
 void relations(const RelationsRequest &Req,
llvm::function_ref
Callback) const override {}
+
+llvm::unique_function
+indexedFiles() const override {
+  return [](llvm::StringRef) { return false; };
+}
+
 size_t estimateMemoryUsage() const override { return 0; }
   } PIndex;
   Results = rename({MainCode.point(),
@@ -1285,6 +1291,12 @@
 void relations(const RelationsRequest &,
llvm::function_ref)
 const override {}
+
+llvm::unique_function
+indexedFiles() const override {
+  return [](llvm::StringRef) { return false; };
+}
+
 size_t estimateMemoryUsage() const override { return 0; }
 Ref ReturnedRef;
   } DIndex(XRefInBarCC);
Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -224,6 +224,20 @@
   EXPECT_THAT(lookup(*I, SymbolID("ns::nonono")), UnorderedElementsAre());
 }
 
+TEST(MemIndexTest, IndexedFiles) {
+  SymbolSlab Symbols;
+  RefSlab Refs;
+  auto Size = Symbols.bytes() + Refs.bytes();
+  auto Data = std::make_pair(std::move(Symbols), std::move(Refs));
+  llvm::StringSet<> Files = {testPath("foo.cc"), testPath("bar.cc")};
+  MemIndex I(std::move(Data.first), std::move(Data.second), RelationSlab(),
+ std::move(Files), std::move(Data), Size);
+  auto ContainsFile = I.indexedFiles();
+  EXPECT_TRUE(ContainsFile("unittest:///foo.cc"));
+  EXPECT_TRUE(ContainsFile("unittest:///bar.cc"));
+  EXPECT_FALSE(ContainsFile("unittest:///foobar.cc"));
+}
+
 TEST(MemIndexTest, TemplateSpecialization) {
   SymbolSlab::Builder B;
 
@@ -367,7 +381,7 @@
   Test.Code = std::string(Test1Code.code());
   Test.Filename = "test.cc";
   auto AST = Test.build();
-  Dyn.updateMain(Test.Filename, AST);
+  Dyn.updateMain(testPath(Test.Filename), AST);
 
   // Build static index for test.cc.
   Test.HeaderCode = HeaderCode;
@@ -375,7 +389,7 @@
   Test.Filename = "test.cc";
   auto StaticAST = Test.build();
   // Add stale refs for test.cc.
-  StaticIndex.updateMain(Test.Filename, StaticAST);
+  StaticIndex.updateMain(testPath(Test.Filename), StaticAST);
 
   // Add refs for test2.cc
   Annotations Test2Code(R"(class $Foo[[Foo]] {};)");
@@ -384,7 +398,7 @@
   Test2.Code = std::string(Test2Code.code());
   Test2.Filename = "test2.cc";
   StaticAST = Test2.build();
-  StaticIndex.updateMain(Test2.Filename, StaticAST);
+  StaticIndex.updateMain(testPath(Test2.Filename), StaticAST);
 
   RefsRequest Request;
   Request.IDs = {Foo.ID};
@@ -403,10 +417,47 @@
   RefSlab::Builder Results2;
   EXPECT_TRUE(
   Merge.refs(Request, [&](const Ref &O) { Results2.insert(Foo.ID, O); }));
-  EXPECT_THAT(std::move(Results2).build(),
-  Elements

[PATCH] D92663: [clangd] Add hot-reload of compile_commands.json and compile_flags.txt

2020-12-18 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Seems to break tests on windows: http://45.33.8.238/win/30129/step_9.txt


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92663

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


[PATCH] D93227: [clangd] Smarter hover on auto and decltype

2020-12-18 Thread Quentin Chateau via Phabricator via cfe-commits
qchateau updated this revision to Diff 312747.
qchateau marked 5 inline comments as done.
qchateau added a comment.

- Verify documentation in hover test on 'auto'
- Fixed comments
- Converted raw string to string to avoid trailing whitespace


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93227

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp

Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -379,6 +379,30 @@
  HI.Definition = "class X {}";
}},
 
+  // auto on structured bindings
+  {R"cpp(
+void foo() {
+  struct S { int x; float y; };
+  [[au^to]] [x, y] = S();
+}
+)cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "struct S";
+   }},
+  // undeduced auto
+  {R"cpp(
+template
+void foo() {
+  [[au^to]] x = T{};
+}
+)cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "/* not deduced */";
+   }},
   // auto on lambda
   {R"cpp(
 void foo() {
@@ -386,8 +410,9 @@
 }
 )cpp",
[](HoverInfo &HI) {
- HI.Name = "(lambda)";
- HI.Kind = index::SymbolKind::Class;
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "class(lambda)";
}},
   // auto on template instantiation
   {R"cpp(
@@ -397,8 +422,9 @@
 }
 )cpp",
[](HoverInfo &HI) {
- HI.Name = "Foo";
- HI.Kind = index::SymbolKind::Class;
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "class Foo";
}},
   // auto on specialized template
   {R"cpp(
@@ -409,8 +435,9 @@
 }
 )cpp",
[](HoverInfo &HI) {
- HI.Name = "Foo";
- HI.Kind = index::SymbolKind::Class;
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "class Foo";
}},
 
   // macro
@@ -582,8 +609,9 @@
   }
   )cpp",
   [](HoverInfo &HI) {
-HI.Name = "Foo";
-HI.Kind = index::SymbolKind::Class;
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "class Foo";
   }},
   {// Falls back to primary template, when the type is not instantiated.
R"cpp(
@@ -955,20 +983,11 @@
   llvm::StringRef Tests[] = {
   "^int main() {}",
   "void foo() {^}",
-  R"cpp(// structured binding. Not supported yet
-struct Bar {};
-void foo() {
-  Bar a[2];
-  ^auto [x,y] = a;
-}
-  )cpp",
-  R"cpp(// Template auto parameter. Nothing (Not useful).
-template
-void func() {
-}
-void foo() {
-   func<1>();
-}
+  // FIXME: "decltype(auto)" should be a single hover
+  "decltype(au^to) x = 0;",
+  // FIXME: not supported yet
+  R"cpp(// Lambda auto parameter
+auto lamb = [](a^uto){};
   )cpp",
   R"cpp(// non-named decls don't get hover. Don't crash!
 ^static_assert(1, "");
@@ -1545,9 +1564,9 @@
 }
   )cpp",
   [](HoverInfo &HI) {
-HI.Name = "int";
-// FIXME: Should be Builtin/Integral.
-HI.Kind = index::SymbolKind::Unknown;
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "int";
   }},
   {
   R"cpp(// Simple initialization with const auto
@@ -1555,14 +1574,22 @@
   const ^[[auto]] i = 1;
 }
   )cpp",
-  [](HoverInfo &HI) { HI.Name = "int"; }},
+  [](HoverInfo &HI) {
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "int";
+  }},
   {
   R"cpp(// Simple initialization with const auto&
 void foo() {
   const ^[[auto]]& i = 1;
 }
   )cpp",
-  [](HoverInfo &HI) { HI.Name = "int"; }},
+  [](HoverInfo &HI) {
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "int";
+  }},
   {
   R"cpp(// Simple initialization with auto&
 void foo() {
@@ -1570,7 +1597,11 @@
   ^[[auto]]& i = x;
 }
   )cpp",
- 

[PATCH] D93227: [clangd] Smarter hover on auto and decltype

2020-12-18 Thread Quentin Chateau via Phabricator via cfe-commits
qchateau added a comment.

You can land this if it is still fine after my final update.

email: quentin.chat...@gmail.com

Thanks !




Comment at: clang-tools-extra/clangd/unittests/HoverTests.cpp:2452
 // In namespace ns
 ret_type foo(params) {})",
   },

I've also changed this raw string to a normal string (and another one line 
2729) because they include whitespace at the end of the line. Git complains 
about it and my editor automatically trims trailing whitespace. I assume I'm 
not the only one using this setting and it annoyed me more than it should.



Comment at: clang-tools-extra/clangd/unittests/HoverTests.cpp:999
+  "decltype(au^to) x = 0;",
+  R"cpp(// Lambda auto parameter. Nothing (Not useful).
+auto lamb = [](a^uto){};

sammccall wrote:
> qchateau wrote:
> > sammccall wrote:
> > > (not convinced this is fundamentally not useful - the fact that it's a 
> > > template parameter means it's probably worth having a hover card for it 
> > > at some point. But I agree with suppressing it for now)
> > As a user I'd prefer the hover to work over the whole `decltype(auto)` 
> > expression. But that does not seem quite compatible with the way tokens are 
> > parsed.
> > 
> > Are you suggesting I remove the test case or should I add a `FIXME` comment 
> > ?
> Sorry, I think we're talking about different examples.
> 
> (I agree decltype(auto) should ideally be a single thing and we should 
> support hover on all of it, no need to address in this patch, FIXME would be 
> nice).
> 
> But I was talking about the lambda auto parameter, where your comment says 
> "not useful". Anyway, nothing to do here either except maybe soften the 
> comment to "not supported at the moment".
Ahah yes my bad, I copy pasted the comment x)
I fixed it


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93227

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


[PATCH] D93531: [clangd] Reuse buffer for JSONTransport::readRawMessage

2020-12-18 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
njames93 requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Reusing the buffers for reading messages will alleviate some malloc pressure, 
alluded to in D93452 .
This is potentially unsafe as the StringRef returned will be invalidated on 
sucessive calls and its not thread-safe.
However given there is only 1 call site those both appear to be non-issues.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93531

Files:
  clang-tools-extra/clangd/JSONTransport.cpp

Index: clang-tools-extra/clangd/JSONTransport.cpp
===
--- clang-tools-extra/clangd/JSONTransport.cpp
+++ clang-tools-extra/clangd/JSONTransport.cpp
@@ -136,12 +136,20 @@
   }
 
   // Read raw string messages from input stream.
-  llvm::Optional readRawMessage() {
+  // This stores the message in buffer owned by this class, as such once this
+  // method is called, any previous StringRefs held from this are invalidated.
+  llvm::Optional readRawMessage() {
 return Style == JSONStreamStyle::Delimited ? readDelimitedMessage()
: readStandardMessage();
   }
-  llvm::Optional readDelimitedMessage();
-  llvm::Optional readStandardMessage();
+  llvm::Optional readDelimitedMessage();
+  llvm::Optional readStandardMessage();
+
+  // Accept that these buffers are going to be large enough that there is no
+  // point in inline storage. Using a SmallString also saves the need for
+  // unnecessary things null terminators.
+  llvm::SmallString<0> JsonContentBuffer;
+  llvm::SmallString<0> JsonLineBuffer;
 
   std::FILE *In;
   llvm::raw_ostream &Out;
@@ -190,7 +198,7 @@
 
 // Tries to read a line up to and including \n.
 // If failing, feof(), ferror(), or shutdownRequested() will be set.
-bool readLine(std::FILE *In, std::string &Out) {
+bool readLine(std::FILE *In, llvm::SmallVectorImpl &Out) {
   static constexpr int BufSize = 1024;
   size_t Size = 0;
   Out.clear();
@@ -215,17 +223,16 @@
 // Returns None when:
 //  - ferror(), feof(), or shutdownRequested() are set.
 //  - Content-Length is missing or empty (protocol error)
-llvm::Optional JSONTransport::readStandardMessage() {
+llvm::Optional JSONTransport::readStandardMessage() {
   // A Language Server Protocol message starts with a set of HTTP headers,
   // delimited  by \r\n, and terminated by an empty line (\r\n).
   unsigned long long ContentLength = 0;
-  std::string Line;
   while (true) {
-if (feof(In) || ferror(In) || !readLine(In, Line))
+if (feof(In) || ferror(In) || !readLine(In, JsonLineBuffer))
   return llvm::None;
-InMirror << Line;
+InMirror << JsonLineBuffer;
 
-llvm::StringRef LineRef(Line);
+llvm::StringRef LineRef(JsonLineBuffer);
 
 // We allow comments in headers. Technically this isn't part
 
@@ -264,23 +271,23 @@
 return llvm::None;
   }
 
-  std::string JSON(ContentLength, '\0');
+  JsonContentBuffer.resize(ContentLength);
   for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
 // Handle EINTR which is sent when a debugger attaches on some platforms.
-Read = retryAfterSignalUnlessShutdown(0, [&]{
-  return std::fread(&JSON[Pos], 1, ContentLength - Pos, In);
+Read = retryAfterSignalUnlessShutdown(0, [&] {
+  return std::fread(&JsonContentBuffer[Pos], 1, ContentLength - Pos, In);
 });
 if (Read == 0) {
   elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos,
ContentLength);
   return llvm::None;
 }
-InMirror << llvm::StringRef(&JSON[Pos], Read);
+InMirror << llvm::StringRef(&JsonContentBuffer[Pos], Read);
 clearerr(In); // If we're done, the error was transient. If we're not done,
   // either it was transient or we'll see it again on retry.
 Pos += Read;
   }
-  return std::move(JSON);
+  return StringRef(JsonContentBuffer);
 }
 
 // For lit tests we support a simplified syntax:
@@ -288,12 +295,11 @@
 // - lines starting with # are ignored.
 // This is a testing path, so favor simplicity over performance here.
 // When returning None, feof(), ferror(), or shutdownRequested() will be set.
-llvm::Optional JSONTransport::readDelimitedMessage() {
-  std::string JSON;
-  std::string Line;
-  while (readLine(In, Line)) {
-InMirror << Line;
-auto LineRef = llvm::StringRef(Line).trim();
+llvm::Optional JSONTransport::readDelimitedMessage() {
+  JsonContentBuffer.clear();
+  while (readLine(In, JsonLineBuffer)) {
+InMirror << JsonLineBuffer;
+auto LineRef = llvm::StringRef(JsonLineBuffer).trim();
 if (LineRef.startswith("#")) // comment
   continue;
 
@@ -301,7 +307,7 @@
 if (LineRef.rtrim() == "---")
   break;
 
-JSON += Line;
+JsonContentBu

[PATCH] D87188: [InstCombine] Canonicalize SPF to abs intrinc

2020-12-18 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

In D87188#2461510 , @mstorsjo wrote:

> In D87188#2461497 , @lebedev.ri 
> wrote:
>
>> @mstorsjo i've bothered @dmajor to give this a try on some of mozilla's CI, 
>> and unfortunately it came back green..
>> I don't recall if i can reproduce it locally (on vanilla test suite, i'll 
>> recheck),
>> but right now it would seem that you are the only one who can reproduce this 
>> :/
>>
>> Were you able to make any progress on a somewhat more actionable reproducer?
>>
>> What would be really helpful is a standalone source that can be compiled and 
>> run (here by be locally, on linux x86_64)
>> that produces different result with/without this change.
>
> IIRC I'm only able to reproduce this for aarch64 (and possibly arm) targets 
> unfortunately. I can make a kind of standalone testcase with one single file 
> built from source, linked and executed along with a bigger piece of code 
> (either from source or prebuilt object files), but it'd be for aarch64-linux 
> (or aarch64-darwin if that helps - I haven't tried reproducing it there but 
> I'd presume it behaves the same as I noticed the bug first on aarch64 
> windows).

Ok, here's a reproduction environment, requiring aarch64 linux (tested on 
ubuntu 18.04, but anything similar or newer should be fine, and AWS and other 
cloud providers makes it fairly easy to spin up such an instance) - with 
https://martin.st/temp/ffmpeg-repro.zip downloaded and unzipped:

  $ gcc -c vc1_block-debug.c -o vc1_block-debug.o
  $ gcc *.o -Wl,--start-group *.a -Wl,--end-group -o ffmpeg -lm -lpthread -lz
  $ ./ffmpeg -v quiet -i SA00040.vc1 -f framecrc -
  #software: Lavf58.65.100
  #tb 0: 1/25
  #media_type 0: video
  #codec_id 0: rawvideo
  #dimensions 0: 176x144
  #sar 0: 1/1
  0,  0,  0,1,38016, 0xa6f15db5
  0,  1,  1,1,38016, 0xa6f15db5
  0,  2,  2,1,38016, 0xa6f15db5
  0,  4,  4,1,38016, 0x5c4ef0e7
  0,  5,  5,1,38016, 0x53a42d1d
  0,  6,  6,1,38016, 0x68f7d89e
  0,  7,  7,1,38016, 0xc15f4368
  0,  8,  8,1,38016, 0xc15f4368
  0,  9,  9,1,38016, 0xd1bd47a8
  0, 10, 10,1,38016, 0xd1bd47a8
  0, 11, 11,1,38016, 0xe1e821ca
  0, 12, 12,1,38016, 0xe1e821ca
  0, 13, 13,1,38016, 0xe1e821ca
  0, 14, 14,1,38016, 0xe1e821ca
  0, 15, 15,1,38016, 0xe1e821ca
  $ clang -c vc1_block-debug.c -o vc1_block-debug.o -O2 # Recompile the 
problematic function with clang with this patch included
  $ gcc *.o -Wl,--start-group *.a -Wl,--end-group -o ffmpeg -lm -lpthread -lz
  $ ./ffmpeg -v quiet -i SA00040.vc1 -f framecrc -
  #software: Lavf58.65.100
  #tb 0: 1/25
  #media_type 0: video
  #codec_id 0: rawvideo
  #dimensions 0: 176x144
  #sar 0: 1/1
  0,  0,  0,1,38016, 0xa6f15db5
  0,  1,  1,1,38016, 0xa6f15db5
  0,  2,  2,1,38016, 0xa6f15db5
  0,  4,  4,1,38016, 0x5c4ef0e7
  0,  5,  5,1,38016, 0x53a42d1d
  0,  6,  6,1,38016, 0x68f7d89e
  0,  7,  7,1,38016, 0xc15f4368
  0,  8,  8,1,38016, 0xc15f4368
  0,  9,  9,1,38016, 0xd1bd47a8
  0, 10, 10,1,38016, 0xd1bd47a8
  0, 11, 11,1,38016, 0x3bf00b9a # The hashes from 
here onwards differ
  0, 12, 12,1,38016, 0x3bf00b9a
  0, 13, 13,1,38016, 0x3bf00b9a
  0, 14, 14,1,38016, 0x3bf00b9a
  0, 15, 15,1,38016, 0x3bf00b9a

Alternative repro, fully from source:

  $ git clone https://github.com/mstorsjo/ffmpeg.git
  $ cd ffmpeg
  $ git checkout origin/vc1-debug 
  $ mkdir ../ffmpeg-build; cd ../ffmpeg-build
  $ ../ffmpeg/configure --disable-everything --enable-decoder=vc1 
--enable-demuxer=vc1 --enable-encoder=rawvideo --enable-muxer=framecrc 
--enable-protocol=file --enable-protocol=pipe --enable-parser=vc1 
--enable-bsf=extract_extradata --samples=$(pwd)/../samples
  $ make -j$(nproc)
  $ make fate-rsync # Fetch reference test samples
  $ make fate-vc1 # Succeeds
  $ clang -c ../ffmpeg/libavcodec/vc1_block-debug.c -o 
libavcodec/vc1_block-debug.o -O3 -I../ffmpeg -I. # Recompile the problematic 
function with clang with this patch included
  $ make fate-vc1 # Fails
  TESTvc1_sa00040
  --- /home/ubuntu/code/ffmpeg/tests/ref/fate/vc1_sa00040   2020-12-18 
12:04:27.216500325 +
  +++ tests/data/fate/vc1_sa00040   2020-1

[PATCH] D93528: [clang-format] Add basic support for formatting JSON

2020-12-18 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

Why not using clang-format's support for JavaScript? It seems more complicated 
now, but it will probably allow to more easily change/add style options. WDYT?
And what happens when reformatting only a part of a JSON? Should there be some 
tests for that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93528

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


[clang-tools-extra] e35f922 - [clangd] Ignore the static index refs from the dynamic index files.

2020-12-18 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2020-12-18T15:36:30+03:00
New Revision: e35f9229dcb264be4a0a1ecf5cca2493f2c48878

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

LOG: [clangd] Ignore the static index refs from the dynamic index files.

This patch fixes the following problem:
- open a file with references to the symbol `Foo`
- remove all references to `Foo` (from the dynamic index).
- `MergedIndex::refs()` result will contain positions of removed references 
(from the static index).

The idea of this patch is to keep a set of files which were used during index 
build inside the index.
Thus at processing the static index references we can check if the file of 
processing reference is a part of the dynamic index or not.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/index/FileIndex.cpp
clang-tools-extra/clangd/index/Index.cpp
clang-tools-extra/clangd/index/Index.h
clang-tools-extra/clangd/index/MemIndex.cpp
clang-tools-extra/clangd/index/MemIndex.h
clang-tools-extra/clangd/index/Merge.cpp
clang-tools-extra/clangd/index/Merge.h
clang-tools-extra/clangd/index/ProjectAware.cpp
clang-tools-extra/clangd/index/dex/Dex.cpp
clang-tools-extra/clangd/index/dex/Dex.h
clang-tools-extra/clangd/index/remote/Client.cpp
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
clang-tools-extra/clangd/unittests/DexTests.cpp
clang-tools-extra/clangd/unittests/IndexTests.cpp
clang-tools-extra/clangd/unittests/RenameTests.cpp
clang-tools-extra/clangd/unittests/TestFS.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/index/FileIndex.cpp 
b/clang-tools-extra/clangd/index/FileIndex.cpp
index 1ccfb4485638..143e76863777 100644
--- a/clang-tools-extra/clangd/index/FileIndex.cpp
+++ b/clang-tools-extra/clangd/index/FileIndex.cpp
@@ -266,11 +266,14 @@ FileSymbols::buildIndex(IndexType Type, DuplicateHandling 
DuplicateHandle,
   std::vector> SymbolSlabs;
   std::vector> RefSlabs;
   std::vector> RelationSlabs;
+  llvm::StringSet<> Files;
   std::vector MainFileRefs;
   {
 std::lock_guard Lock(Mutex);
-for (const auto &FileAndSymbols : SymbolsSnapshot)
+for (const auto &FileAndSymbols : SymbolsSnapshot) {
   SymbolSlabs.push_back(FileAndSymbols.second);
+  Files.insert(FileAndSymbols.first());
+}
 for (const auto &FileAndRefs : RefsSnapshot) {
   RefSlabs.push_back(FileAndRefs.second.Slab);
   if (FileAndRefs.second.CountReferences)
@@ -372,14 +375,14 @@ FileSymbols::buildIndex(IndexType Type, DuplicateHandling 
DuplicateHandle,
   case IndexType::Light:
 return std::make_unique(
 llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
-std::move(AllRelations),
+std::move(AllRelations), std::move(Files),
 std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
 std::move(RefsStorage), std::move(SymsStorage)),
 StorageSize);
   case IndexType::Heavy:
 return std::make_unique(
 llvm::make_pointee_range(AllSymbols), std::move(AllRefs),
-std::move(AllRelations),
+std::move(AllRelations), std::move(Files),
 std::make_tuple(std::move(SymbolSlabs), std::move(RefSlabs),
 std::move(RefsStorage), std::move(SymsStorage)),
 StorageSize);

diff  --git a/clang-tools-extra/clangd/index/Index.cpp 
b/clang-tools-extra/clangd/index/Index.cpp
index b309053972eb..5da06f36ffe4 100644
--- a/clang-tools-extra/clangd/index/Index.cpp
+++ b/clang-tools-extra/clangd/index/Index.cpp
@@ -76,6 +76,11 @@ void SwapIndex::relations(
   return snapshot()->relations(R, CB);
 }
 
+llvm::unique_function
+SwapIndex::indexedFiles() const {
+  return snapshot()->indexedFiles();
+}
+
 size_t SwapIndex::estimateMemoryUsage() const {
   return snapshot()->estimateMemoryUsage();
 }

diff  --git a/clang-tools-extra/clangd/index/Index.h 
b/clang-tools-extra/clangd/index/Index.h
index f0959e71d50f..c961aa9d8bd9 100644
--- a/clang-tools-extra/clangd/index/Index.h
+++ b/clang-tools-extra/clangd/index/Index.h
@@ -14,6 +14,7 @@
 #include "Symbol.h"
 #include "SymbolID.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/FunctionExtras.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/JSON.h"
@@ -121,6 +122,11 @@ class SymbolIndex {
   llvm::function_ref
   Callback) const = 0;
 
+  /// Returns function which checks if the specified file was used to build 
this
+  /// index or not. The function must only be called while the index is alive.
+  virtual llvm::unique_function
+  indexedFiles() const = 0;
+
   /// Returns estimated size of index (in bytes).
   virtual size_t estimateM

[PATCH] D93393: [clangd] Ignore the static index refs from the dynamic index files.

2020-12-18 Thread Aleksandr Platonov via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe35f9229dcb2: [clangd] Ignore the static index refs from the 
dynamic index files. (authored by ArcsinX).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93393

Files:
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/index/Index.cpp
  clang-tools-extra/clangd/index/Index.h
  clang-tools-extra/clangd/index/MemIndex.cpp
  clang-tools-extra/clangd/index/MemIndex.h
  clang-tools-extra/clangd/index/Merge.cpp
  clang-tools-extra/clangd/index/Merge.h
  clang-tools-extra/clangd/index/ProjectAware.cpp
  clang-tools-extra/clangd/index/dex/Dex.cpp
  clang-tools-extra/clangd/index/dex/Dex.h
  clang-tools-extra/clangd/index/remote/Client.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
  clang-tools-extra/clangd/unittests/DexTests.cpp
  clang-tools-extra/clangd/unittests/IndexTests.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp
  clang-tools-extra/clangd/unittests/TestFS.cpp

Index: clang-tools-extra/clangd/unittests/TestFS.cpp
===
--- clang-tools-extra/clangd/unittests/TestFS.cpp
+++ clang-tools-extra/clangd/unittests/TestFS.cpp
@@ -99,8 +99,9 @@
   llvm::Expected
   getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
   llvm::StringRef HintPath) const override {
-if (!HintPath.startswith(testRoot()))
-  return error("Hint path doesn't start with test root: {0}", HintPath);
+if (!HintPath.empty() && !HintPath.startswith(testRoot()))
+  return error("Hint path is not empty and doesn't start with {0}: {1}",
+   testRoot(), HintPath);
 if (!Body.consume_front("/"))
   return error("Body of an unittest: URI must start with '/'");
 llvm::SmallString<16> Path(Body.begin(), Body.end());
Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1237,6 +1237,12 @@
 void relations(const RelationsRequest &Req,
llvm::function_ref
Callback) const override {}
+
+llvm::unique_function
+indexedFiles() const override {
+  return [](llvm::StringRef) { return false; };
+}
+
 size_t estimateMemoryUsage() const override { return 0; }
   } PIndex;
   Results = rename({MainCode.point(),
@@ -1285,6 +1291,12 @@
 void relations(const RelationsRequest &,
llvm::function_ref)
 const override {}
+
+llvm::unique_function
+indexedFiles() const override {
+  return [](llvm::StringRef) { return false; };
+}
+
 size_t estimateMemoryUsage() const override { return 0; }
 Ref ReturnedRef;
   } DIndex(XRefInBarCC);
Index: clang-tools-extra/clangd/unittests/IndexTests.cpp
===
--- clang-tools-extra/clangd/unittests/IndexTests.cpp
+++ clang-tools-extra/clangd/unittests/IndexTests.cpp
@@ -224,6 +224,20 @@
   EXPECT_THAT(lookup(*I, SymbolID("ns::nonono")), UnorderedElementsAre());
 }
 
+TEST(MemIndexTest, IndexedFiles) {
+  SymbolSlab Symbols;
+  RefSlab Refs;
+  auto Size = Symbols.bytes() + Refs.bytes();
+  auto Data = std::make_pair(std::move(Symbols), std::move(Refs));
+  llvm::StringSet<> Files = {testPath("foo.cc"), testPath("bar.cc")};
+  MemIndex I(std::move(Data.first), std::move(Data.second), RelationSlab(),
+ std::move(Files), std::move(Data), Size);
+  auto ContainsFile = I.indexedFiles();
+  EXPECT_TRUE(ContainsFile("unittest:///foo.cc"));
+  EXPECT_TRUE(ContainsFile("unittest:///bar.cc"));
+  EXPECT_FALSE(ContainsFile("unittest:///foobar.cc"));
+}
+
 TEST(MemIndexTest, TemplateSpecialization) {
   SymbolSlab::Builder B;
 
@@ -367,7 +381,7 @@
   Test.Code = std::string(Test1Code.code());
   Test.Filename = "test.cc";
   auto AST = Test.build();
-  Dyn.updateMain(Test.Filename, AST);
+  Dyn.updateMain(testPath(Test.Filename), AST);
 
   // Build static index for test.cc.
   Test.HeaderCode = HeaderCode;
@@ -375,7 +389,7 @@
   Test.Filename = "test.cc";
   auto StaticAST = Test.build();
   // Add stale refs for test.cc.
-  StaticIndex.updateMain(Test.Filename, StaticAST);
+  StaticIndex.updateMain(testPath(Test.Filename), StaticAST);
 
   // Add refs for test2.cc
   Annotations Test2Code(R"(class $Foo[[Foo]] {};)");
@@ -384,7 +398,7 @@
   Test2.Code = std::string(Test2Code.code());
   Test2.Filename = "test2.cc";
   StaticAST = Test2.build();
-  StaticIndex.updateMain(Test2.Filename, StaticAST);
+  StaticIndex.updateMain(testPath(Test2.Filename), StaticAST);
 
   RefsRequest Request;
   Request.IDs = {Foo.ID};
@@ -403,10 +417,47 @@
   RefSlab::Builder Results2;

[PATCH] D93227: [clangd] Smarter hover on auto and decltype

2020-12-18 Thread Quentin Chateau via Phabricator via cfe-commits
qchateau updated this revision to Diff 312757.
qchateau added a comment.

Fix ExpandAutoType to not expand undeduced auto


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93227

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp

Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -379,6 +379,30 @@
  HI.Definition = "class X {}";
}},
 
+  // auto on structured bindings
+  {R"cpp(
+void foo() {
+  struct S { int x; float y; };
+  [[au^to]] [x, y] = S();
+}
+)cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "struct S";
+   }},
+  // undeduced auto
+  {R"cpp(
+template
+void foo() {
+  [[au^to]] x = T{};
+}
+)cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "/* not deduced */";
+   }},
   // auto on lambda
   {R"cpp(
 void foo() {
@@ -386,8 +410,9 @@
 }
 )cpp",
[](HoverInfo &HI) {
- HI.Name = "(lambda)";
- HI.Kind = index::SymbolKind::Class;
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "class(lambda)";
}},
   // auto on template instantiation
   {R"cpp(
@@ -397,8 +422,9 @@
 }
 )cpp",
[](HoverInfo &HI) {
- HI.Name = "Foo";
- HI.Kind = index::SymbolKind::Class;
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "class Foo";
}},
   // auto on specialized template
   {R"cpp(
@@ -409,8 +435,9 @@
 }
 )cpp",
[](HoverInfo &HI) {
- HI.Name = "Foo";
- HI.Kind = index::SymbolKind::Class;
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "class Foo";
}},
 
   // macro
@@ -582,8 +609,9 @@
   }
   )cpp",
   [](HoverInfo &HI) {
-HI.Name = "Foo";
-HI.Kind = index::SymbolKind::Class;
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "class Foo";
   }},
   {// Falls back to primary template, when the type is not instantiated.
R"cpp(
@@ -955,20 +983,11 @@
   llvm::StringRef Tests[] = {
   "^int main() {}",
   "void foo() {^}",
-  R"cpp(// structured binding. Not supported yet
-struct Bar {};
-void foo() {
-  Bar a[2];
-  ^auto [x,y] = a;
-}
-  )cpp",
-  R"cpp(// Template auto parameter. Nothing (Not useful).
-template
-void func() {
-}
-void foo() {
-   func<1>();
-}
+  // FIXME: "decltype(auto)" should be a single hover
+  "decltype(au^to) x = 0;",
+  // FIXME: not supported yet
+  R"cpp(// Lambda auto parameter
+auto lamb = [](a^uto){};
   )cpp",
   R"cpp(// non-named decls don't get hover. Don't crash!
 ^static_assert(1, "");
@@ -1545,9 +1564,9 @@
 }
   )cpp",
   [](HoverInfo &HI) {
-HI.Name = "int";
-// FIXME: Should be Builtin/Integral.
-HI.Kind = index::SymbolKind::Unknown;
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "int";
   }},
   {
   R"cpp(// Simple initialization with const auto
@@ -1555,14 +1574,22 @@
   const ^[[auto]] i = 1;
 }
   )cpp",
-  [](HoverInfo &HI) { HI.Name = "int"; }},
+  [](HoverInfo &HI) {
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "int";
+  }},
   {
   R"cpp(// Simple initialization with const auto&
 void foo() {
   const ^[[auto]]& i = 1;
 }
   )cpp",
-  [](HoverInfo &HI) { HI.Name = "int"; }},
+  [](HoverInfo &HI) {
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "int";
+  }},
   {
   R"cpp(// Simple initialization with auto&
 void foo() {
@@ -1570,7 +1597,11 @@
   ^[[auto]]& i = x;
 }
   )cpp",
-  [](HoverInfo &HI) { HI.Name = "int"; }},
+  []

[clang-tools-extra] e69e551 - new altera single work item barrier check

2020-12-18 Thread Aaron Ballman via cfe-commits

Author: Frank Derry Wanye
Date: 2020-12-18T07:52:20-05:00
New Revision: e69e551e0e5fddffb6479da6a2998457104ba9e6

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

LOG: new altera single work item barrier check

This lint check is a part of the FLOCL (FPGA Linters for OpenCL)
project out of the Synergy Lab at Virginia Tech.

FLOCL is a set of lint checks aimed at FPGA developers who write code
in OpenCL.

The altera single work item barrier check finds OpenCL kernel functions
that call a barrier function but do not call an ID function. These
kernel functions will be treated as single work-item kernels, which
could be inefficient or lead to errors.

Based on the "Altera SDK for OpenCL: Best Practices Guide."

Added: 
clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.h
clang-tools-extra/docs/clang-tidy/checks/altera-single-work-item-barrier.rst

clang-tools-extra/test/clang-tidy/checkers/altera-single-work-item-barrier.cpp

Modified: 
clang-tools-extra/clang-tidy/altera/AlteraTidyModule.cpp
clang-tools-extra/clang-tidy/altera/CMakeLists.txt
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/altera/AlteraTidyModule.cpp 
b/clang-tools-extra/clang-tidy/altera/AlteraTidyModule.cpp
index d3e906b673ce..a328f05da5d0 100644
--- a/clang-tools-extra/clang-tidy/altera/AlteraTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/altera/AlteraTidyModule.cpp
@@ -10,6 +10,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "KernelNameRestrictionCheck.h"
+#include "SingleWorkItemBarrierCheck.h"
 #include "StructPackAlignCheck.h"
 
 using namespace clang::ast_matchers;
@@ -23,6 +24,8 @@ class AlteraModule : public ClangTidyModule {
   void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override {
 CheckFactories.registerCheck(
 "altera-kernel-name-restriction");
+CheckFactories.registerCheck(
+"altera-single-work-item-barrier");
 CheckFactories.registerCheck(
 "altera-struct-pack-align");
   }

diff  --git a/clang-tools-extra/clang-tidy/altera/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/altera/CMakeLists.txt
index 8ab5cc1aa4ad..0765b9735cf9 100644
--- a/clang-tools-extra/clang-tidy/altera/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/altera/CMakeLists.txt
@@ -6,6 +6,7 @@ set(LLVM_LINK_COMPONENTS
 add_clang_library(clangTidyAlteraModule
   AlteraTidyModule.cpp
   KernelNameRestrictionCheck.cpp
+  SingleWorkItemBarrierCheck.cpp
   StructPackAlignCheck.cpp
 
   LINK_LIBS

diff  --git 
a/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp 
b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
new file mode 100644
index ..759c81c34ca6
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp
@@ -0,0 +1,84 @@
+//===--- SingleWorkItemBarrierCheck.cpp - 
clang-tidy---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "SingleWorkItemBarrierCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace altera {
+
+void SingleWorkItemBarrierCheck::registerMatchers(MatchFinder *Finder) {
+  // Find any function that calls barrier but does not call an ID function.
+  // hasAttr(attr::Kind::OpenCLKernel) restricts it to only kernel functions.
+  // FIXME: Have it accept all functions but check for a parameter that gets an
+  // ID from one of the four ID functions.
+  Finder->addMatcher(
+  // Find function declarations...
+  functionDecl(
+  allOf(
+  // That are OpenCL kernels...
+  hasAttr(attr::Kind::OpenCLKernel),
+  // And call a barrier function (either 1.x or 2.x version)...
+  forEachDescendant(callExpr(callee(functionDecl(hasAnyName(
+ "barrier", 
"work_group_barrier"
+.bind("barrier")),
+  // But do not call an ID function.
+  unless(hasDescendant(callExpr(callee(functionDecl(
+  hasAnyName("get_global_id", "get_local_id", "get_group_id",
+ "get_local_linear_id"
+  .bind("function"),
+  this);
+}
+
+void SingleWorkItemBarrie

[PATCH] D72241: [clang-tidy] new altera single work item barrier check

2020-12-18 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

In D72241#2461921 , @ffrankies wrote:

> @aaron.ballman hmm, that is strange. I've rebased the patch and updated the 
> diff, let me know if this one doesn't work either or there's something else 
> you'd like me to try. Thanks! For what it's worth it's building just fine and 
> passing the clang-tools tests on my end.

This time everything applied cleanly and worked fine -- not certain what was up 
before. I've commit on your behalf in e69e551e0e5fddffb6479da6a2998457104ba9e6 
, thank 
you for the new check!


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

https://reviews.llvm.org/D72241

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


[PATCH] D72241: [clang-tidy] new altera single work item barrier check

2020-12-18 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D72241#2461921 , @ffrankies wrote:

> @aaron.ballman hmm, that is strange. I've rebased the patch and updated the 
> diff, let me know if this one doesn't work either or there's something else 
> you'd like me to try. Thanks! For what it's worth it's building just fine and 
> passing the clang-tools tests on my end.

FWIW This version I was able to pull just fine and run the clang tidy tests 
without a hitch


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

https://reviews.llvm.org/D72241

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


[PATCH] D93531: [clangd] Reuse buffer for JSONTransport::readRawMessage

2020-12-18 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

100% sure that failure is from trunk


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93531

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


[PATCH] D84189: [clang][cli] Let denormalizer decide how to render the option based on the option class

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 312761.
jansvoboda11 added a comment.

Rebase, add tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84189

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/unittests/Frontend/CompilerInvocationTest.cpp
  llvm/include/llvm/Option/OptParser.td

Index: llvm/include/llvm/Option/OptParser.td
===
--- llvm/include/llvm/Option/OptParser.td
+++ llvm/include/llvm/Option/OptParser.td
@@ -202,9 +202,6 @@
   code Normalizer = "normalizeSimpleEnum";
   code Denormalizer = "denormalizeSimpleEnum";
 }
-class AutoNormalizeEnumJoined : AutoNormalizeEnum {
-  code Denormalizer = "denormalizeSimpleEnumJoined";
-}
 class ValueMerger { code ValueMerger = merger; }
 class ValueExtractor { code ValueExtractor = extractor; }
 
Index: clang/unittests/Frontend/CompilerInvocationTest.cpp
===
--- clang/unittests/Frontend/CompilerInvocationTest.cpp
+++ clang/unittests/Frontend/CompilerInvocationTest.cpp
@@ -342,30 +342,70 @@
   ASSERT_THAT(GeneratedArgs, Contains(StrEq(DefaultTriple.c_str(;
 }
 
-TEST_F(CommandLineTest, CanGenerateCC1CommandLineSeparateEnumNonDefault) {
+TEST_F(CommandLineTest, SeparateEnumNonDefault) {
   const char *Args[] = {"-mrelocation-model", "static"};
 
   CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
 
   ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_EQ(Invocation.getCodeGenOpts().RelocationModel, Reloc::Model::Static);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
 
   // Non default relocation model.
+  ASSERT_THAT(GeneratedArgs, Contains(StrEq("-mrelocation-model")));
   ASSERT_THAT(GeneratedArgs, Contains(StrEq("static")));
+  ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("-mrelocation-model=static";
 }
 
-TEST_F(CommandLineTest, CanGenerateCC1COmmandLineSeparateEnumDefault) {
+TEST_F(CommandLineTest, SeparateEnumDefault) {
   const char *Args[] = {"-mrelocation-model", "pic"};
 
   CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
 
   ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_EQ(Invocation.getCodeGenOpts().RelocationModel, Reloc::Model::PIC_);
 
   Invocation.generateCC1CommandLine(GeneratedArgs, *this);
 
   // Default relocation model.
+  ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("-mrelocation-model";
   ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("pic";
+  ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("-mrelocation-model=pic";
+}
+
+TEST_F(CommandLineTest, JoinedEnumNonDefault) {
+  const char *Args[] = {"-fobjc-dispatch-method=non-legacy"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_EQ(Invocation.getCodeGenOpts().getObjCDispatchMethod(),
+CodeGenOptions::NonLegacy);
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+
+  ASSERT_THAT(GeneratedArgs,
+  Contains(StrEq("-fobjc-dispatch-method=non-legacy")));
+  ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("-fobjc-dispatch-method=";
+  ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("non-legacy";
+}
+
+TEST_F(CommandLineTest, JoinedEnumDefault) {
+  const char *Args[] = {"-fobjc-dispatch-method=legacy"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_EQ(Invocation.getCodeGenOpts().getObjCDispatchMethod(),
+CodeGenOptions::Legacy);
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+
+  ASSERT_THAT(GeneratedArgs,
+  Not(Contains(StrEq("-fobjc-dispatch-method=legacy";
+  ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("-fobjc-dispatch-method=";
+  ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("legacy";
 }
 
 // Tree of boolean options that can be (directly or transitively) implied by
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -152,8 +152,8 @@
 /// argument.
 static void denormalizeSimpleFlag(SmallVectorImpl &Args,
   const char *Spelling,
-  CompilerInvocation::StringAllocator, unsigned,
-  /*T*/...) {
+  CompilerInvocation::StringAllocator,
+  Option::OptionClass, unsigned, /*T*/...) {
   Args.push_back(Spelling);
 }
 
@@ -200,12 +200,41 @@
 
 static auto makeBooleanOptionDenormalizer(bool Value) {
   return [Value](SmallVectorImpl &Args, const char *Spelling,
- CompilerInvocation::StringAllocator, unsigned, bool KeyPath) {
+ CompilerInvocation::StringAllocator, Option::Optio

[clang] 2d2498e - No longer reject tag declarations in the clause-1 of a for loop.

2020-12-18 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2020-12-18T07:56:17-05:00
New Revision: 2d2498ec6c42b12eae873257e6ddcefe8348

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

LOG: No longer reject tag declarations in the clause-1 of a for loop.

We currently reject this valid C construct by claiming it declares a
non-local variable: for (struct { int i; } s={0}; s.i != 0; s.i--) ;

We expected all declaration in the clause-1 declaration statement to be
a local VarDecl, but there can be other declarations involved such as a
tag declaration. This fixes PR35757.

Added: 


Modified: 
clang/lib/Sema/SemaStmt.cpp
clang/test/Sema/for.c

Removed: 




diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index d89dfaf78a9c..8d0ebe7e2409 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -1822,15 +1822,27 @@ StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, 
SourceLocation LParenLoc,
   // C99 6.8.5p3: The declaration part of a 'for' statement shall only
   // declare identifiers for objects having storage class 'auto' or
   // 'register'.
+  const Decl *NonVarSeen = nullptr;
+  bool VarDeclSeen = false;
   for (auto *DI : DS->decls()) {
-VarDecl *VD = dyn_cast(DI);
-if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
-  VD = nullptr;
-if (!VD) {
-  Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
-  DI->setInvalidDecl();
+if (VarDecl *VD = dyn_cast(DI)) {
+  VarDeclSeen = true;
+  if (VD->isLocalVarDecl() && !VD->hasLocalStorage()) {
+Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
+DI->setInvalidDecl();
+  }
+} else if (!NonVarSeen) {
+  // Keep track of the first non-variable declaration we saw so that
+  // we can diagnose if we don't see any variable declarations. This
+  // covers a case like declaring a typedef, function, or structure
+  // type rather than a variable.
+  NonVarSeen = DI;
 }
   }
+  // Diagnose if we saw a non-variable declaration but no variable
+  // declarations.
+  if (NonVarSeen && !VarDeclSeen)
+Diag(NonVarSeen->getLocation(), diag::err_non_variable_decl_in_for);
 }
   }
 

diff  --git a/clang/test/Sema/for.c b/clang/test/Sema/for.c
index b998f4b07cf0..d0c2f7f21a96 100644
--- a/clang/test/Sema/for.c
+++ b/clang/test/Sema/for.c
@@ -2,6 +2,12 @@
 
 // Check C99 6.8.5p3
 void b1 (void) { for (void (*f) (void);;); }
-void b2 (void) { for (void f (void);;); }   // expected-error {{declaration of 
non-local variable}}
+void b2 (void) { for (void f (void);;); }   // expected-error {{non-variable 
declaration in 'for' loop}}
 void b3 (void) { for (static int f;;); }// expected-error {{declaration of 
non-local variable}}
-void b4 (void) { for (typedef int f;;); }   // expected-error {{declaration of 
non-local variable}}
+void b4 (void) { for (typedef int f;;); }   // expected-error {{non-variable 
declaration in 'for' loop}}
+void b5 (void) { for (struct { int i; } s;;); }
+void b6 (void) { for (enum { zero, ten = 10 } i;;); }
+void b7 (void) { for (struct s { int i; };;); } // expected-error 
{{non-variable declaration in 'for' loop}}
+void b8 (void) { for (static struct { int i; } s;;); } // expected-error 
{{declaration of non-local variable}}
+void b9 (void) { for (struct { int i; } (*s)(struct { int j; } o) = 0;;); }
+void b10(void) { for (typedef struct { int i; } (*s)(struct { int j; });;); } 
// expected-error {{non-variable declaration in 'for' loop}}



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


[PATCH] D92577: Don't reject tag declarations in for loop clause-1

2020-12-18 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

Thank you for the review! I've commit in 
2d2498ec6c42b12eae873257e6ddcefe8348 



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

https://reviews.llvm.org/D92577

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


[PATCH] D92039: [-Wcalled-once-parameter] Introduce 'called_once' attribute

2020-12-18 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D92039#2462255 , @vsavchenko wrote:

> In D92039#2458392 , @aaron.ballman 
> wrote:
>
>> 
>
>
>
>> There have been efforts to add cross-TU support to the static analyzer, so 
>> I'm less worried about cross-TU inter-procedural bugs over the long term as 
>> I would expect that situation to be improved.
>
> I'm a bit less optimistic on that front, the whole model of how we do the 
> analysis should be redesigned in order to get true cross-TU inter-procedural 
> analysis.  Additionally, some checkers when essentially inter-procedural rely 
> on function conventions to assume behavior of called functions, the same way 
> it is done with this analysis.
>
>> I think my concern is somewhat different. If the goal is for the semantics 
>> to follow the parameter (which I also think is the correct behavior), then I 
>> think adding this as a frontend analysis is the incorrect place for the 
>> check to go because someday we're going to want the inter-procedural 
>> analysis and that will require us to figure out what to do with the frontend 
>> bits vs the static analyzer bits. If it starts off in the static analyzer, 
>> then the later improvements to the analysis capabilities don't require the 
>> user to change the way they interact with the toolchain.
>>
>> Or do you expect that this analysis is sufficient and you don't expect to 
>> ever extend it to be inter-procedural?
>
> As I noted above, in some sense it is already inter-procedural because 
> usually called functions follow completion handler conventions as well.

Your test cases suggest that this is not inter-procedurally checked; it seems 
to require all of the APIs to be annotated in order to get the same effect that 
an inter-procedural check could determine on its own.

> So, we can actually make it inter-procedural if all involved functions follow 
> conventions. 
> And we can warn people if they leak `called_once` parameter into a function 
> that doesn't specify what it will do with that parameter.
>
> It was a decision not to do this and to be more lenient in the first version. 
>  You can see that in a lot of cases during the analysis we assume that the 
> user knows what they are doing.  And even in this model the number of 
> reported warnings is pretty high.
> We hope that this warning will help to change those cases and, maybe in the 
> future, we can harden the analysis to be more demanding.

I'm not worried about the leniency and I'm sorry if it sounds like I'm implying 
that it has to be inter-procedural to land -- that's not the case. What I am 
worried about is that the way the user runs the frontend is very different than 
the way the user runs the static analyzer, and migrating the warning from the 
FE to the static analyzer could leave us with problems. If the intention is 
that this check will live in the FE as-is (not getting inter-procedural 
support), then that's fine. But if the intention is to extend the check in the 
future in a way that might need it to move out of the FE and into the CSA, then 
I think the check should live in the CSA from the start (even if it doesn't do 
inter-procedural analysis). It's not clear to me whether "in the first version" 
implies that you expect a subsequent version to live in the CSA or not.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92039

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


[PATCH] D93531: [clangd] Reuse buffer for JSONTransport::readRawMessage

2020-12-18 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 312780.
njames93 added a comment.

Extend buffer behaviour to sendMessage.

Calls to this function seem to be guarded(up the call stack) by a mutex so 
again we shouldn't worry about races.
Besides there is no synchronization in the function currently when writing to 
the output stream.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93531

Files:
  clang-tools-extra/clangd/JSONTransport.cpp

Index: clang-tools-extra/clangd/JSONTransport.cpp
===
--- clang-tools-extra/clangd/JSONTransport.cpp
+++ clang-tools-extra/clangd/JSONTransport.cpp
@@ -126,22 +126,31 @@
   bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
   // Writes outgoing message to Out stream.
   void sendMessage(llvm::json::Value Message) {
-std::string S;
-llvm::raw_string_ostream OS(S);
+OutputBuffer.clear();
+llvm::raw_svector_ostream OS(OutputBuffer);
 OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
-OS.flush();
-Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
+Out << "Content-Length: " << OutputBuffer.size() << "\r\n\r\n"
+<< OutputBuffer;
 Out.flush();
-vlog(">>> {0}\n", S);
+vlog(">>> {0}\n", OutputBuffer);
   }
 
   // Read raw string messages from input stream.
-  llvm::Optional readRawMessage() {
+  // This stores the message in buffer owned by this class, as such once this
+  // method is called, any previous StringRefs held from this are invalidated.
+  llvm::Optional readRawMessage() {
 return Style == JSONStreamStyle::Delimited ? readDelimitedMessage()
: readStandardMessage();
   }
-  llvm::Optional readDelimitedMessage();
-  llvm::Optional readStandardMessage();
+  llvm::Optional readDelimitedMessage();
+  llvm::Optional readStandardMessage();
+
+  // Accept that these buffers are going to be large enough that there is no
+  // point in inline storage. Using a SmallString also saves the need for
+  // unnecessary things null terminators.
+  llvm::SmallString<0> JsonContentBuffer;
+  llvm::SmallString<0> JsonLineBuffer;
+  llvm::SmallString<0> OutputBuffer;
 
   std::FILE *In;
   llvm::raw_ostream &Out;
@@ -190,7 +199,7 @@
 
 // Tries to read a line up to and including \n.
 // If failing, feof(), ferror(), or shutdownRequested() will be set.
-bool readLine(std::FILE *In, std::string &Out) {
+bool readLine(std::FILE *In, llvm::SmallVectorImpl &Out) {
   static constexpr int BufSize = 1024;
   size_t Size = 0;
   Out.clear();
@@ -215,17 +224,16 @@
 // Returns None when:
 //  - ferror(), feof(), or shutdownRequested() are set.
 //  - Content-Length is missing or empty (protocol error)
-llvm::Optional JSONTransport::readStandardMessage() {
+llvm::Optional JSONTransport::readStandardMessage() {
   // A Language Server Protocol message starts with a set of HTTP headers,
   // delimited  by \r\n, and terminated by an empty line (\r\n).
   unsigned long long ContentLength = 0;
-  std::string Line;
   while (true) {
-if (feof(In) || ferror(In) || !readLine(In, Line))
+if (feof(In) || ferror(In) || !readLine(In, JsonLineBuffer))
   return llvm::None;
-InMirror << Line;
+InMirror << JsonLineBuffer;
 
-llvm::StringRef LineRef(Line);
+llvm::StringRef LineRef(JsonLineBuffer);
 
 // We allow comments in headers. Technically this isn't part
 
@@ -264,23 +272,23 @@
 return llvm::None;
   }
 
-  std::string JSON(ContentLength, '\0');
+  JsonContentBuffer.resize(ContentLength);
   for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
 // Handle EINTR which is sent when a debugger attaches on some platforms.
-Read = retryAfterSignalUnlessShutdown(0, [&]{
-  return std::fread(&JSON[Pos], 1, ContentLength - Pos, In);
+Read = retryAfterSignalUnlessShutdown(0, [&] {
+  return std::fread(&JsonContentBuffer[Pos], 1, ContentLength - Pos, In);
 });
 if (Read == 0) {
   elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos,
ContentLength);
   return llvm::None;
 }
-InMirror << llvm::StringRef(&JSON[Pos], Read);
+InMirror << llvm::StringRef(&JsonContentBuffer[Pos], Read);
 clearerr(In); // If we're done, the error was transient. If we're not done,
   // either it was transient or we'll see it again on retry.
 Pos += Read;
   }
-  return std::move(JSON);
+  return StringRef(JsonContentBuffer);
 }
 
 // For lit tests we support a simplified syntax:
@@ -288,12 +296,11 @@
 // - lines starting with # are ignored.
 // This is a testing path, so favor simplicity over performance here.
 // When returning None, feof(), ferror(), or shutdownRequested() will be set.
-llvm::Optional JSONTransport::readDelimitedMessage() {
-  std::string JSON;
-  std::string Line;
-  while (readLine(In, Line)) {
-InMir

[clang-tools-extra] 0336ff0 - [clangd] Fix broken JSON test on windows

2020-12-18 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2020-12-18T15:11:08+01:00
New Revision: 0336ff0a17e6aec831334aeb50e6685f6b184065

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

LOG: [clangd] Fix broken JSON test on windows

Added: 


Modified: 
clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp 
b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
index d9fccb835c96..12c986572d8b 100644
--- a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
+++ b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp
@@ -432,12 +432,13 @@ TEST_F(DirectoryBasedGlobalCompilationDatabaseCacheTest, 
Cacheable) {
   EXPECT_THAT(FooBar, hasFlag("-DFOOBAR")) << "cdb reloaded";
 
   // compile_commands.json takes precedence over compile_flags.txt.
-  FS.Files["foo/compile_commands.json"] = llvm::formatv(R"json([{
+  FS.Files["foo/compile_commands.json"] =
+  llvm::formatv(R"json([{
 "file": "{0}/foo/dummy.cc",
 "command": "clang -DBAZ dummy.cc",
 "directory": "{0}/foo",
   }])json",
-testRoot());
+llvm::sys::path::convert_to_slash(testRoot()));
   EXPECT_EQ(FooBar, lookupCDB(GDB, testPath("foo/test.cc"), Stale))
   << "cache still valid";
   auto Baz = lookupCDB(GDB, testPath("foo/test.cc"), Fresh);



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


[PATCH] D93221: [ARM] Add clang command line support for -mharden-sls=

2020-12-18 Thread Kristof Beyls via Phabricator via cfe-commits
kristof.beyls added a comment.

In D93221#2459903 , @ostannard wrote:

> Why is this restricted to v7-A or later? The DSB and ISB instructions have 
> existed since v6T2 and v6M.

This mitigation is never needed for M-class cores nor for v6T2.
By restricting it to v7-A it's simpler to explain in the diagnostic for which 
targets this is supported.
I thought that overall this was a better trade-off.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93221

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


[PATCH] D92663: [clangd] Add hot-reload of compile_commands.json and compile_flags.txt

2020-12-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D92663#2462642 , @thakis wrote:

> Seems to break tests on windows: http://45.33.8.238/win/30129/step_9.txt

Sorry (and for the delay getting back to keyboard). 
0336ff0a17e6aec831334aeb50e6685f6b184065 
 should 
fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92663

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


[PATCH] D93490: [clang-format] PR48539 ReflowComments breaks Qt translation comments

2020-12-18 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a reviewer: HazardyKnusperkeks.
HazardyKnusperkeks requested changes to this revision.
HazardyKnusperkeks added a comment.
This revision now requires changes to proceed.

I don't know if this really fixes the problem.

From the Docs:

> An alternative way to attach meta-data is to use the following syntax:
>
> //~  

With the example

  //~ loc-layout_id foo_dialog
  //~ loc-blank False
  //~ magic-stuff This might mean something magic.

So I would say breaking the `~` comment is a no go, but I would have to test 
it. (Which I can do next week.)
`//:` should be fine, `//=` would have the same problem, with the exception 
that it seems not to be used normally with long comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93490

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


[PATCH] D93452: [clangd] Trim memory after buildINdex

2020-12-18 Thread Quentin Chateau via Phabricator via cfe-commits
qchateau updated this revision to Diff 312781.
qchateau added a comment.
Herald added subscribers: llvm-commits, dexonsmith, hiraditya.
Herald added a project: LLVM.

- Add MallocTrim to llvm::sys::Process
- Implement malloc trimming in ClangdLSPServer


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93452

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/ClangdLSPServer.h
  clang-tools-extra/clangd/index/FileIndex.cpp
  clang-tools-extra/clangd/tool/ClangdMain.cpp
  llvm/cmake/config-ix.cmake
  llvm/include/llvm/Config/config.h.cmake
  llvm/include/llvm/Support/Process.h
  llvm/lib/Support/Unix/Process.inc
  llvm/lib/Support/Windows/Process.inc

Index: llvm/lib/Support/Windows/Process.inc
===
--- llvm/lib/Support/Windows/Process.inc
+++ llvm/lib/Support/Windows/Process.inc
@@ -81,6 +81,11 @@
   return size;
 }
 
+bool Process::MallocTrim(size_t Pad) {
+#warning Cannot get malloc info on this platform
+  return false;
+}
+
 void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
std::chrono::nanoseconds &sys_time) {
   elapsed = std::chrono::system_clock::now();;
Index: llvm/lib/Support/Unix/Process.inc
===
--- llvm/lib/Support/Unix/Process.inc
+++ llvm/lib/Support/Unix/Process.inc
@@ -31,7 +31,7 @@
 #if HAVE_SIGNAL_H
 #include 
 #endif
-#if defined(HAVE_MALLINFO)
+#if defined(HAVE_MALLINFO) || defined(HAVE_MALLOC_TRIM)
 #include 
 #endif
 #if defined(HAVE_MALLCTL)
@@ -117,6 +117,15 @@
 #endif
 }
 
+bool Process::MallocTrim(size_t Pad) {
+#if defined(HAVE_MALLOC_TRIM)
+  return malloc_trim(Pad);
+#else
+#warning Cannot get malloc info on this platform
+  return false;
+#endif
+}
+
 void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
std::chrono::nanoseconds &sys_time) {
   elapsed = std::chrono::system_clock::now();
Index: llvm/include/llvm/Support/Process.h
===
--- llvm/include/llvm/Support/Process.h
+++ llvm/include/llvm/Support/Process.h
@@ -75,6 +75,12 @@
   /// allocated space.
   static size_t GetMallocUsage();
 
+  /// Attempts to free unused memory from the heap.
+  /// This function is basically a call to malloc_trim(3).
+  /// \param Pad Free space to leave at the top of the heap
+  /// \returns true if memory was actually released
+  static bool MallocTrim(size_t Pad);
+
   /// This static function will set \p user_time to the amount of CPU time
   /// spent in user (non-kernel) mode and \p sys_time to the amount of CPU
   /// time spent in system (kernel) mode.  If the operating system does not
Index: llvm/include/llvm/Config/config.h.cmake
===
--- llvm/include/llvm/Config/config.h.cmake
+++ llvm/include/llvm/Config/config.h.cmake
@@ -136,6 +136,9 @@
 /* Define to 1 if you have the `mallinfo' function. */
 #cmakedefine HAVE_MALLINFO ${HAVE_MALLINFO}
 
+/* Define to 1 if you have the `mallinfo' function. */
+#cmakedefine HAVE_MALLOC_TRIM ${HAVE_MALLOC_TRIM}
+
 /* Define to 1 if you have the  header file. */
 #cmakedefine HAVE_MALLOC_MALLOC_H ${HAVE_MALLOC_MALLOC_H}
 
Index: llvm/cmake/config-ix.cmake
===
--- llvm/cmake/config-ix.cmake
+++ llvm/cmake/config-ix.cmake
@@ -232,6 +232,7 @@
 set(CMAKE_REQUIRED_DEFINITIONS "")
 check_symbol_exists(mallctl malloc_np.h HAVE_MALLCTL)
 check_symbol_exists(mallinfo malloc.h HAVE_MALLINFO)
+check_symbol_exists(malloc_trim malloc.h HAVE_MALLOC_TRIM)
 check_symbol_exists(malloc_zone_statistics malloc/malloc.h
 HAVE_MALLOC_ZONE_STATISTICS)
 check_symbol_exists(getrlimit "sys/types.h;sys/time.h;sys/resource.h" HAVE_GETRLIMIT)
Index: clang-tools-extra/clangd/tool/ClangdMain.cpp
===
--- clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -497,6 +497,14 @@
 init(ClangdServer::Options().CollectMainFileRefs),
 };
 
+opt MemoryCleanupPeriod{
+"memory-cleanup-period",
+cat(Misc),
+desc("Period at which clangd will actively try to perform a "
+ "memory cleanup (in seconds)."),
+init(ClangdLSPServer::Options().MemoryCleanupPeriod.count()),
+};
+
 #if CLANGD_ENABLE_REMOTE
 opt RemoteIndexAddress{
 "remote-index-address",
@@ -797,6 +805,7 @@
   Opts.BuildRecoveryAST = RecoveryAST;
   Opts.PreserveRecoveryASTType = RecoveryASTType;
   Opts.FoldingRanges = FoldingRanges;
+  Opts.MemoryCleanupPeriod = std::chrono::seconds(MemoryCleanupPeriod);
 
   Opts.CodeComplete.IncludeIneligibleResults = IncludeIneligibleResults;
   Opts.CodeComplete.Limit = LimitResults;
Index: clang

[PATCH] D93528: [clang-format] Add basic support for formatting JSON

2020-12-18 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D93528#2462723 , @curdeius wrote:

> Why not using clang-format's support for JavaScript? It seems more 
> complicated now, but it will probably allow to more easily change/add style 
> options. WDYT?
> And what happens when reformatting only a part of a JSON? Should there be 
> some tests for that?

I've attempted to do this via JavaScript before and failed ;-( and had to 
abandoned the attempt. This is partially because clang-format isn't very good 
at even handling any braced initialization (let alone nested initialization) 
and it made the code much more complex. (my guess is that is why it was never 
attempted before by others before)

So I decided to reset my expectations first, My intent here is to introduce the 
concept of JSON Language support (to gauge if adding JSON support is something 
the community might accept), but also to let me build the infrastructure that 
means we have some support which we know will work out of the box (at least to 
give us clean JSON full file formatting formatting)

Ultimately the JSON pretty printing in the Support library cannot really handle 
what realistically might be wanted i.e. ideally I'd like to support different 
positioning types for the `{`

  [
  "name": {
   "bar": 1 
  },
  "name": {
   "foo": 2
  }
  ]

This first revision handles some basic concepts, introduction of the JSON 
support and full file formatting (to a compatible LLVM Style as defined by its 
own JSON library) + allowing setting different IndentWidths

Ultimately once we have this support, which I think is a necessity, we can 
switch the underlying formatting to support, partial  formatting (as we would 
see via git clang-format) and the potential other options we'd like to support 
(which I consider we'd most likely handle inside reformat using tokens as you 
are suggesting).

So I guess my question is:

1. is this useful to pursue (either as is, or by switching to us the reformat 
method)
2. is this useful standalone as the first pass
3. is adding support for JSON something people would welcome (as we did with C#)

If the answer is no, then I don't want to waste the effort trying to fathom how 
we might do this inside reformat.

> And what happens when reformatting only a part of a JSON? Should there be 
> some tests for that?

Ultimately yes, but I don't think I can easily do that with the llvm/Support 
code, so that would need to be integrated into the `refomat()` (and this is why 
I didn't include a change into git-clang-format or clang-format-diff.py)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93528

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


[PATCH] D92039: [-Wcalled-once-parameter] Introduce 'called_once' attribute

2020-12-18 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added a comment.

In D92039#2462889 , @aaron.ballman 
wrote:

> Your test cases suggest that this is not inter-procedurally checked; it seems 
> to require all of the APIs to be annotated in order to get the same effect 
> that an inter-procedural check could determine on its own.

I mean, of course, it doesn't have real inter-procedural analysis.  But if 
everything is annotated or conventional - it is identical to inter-procedural 
case (like in tests with `indirect` in their names).

> I'm not worried about the leniency and I'm sorry if it sounds like I'm 
> implying that it has to be inter-procedural to land -- that's not the case. 
> What I am worried about is that the way the user runs the frontend is very 
> different than the way the user runs the static analyzer, and migrating the 
> warning from the FE to the static analyzer could leave us with problems. If 
> the intention is that this check will live in the FE as-is (not getting 
> inter-procedural support), then that's fine. But if the intention is to 
> extend the check in the future in a way that might need it to move out of the 
> FE and into the CSA, then I think the check should live in the CSA from the 
> start (even if it doesn't do inter-procedural analysis). It's not clear to me 
> whether "in the first version" implies that you expect a subsequent version 
> to live in the CSA or not.

No, we don't plan on moving it to the CSA.  As I mentioned above, for hardening 
we can simply warn if `called_once` parameters leak into functions we don't 
know about (not annotated or not following conventions).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92039

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


[PATCH] D92663: [clangd] Add hot-reload of compile_commands.json and compile_flags.txt

2020-12-18 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Thanks for the fix :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92663

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


[PATCH] D84674: Allow users to specify a conditional to prevent parsing options with MarshallingInfo

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 commandeered this revision.
jansvoboda11 added a reviewer: dang.
jansvoboda11 added a comment.

Taking over this patch, as Daniel is no longer involved.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84674

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


[PATCH] D84674: Allow users to specify a conditional to prevent parsing options with MarshallingInfo

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 312785.
jansvoboda11 added a comment.

Rebase, add tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84674

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

Index: llvm/utils/TableGen/OptParserEmitter.cpp
===
--- llvm/utils/TableGen/OptParserEmitter.cpp
+++ llvm/utils/TableGen/OptParserEmitter.cpp
@@ -71,6 +71,7 @@
   StringRef NormalizedValuesScope;
   StringRef ImpliedCheck;
   StringRef ImpliedValue;
+  StringRef ShouldParse;
   StringRef Normalizer;
   StringRef Denormalizer;
   StringRef ValueMerger;
@@ -102,6 +103,8 @@
   void emit(raw_ostream &OS) const {
 write_cstring(OS, StringRef(getOptionSpelling(R)));
 OS << ", ";
+OS << ShouldParse;
+OS << ", ";
 OS << ShouldAlwaysEmit;
 OS << ", ";
 OS << KeyPath;
@@ -167,6 +170,7 @@
   Ret.ImpliedValue =
   R.getValueAsOptionalString("ImpliedValue").getValueOr(Ret.DefaultValue);
 
+  Ret.ShouldParse = R.getValueAsString("ShouldParse");
   Ret.Normalizer = R.getValueAsString("Normalizer");
   Ret.Denormalizer = R.getValueAsString("Denormalizer");
   Ret.ValueMerger = R.getValueAsString("ValueMerger");
Index: llvm/include/llvm/Option/OptParser.td
===
--- llvm/include/llvm/Option/OptParser.td
+++ llvm/include/llvm/Option/OptParser.td
@@ -101,6 +101,7 @@
   code DefaultValue = ?;
   code ImpliedValue = ?;
   code ImpliedCheck = "false";
+  code ShouldParse = "true";
   bit ShouldAlwaysEmit = false;
   code NormalizerRetTy = ?;
   code NormalizedValuesScope = "";
@@ -193,6 +194,7 @@
 class IsNegative {
   code Normalizer = "normalizeSimpleNegativeFlag";
 }
+class ShouldParseIf { code ShouldParse = condition; }
 class AlwaysEmit { bit ShouldAlwaysEmit = true; }
 class Normalizer { code Normalizer = normalizer; }
 class Denormalizer { code Denormalizer = denormalizer; }
Index: clang/unittests/Frontend/CompilerInvocationTest.cpp
===
--- clang/unittests/Frontend/CompilerInvocationTest.cpp
+++ clang/unittests/Frontend/CompilerInvocationTest.cpp
@@ -19,6 +19,7 @@
 
 using ::testing::Contains;
 using ::testing::StrEq;
+using ::testing::HasSubstr;
 
 namespace {
 class CommandLineTest : public ::testing::Test {
@@ -408,6 +409,68 @@
   ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("legacy";
 }
 
+// A flag that should be parsed only if a condition is met.
+
+TEST_F(CommandLineTest, ConditionalParsingIfFalseFlagNotPresent) {
+  const char *Args[] = {""};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_FALSE(Invocation.getLangOpts()->SYCL);
+  ASSERT_EQ(Invocation.getLangOpts()->getSYCLVersion(), LangOptions::SYCL_None);
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+
+  ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("-fsycl";
+  ASSERT_THAT(GeneratedArgs, Not(Contains(HasSubstr("-sycl-std=";
+}
+
+TEST_F(CommandLineTest, ConditionalParsingIfFalseFlagPresent) {
+  const char *Args[] = {"-sycl-std=2017"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_FALSE(Invocation.getLangOpts()->SYCL);
+  ASSERT_EQ(Invocation.getLangOpts()->getSYCLVersion(), LangOptions::SYCL_None);
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+
+  ASSERT_THAT(GeneratedArgs, Not(Contains(StrEq("-fsycl";
+  ASSERT_THAT(GeneratedArgs, Not(Contains(HasSubstr("-sycl-std=";
+}
+
+TEST_F(CommandLineTest, ConditionalParsingIfTrueFlagNotPresent) {
+  const char *Args[] = {"-fsycl"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(Invocation.getLangOpts()->SYCL);
+  ASSERT_EQ(Invocation.getLangOpts()->getSYCLVersion(), LangOptions::SYCL_None);
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+
+  ASSERT_THAT(GeneratedArgs, Contains(StrEq("-fsycl")));
+  ASSERT_THAT(GeneratedArgs, Not(Contains(HasSubstr("-sycl-std=";
+}
+
+TEST_F(CommandLineTest, ConditionalParsingIfTrueFlagPresent) {
+  const char *Args[] = {"-fsycl", "-sycl-std=2017"};
+
+  CompilerInvocation::CreateFromArgs(Invocation, Args, *Diags);
+
+  ASSERT_FALSE(Diags->hasErrorOccurred());
+  ASSERT_TRUE(Invocation.getLangOpts()->SYCL);
+  ASSERT_EQ(Invocation.getLangOpts()->getSYCLVersion(), LangOptions::SYCL_2017);
+
+  Invocation.generateCC1CommandLine(GeneratedArgs, *this);
+
+  ASSERT_THAT(GeneratedArgs, Contains(StrEq("-fsycl")));
+  ASSERT_THAT(GeneratedArgs, Contains(StrEq("-sycl-std=2017")));
+}
+
 // Tree of boolean options 

[PATCH] D93528: [clang-format] Add basic support for formatting JSON

2020-12-18 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

In D93528#2462969 , @MyDeveloperDay 
wrote:

> So I guess my question is:
>
> 1. is this useful to pursue (either as is, or by switching to us the reformat 
> method)
> 2. is this useful standalone as the first pass
> 3. is adding support for JSON something people would welcome (as we did with 
> C#)
>
> If the answer is no, then I don't want to waste the effort trying to fathom 
> how we might do this inside reformat.

For me that's three times yes.




Comment at: clang/unittests/Format/FormatTestJson.cpp:14
+
+#define DEBUG_TYPE "format-test"
+

I don't know what's the practice right now. But I would suggest renaming that 
to "format-test-json", so you can see directly that's for JSON.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93528

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


[PATCH] D93540: [clang] Use enum for LangOptions::SYCLVersion instead of unsigned

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: dexonsmith, Bigcheese, bader, ABataev.
Herald added subscribers: Anastasia, ebevhan, yaxunl.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

`LangOptions::SYCLVersion` can only have two values. This patch introduces an 
enum that allows us to reduce the member size from 32 bits to 1 bit.

Consequently, this also makes marshalling of this option fit into our model for 
enums: D84674 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93540

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Basic/LangOptions.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/InitPreprocessor.cpp


Index: clang/lib/Frontend/InitPreprocessor.cpp
===
--- clang/lib/Frontend/InitPreprocessor.cpp
+++ clang/lib/Frontend/InitPreprocessor.cpp
@@ -476,7 +476,7 @@
 
   if (LangOpts.SYCL) {
 // SYCL Version is set to a value when building SYCL applications
-if (LangOpts.SYCLVersion == 2017)
+if (LangOpts.getSYCLVersion() == LangOptions::SYCL_2017)
   Builder.defineMacro("CL_SYCL_LANGUAGE_VERSION", "121");
   }
 
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2277,11 +2277,13 @@
 // -sycl-std applies to any SYCL source, not only those containing kernels,
 // but also those using the SYCL API
 if (const Arg *A = Args.getLastArg(OPT_sycl_std_EQ)) {
-  Opts.SYCLVersion = llvm::StringSwitch(A->getValue())
- .Cases("2017", "1.2.1", "121", "sycl-1.2.1", 2017)
- .Default(0U);
+  Opts.setSYCLVersion(
+  llvm::StringSwitch(A->getValue())
+  .Cases("2017", "1.2.1", "121", "sycl-1.2.1",
+ LangOptions::SYCL_2017)
+  .Default(LangOptions::SYCL_None));
 
-  if (Opts.SYCLVersion == 0U) {
+  if (Opts.getSYCLVersion() == LangOptions::SYCL_None) {
 // User has passed an invalid value to the flag, this is an error
 Diags.Report(diag::err_drv_invalid_value)
 << A->getAsString(Args) << A->getValue();
Index: clang/include/clang/Basic/LangOptions.h
===
--- clang/include/clang/Basic/LangOptions.h
+++ clang/include/clang/Basic/LangOptions.h
@@ -125,6 +125,11 @@
 MSVC2019 = 1920,
   };
 
+  enum SYCLMajorVersion {
+SYCL_None,
+SYCL_2017,
+  };
+
   /// Clang versions with different platform ABI conformance.
   enum class ClangABI {
 /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
Index: clang/include/clang/Basic/LangOptions.def
===
--- clang/include/clang/Basic/LangOptions.def
+++ clang/include/clang/Basic/LangOptions.def
@@ -246,7 +246,7 @@
 
 LANGOPT(SYCL  , 1, 0, "SYCL")
 LANGOPT(SYCLIsDevice  , 1, 0, "Generate code for SYCL device")
-LANGOPT(SYCLVersion   , 32, 0, "Version of the SYCL standard used")
+ENUM_LANGOPT(SYCLVersion  , SYCLMajorVersion, 1, SYCL_None, "Version of the 
SYCL standard used")
 
 LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching API for HIP")
 


Index: clang/lib/Frontend/InitPreprocessor.cpp
===
--- clang/lib/Frontend/InitPreprocessor.cpp
+++ clang/lib/Frontend/InitPreprocessor.cpp
@@ -476,7 +476,7 @@
 
   if (LangOpts.SYCL) {
 // SYCL Version is set to a value when building SYCL applications
-if (LangOpts.SYCLVersion == 2017)
+if (LangOpts.getSYCLVersion() == LangOptions::SYCL_2017)
   Builder.defineMacro("CL_SYCL_LANGUAGE_VERSION", "121");
   }
 
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -2277,11 +2277,13 @@
 // -sycl-std applies to any SYCL source, not only those containing kernels,
 // but also those using the SYCL API
 if (const Arg *A = Args.getLastArg(OPT_sycl_std_EQ)) {
-  Opts.SYCLVersion = llvm::StringSwitch(A->getValue())
- .Cases("2017", "1.2.1", "121", "sycl-1.2.1", 2017)
- .Default(0U);
+  Opts.setSYCLVersion(
+  llvm::StringSwitch(A->getValue())
+  .Cases("2017", "1.2.1", "121", "sycl-1.2.1",
+ LangOptions::SYCL_2017)
+  .Default(LangOptions::SYCL_None));
 
-  if (Opts.SYCLVersion == 0U) {
+  if (Opts.getSYCLVersion() == LangOptions::SYCL_None) {
 // User has passed an invalid value to the flag, this is an error
 

[PATCH] D93531: [clangd] Reuse buffer for JSONTransport::readRawMessage

2020-12-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

This adds a bit of complexity, making the code here a fair amount harder to 
follow and verify the correctness of.

- Do we have evidence that these allocations are causing a problem? (e.g. do we 
observe a significant decrease in RSS after the patch)? Naively I would expect 
these allocations to be basically unimportant compared to those of the JSON 
objects themselves.(And I don't particularly expect either of them to be 
significant - the comment on the other review was really just "0 probably isn't 
the right arg to  malloc_trim if there's any allocation going on").
- there seem to be simpler ways to structure this avoiding allocations. 
JSONLineBuffer is effectively statically bounded, and can be `SmallString<32>` 
or so. The content buffer could simply be passed in if I'm reading right: `bool 
readRawMessage(std::string&)`? OutputBuffer probably does need to be a member 
variable though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93531

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


[PATCH] D84675: Streamline MarhsallingInfoFlag description

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 commandeered this revision.
jansvoboda11 added a reviewer: dang.
jansvoboda11 added a comment.

Taking over this patch, as Daniel is no longer involved.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84675

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


[PATCH] D93490: [clang-format] PR48539 ReflowComments breaks Qt translation comments

2020-12-18 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Maybe @JVApen can help as they logged 
https://bugs.llvm.org/show_bug.cgi?id=48539

I'm not a Qt developer so I can't really comment beyond fixing what was in the 
bug rpeort


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93490

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


[PATCH] D84675: [clang][cli] Streamline MarhsallingInfoFlag description

2020-12-18 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 312790.
jansvoboda11 added a comment.

Rebase, remove `DefaultValue` to avoid confusion with `Default` used for 
`BoolOptionBase`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D84675

Files:
  clang/include/clang/Driver/Options.td
  llvm/include/llvm/Option/OptParser.td

Index: llvm/include/llvm/Option/OptParser.td
===
--- llvm/include/llvm/Option/OptParser.td
+++ llvm/include/llvm/Option/OptParser.td
@@ -173,6 +173,12 @@
   code Denormalizer = "denormalizeSimpleFlag";
 }
 
+class MarshallingInfoNegativeFlag
+  : MarshallingInfo {
+  code Normalizer = "normalizeSimpleNegativeFlag";
+  code Denormalizer = "denormalizeSimpleFlag";
+}
+
 class MarshallingInfoBitfieldFlag
   : MarshallingInfoFlag {
   code Normalizer = "makeFlagToValueNormalizer("#value#")";
@@ -190,9 +196,6 @@
 
 // Mixins for additional marshalling attributes.
 
-class IsNegative {
-  code Normalizer = "normalizeSimpleNegativeFlag";
-}
 class AlwaysEmit { bit ShouldAlwaysEmit = true; }
 class Normalizer { code Normalizer = normalizer; }
 class Denormalizer { code Denormalizer = denormalizer; }
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -696,7 +696,7 @@
 def Ofast : Joined<["-"], "Ofast">, Group, Flags<[CC1Option]>;
 def P : Flag<["-"], "P">, Flags<[CC1Option]>, Group,
   HelpText<"Disable linemarker output in -E mode">,
-  MarshallingInfoFlag<"PreprocessorOutputOpts.ShowLineMarkers", "true">, IsNegative;
+  MarshallingInfoNegativeFlag<"PreprocessorOutputOpts.ShowLineMarkers">;
 def Qy : Flag<["-"], "Qy">, Flags<[CC1Option]>,
   HelpText<"Emit metadata containing compiler name and version">;
 def Qn : Flag<["-"], "Qn">, Flags<[CC1Option]>,
@@ -1212,7 +1212,7 @@
 def : Flag<["-"], "fno-record-gcc-switches">, Alias;
 def fcommon : Flag<["-"], "fcommon">, Group,
   Flags<[CoreOption, CC1Option]>, HelpText<"Place uninitialized global variables in a common block">,
-  MarshallingInfoFlag<"CodeGenOpts.NoCommon", "true">, IsNegative;
+  MarshallingInfoNegativeFlag<"CodeGenOpts.NoCommon">;
 def fcompile_resource_EQ : Joined<["-"], "fcompile-resource=">, Group;
 defm complete_member_pointers : BoolOption<"complete-member-pointers",
   "LangOpts->CompleteMemberPointers", DefaultsToFalse,
@@ -1856,7 +1856,7 @@
 def fmodules_disable_diagnostic_validation : Flag<["-"], "fmodules-disable-diagnostic-validation">,
   Group, Flags<[CC1Option]>,
   HelpText<"Disable validation of the diagnostic options when loading the module">,
-  MarshallingInfoFlag<"HeaderSearchOpts->ModulesValidateDiagnosticOptions", "true">, IsNegative;
+  MarshallingInfoNegativeFlag<"HeaderSearchOpts->ModulesValidateDiagnosticOptions">;
 defm modules_validate_system_headers : BoolOption<"modules-validate-system-headers",
   "HeaderSearchOpts->ModulesValidateSystemHeaders", DefaultsToFalse,
   ChangedBy,
@@ -1944,7 +1944,7 @@
 def fno_asynchronous_unwind_tables : Flag<["-"], "fno-asynchronous-unwind-tables">, Group;
 def fno_assume_sane_operator_new : Flag<["-"], "fno-assume-sane-operator-new">, Group,
   HelpText<"Don't assume that C++'s global operator new can't alias any pointer">,
-  Flags<[CC1Option]>, MarshallingInfoFlag<"CodeGenOpts.AssumeSaneOperatorNew", "true">, IsNegative;
+  Flags<[CC1Option]>, MarshallingInfoNegativeFlag<"CodeGenOpts.AssumeSaneOperatorNew">;
 def fno_builtin : Flag<["-"], "fno-builtin">, Group, Flags<[CC1Option, CoreOption]>,
   HelpText<"Disable implicit builtin knowledge of functions">;
 def fno_builtin_ : Joined<["-"], "fno-builtin-">, Group, Flags<[CC1Option, CoreOption]>,
@@ -2022,7 +2022,7 @@
 def fno_temp_file : Flag<["-"], "fno-temp-file">, Group,
   Flags<[CC1Option, CoreOption]>, HelpText<
   "Directly create compilation output files. This may lead to incorrect incremental builds if the compiler crashes">,
-  MarshallingInfoFlag<"FrontendOpts.UseTemporary", "true">, IsNegative;
+  MarshallingInfoNegativeFlag<"FrontendOpts.UseTemporary">;
 defm use_cxa_atexit : BoolFOption<"use-cxa-atexit",
   "CodeGenOpts.CXAAtExit", DefaultsToTrue,
   ChangedBy,
@@ -2030,7 +2030,7 @@
 def fno_unit_at_a_time : Flag<["-"], "fno-unit-at-a-time">, Group;
 def fno_unwind_tables : Flag<["-"], "fno-unwind-tables">, Group;
 def fno_verbose_asm : Flag<["-"], "fno-verbose-asm">, Group, Flags<[CC1Option]>,
-  MarshallingInfoFlag<"CodeGenOpts.AsmVerbose", "true">, IsNegative;
+  MarshallingInfoNegativeFlag<"CodeGenOpts.AsmVerbose">;
 def fno_working_directory : Flag<["-"], "fno-working-directory">, Group;
 def fno_wrapv : Flag<["-"], "fno-wrapv">, Group;
 def fobjc_arc : Flag<["-"], "fobjc-arc">, Group, Flags<[CC1Option]>,
@@ -3313,7 +3313,7 @@
 def no__dead__strip__inits__and__terms : Flag<["-"], "no_dead_strip_inits_and_terms">;
 

[PATCH] D93528: [clang-format] Add basic support for formatting JSON

2020-12-18 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

In D93528#2463030 , 
@HazardyKnusperkeks wrote:

> In D93528#2462969 , @MyDeveloperDay 
> wrote:
>
>> So I guess my question is:
>>
>> 1. is this useful to pursue (either as is, or by switching to us the 
>> reformat method)
>> 2. is this useful standalone as the first pass
>> 3. is adding support for JSON something people would welcome (as we did with 
>> C#)
>>
>> If the answer is no, then I don't want to waste the effort trying to fathom 
>> how we might do this inside reformat.
>
> For me that's three times yes.

For me as well. I believe it's a useful addition, even if it handles only the 
basic cases for the moment.
I was just wondering whether it would be better to start a different way, but I 
understand that implementing it the "clang-format's way" can take some effort.

Anyway, I'd like to see a big warning banner (somewhere in the doc) about 
current limitations, so that nobody switches hastily to clang-format and then 
gets disappointed by these limitations.
Not sure that having a small note about it in release notes is enough.
So to the point, please document that only full-context/file is supported and 
that the only formatting option is indentation level (as you partially did in 
release notes).




Comment at: clang/docs/ReleaseNotes.rst:284
 
+- Basic Support has been adding for Formatting .json files (with very limited 
options)
+

Maybe instead of putting "with very limited options", you may add a link to the 
doc describing limitations?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93528

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


[PATCH] D93227: [clangd] Smarter hover on auto and decltype

2020-12-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/AST.cpp:353
 if (auto *AT = D->getType()->getContainedAutoType()) {
-  if (!AT->getDeducedType().isNull())
-DeducedType = AT->getDeducedType();
+  DeducedType = AT->desugar();
 }

I added a comment to getDeducedType() - I think the intent here is that we 
return the AutoType itself if it's not deduced, right?



Comment at: clang-tools-extra/clangd/Hover.cpp:591
+   ASTContext &ASTCtx,
+   const SymbolIndex *Index) {
+  QualType OriginThisType = CTE->getType()->getPointeeType();

I dropped this unused param



Comment at: clang-tools-extra/clangd/Hover.cpp:618
+  } else {
+CXXRecordDecl *D = QT->getAsCXXRecordDecl();
+if (D && D->isLambda())

sammccall wrote:
> qchateau wrote:
> > sammccall wrote:
> > > You've rewritten this logic compared to the old 
> > > `getHoverContents(QualType)`, and I think there are regressions:
> > >  - We've dropped class documentation (see e.g. 
> > > ac3f9e48421712168884d59cbfe8b294dd76a19b, this is visible in the tests)
> > >  - we're no longer using printName() to print tag-decls, which I expect 
> > > changes e.g. the printing of anyonymous structs which is special-cased in 
> > > that function (we have tests for this but probably not in combination 
> > > with auto)
> > >  - we're no longer using the printing-policy to print non-tag types, 
> > > which will lead to some random changes
> > > 
> > > I don't see a reason for these changes, can we revert them?
> > - I can re-add class documentation, but should it work when `auto` is a 
> > pointer or a ref ? In that case, I'll need something like your `unwrapType` 
> > of https://reviews.llvm.org/D93314
> > - `printName` will print `C` instead of `class C` even if I hack around and 
> > give it the right `PrintingPolicy`. The problem is that IDE (at least 
> > VSCode) does not know what `C` is and cannot color it, which looks a nice 
> > less nice. Up to you !
> > - I can re-add the printing policy for non-tag types, and add it for 
> > tag-types if we chose not to use `printName`.
> > should it work when auto is a pointer or a ref?
> 
> I think no need for now, I just want to avoid the regression.
> (Nice to have, but at least in the codebases I work in, `auto` is much more 
> common than `decltype(auto)` so it's rarely a reference, and pointers are 
> idiomatically written `auto*`)
> 
> > printName will print C instead of class C even if I hack around and give it 
> > the right PrintingPolicy.
> 
> Yeah... it's not supposed to, though the extra clarity is valuable here. You 
> could just hack around this and prepend the TagTypeKind yourself :-)
Hmm, it looks like this wasn't done. It's now printing e.g. `class vector` which seems more confusing than either `class vector` or 
`vector` (even if we lose some highlighting). I'll send a followup with 
proposed changes here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93227

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


[clang-tools-extra] c46c7c9 - [clangd] Smarter hover on auto and decltype

2020-12-18 Thread Sam McCall via cfe-commits

Author: Quentin Chateau
Date: 2020-12-18T16:27:09+01:00
New Revision: c46c7c9bcf9752971fe4bbcf67140c99066ad2e0

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

LOG: [clangd] Smarter hover on auto and decltype

Only show the keyword as the hover "Name".

Show whether the type is deduced or undeduced as
the hover "Documentation".

Show the deduced type (if any) as the "Definition".

Don't show any hover information for:
- the "auto" word of "decltype(auto)"
- "auto" in lambda parameters
- "auto" in template arguments

---

This diff is a suggestion based on what @sammccall  suggested in 
https://reviews.llvm.org/D92977 about hover on "auto". It somehow "hacks" onto 
the "Documentation" and "Definition" fields of `HoverInfo`. It sure looks good 
on VSCode, let me know if this seem acceptable to you.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/AST.cpp
clang-tools-extra/clangd/AST.h
clang-tools-extra/clangd/Hover.cpp
clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
clang-tools-extra/clangd/unittests/HoverTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/AST.cpp 
b/clang-tools-extra/clangd/AST.cpp
index b0c9ecab1e05..c5f87af86319 100644
--- a/clang-tools-extra/clangd/AST.cpp
+++ b/clang-tools-extra/clangd/AST.cpp
@@ -350,8 +350,7 @@ class DeducedTypeVisitor : public 
RecursiveASTVisitor {
   return true;
 
 if (auto *AT = D->getType()->getContainedAutoType()) {
-  if (!AT->getDeducedType().isNull())
-DeducedType = AT->getDeducedType();
+  DeducedType = AT->desugar();
 }
 return true;
   }

diff  --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h
index 1e3447376c10..b603964189e8 100644
--- a/clang-tools-extra/clangd/AST.h
+++ b/clang-tools-extra/clangd/AST.h
@@ -109,6 +109,7 @@ QualType declaredType(const TypeDecl *D);
 
 /// Retrieves the deduced type at a given location (auto, decltype).
 /// It will return the underlying type.
+/// If the type is an undeduced auto, returns the type itself.
 llvm::Optional getDeducedType(ASTContext &, SourceLocation Loc);
 
 /// Gets the nested name specifier necessary for spelling \p ND in \p

diff  --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index e461c7c43364..b5eda93ddbbc 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -27,6 +27,7 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/OperationKinds.h"
 #include "clang/AST/PrettyPrinter.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Specifiers.h"
@@ -550,29 +551,6 @@ HoverInfo getHoverContents(const NamedDecl *D, const 
SymbolIndex *Index) {
   return HI;
 }
 
-/// Generate a \p Hover object given the type \p T.
-HoverInfo getHoverContents(QualType T, ASTContext &ASTCtx,
-   const SymbolIndex *Index,
-   bool SuppressScope = false) {
-  HoverInfo HI;
-
-  if (const auto *D = T->getAsTagDecl()) {
-HI.Name = printName(ASTCtx, *D);
-HI.Kind = index::getSymbolInfo(D).Kind;
-
-const auto *CommentD = getDeclForComment(D);
-HI.Documentation = getDeclComment(ASTCtx, *CommentD);
-enhanceFromIndex(HI, *CommentD, Index);
-  } else {
-// Builtin types
-auto Policy = printingPolicyForDecls(ASTCtx.getPrintingPolicy());
-Policy.SuppressTagKeyword = true;
-Policy.SuppressScope = SuppressScope;
-HI.Name = T.getAsString(Policy);
-  }
-  return HI;
-}
-
 /// Generate a \p Hover object given the macro \p MacroDecl.
 HoverInfo getHoverContents(const DefinedMacro &Macro, ParsedAST &AST) {
   HoverInfo HI;
@@ -608,6 +586,52 @@ HoverInfo getHoverContents(const DefinedMacro &Macro, 
ParsedAST &AST) {
   return HI;
 }
 
+llvm::Optional getThisExprHoverContents(const CXXThisExpr *CTE,
+   ASTContext &ASTCtx) {
+  QualType OriginThisType = CTE->getType()->getPointeeType();
+  QualType ClassType = declaredType(OriginThisType->getAsTagDecl());
+  // For partial specialization class, origin `this` pointee type will be
+  // parsed as `InjectedClassNameType`, which will ouput template arguments
+  // like "type-parameter-0-0". So we retrieve user written class type in this
+  // case.
+  QualType PrettyThisType = ASTCtx.getPointerType(
+  QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
+
+  auto Policy = printingPolicyForDecls(ASTCtx.getPrintingPolicy());
+  Policy.SuppressTagKeyword = true;
+  Policy.SuppressScope = true;
+  HoverInfo HI;
+  HI.Name = "this";
+  HI.Definition = PrettyThisType.getAsString(Poli

[PATCH] D93227: [clangd] Smarter hover on auto and decltype

2020-12-18 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc46c7c9bcf97: [clangd] Smarter hover on auto and decltype 
(authored by qchateau, committed by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D93227?vs=312757&id=312791#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93227

Files:
  clang-tools-extra/clangd/AST.cpp
  clang-tools-extra/clangd/AST.h
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp

Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -379,6 +379,30 @@
  HI.Definition = "class X {}";
}},
 
+  // auto on structured bindings
+  {R"cpp(
+void foo() {
+  struct S { int x; float y; };
+  [[au^to]] [x, y] = S();
+}
+)cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "struct S";
+   }},
+  // undeduced auto
+  {R"cpp(
+template
+void foo() {
+  [[au^to]] x = T{};
+}
+)cpp",
+   [](HoverInfo &HI) {
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "/* not deduced */";
+   }},
   // auto on lambda
   {R"cpp(
 void foo() {
@@ -386,8 +410,9 @@
 }
 )cpp",
[](HoverInfo &HI) {
- HI.Name = "(lambda)";
- HI.Kind = index::SymbolKind::Class;
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "class(lambda)";
}},
   // auto on template instantiation
   {R"cpp(
@@ -397,8 +422,9 @@
 }
 )cpp",
[](HoverInfo &HI) {
- HI.Name = "Foo";
- HI.Kind = index::SymbolKind::Class;
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "class Foo";
}},
   // auto on specialized template
   {R"cpp(
@@ -409,8 +435,9 @@
 }
 )cpp",
[](HoverInfo &HI) {
- HI.Name = "Foo";
- HI.Kind = index::SymbolKind::Class;
+ HI.Name = "auto";
+ HI.Kind = index::SymbolKind::TypeAlias;
+ HI.Definition = "class Foo";
}},
 
   // macro
@@ -582,8 +609,9 @@
   }
   )cpp",
   [](HoverInfo &HI) {
-HI.Name = "Foo";
-HI.Kind = index::SymbolKind::Class;
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "class Foo";
   }},
   {// Falls back to primary template, when the type is not instantiated.
R"cpp(
@@ -955,20 +983,11 @@
   llvm::StringRef Tests[] = {
   "^int main() {}",
   "void foo() {^}",
-  R"cpp(// structured binding. Not supported yet
-struct Bar {};
-void foo() {
-  Bar a[2];
-  ^auto [x,y] = a;
-}
-  )cpp",
-  R"cpp(// Template auto parameter. Nothing (Not useful).
-template
-void func() {
-}
-void foo() {
-   func<1>();
-}
+  // FIXME: "decltype(auto)" should be a single hover
+  "decltype(au^to) x = 0;",
+  // FIXME: not supported yet
+  R"cpp(// Lambda auto parameter
+auto lamb = [](a^uto){};
   )cpp",
   R"cpp(// non-named decls don't get hover. Don't crash!
 ^static_assert(1, "");
@@ -1545,9 +1564,9 @@
 }
   )cpp",
   [](HoverInfo &HI) {
-HI.Name = "int";
-// FIXME: Should be Builtin/Integral.
-HI.Kind = index::SymbolKind::Unknown;
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "int";
   }},
   {
   R"cpp(// Simple initialization with const auto
@@ -1555,14 +1574,22 @@
   const ^[[auto]] i = 1;
 }
   )cpp",
-  [](HoverInfo &HI) { HI.Name = "int"; }},
+  [](HoverInfo &HI) {
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "int";
+  }},
   {
   R"cpp(// Simple initialization with const auto&
 void foo() {
   const ^[[auto]]& i = 1;
 }
   )cpp",
-  [](HoverInfo &HI) { HI.Name = "int"; }},
+  [](HoverInfo &HI) {
+HI.Name = "auto";
+HI.Kind = index::SymbolKind::TypeAlias;
+HI.Definition = "int";
+  }},
   {
   R"cpp(// Simple initializati

[PATCH] D93531: [clangd] Reuse buffer for JSONTransport::readRawMessage

2020-12-18 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D93531#2463052 , @sammccall wrote:

> This adds a bit of complexity, making the code here a fair amount harder to 
> follow and verify the correctness of.
>
> - Do we have evidence that these allocations are causing a problem? (e.g. do 
> we observe a significant decrease in RSS after the patch)? Naively I would 
> expect these allocations to be basically unimportant compared to those of the 
> JSON objects themselves.(And I don't particularly expect either of them to be 
> significant - the comment on the other review was really just "0 probably 
> isn't the right arg to  malloc_trim if there's any allocation going on").

It's not causing problems per say. but given the incoming json messages can 
contain a whole file plus things like escape chars. its wise to allocate a 
buffer that will grow to the largest json it receives but never shrink.

> - there seem to be simpler ways to structure this avoiding allocations. 
> JSONLineBuffer is effectively statically bounded, and can be 
> `SmallString<32>` or so. The content buffer could simply be passed in if I'm 
> reading right: `bool readRawMessage(std::string&)`? OutputBuffer probably 
> does need to be a member variable though.

Its not statically bounded unfortunately, the length is how ever long a line in 
the json is, which can be infinite. the read line function uses a buffer size 
of 1024 as an upperbound.
However that can easily be exceeded as I think the contents of files are 
escaped so they will be read as 1 long line. It may be slightly more readable 
to make the function take a reference to the buffer though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93531

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


[PATCH] D93543: clang-tidy: Leave the possibility of opting out having coloured diagnostic messages.

2020-12-18 Thread Andi via Phabricator via cfe-commits
Abpostelnicu created this revision.
Abpostelnicu requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Afer this 

 commit landed we always have coloured diagnotic messages. Maybe it's a good 
idea to leave the user the posibility of opting out of this.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93543

Files:
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -80,10 +80,13 @@
 
 
 def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
-header_filter, allow_enabling_alpha_checkers,
-extra_arg, extra_arg_before, quiet, config):
+header_filter, no_diagnostic_color,
+allow_enabling_alpha_checkers, extra_arg,
+extra_arg_before, quiet, config):
   """Gets a command line for clang-tidy."""
-  start = [clang_tidy_binary, '--use-color']
+  start = [clang_tidy_binary]
+  if not no_diagnostic_color:
+start.append('--use-color')
   if allow_enabling_alpha_checkers:
 start.append('-allow-enabling-analyzer-alpha-checkers')
   if header_filter is not None:
@@ -163,6 +166,7 @@
 name = queue.get()
 invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
  tmpdir, build_path, args.header_filter,
+ args.no_diagnostic_color,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
  args.quiet, args.config)
@@ -204,6 +208,8 @@
   'When the value is empty, clang-tidy will '
   'attempt to find a file named .clang-tidy for '
   'each source file in its parent directories.')
+  parser.add_argument('-no-diagnostic-color', action='store_true',
+  help='Disable diagnostic message colors.')
   parser.add_argument('-header-filter', default=None,
   help='regular expression matching the names of the '
   'headers to output diagnostics from. Diagnostics from '


Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -80,10 +80,13 @@
 
 
 def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
-header_filter, allow_enabling_alpha_checkers,
-extra_arg, extra_arg_before, quiet, config):
+header_filter, no_diagnostic_color,
+allow_enabling_alpha_checkers, extra_arg,
+extra_arg_before, quiet, config):
   """Gets a command line for clang-tidy."""
-  start = [clang_tidy_binary, '--use-color']
+  start = [clang_tidy_binary]
+  if not no_diagnostic_color:
+start.append('--use-color')
   if allow_enabling_alpha_checkers:
 start.append('-allow-enabling-analyzer-alpha-checkers')
   if header_filter is not None:
@@ -163,6 +166,7 @@
 name = queue.get()
 invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
  tmpdir, build_path, args.header_filter,
+ args.no_diagnostic_color,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
  args.quiet, args.config)
@@ -204,6 +208,8 @@
   'When the value is empty, clang-tidy will '
   'attempt to find a file named .clang-tidy for '
   'each source file in its parent directories.')
+  parser.add_argument('-no-diagnostic-color', action='store_true',
+  help='Disable diagnostic message colors.')
   parser.add_argument('-header-filter', default=None,
   help='regular expression matching the names of the '
   'headers to output diagnostics from. Diagnostics from '
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 95c7b6c - [clangd] zap a few warnings

2020-12-18 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2020-12-18T16:34:34+01:00
New Revision: 95c7b6cadbc9a3d4376ef44edbeb3c8bb5b8d7fc

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

LOG: [clangd] zap a few warnings

Added: 


Modified: 
clang-tools-extra/clangd/DumpAST.cpp
clang-tools-extra/clangd/FindTarget.cpp
clang-tools-extra/clangd/index/remote/Client.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/DumpAST.cpp 
b/clang-tools-extra/clangd/DumpAST.cpp
index 12698b42ef3e..8f1b3f3a1aae 100644
--- a/clang-tools-extra/clangd/DumpAST.cpp
+++ b/clang-tools-extra/clangd/DumpAST.cpp
@@ -143,6 +143,7 @@ class DumpVisitor : public RecursiveASTVisitor 
{
   TEMPLATE_ARGUMENT_KIND(Declaration);
   TEMPLATE_ARGUMENT_KIND(Template);
   TEMPLATE_ARGUMENT_KIND(TemplateExpansion);
+  TEMPLATE_ARGUMENT_KIND(UncommonValue);
 #undef TEMPLATE_ARGUMENT_KIND
 }
 llvm_unreachable("Unhandled ArgKind enum");

diff  --git a/clang-tools-extra/clangd/FindTarget.cpp 
b/clang-tools-extra/clangd/FindTarget.cpp
index 3afd65522680..c5c7d71be661 100644
--- a/clang-tools-extra/clangd/FindTarget.cpp
+++ b/clang-tools-extra/clangd/FindTarget.cpp
@@ -1069,6 +1069,7 @@ class ExplicitReferenceCollector
 case TemplateArgument::Pack:
 case TemplateArgument::Type:
 case TemplateArgument::Expression:
+case TemplateArgument::UncommonValue:
   break; // Handled by VisitType and VisitExpression.
 };
 return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);

diff  --git a/clang-tools-extra/clangd/index/remote/Client.cpp 
b/clang-tools-extra/clangd/index/remote/Client.cpp
index b09dbf915e46..a153a8812baf 100644
--- a/clang-tools-extra/clangd/index/remote/Client.cpp
+++ b/clang-tools-extra/clangd/index/remote/Client.cpp
@@ -152,7 +152,8 @@ class IndexClient : public clangd::SymbolIndex {
   });
   }
 
-  llvm::unique_function indexedFiles() const {
+  llvm::unique_function
+  indexedFiles() const override {
 // FIXME: For now we always return "false" regardless of whether the file
 //was indexed or not. A possible implementation could be based on
 //the idea that we do not want to send a request at every



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


[PATCH] D93227: [clangd] Smarter hover on auto and decltype

2020-12-18 Thread Quentin Chateau via Phabricator via cfe-commits
qchateau added inline comments.



Comment at: clang-tools-extra/clangd/AST.cpp:353
 if (auto *AT = D->getType()->getContainedAutoType()) {
-  if (!AT->getDeducedType().isNull())
-DeducedType = AT->getDeducedType();
+  DeducedType = AT->desugar();
 }

sammccall wrote:
> I added a comment to getDeducedType() - I think the intent here is that we 
> return the AutoType itself if it's not deduced, right?
It is already the case for return types in `VisitFunctionDecl`, but not for 
types visited in in `VisitDeclaratorDecl`. I simply made it consistent. One 
could argue `getDeducedType` should return `None` when the type is not deduced, 
and I'd not argue against that. Though I have t admit this behavior makes 
things simpler for the hover feature.



Comment at: clang-tools-extra/clangd/Hover.cpp:591
+   ASTContext &ASTCtx,
+   const SymbolIndex *Index) {
+  QualType OriginThisType = CTE->getType()->getPointeeType();

sammccall wrote:
> I dropped this unused param
Good catch



Comment at: clang-tools-extra/clangd/Hover.cpp:618
+  } else {
+CXXRecordDecl *D = QT->getAsCXXRecordDecl();
+if (D && D->isLambda())

sammccall wrote:
> sammccall wrote:
> > qchateau wrote:
> > > sammccall wrote:
> > > > You've rewritten this logic compared to the old 
> > > > `getHoverContents(QualType)`, and I think there are regressions:
> > > >  - We've dropped class documentation (see e.g. 
> > > > ac3f9e48421712168884d59cbfe8b294dd76a19b, this is visible in the tests)
> > > >  - we're no longer using printName() to print tag-decls, which I expect 
> > > > changes e.g. the printing of anyonymous structs which is special-cased 
> > > > in that function (we have tests for this but probably not in 
> > > > combination with auto)
> > > >  - we're no longer using the printing-policy to print non-tag types, 
> > > > which will lead to some random changes
> > > > 
> > > > I don't see a reason for these changes, can we revert them?
> > > - I can re-add class documentation, but should it work when `auto` is a 
> > > pointer or a ref ? In that case, I'll need something like your 
> > > `unwrapType` of https://reviews.llvm.org/D93314
> > > - `printName` will print `C` instead of `class C` even if I hack around 
> > > and give it the right `PrintingPolicy`. The problem is that IDE (at least 
> > > VSCode) does not know what `C` is and cannot color it, which looks a nice 
> > > less nice. Up to you !
> > > - I can re-add the printing policy for non-tag types, and add it for 
> > > tag-types if we chose not to use `printName`.
> > > should it work when auto is a pointer or a ref?
> > 
> > I think no need for now, I just want to avoid the regression.
> > (Nice to have, but at least in the codebases I work in, `auto` is much more 
> > common than `decltype(auto)` so it's rarely a reference, and pointers are 
> > idiomatically written `auto*`)
> > 
> > > printName will print C instead of class C even if I hack around and give 
> > > it the right PrintingPolicy.
> > 
> > Yeah... it's not supposed to, though the extra clarity is valuable here. 
> > You could just hack around this and prepend the TagTypeKind yourself :-)
> Hmm, it looks like this wasn't done. It's now printing e.g. `class 
> vector` which seems more confusing than either `class vector` 
> or `vector` (even if we lose some highlighting). I'll send a followup 
> with proposed changes here.
We can probably use `printDefinition` for tag types and keep `getAsString` for 
non tag types. That would also make the definition close to what we get when 
hovering on an explicit type (as opposed to 'auto'). We'd probably need to set 
the scopes in `HoverInfo` as well, `printDefinition` does not print them.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93227

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


[PATCH] D92039: [-Wcalled-once-parameter] Introduce 'called_once' attribute

2020-12-18 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D92039#2462995 , @vsavchenko wrote:

> In D92039#2462889 , @aaron.ballman 
> wrote:
>
>> Your test cases suggest that this is not inter-procedurally checked; it 
>> seems to require all of the APIs to be annotated in order to get the same 
>> effect that an inter-procedural check could determine on its own.
>
> I mean, of course, it doesn't have real inter-procedural analysis.  But if 
> everything is annotated or conventional - it is identical to inter-procedural 
> case (like in tests with `indirect` in their names).

Okay, I'm glad to know I wasn't misunderstanding something there!

>> I'm not worried about the leniency and I'm sorry if it sounds like I'm 
>> implying that it has to be inter-procedural to land -- that's not the case. 
>> What I am worried about is that the way the user runs the frontend is very 
>> different than the way the user runs the static analyzer, and migrating the 
>> warning from the FE to the static analyzer could leave us with problems. If 
>> the intention is that this check will live in the FE as-is (not getting 
>> inter-procedural support), then that's fine. But if the intention is to 
>> extend the check in the future in a way that might need it to move out of 
>> the FE and into the CSA, then I think the check should live in the CSA from 
>> the start (even if it doesn't do inter-procedural analysis). It's not clear 
>> to me whether "in the first version" implies that you expect a subsequent 
>> version to live in the CSA or not.
>
> No, we don't plan on moving it to the CSA.  As I mentioned above, for 
> hardening we can simply warn if `called_once` parameters leak into functions 
> we don't know about (not annotated or not following conventions).

Okay, thank you for verifying. The attribute bits of the patch LG to me (aside 
from a minor testing request). Someone else should validate the actual analysis 
bits.




Comment at: clang/test/SemaObjC/attr-called-once.m:7
+void test2(double x CALLED_ONCE); // expected-error{{'called_once' attribute 
only applies to function-like parameters}}
+
+void test3(void (*foo)() CALLED_ONCE);   // no-error

Can you also add tests that the attribute accepts no arguments and only 
appertains to parameters?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92039

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


[PATCH] D92039: [-Wcalled-once-parameter] Introduce 'called_once' attribute

2020-12-18 Thread Valeriy Savchenko via Phabricator via cfe-commits
vsavchenko added inline comments.



Comment at: clang/test/SemaObjC/attr-called-once.m:7
+void test2(double x CALLED_ONCE); // expected-error{{'called_once' attribute 
only applies to function-like parameters}}
+
+void test3(void (*foo)() CALLED_ONCE);   // no-error

aaron.ballman wrote:
> Can you also add tests that the attribute accepts no arguments and only 
> appertains to parameters?
Sure!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92039

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


[PATCH] D92762: [clang][AArch64][SVE] Avoid going through memory for coerced VLST arguments

2020-12-18 Thread Cullen Rhodes via Phabricator via cfe-commits
c-rhodes added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:2671-2673
+  // See if this is a VLST coerced to a VLAT at the function boundary and
+  // the types match up. If so, use llvm.experimental.vector.extract to
+  // perform the conversion.

this is slightly confusing since the coercion done in TargetInfo is from fixed 
-> scalable so VLSTs are represented as scalable vectors in functions 
args/return, yet this is casting back to fixed in the function prolog using 
`llvm.experimental.vector.extract` like you mention in the commit message, 
could this comment clarify that?



Comment at: clang/lib/CodeGen/CGCall.cpp:2674
+  // perform the conversion.
+  if (Ty->getAs()) {
+auto *Coerced = Fn->getArg(FirstIRArg);

Do we want to check `VT->getVectorKind() == 
VectorType::SveFixedLengthDataVector` and 
`isa(Coerced->getType());`?



Comment at: clang/lib/CodeGen/CGCall.cpp:2681
+VecTyFrom->getElementType() == VecTyTo->getElementType()) {
+  llvm::Value *Zero = llvm::Constant::getNullValue(this->CGM.Int64Ty);
+

`this->` can be dropped?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92762

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


[PATCH] D93531: [clangd] Reuse buffer for JSONTransport::readRawMessage

2020-12-18 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 312796.
njames93 added a comment.

Moved a few members out of the class.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93531

Files:
  clang-tools-extra/clangd/JSONTransport.cpp

Index: clang-tools-extra/clangd/JSONTransport.cpp
===
--- clang-tools-extra/clangd/JSONTransport.cpp
+++ clang-tools-extra/clangd/JSONTransport.cpp
@@ -99,6 +99,11 @@
   }
 
   llvm::Error loop(MessageHandler &Handler) override {
+// We dont want any inline storage because these are expected to grow quite
+// a lot, SmallString happens to give slightly better codegen than
+// std::string when we aren't expecting to use any inline storage.
+llvm::SmallString<0> JsonContents;
+llvm::SmallString<0> ScratchSpace;
 while (!feof(In)) {
   if (shutdownRequested())
 return error(std::make_error_code(std::errc::operation_canceled),
@@ -106,7 +111,7 @@
   if (ferror(In))
 return llvm::errorCodeToError(
 std::error_code(errno, std::system_category()));
-  if (auto JSON = readRawMessage()) {
+  if (auto JSON = readRawMessage(JsonContents, ScratchSpace)) {
 if (auto Doc = llvm::json::parse(*JSON)) {
   vlog(Pretty ? "<<< {0:2}\n" : "<<< {0}\n", *Doc);
   if (!handleMessage(std::move(*Doc), Handler))
@@ -126,22 +131,31 @@
   bool handleMessage(llvm::json::Value Message, MessageHandler &Handler);
   // Writes outgoing message to Out stream.
   void sendMessage(llvm::json::Value Message) {
-std::string S;
-llvm::raw_string_ostream OS(S);
+OutputBuffer.clear();
+llvm::raw_svector_ostream OS(OutputBuffer);
 OS << llvm::formatv(Pretty ? "{0:2}" : "{0}", Message);
-OS.flush();
-Out << "Content-Length: " << S.size() << "\r\n\r\n" << S;
+Out << "Content-Length: " << OutputBuffer.size() << "\r\n\r\n"
+<< OutputBuffer;
 Out.flush();
-vlog(">>> {0}\n", S);
+vlog(">>> {0}\n", OutputBuffer);
   }
 
   // Read raw string messages from input stream.
-  llvm::Optional readRawMessage() {
-return Style == JSONStreamStyle::Delimited ? readDelimitedMessage()
-   : readStandardMessage();
+  llvm::Optional readRawMessage(SmallVectorImpl &Buffer,
+   SmallVectorImpl &Scratch) {
+return Style == JSONStreamStyle::Delimited
+   ? readDelimitedMessage(Buffer, Scratch)
+   : readStandardMessage(Buffer, Scratch);
   }
-  llvm::Optional readDelimitedMessage();
-  llvm::Optional readStandardMessage();
+  llvm::Optional
+  readDelimitedMessage(SmallVectorImpl &Buffer,
+   SmallVectorImpl &Scratch);
+  llvm::Optional readStandardMessage(SmallVectorImpl &Buffer,
+SmallVectorImpl &Scratch);
+
+  // Accept that these buffers are going to be large enough that there is no
+  // point in inline storage.
+  llvm::SmallString<0> OutputBuffer;
 
   std::FILE *In;
   llvm::raw_ostream &Out;
@@ -190,7 +204,7 @@
 
 // Tries to read a line up to and including \n.
 // If failing, feof(), ferror(), or shutdownRequested() will be set.
-bool readLine(std::FILE *In, std::string &Out) {
+bool readLine(std::FILE *In, llvm::SmallVectorImpl &Out) {
   static constexpr int BufSize = 1024;
   size_t Size = 0;
   Out.clear();
@@ -215,17 +229,18 @@
 // Returns None when:
 //  - ferror(), feof(), or shutdownRequested() are set.
 //  - Content-Length is missing or empty (protocol error)
-llvm::Optional JSONTransport::readStandardMessage() {
+llvm::Optional
+JSONTransport::readStandardMessage(SmallVectorImpl &Buffer,
+   SmallVectorImpl &Scratch) {
   // A Language Server Protocol message starts with a set of HTTP headers,
   // delimited  by \r\n, and terminated by an empty line (\r\n).
   unsigned long long ContentLength = 0;
-  std::string Line;
   while (true) {
-if (feof(In) || ferror(In) || !readLine(In, Line))
+if (feof(In) || ferror(In) || !readLine(In, Scratch))
   return llvm::None;
-InMirror << Line;
+InMirror << Scratch;
 
-llvm::StringRef LineRef(Line);
+llvm::StringRef LineRef(Scratch.begin(), Scratch.size());
 
 // We allow comments in headers. Technically this isn't part
 
@@ -264,23 +279,23 @@
 return llvm::None;
   }
 
-  std::string JSON(ContentLength, '\0');
+  Buffer.resize(ContentLength);
   for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
 // Handle EINTR which is sent when a debugger attaches on some platforms.
-Read = retryAfterSignalUnlessShutdown(0, [&]{
-  return std::fread(&JSON[Pos], 1, ContentLength - Pos, In);
+Read = retryAfterSignalUnlessShutdown(0, [&] {
+  return std::fread(&Buffer[Pos], 1, ContentLength - Pos, In);
 });
 if (Read == 0) {
   elog("In

[PATCH] D93546: [clangd][NFC] Improve clangd status messages

2020-12-18 Thread Quentin Chateau via Phabricator via cfe-commits
qchateau created this revision.
qchateau added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman, javed.absar.
qchateau requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

clangd actions have various naming schemes, the most
common being PascalCase. This commit applies PascalCase
to all clangd actions, and fix the status rendering
in `renderTUAction` to look more consistent.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93546

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


Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -1184,7 +1184,7 @@
   llvm::SmallVector Result;
   switch (PA) {
   case PreambleAction::Building:
-Result.push_back("parsing includes");
+Result.push_back("Parsing includes");
 break;
   case PreambleAction::Idle:
 // We handle idle specially below.
@@ -1192,13 +1192,13 @@
   }
   switch (AA.K) {
   case ASTAction::Queued:
-Result.push_back("file is queued");
+Result.push_back("File is queued");
 break;
   case ASTAction::RunningAction:
-Result.push_back("running " + AA.Name);
+Result.push_back("Running " + AA.Name);
 break;
   case ASTAction::Building:
-Result.push_back("parsing main file");
+Result.push_back("Parsing main file");
 break;
   case ASTAction::Idle:
 // We handle idle specially below.
@@ -1206,7 +1206,7 @@
   }
   if (Result.empty())
 return "idle";
-  return llvm::join(Result, ",");
+  return llvm::join(Result, ", ");
 }
 
 } // namespace
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -621,7 +621,7 @@
 File));
   };
 
-  WorkScheduler.runWithAST("Type Hierarchy", File, std::move(Action));
+  WorkScheduler.runWithAST("TypeHierarchy", File, std::move(Action));
 }
 
 void ClangdServer::resolveTypeHierarchy(
@@ -642,7 +642,7 @@
   return CB(InpAST.takeError());
 CB(clangd::prepareCallHierarchy(InpAST->AST, Pos, File));
   };
-  WorkScheduler.runWithAST("Call Hierarchy", File, std::move(Action));
+  WorkScheduler.runWithAST("CallHierarchy", File, std::move(Action));
 }
 
 void ClangdServer::incomingCalls(
@@ -678,7 +678,7 @@
   return CB(InpAST.takeError());
 CB(clangd::getDocumentSymbols(InpAST->AST));
   };
-  WorkScheduler.runWithAST("documentSymbols", File, std::move(Action),
+  WorkScheduler.runWithAST("DocumentSymbols", File, std::move(Action),
TUScheduler::InvalidateOnUpdate);
 }
 
@@ -690,7 +690,7 @@
   return CB(InpAST.takeError());
 CB(clangd::getFoldingRanges(InpAST->AST));
   };
-  WorkScheduler.runWithAST("foldingRanges", File, std::move(Action),
+  WorkScheduler.runWithAST("FoldingRanges", File, std::move(Action),
TUScheduler::InvalidateOnUpdate);
 }
 


Index: clang-tools-extra/clangd/TUScheduler.cpp
===
--- clang-tools-extra/clangd/TUScheduler.cpp
+++ clang-tools-extra/clangd/TUScheduler.cpp
@@ -1184,7 +1184,7 @@
   llvm::SmallVector Result;
   switch (PA) {
   case PreambleAction::Building:
-Result.push_back("parsing includes");
+Result.push_back("Parsing includes");
 break;
   case PreambleAction::Idle:
 // We handle idle specially below.
@@ -1192,13 +1192,13 @@
   }
   switch (AA.K) {
   case ASTAction::Queued:
-Result.push_back("file is queued");
+Result.push_back("File is queued");
 break;
   case ASTAction::RunningAction:
-Result.push_back("running " + AA.Name);
+Result.push_back("Running " + AA.Name);
 break;
   case ASTAction::Building:
-Result.push_back("parsing main file");
+Result.push_back("Parsing main file");
 break;
   case ASTAction::Idle:
 // We handle idle specially below.
@@ -1206,7 +1206,7 @@
   }
   if (Result.empty())
 return "idle";
-  return llvm::join(Result, ",");
+  return llvm::join(Result, ", ");
 }
 
 } // namespace
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -621,7 +621,7 @@
 File));
   };
 
-  WorkScheduler.runWithAST("Type Hierarchy", File, std::move(Action));
+  WorkScheduler.runWithAST("TypeHierarchy", File, std::move(Action));
 }
 
 void ClangdServer::resolveTypeHierarchy(
@@ -642,7 +642,7 @@
   return CB(InpAST.takeError());
 CB(clangd::prepareCallHierarchy(InpAST->AST, Pos, File));
   };
-  WorkScheduler.runWithAST

[PATCH] D89031: [SVE] Add support to vectorize_width loop pragma for scalable vectors

2020-12-18 Thread David Sherwood via Phabricator via cfe-commits
david-arm updated this revision to Diff 312802.
david-arm edited the summary of this revision.
Herald added a subscriber: NickHung.

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

https://reviews.llvm.org/D89031

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/AST/AttrImpl.cpp
  clang/lib/CodeGen/CGLoopInfo.cpp
  clang/lib/CodeGen/CGLoopInfo.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Sema/SemaStmtAttr.cpp
  clang/test/CodeGenCXX/pragma-loop-pr27643.cpp
  clang/test/CodeGenCXX/pragma-loop.cpp
  clang/test/Parser/pragma-loop.cpp

Index: clang/test/Parser/pragma-loop.cpp
===
--- clang/test/Parser/pragma-loop.cpp
+++ clang/test/Parser/pragma-loop.cpp
@@ -60,7 +60,8 @@
 
 template 
 void test_nontype_template_badarg(int *List, int Length) {
-  /* expected-error {{use of undeclared identifier 'Vec'}} */ #pragma clang loop vectorize_width(Vec) interleave_count(I)
+  /* expected-error {{use of undeclared identifier 'Vec'}} */ #pragma clang loop vectorize_width(Vec) interleave_count(I) /*
+ expected-note {{vectorize_width loop hint malformed; use vectorize_width(X, 'fixed' or 'scalable') where X is an integer, or vectorize_width('fixed' or 'scalable')}} */
   /* expected-error {{use of undeclared identifier 'Int'}} */ #pragma clang loop vectorize_width(V) interleave_count(Int)
   for (int i = 0; i < Length; i++) {
 List[i] = i;
@@ -189,12 +190,15 @@
 /* expected-warning {{extra tokens at end of '#pragma clang loop'}} */ #pragma clang loop vectorize_width(1 +) 1
 /* expected-warning {{extra tokens at end of '#pragma clang loop'}} */ #pragma clang loop vectorize_width(1) +1
 const int VV = 4;
-/* expected-error {{expected expression}} */ #pragma clang loop vectorize_width(VV +/ 2)
-/* expected-error {{use of undeclared identifier 'undefined'}} */ #pragma clang loop vectorize_width(VV+undefined)
+/* expected-error {{expected expression}} */ #pragma clang loop vectorize_width(VV +/ 2) /*
+   expected-note {{vectorize_width loop hint malformed; use vectorize_width(X, 'fixed' or 'scalable') where X is an integer, or vectorize_width('fixed' or 'scalable')}} */
+/* expected-error {{use of undeclared identifier 'undefined'}} */ #pragma clang loop vectorize_width(VV+undefined) /*
+   expected-note {{vectorize_width loop hint malformed; use vectorize_width(X, 'fixed' or 'scalable') where X is an integer, or vectorize_width('fixed' or 'scalable')}} */
 /* expected-error {{expected ')'}} */ #pragma clang loop vectorize_width(1+(^*/2 * ()
 /* expected-warning {{extra tokens at end of '#pragma clang loop' - ignored}} */ #pragma clang loop vectorize_width(1+(-0[0]))
 
-/* expected-error {{use of undeclared identifier 'badvalue'}} */ #pragma clang loop vectorize_width(badvalue)
+/* expected-error {{use of undeclared identifier 'badvalue'}} */ #pragma clang loop vectorize_width(badvalue) /*
+   expected-note {{vectorize_width loop hint malformed; use vectorize_width(X, 'fixed' or 'scalable') where X is an integer, or vectorize_width('fixed' or 'scalable')}} */
 /* expected-error {{use of undeclared identifier 'badvalue'}} */ #pragma clang loop interleave_count(badvalue)
 /* expected-error {{use of undeclared identifier 'badvalue'}} */ #pragma clang loop unroll_count(badvalue)
   while (i-6 < Length) {
@@ -215,7 +219,7 @@
 /* expected-error {{invalid argument; expected 'enable', 'assume_safety' or 'disable'}} */ #pragma clang loop interleave(*)
 /* expected-error {{invalid argument; expected 'enable', 'full' or 'disable'}} */ #pragma clang loop unroll(=)
 /* expected-error {{invalid argument; expected 'enable' or 'disable'}} */ #pragma clang loop distribute(+)
-/* expected-error {{type name requires a specifier or qualifier}} expected-error {{expected expression}} */ #pragma clang loop vectorize_width(^)
+/* expected-error {{type name requires a specifier or qualifier}} expected-error {{expected expression}} */ #pragma clang loop vectorize_width(^) /* expected-note {{vectorize_width loop hint malformed; use vectorize_width(X, 'fixed' or 'scalable') where X is an integer, or vectorize_width('fixed' or 'scalable')}} */
 /* expected-error {{expected expression}} expected-error {{expected expression}} */ #pragma clang loop interleave_count(/)
 /* expected-error {{expected expression}} expected-error {{expected expression}} */ #pragma clang loop unroll_count(==)
   while (i-8 < Length) {
Index: clang/test/CodeGenCXX/pragma-loop.cpp
===
--- clang/test/CodeGenCXX/pragma-loop.cpp
+++ clang/test/CodeGenCXX/pragma-loop.cpp
@@ -158,51 +158,88 @@
   for_template_constant_expression_test(List, Length);
 }
 
+// Verify for loop is performing fixed width vectorization
+void for_test_fixed_16(int *List, int Length) {
+#pragma clang loop vectorize_width(16, fixed) interleave_count(4) unroll(disab

[PATCH] D72241: [clang-tidy] new altera single work item barrier check

2020-12-18 Thread Frank Derry Wanye via Phabricator via cfe-commits
ffrankies added a comment.

@aaron.ballman @njames93 thanks for testing this out, the feedback, and the 
commit!

Could you also take a look at D72235 unroll loops check 
 ? It's been updated and is ready for review.


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

https://reviews.llvm.org/D72241

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


[PATCH] D89031: [SVE] Add support to vectorize_width loop pragma for scalable vectors

2020-12-18 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/Attr.td:3356
   EnumArgument<"State", "LoopHintState",
-   ["enable", "disable", "numeric", "assume_safety", 
"full"],
-   ["Enable", "Disable", "Numeric", "AssumeSafety", 
"Full"]>,
+   ["enable", "disable", "numeric", "fixed_width", 
"scalable_width", "assume_safety", "full"],
+   ["Enable", "Disable", "Numeric", "FixedWidth", 
"ScalableWidth", "AssumeSafety", "Full"]>,

Should the documentation in AttrDocs.td be updated for this change?


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

https://reviews.llvm.org/D89031

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


[PATCH] D87188: [InstCombine] Canonicalize SPF to abs intrinc

2020-12-18 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

Thanks for the reproducer. I verified that it does indeed fail with this patch.

It seems to be doing this as a knock-on effect: https://godbolt.org/z/Y4z3je, 
which does not verify: https://alive2.llvm.org/ce/z/PN7Rv5 ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87188

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


[PATCH] D72235: [clang-tidy] new altera unroll loops check

2020-12-18 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:22
+void UnrollLoopsCheck::registerMatchers(MatchFinder *Finder) {
+  const auto ANYLOOP = anyOf(forStmt(), whileStmt(), doStmt());
+  Finder->addMatcher(stmt(allOf(ANYLOOP, // Match all loop types,

Dont use all caps variable names, preferred style is CamelCase.



Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:24-26
+unless(hasDescendant(forStmt())),
+unless(hasDescendant(whileStmt())),
+unless(hasDescendant(doStmt()





Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:35
+  UnrollType Unroll = unrollType(MatchedLoop, Result.Context);
+  if (Unroll == NotUnrolled) {
+diag(MatchedLoop->getBeginLoc(),

This loops like it should be a switch



Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:68
+for (const Attr *Attribute : ParentStmt->getAttrs()) {
+  const auto *LoopHint = static_cast(Attribute);
+  if (LoopHint) {

Shouldn't this by dyn_cast too.



Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:69
+  const auto *LoopHint = static_cast(Attribute);
+  if (LoopHint) {
+switch (LoopHint->getState()) {

To reduce indentations can this be an early exit



Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:79
+  return FullyUnrolled;
+default:
+  return NotUnrolled;

Default statements are usually bad as the prevent compiler diagnostics if the 
enum is ever updated.



Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:93-94
+return false;
+  if (isa(Conditional)) {
+const auto *BinaryOp = static_cast(Conditional);
+const Expr *LHS = BinaryOp->getLHS();





Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:107-120
+  const Expr *Conditional;
+  if (isa(Statement)) {
+const auto *ForLoop = static_cast(Statement);
+Conditional = ForLoop->getCond();
+  }
+  if (isa(Statement)) {
+const auto *WhileLoop = static_cast(Statement);





Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:128
+return false;
+  if (isa(Conditional)) {
+const auto *BinaryOp = static_cast(Conditional);

dyn_cast again



Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:145
+  if (Expression->EvaluateAsRValue(Result, *Context)) {
+if (!(Result.Val.isInt()))
+  return false; // Cannot check number of iterations, return false to be

Elide inner parens



Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp:148-150
+if (Result.Val.getInt() > MaxLoopIterations)
+  return true; // Assumes values go from 0 to Val in increments of 1.
+return false; // Number of iterations likely less than MaxLoopIterations.





Comment at: clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.h:31-33
+  UnrollLoopsCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context),
+MaxLoopIterations(Options.get("MaxLoopIterations", 100U)) {}

Should probably define this out of line in the cpp file.


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

https://reviews.llvm.org/D72235

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


[PATCH] D93525: [OpenMP] Add unbundling of archives containing bundled object files into device specific archives

2020-12-18 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:142-144
+  } else {
+return Triple;
+  }

No need `else` here



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:953-957
+  else {
+WithColor::warning() << "Could not determine extension for archive "
+"members, using \".o\"\n";
+return ".o";
+  }

No need for `else` here



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:960-962
+static StringRef removeExtension(StringRef FileName) {
+  return (FileName.contains(".")) ? FileName.rsplit('.').first : FileName;
+}

I think llvm Support lib has all required functions for this.



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:1000
+  ArchiveBuffers.push_back(std::move(*BufOrErr));
+  auto LibOrErr = Archive::create(ArchiveBuffers.back()->getMemBufferRef());
+  if (!LibOrErr)

Do not use `auto` where the type is not obvious.



Comment at: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp:1048-1049
+while (!CurKindTriple.empty()) {
+  if (hasHostKind(CurKindTriple)) {
+// Do nothing, we don't extract host code yet
+  } else if (checkDeviceOptions(getDevice(getTriple(CurKindTriple)),

Just `continue` and make `else if` just `if`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93525

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


[PATCH] D91556: [OpenMPIRBuilder} Add capturing of parameters to pass to omp::parallel

2020-12-18 Thread Alex Zinenko via Phabricator via cfe-commits
ftynse added a comment.

Thanks! I have a couple of comments, but I will defer to @jdoerfert for 
approval in any case.




Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:676
+
+  /// Capture the above-defined paraneters for the parallel regions.
+  ///





Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:678
+  ///
+  /// \param CaptureAllocaInsPoint Insertion point for the alloca-ed struct.
+  /// \param OuterFn The function containing the omp::Parallel.

Nit: it looks like this file uses IP rather than InsPoint for names related to 
insertion points



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:760
+  SetVector BlockParents;
+  for (unsigned Counter = 0; Counter < Blocks.size(); Counter++) {
+BasicBlock *ParallelRegionBlock = Blocks[Counter];

Nit:  I think 
https://llvm.org/docs/CodingStandards.html#don-t-evaluate-end-every-time-through-a-loop
 applies to `.size()` the same way it applies to `.end()`



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:795
+  // captured values with the extracted ones from the struct.
+  if (CapturedValues.size()) {
+// Create the StructTy

Nit: 
https://llvm.org/docs/CodingStandards.html#use-early-exits-and-continue-to-simplify-code

```
if (CapturedValues.empty())
  return;
```



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:796
+  if (CapturedValues.size()) {
+// Create the StructTy
+std::vector StructTypes;

Nit: trailing dot



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:799
+for (unsigned Counter = 0; Counter < CapturedValues.size(); Counter++)
+  StructTypes.push_back(CapturedValues[Counter]->getType());
+

Nit: please `reserve` before pushing back in a loop



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:807-808
+  llvm::IRBuilder<>::InsertPointGuard Guard(Builder);
+  Builder.SetInsertPoint(CaptureAllocaInsPoint.getBlock(),
+ CaptureAllocaInsPoint.getPoint());
+  // Allocate and populate the capture struct.

Nit: `Builder.restoreIP(CaptureAllocaInsPoint)` looks shorter



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:810-815
+  AllocaInst = Builder.CreateAlloca(CaptureStructType, nullptr,
+"CaptureStructAlloca");
+  Value *InsertValue = UndefValue::get(CaptureStructType);
+  for (auto SrcIdx : enumerate(CapturedValues))
+InsertValue = Builder.CreateInsertValue(InsertValue, SrcIdx.value(),
+SrcIdx.index());

I suppose you may want to have `alloca` inserted in a block (function entry) 
different from the one where you store into the memory. You need to store just 
before calling the fork function (or, at least, so that the store postdominates 
all stored values). Looking at the function API, I would have assumed 
`CaptureAllocaInsPoint` to be an insertion point at the function entry block 
specifically for `alloca`s, where these `insertvalue`s are invalid.



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:826-829
+  for (unsigned Counter = 0; Counter < Blocks.size(); Counter++)
+for (auto I = Blocks[Counter]->begin(), E = Blocks[Counter]->end();
+ I != E; ++I)
+  for (Use &U : I->operands())

Can we rather take each captured value and enumerate its uses, replacing those 
within the parallel block set?



Comment at: llvm/test/CodeGen/XCore/threads.ll:84-140
+; This test fails on Windows because the second and third
+; register of the add operations are swapped.
+; Windows test is below.
+; REQUIRES: !windows
 define i32* @f_tle() {
 ; CHECK-LABEL: f_tle:
 ; CHECK: get r11, id

These look irrelevant to the patch, but seem to fix a breakage upstream. Would 
you mind committing this separately?



Comment at: mlir/test/Conversion/OpenMPToLLVM/openmp_float-parallel_param.mlir:1
+// RUN: mlir-translate  --mlir-to-llvmir %s | FileCheck %s
+

Changes to MLIR are no longer necessary


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D91556

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


[PATCH] D92054: [Driver] Default Generic_GCC ppc/ppc64/ppc64le to -fasynchronous-unwind-tables

2020-12-18 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92054

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


[PATCH] D87188: [InstCombine] Canonicalize SPF to abs intrinc

2020-12-18 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D87188#2463285 , @dmgreen wrote:

> Thanks for the reproducer. I verified that it does indeed fail with this 
> patch.
>
> It seems to be doing this as a knock-on effect: https://godbolt.org/z/Y4z3je, 
> which does not verify: https://alive2.llvm.org/ce/z/PN7Rv5 ?

@dmgreen THANK YOU!
That was sufficient information for me, the actual miscompiling fold is D87197 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87188

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


[PATCH] D86694: [scudo] Allow -fsanitize=scudo on Linux and Windows (WIP, don't land as is)

2020-12-18 Thread Russell Gallop via Phabricator via cfe-commits
russell.gallop updated this revision to Diff 312827.
russell.gallop edited the summary of this revision.
russell.gallop added a comment.

Apologies for the delay, I've had other things taking my time.

Latest version uploaded. This fixes stage1 lit tests (on Windows and Linux) and 
adds scudo_cxx to linking.

Usage has changed slightly, now -DLLVM_INTEGRATED_CRT_ALLOC should point to the 
directory with scudo built libraries (e.g. 
c:/git/llvm-project/stage1/lib/clang/12.0.0/lib/windows) rather than the 
library itself. -fsanitize=scudo works for the lit tests (as clang adds the 
libraries when driving the linker) but doesn't work for building LLVM as cmake 
links with the linker directly so this uses LLVM_INTEGRATED_CRT_ALLOC.

There are two issues I'm aware of now:

- Linking c-index-test.exe with scudo fails due to new being redefined

  lld-link: error: void * __cdecl operator new(unsigned __int64) was replaced

Or from link.exe

  clang_rt.scudo_cxx-x86_64.lib(scudo_new_delete.cpp.obj) : error LNK2005: 
"void * __cdecl operator new(unsigned __int64)" (??2@YAPEAX_K@Z) already 
defined in libclang.lib(libclang.dll)
  ...



- With scudo all lit tests (generally) pass, but there are some intermittent 
failures (Access Violation) on the following tests:

> ExecutionEngine/MCJIT/test-global-init-nonzero-sm-pic.ll
> ExecutionEngine/MCJIT/test-ptr-reloc-sm-pic.ll
> ExecutionEngine/MCJIT/multi-module-sm-pic-a.ll

This happens with VS2019 or clang-cl as the toolchain. I've run multiple times 
without scudo and don't see these. Unfortunately I haven't been able to get 
this to fail in a debugger.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86694

Files:
  clang/lib/Driver/ToolChains/MSVC.cpp
  compiler-rt/cmake/config-ix.cmake
  compiler-rt/lib/sanitizer_common/sanitizer_win.cpp
  compiler-rt/lib/scudo/CMakeLists.txt
  compiler-rt/lib/scudo/scudo_allocator.cpp
  compiler-rt/lib/scudo/scudo_crc32.cpp
  compiler-rt/lib/scudo/scudo_new_delete.cpp
  compiler-rt/lib/scudo/scudo_platform.h
  compiler-rt/lib/scudo/scudo_tsd.h
  compiler-rt/lib/scudo/scudo_tsd_shared.cpp
  compiler-rt/lib/scudo/scudo_tsd_shared.inc
  compiler-rt/test/scudo/cxx_threads.cpp
  compiler-rt/test/scudo/dealloc-race.c
  compiler-rt/test/scudo/fsanitize.c
  compiler-rt/test/scudo/interface.cpp
  compiler-rt/test/scudo/lit.cfg.py
  compiler-rt/test/scudo/malloc.cpp
  compiler-rt/test/scudo/memalign.c
  compiler-rt/test/scudo/mismatch.cpp
  compiler-rt/test/scudo/overflow.c
  compiler-rt/test/scudo/preload.cpp
  compiler-rt/test/scudo/rss.c
  compiler-rt/test/scudo/secondary.c
  compiler-rt/test/scudo/symbols.test
  compiler-rt/test/scudo/threads.c
  compiler-rt/test/scudo/tsd_destruction.c
  compiler-rt/test/scudo/valloc.c
  llvm/CMakeLists.txt
  llvm/cmake/modules/HandleLLVMOptions.cmake
  llvm/lib/Support/CMakeLists.txt

Index: llvm/lib/Support/CMakeLists.txt
===
--- llvm/lib/Support/CMakeLists.txt
+++ llvm/lib/Support/CMakeLists.txt
@@ -58,7 +58,7 @@
   string(REGEX REPLACE "(/|)$" "" LLVM_INTEGRATED_CRT_ALLOC "${LLVM_INTEGRATED_CRT_ALLOC}")
 
   if(NOT EXISTS "${LLVM_INTEGRATED_CRT_ALLOC}")
-message(FATAL_ERROR "Cannot find the path to `git clone` for the CRT allocator! (${LLVM_INTEGRATED_CRT_ALLOC}). Currently, rpmalloc, snmalloc and mimalloc are supported.")
+message(FATAL_ERROR "Cannot find the path to `git clone` for the CRT allocator! (${LLVM_INTEGRATED_CRT_ALLOC}). Currently, rpmalloc, snmalloc, mimalloc and scudo are supported.")
   endif()
 
   if(LLVM_INTEGRATED_CRT_ALLOC MATCHES "rpmalloc$")
@@ -73,6 +73,8 @@
 	  message(FATAL_ERROR "Cannot find the mimalloc static library. To build it, first apply the patch from https://github.com/microsoft/mimalloc/issues/268 then build the Release x64 target through ${LLVM_INTEGRATED_CRT_ALLOC}\\ide\\vs2019\\mimalloc.sln")
 endif()
 set(system_libs ${system_libs} "${MIMALLOC_LIB}" "-INCLUDE:malloc")
+  elseif(EXISTS "${LLVM_INTEGRATED_CRT_ALLOC}/clang_rt.scudo-x86_64.lib" AND EXISTS "${LLVM_INTEGRATED_CRT_ALLOC}/clang_rt.scudo_cxx-x86_64.lib")
+  set(system_libs ${system_libs} "${LLVM_INTEGRATED_CRT_ALLOC}/clang_rt.scudo-x86_64.lib" "${LLVM_INTEGRATED_CRT_ALLOC}/clang_rt.scudo_cxx-x86_64.lib" "-INCLUDE:malloc")
   endif()
 endif()
 
Index: llvm/cmake/modules/HandleLLVMOptions.cmake
===
--- llvm/cmake/modules/HandleLLVMOptions.cmake
+++ llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -790,6 +790,9 @@
 elseif (LLVM_USE_SANITIZER STREQUAL "Leaks")
   append_common_sanitizer_flags()
   append("-fsanitize=leak" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
+elseif (LLVM_USE_SANITIZER STREQUAL "Scudo")
+  append_common_sanitizer_flags()
+  append("-fsanitize=scudo" CMAKE_C_FLAGS CMAKE_CXX_FLAGS)
 else()
   message(FATAL_ERROR "Unsupported value of L

[PATCH] D87188: [InstCombine] Canonicalize SPF to abs intrinc

2020-12-18 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

Yeah. The reproducer seems to work OK with a patch something like this:

  diff --git a/llvm/lib/Analysis/InstructionSimplify.cpp 
b/llvm/lib/Analysis/InstructionSimplify.cpp
  index 35c21a0..c517286 100644 

  --- a/llvm/lib/Analysis/InstructionSimplify.cpp   

  +++ b/llvm/lib/Analysis/InstructionSimplify.cpp   

  @@ -4020,11 +4020,11 @@ static Value *simplifySelectWithICmpCond(Value 
*CondVal, Value *TrueVal,  


   // X == 0 ? abs(X) : -abs(X) --> -abs(X) 

   // X == 0 ? -abs(X) : abs(X) --> abs(X)  

  -if (match(TrueVal, m_Intrinsic(m_Value(X))) &&   

  -match(FalseVal, m_Neg(m_Intrinsic(m_Specific(X)  

  +if (match(TrueVal, m_Intrinsic(m_Specific(CmpLHS))) &&   

  +match(FalseVal, 
m_Neg(m_Intrinsic(m_Specific(CmpLHS) 
 return FalseVal;   

  -if (match(TrueVal, m_Neg(m_Intrinsic(m_Value(X &&

  -match(FalseVal, m_Intrinsic(m_Specific(X 

  +if (match(TrueVal, 
m_Neg(m_Intrinsic(m_Specific(CmpLHS &&
  +match(FalseVal, m_Intrinsic(m_Specific(CmpLHS

 return FalseVal;   

 }  




(I must admit, was fully expecting this to be something wrong in the AArch64 
backend. I'll leave that fix to you if you are happy to add tests and whatnot.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87188

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


[PATCH] D87188: [InstCombine] Canonicalize SPF to abs intrinc

2020-12-18 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

In D87188#2463447 , @dmgreen wrote:

> Yeah. The reproducer seems to work OK with a patch something like this:
>
>   diff --git a/llvm/lib/Analysis/InstructionSimplify.cpp 
> b/llvm/lib/Analysis/InstructionSimplify.cpp
>   index 35c21a0..c517286 100644   
>   
>   --- a/llvm/lib/Analysis/InstructionSimplify.cpp 
>   
>   +++ b/llvm/lib/Analysis/InstructionSimplify.cpp 
>   
>   @@ -4020,11 +4020,11 @@ static Value *simplifySelectWithICmpCond(Value 
> *CondVal, Value *TrueVal,  
>   
>   
>// X == 0 ? abs(X) : -abs(X) --> -abs(X)   
>   
>// X == 0 ? -abs(X) : abs(X) --> abs(X)
>   
>   -if (match(TrueVal, m_Intrinsic(m_Value(X))) && 
>   
>   -match(FalseVal, 
> m_Neg(m_Intrinsic(m_Specific(X)  
>   +if (match(TrueVal, m_Intrinsic(m_Specific(CmpLHS))) && 
>   
>   +match(FalseVal, 
> m_Neg(m_Intrinsic(m_Specific(CmpLHS) 
>  return FalseVal; 
>   
>   -if (match(TrueVal, m_Neg(m_Intrinsic(m_Value(X &&  
>   
>   -match(FalseVal, m_Intrinsic(m_Specific(X   
>   
>   +if (match(TrueVal, 
> m_Neg(m_Intrinsic(m_Specific(CmpLHS &&
>   +match(FalseVal, m_Intrinsic(m_Specific(CmpLHS  
>   
>  return FalseVal; 
>   
>  }
>   
>   
>   

Indeed, that is what i have already committed locally and will push in a sec.

> (I must admit, was fully expecting this to be something wrong in the AArch64 
> backend. I'll leave that fix to you if you are happy to add tests and 
> whatnot.)

Yeah, i also was almost convinced it was :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87188

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


[PATCH] D93553: [clangd] Make our printing policies for Hover more consistent, especially tags

2020-12-18 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: qchateau.
Herald added subscribers: usaxena95, kadircet, arphaman.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang.

Different cases were using a bunch of different variants of the printing policy.
Each of these had something going for it, but the result was inconsistent.

Goals:

- single printing policy used (almost) everywhere
- avoid unidiomatic tags like `class vector`
- be informative and easy to understand

For tags, the solution I wound up with is: we print only the outer tag and only
in the simplest cases where this elaboration won't cause confusion.

For example:

- class X
- enum Foo
- vector
- X*

This seems to strike a nice balance of providing plenty of info/context in 
common
cases while never being confusing.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D93553

Files:
  clang-tools-extra/clangd/Hover.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp

Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -239,7 +239,7 @@
  HI.Name = "c";
  HI.Kind = index::SymbolKind::Variable;
  HI.Definition = "auto *c = &b";
- HI.Type = "class (lambda) **";
+ HI.Type = "(lambda) **";
  HI.ReturnType = "bool";
  HI.Parameters = {
  {std::string("int"), std::string("T"), llvm::None},
@@ -611,7 +611,7 @@
   [](HoverInfo &HI) {
 HI.Name = "auto";
 HI.Kind = index::SymbolKind::TypeAlias;
-HI.Definition = "class Foo";
+HI.Definition = "class Foo";
   }},
   {// Falls back to primary template, when the type is not instantiated.
R"cpp(
@@ -718,8 +718,8 @@
  HI.Definition = "X &setY(float v)";
  HI.LocalScope = "X::";
  HI.Documentation = "Trivial setter for `Y`.";
- HI.Type = "struct X &(float)";
- HI.ReturnType = "struct X &";
+ HI.Type = "X &(float)";
+ HI.ReturnType = "X &";
  HI.Parameters.emplace();
  HI.Parameters->emplace_back();
  HI.Parameters->back().Type = "float";
@@ -1943,7 +1943,7 @@
 HI.Kind = index::SymbolKind::Variable;
 HI.NamespaceScope = "";
 HI.LocalScope = "test::";
-HI.Type = "struct Test &&";
+HI.Type = "Test &&";
 HI.Definition = "Test &&test = {}";
   }},
   {
@@ -2211,7 +2211,7 @@
   )cpp",
   [](HoverInfo &HI) {
 HI.Name = "this";
-HI.Definition = "Foo *";
+HI.Definition = "ns::Foo *";
   }},
   {
   R"cpp(// this expr for template class
Index: clang-tools-extra/clangd/Hover.cpp
===
--- clang-tools-extra/clangd/Hover.cpp
+++ clang-tools-extra/clangd/Hover.cpp
@@ -49,16 +49,13 @@
 namespace clangd {
 namespace {
 
-PrintingPolicy printingPolicyForDecls(PrintingPolicy Base) {
-  PrintingPolicy Policy(Base);
-
-  Policy.AnonymousTagLocations = false;
-  Policy.TerseOutput = true;
-  Policy.PolishForDeclaration = true;
-  Policy.ConstantsAsWritten = true;
-  Policy.SuppressTagKeyword = false;
-
-  return Policy;
+PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
+  Base.AnonymousTagLocations = false;
+  Base.TerseOutput = true;
+  Base.PolishForDeclaration = true;
+  Base.ConstantsAsWritten = true;
+  Base.SuppressTemplateArgsInCXXConstructors = true;
+  return Base;
 }
 
 /// Given a declaration \p D, return a human-readable string representing the
@@ -108,26 +105,33 @@
   return "";
 }
 
-std::string printDefinition(const Decl *D) {
+std::string printDefinition(const Decl *D, const PrintingPolicy &PP) {
   std::string Definition;
   llvm::raw_string_ostream OS(Definition);
-  PrintingPolicy Policy =
-  printingPolicyForDecls(D->getASTContext().getPrintingPolicy());
-  Policy.IncludeTagDefinition = false;
-  Policy.SuppressTemplateArgsInCXXConstructors = true;
-  Policy.SuppressTagKeyword = true;
-  D->print(OS, Policy);
+  D->print(OS, PP);
   OS.flush();
   return Definition;
 }
 
-std::string printType(QualType QT, const PrintingPolicy &Policy) {
+std::string printType(QualType QT, const PrintingPolicy &PP) {
   // TypePrinter doesn't resolve decltypes, so resolve them here.
   // FIXME: This doesn't handle composite types that contain a decltype in them.
   // We should rather have a printing policy for that.
   while (!QT.isNull() && QT->isDecltypeType())
 QT = QT->getAs()->getUnderlyingType();
-  return QT.getAsString(Policy);
+  std::string Result;
+  llvm::raw_string_ostream OS(Result);
+  // Special case: if the outer type is a tag type without qualifiers, then
+  // include th

[PATCH] D93221: [ARM] Add clang command line support for -mharden-sls=

2020-12-18 Thread Oliver Stannard (Linaro) via Phabricator via cfe-commits
ostannard accepted this revision.
ostannard added a comment.
This revision is now accepted and ready to land.

Ok, LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93221

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


[clang] 7fef551 - Revert "Revert "[FPEnv] Teach the IRBuilder about invoke's correct use of the strictfp attribute.""

2020-12-18 Thread Kevin P. Neal via cfe-commits

Author: Kevin P. Neal
Date: 2020-12-18T12:42:06-05:00
New Revision: 7fef551cb123d9f1956f8ec7a142bd8a63d25fa9

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

LOG: Revert "Revert "[FPEnv] Teach the IRBuilder about invoke's correct use of 
the strictfp attribute.""

Similar to D69312, and documented in D69839, the IRBuilder needs to add
the strictfp attribute to invoke instructions when constrained floating
point is enabled.

This is try 2, with the test corrected.

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

Added: 
clang/test/CodeGen/exceptions-strictfp.c

Modified: 
llvm/include/llvm/IR/IRBuilder.h

Removed: 




diff  --git a/clang/test/CodeGen/exceptions-strictfp.c 
b/clang/test/CodeGen/exceptions-strictfp.c
new file mode 100644
index ..6f9e9f891b6c
--- /dev/null
+++ b/clang/test/CodeGen/exceptions-strictfp.c
@@ -0,0 +1,37 @@
+// RUN: %clang_cc1 -triple armv7-apple-unknown -ffp-exception-behavior=strict 
-fexperimental-strict-floating-point -emit-llvm -o - %s -fexceptions 
-exception-model=sjlj -fblocks | FileCheck %s
+
+// Verify strictfp attributes on invoke calls (and therefore also on
+// function definitions).
+
+// rdar://problem/8621849
+void test1() {
+  extern void test1_helper(void (^)(int));
+
+  // CHECK: define arm_aapcscc void @test1() [[STRICTFP0:#[0-9]+]] personality 
i8* bitcast (i32 (...)* @__gcc_personality_sj0 to i8*)
+
+  __block int x = 10;
+
+  // CHECK: invoke arm_aapcscc void @test1_helper({{.*}}) [[STRICTFP1:#[0-9]+]]
+  test1_helper(^(int v) { x = v; });
+
+  // CHECK:  landingpad { i8*, i32 }
+  // CHECK-NEXT:   cleanup
+}
+
+void test2_helper();
+void test2() {
+  // CHECK: define arm_aapcscc void @test2() [[STRICTFP0]] personality i8* 
bitcast (i32 (...)* @__gcc_personality_sj0 to i8*) {
+  __block int x = 10;
+  ^{ (void)x; };
+
+  // CHECK: invoke arm_aapcscc void @test2_helper({{.*}}) [[STRICTFP1:#[0-9]+]]
+  test2_helper(5, 6, 7);
+
+  // CHECK:  landingpad { i8*, i32 }
+  // CHECK-NEXT:   cleanup
+}
+void test2_helper(int x, int y) {
+}
+
+// CHECK: attributes [[STRICTFP0]] = { {{.*}}strictfp{{.*}} }
+// CHECK: attributes [[STRICTFP1]] = { strictfp }

diff  --git a/llvm/include/llvm/IR/IRBuilder.h 
b/llvm/include/llvm/IR/IRBuilder.h
index 56005b26a538..6bc5e89453ad 100644
--- a/llvm/include/llvm/IR/IRBuilder.h
+++ b/llvm/include/llvm/IR/IRBuilder.h
@@ -350,7 +350,7 @@ class IRBuilderBase {
 }
   }
 
-  void setConstrainedFPCallAttr(CallInst *I) {
+  void setConstrainedFPCallAttr(CallBase *I) {
 I->addAttribute(AttributeList::FunctionIndex, Attribute::StrictFP);
   }
 
@@ -1088,16 +1088,21 @@ class IRBuilderBase {
ArrayRef Args,
ArrayRef OpBundles,
const Twine &Name = "") {
-return Insert(
-InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args, 
OpBundles),
-Name);
+InvokeInst *II =
+InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args, 
OpBundles);
+if (IsFPConstrained)
+  setConstrainedFPCallAttr(II);
+return Insert(II, Name);
   }
   InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
BasicBlock *NormalDest, BasicBlock *UnwindDest,
ArrayRef Args = None,
const Twine &Name = "") {
-return Insert(InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args),
-  Name);
+InvokeInst *II =
+InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args);
+if (IsFPConstrained)
+  setConstrainedFPCallAttr(II);
+return Insert(II, Name);
   }
 
   InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,



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


[PATCH] D93170: [clang-format][NFC] Expand BreakBeforeBraces examples

2020-12-18 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5e5ef5359742: [clang-format][NFC] Expand BreakBeforeBraces 
examples (authored by HazardyKnusperkeks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93170

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h

Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -720,163 +720,427 @@
   enum BraceBreakingStyle {
 /// Always attach braces to surrounding context.
 /// \code
-///   try {
-/// foo();
-///   } catch () {
+///   namespace N {
+///   enum E {
+/// E1,
+/// E2,
+///   };
+///
+///   class C {
+///   public:
+/// C();
+///   };
+///
+///   bool baz(int i) {
+/// try {
+///   do {
+/// switch (i) {
+/// case 1: {
+///   foobar();
+///   break;
+/// }
+/// default: {
+///   break;
+/// }
+/// }
+///   } while (--i);
+///   return true;
+/// } catch (...) {
+///   handleError();
+///   return false;
+/// }
 ///   }
-///   void foo() { bar(); }
-///   class foo {};
-///   if (foo()) {
-///   } else {
+///
+///   void foo(bool b) {
+/// if (b) {
+///   baz(2);
+/// } else {
+///   baz(5);
+/// }
 ///   }
-///   enum X : int { A, B };
+///
+///   void bar() { foo(true); }
+///   } // namespace N
 /// \endcode
 BS_Attach,
 /// Like ``Attach``, but break before braces on function, namespace and
 /// class definitions.
 /// \code
-///   try {
-/// foo();
-///   } catch () {
-///   }
-///   void foo() { bar(); }
-///   class foo
+///   namespace N
 ///   {
+///   enum E {
+/// E1,
+/// E2,
 ///   };
-///   if (foo()) {
-///   } else {
+///
+///   class C
+///   {
+///   public:
+/// C();
+///   };
+///
+///   bool baz(int i)
+///   {
+/// try {
+///   do {
+/// switch (i) {
+/// case 1: {
+///   foobar();
+///   break;
+/// }
+/// default: {
+///   break;
+/// }
+/// }
+///   } while (--i);
+///   return true;
+/// } catch (...) {
+///   handleError();
+///   return false;
+/// }
+///   }
+///
+///   void foo(bool b)
+///   {
+/// if (b) {
+///   baz(2);
+/// } else {
+///   baz(5);
+/// }
 ///   }
-///   enum X : int { A, B };
+///
+///   void bar() { foo(true); }
+///   } // namespace N
 /// \endcode
 BS_Linux,
 /// Like ``Attach``, but break before braces on enum, function, and record
 /// definitions.
 /// \code
-///   try {
-/// foo();
-///   } catch () {
-///   }
-///   void foo() { bar(); }
-///   class foo
+///   namespace N {
+///   enum E
 ///   {
+/// E1,
+/// E2,
 ///   };
-///   if (foo()) {
-///   } else {
+///
+///   class C
+///   {
+///   public:
+/// C();
+///   };
+///
+///   bool baz(int i)
+///   {
+/// try {
+///   do {
+/// switch (i) {
+/// case 1: {
+///   foobar();
+///   break;
+/// }
+/// default: {
+///   break;
+/// }
+/// }
+///   } while (--i);
+///   return true;
+/// } catch (...) {
+///   handleError();
+///   return false;
+/// }
+///   }
+///
+///   void foo(bool b)
+///   {
+/// if (b) {
+///   baz(2);
+/// } else {
+///   baz(5);
+/// }
 ///   }
-///   enum X : int { A, B };
+///
+///   void bar() { foo(true); }
+///   } // namespace N
 /// \endcode
 BS_Mozilla,
 /// Like ``Attach``, but break before function definitions, ``catch``, and
 /// ``else``.
 /// \code
-///   try {
-/// foo();
-///   }
-///   catch () {
-///   }
-///   void foo() { bar(); }
-///   class foo {
+///   namespace N {
+///   enum E {
+/// E1,
+/// E2,
 ///   };
-///   if (foo()) {
+///
+///   class C {
+///   public:
+/// C();
+///   };
+///
+///   bool baz(int i)
+///   {
+/// try {
+///  

[clang] 5e5ef53 - [clang-format][NFC] Expand BreakBeforeBraces examples

2020-12-18 Thread Björn Schäpers via cfe-commits

Author: Björn Schäpers
Date: 2020-12-18T19:08:03+01:00
New Revision: 5e5ef5359742c3feb6f41058a356a28c7ab3ea6d

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

LOG: [clang-format][NFC] Expand BreakBeforeBraces examples

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index f63ed168f099..32942648378b 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1205,16 +1205,47 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
-  try {
-foo();
-  } catch () {
+  namespace N {
+  enum E {
+E1,
+E2,
+  };
+
+  class C {
+  public:
+C();
+  };
+
+  bool baz(int i) {
+try {
+  do {
+switch (i) {
+case 1: {
+  foobar();
+  break;
+}
+default: {
+  break;
+}
+}
+  } while (--i);
+  return true;
+} catch (...) {
+  handleError();
+  return false;
+}
   }
-  void foo() { bar(); }
-  class foo {};
-  if (foo()) {
-  } else {
+
+  void foo(bool b) {
+if (b) {
+  baz(2);
+} else {
+  baz(5);
+}
   }
-  enum X : int { A, B };
+
+  void bar() { foo(true); }
+  } // namespace N
 
   * ``BS_Linux`` (in configuration: ``Linux``)
 Like ``Attach``, but break before braces on function, namespace and
@@ -1222,18 +1253,51 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
-  try {
-foo();
-  } catch () {
-  }
-  void foo() { bar(); }
-  class foo
+  namespace N
   {
+  enum E {
+E1,
+E2,
   };
-  if (foo()) {
-  } else {
+
+  class C
+  {
+  public:
+C();
+  };
+
+  bool baz(int i)
+  {
+try {
+  do {
+switch (i) {
+case 1: {
+  foobar();
+  break;
+}
+default: {
+  break;
+}
+}
+  } while (--i);
+  return true;
+} catch (...) {
+  handleError();
+  return false;
+}
   }
-  enum X : int { A, B };
+
+  void foo(bool b)
+  {
+if (b) {
+  baz(2);
+} else {
+  baz(5);
+}
+  }
+
+  void bar() { foo(true); }
+  } // namespace N
 
   * ``BS_Mozilla`` (in configuration: ``Mozilla``)
 Like ``Attach``, but break before braces on enum, function, and record
@@ -1241,18 +1305,51 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
-  try {
-foo();
-  } catch () {
-  }
-  void foo() { bar(); }
-  class foo
+  namespace N {
+  enum E
   {
+E1,
+E2,
   };
-  if (foo()) {
-  } else {
+
+  class C
+  {
+  public:
+C();
+  };
+
+  bool baz(int i)
+  {
+try {
+  do {
+switch (i) {
+case 1: {
+  foobar();
+  break;
+}
+default: {
+  break;
+}
+}
+  } while (--i);
+  return true;
+} catch (...) {
+  handleError();
+  return false;
+}
   }
-  enum X : int { A, B };
+
+  void foo(bool b)
+  {
+if (b) {
+  baz(2);
+} else {
+  baz(5);
+}
+  }
+
+  void bar() { foo(true); }
+  } // namespace N
 
   * ``BS_Stroustrup`` (in configuration: ``Stroustrup``)
 Like ``Attach``, but break before function definitions, ``catch``, and
@@ -1260,75 +1357,175 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
-  try {
-foo();
-  }
-  catch () {
-  }
-  void foo() { bar(); }
-  class foo {
+  namespace N {
+  enum E {
+E1,
+E2,
   };
-  if (foo()) {
+
+  class C {
+  public:
+C();
+  };
+
+  bool baz(int i)
+  {
+try {
+  do {
+switch (i) {
+case 1: {
+  foobar();
+  break;
+}
+default: {
+  break;
+}
+}
+  } while (--i);
+  return true;
+}
+catch (...) {
+  handleError();
+  return false;
+}
   }
-  else {
+

[clang] 897c985 - [InstCombine] Canonicalize SPF to abs intrinsic

2020-12-18 Thread Roman Lebedev via cfe-commits

Author: Roman Lebedev
Date: 2020-12-18T21:18:14+03:00
New Revision: 897c985e1e21927b2870f964bb07ff293bd74407

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

LOG: [InstCombine] Canonicalize SPF to abs intrinsic

This patch enables canonicalization of SPF_ABS and SPF_ABS
to the abs intrinsic.

This is a recommit, the original try was
05d4c4ebc2fb006b8a2bd05b24c6aba10dd2eef8,
but it was reverted due to an apparent miscompile,
which since then has just been fixed by the previous commit.

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

Added: 


Modified: 
clang/test/CodeGen/builtins-wasm.c
llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
llvm/test/Transforms/InstCombine/abs-1.ll
llvm/test/Transforms/InstCombine/abs_abs.ll
llvm/test/Transforms/InstCombine/call-callconv.ll
llvm/test/Transforms/InstCombine/cttz-abs.ll
llvm/test/Transforms/InstCombine/icmp.ll
llvm/test/Transforms/InstCombine/max-of-nots.ll
llvm/test/Transforms/InstCombine/select_meta.ll
llvm/test/Transforms/InstCombine/sub-of-negatible.ll
llvm/test/Transforms/PhaseOrdering/X86/vector-reductions.ll
llvm/test/Transforms/PhaseOrdering/min-max-abs-cse.ll

Removed: 




diff  --git a/clang/test/CodeGen/builtins-wasm.c 
b/clang/test/CodeGen/builtins-wasm.c
index 92fd9843e44b..76dd2622fe2f 100644
--- a/clang/test/CodeGen/builtins-wasm.c
+++ b/clang/test/CodeGen/builtins-wasm.c
@@ -384,26 +384,20 @@ u8x16 sub_saturate_u_i8x16(u8x16 x, u8x16 y) {
 
 i8x16 abs_i8x16(i8x16 v) {
   return __builtin_wasm_abs_i8x16(v);
-  // WEBASSEMBLY: %neg = sub <16 x i8> zeroinitializer, %v
-  // WEBASSEMBLY: %abscond = icmp slt <16 x i8> %v, zeroinitializer
-  // WEBASSEMBLY: %abs = select <16 x i1> %abscond, <16 x i8> %neg, <16 x i8> 
%v
-  // WEBASSEMBLY: ret <16 x i8> %abs
+  // WEBASSEMBLY: call <16 x i8> @llvm.abs.v16i8(<16 x i8> %v, i1 false)
+  // WEBASSEMBLY-NEXT: ret
 }
 
 i16x8 abs_i16x8(i16x8 v) {
   return __builtin_wasm_abs_i16x8(v);
-  // WEBASSEMBLY: %neg = sub <8 x i16> zeroinitializer, %v
-  // WEBASSEMBLY: %abscond = icmp slt <8 x i16> %v, zeroinitializer
-  // WEBASSEMBLY: %abs = select <8 x i1> %abscond, <8 x i16> %neg, <8 x i16> %v
-  // WEBASSEMBLY: ret <8 x i16> %abs
+  // WEBASSEMBLY: call <8 x i16> @llvm.abs.v8i16(<8 x i16> %v, i1 false)
+  // WEBASSEMBLY-NEXT: ret
 }
 
 i32x4 abs_i32x4(i32x4 v) {
   return __builtin_wasm_abs_i32x4(v);
-  // WEBASSEMBLY: %neg = sub <4 x i32> zeroinitializer, %v
-  // WEBASSEMBLY: %abscond = icmp slt <4 x i32> %v, zeroinitializer
-  // WEBASSEMBLY: %abs = select <4 x i1> %abscond, <4 x i32> %neg, <4 x i32> %v
-  // WEBASSEMBLY: ret <4 x i32> %abs
+  // WEBASSEMBLY: call <4 x i32> @llvm.abs.v4i32(<4 x i32> %v, i1 false)
+  // WEBASSEMBLY-NEXT: ret
 }
 
 i8x16 min_s_i8x16(i8x16 x, i8x16 y) {

diff  --git a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
index d6f8d2dcc7ce..e05fa4ffa403 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
@@ -1047,89 +1047,28 @@ static Instruction 
*canonicalizeMinMaxWithConstant(SelectInst &Sel,
   return &Sel;
 }
 
-/// There are many select variants for each of ABS/NABS.
-/// In matchSelectPattern(), there are 
diff erent compare constants, compare
-/// predicates/operands and select operands.
-/// In isKnownNegation(), there are 
diff erent formats of negated operands.
-/// Canonicalize all these variants to 1 pattern.
-/// This makes CSE more likely.
 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
 InstCombinerImpl &IC) {
   if (!Cmp.hasOneUse() || !isa(Cmp.getOperand(1)))
 return nullptr;
 
-  // Choose a sign-bit check for the compare (likely simpler for codegen).
-  // ABS:  (X hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
-  return nullptr;
+  bool IntMinIsPoison = match(RHS, m_NSWNeg(m_Specific(LHS)));
+  Constant *IntMinIsPoisonC =
+  ConstantInt::get(Type::getInt1Ty(Sel.getContext()), IntMinIsPoison);
+  Instruction *Abs =
+  IC.Builder.CreateBinaryIntrinsic(Intrinsic::abs, LHS, IntMinIsPoisonC);
 
-  // Create the canonical compare: icmp slt LHS 0.
-  if (!CmpCanonicalized) {
-Cmp.setPredicate(ICmpInst::ICMP_SLT);
-Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
-if (CmpUsesNegatedOp)
-  Cmp.setOperand(0, LHS);
-  }
-
-  // Create the canonical RHS: RHS = sub (0, LHS).
-  if (!RHSCanonicalized) {
-assert(RHS->hasOneUse() && "RHS use number is not right");
-RHS = IC.Builder.CreateNeg(LHS);
-if (TVal == LHS) {
-  // Replace false value.
-  IC.replaceOperand(Sel, 2, RHS);
-  FVal = RHS;
-} else 

[PATCH] D87188: [InstCombine] Canonicalize SPF to abs intrinc

2020-12-18 Thread Roman Lebedev via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG897c985e1e21: [InstCombine] Canonicalize SPF to abs 
intrinsic (authored by lebedev.ri).

Changed prior to commit:
  https://reviews.llvm.org/D87188?vs=310855&id=312846#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87188

Files:
  clang/test/CodeGen/builtins-wasm.c
  llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
  llvm/test/Transforms/InstCombine/abs-1.ll
  llvm/test/Transforms/InstCombine/abs_abs.ll
  llvm/test/Transforms/InstCombine/call-callconv.ll
  llvm/test/Transforms/InstCombine/cttz-abs.ll
  llvm/test/Transforms/InstCombine/icmp.ll
  llvm/test/Transforms/InstCombine/max-of-nots.ll
  llvm/test/Transforms/InstCombine/select_meta.ll
  llvm/test/Transforms/InstCombine/sub-of-negatible.ll
  llvm/test/Transforms/PhaseOrdering/X86/vector-reductions.ll
  llvm/test/Transforms/PhaseOrdering/min-max-abs-cse.ll

Index: llvm/test/Transforms/PhaseOrdering/min-max-abs-cse.ll
===
--- llvm/test/Transforms/PhaseOrdering/min-max-abs-cse.ll
+++ llvm/test/Transforms/PhaseOrdering/min-max-abs-cse.ll
@@ -33,10 +33,8 @@
 
 define i8 @abs_swapped(i8 %a) {
 ; CHECK-LABEL: @abs_swapped(
-; CHECK-NEXT:[[NEG:%.*]] = sub i8 0, [[A:%.*]]
-; CHECK-NEXT:[[CMP1:%.*]] = icmp slt i8 [[A]], 0
-; CHECK-NEXT:[[M1:%.*]] = select i1 [[CMP1]], i8 [[NEG]], i8 [[A]]
-; CHECK-NEXT:ret i8 [[M1]]
+; CHECK-NEXT:[[TMP1:%.*]] = call i8 @llvm.abs.i8(i8 [[A:%.*]], i1 false)
+; CHECK-NEXT:ret i8 [[TMP1]]
 ;
   %neg = sub i8 0, %a
   %cmp1 = icmp sgt i8 %a, 0
@@ -81,9 +79,8 @@
 
 define i8 @nabs_different_constants(i8 %a) {
 ; CHECK-LABEL: @nabs_different_constants(
-; CHECK-NEXT:[[NEG:%.*]] = sub i8 0, [[A:%.*]]
-; CHECK-NEXT:[[CMP1:%.*]] = icmp slt i8 [[A]], 0
-; CHECK-NEXT:[[M1:%.*]] = select i1 [[CMP1]], i8 [[A]], i8 [[NEG]]
+; CHECK-NEXT:[[TMP1:%.*]] = call i8 @llvm.abs.i8(i8 [[A:%.*]], i1 false)
+; CHECK-NEXT:[[M1:%.*]] = sub i8 0, [[TMP1]]
 ; CHECK-NEXT:ret i8 [[M1]]
 ;
   %neg = sub i8 0, %a
Index: llvm/test/Transforms/PhaseOrdering/X86/vector-reductions.ll
===
--- llvm/test/Transforms/PhaseOrdering/X86/vector-reductions.ll
+++ llvm/test/Transforms/PhaseOrdering/X86/vector-reductions.ll
@@ -71,11 +71,9 @@
 ; CHECK-NEXT:[[TMP2:%.*]] = bitcast i32* [[VEC1:%.*]] to <4 x i32>*
 ; CHECK-NEXT:[[TMP3:%.*]] = load <4 x i32>, <4 x i32>* [[TMP2]], align 4
 ; CHECK-NEXT:[[TMP4:%.*]] = sub nsw <4 x i32> [[TMP1]], [[TMP3]]
-; CHECK-NEXT:[[TMP5:%.*]] = icmp slt <4 x i32> [[TMP4]], zeroinitializer
-; CHECK-NEXT:[[TMP6:%.*]] = sub nsw <4 x i32> zeroinitializer, [[TMP4]]
-; CHECK-NEXT:[[TMP7:%.*]] = select <4 x i1> [[TMP5]], <4 x i32> [[TMP6]], <4 x i32> [[TMP4]]
-; CHECK-NEXT:[[TMP8:%.*]] = call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> [[TMP7]])
-; CHECK-NEXT:[[CMP5_NOT:%.*]] = icmp sle i32 [[TMP8]], [[TOLERANCE:%.*]]
+; CHECK-NEXT:[[TMP5:%.*]] = call <4 x i32> @llvm.abs.v4i32(<4 x i32> [[TMP4]], i1 true)
+; CHECK-NEXT:[[TMP6:%.*]] = call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> [[TMP5]])
+; CHECK-NEXT:[[CMP5_NOT:%.*]] = icmp sle i32 [[TMP6]], [[TOLERANCE:%.*]]
 ; CHECK-NEXT:[[COND6:%.*]] = zext i1 [[CMP5_NOT]] to i32
 ; CHECK-NEXT:ret i32 [[COND6]]
 ;
Index: llvm/test/Transforms/InstCombine/sub-of-negatible.ll
===
--- llvm/test/Transforms/InstCombine/sub-of-negatible.ll
+++ llvm/test/Transforms/InstCombine/sub-of-negatible.ll
@@ -1296,9 +1296,8 @@
 ; CHECK-LABEL: @negate_abs(
 ; CHECK-NEXT:[[T0:%.*]] = sub i8 0, [[X:%.*]]
 ; CHECK-NEXT:call void @use8(i8 [[T0]])
-; CHECK-NEXT:[[T1:%.*]] = icmp slt i8 [[X]], 0
-; CHECK-NEXT:[[TMP1:%.*]] = select i1 [[T1]], i8 [[X]], i8 [[T0]], !prof !0
-; CHECK-NEXT:[[T3:%.*]] = add i8 [[TMP1]], [[Y:%.*]]
+; CHECK-NEXT:[[TMP1:%.*]] = call i8 @llvm.abs.i8(i8 [[X]], i1 false)
+; CHECK-NEXT:[[T3:%.*]] = sub i8 [[Y:%.*]], [[TMP1]]
 ; CHECK-NEXT:ret i8 [[T3]]
 ;
   %t0 = sub i8 0, %x
@@ -1312,8 +1311,7 @@
 ; CHECK-LABEL: @negate_nabs(
 ; CHECK-NEXT:[[T0:%.*]] = sub i8 0, [[X:%.*]]
 ; CHECK-NEXT:call void @use8(i8 [[T0]])
-; CHECK-NEXT:[[T1:%.*]] = icmp slt i8 [[X]], 0
-; CHECK-NEXT:[[TMP1:%.*]] = select i1 [[T1]], i8 [[T0]], i8 [[X]], !prof !0
+; CHECK-NEXT:[[TMP1:%.*]] = call i8 @llvm.abs.i8(i8 [[X]], i1 false)
 ; CHECK-NEXT:[[T3:%.*]] = add i8 [[TMP1]], [[Y:%.*]]
 ; CHECK-NEXT:ret i8 [[T3]]
 ;
Index: llvm/test/Transforms/InstCombine/select_meta.ll
===
--- llvm/test/Transforms/InstCombine/select_meta.ll
+++ llvm/test/Transforms/InstCombine/select_meta.ll
@@ -5,9 +5,9 @@
 
 

[PATCH] D87188: [InstCombine] Canonicalize SPF to abs intrinc

2020-12-18 Thread Roman Lebedev via Phabricator via cfe-commits
lebedev.ri added a comment.

Once again, thank you @mstorsjo and @dmgreen!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87188

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


[PATCH] D93553: [clangd] Make our printing policies for Hover more consistent, especially tags

2020-12-18 Thread Quentin Chateau via Phabricator via cfe-commits
qchateau added a comment.

Looks good to me, it removes a lot of duplication and corner cases.

I'd have printed the tag for reference and pointers as well (`class Foo*` 
instead of `Foo*`). I don't think `Foo*` is much more understandable than 
`Foo`, so we decide that printing `class Foo` is easier to understand for the 
user, we should print `class Foo*` as well. 
But I agree it's even less idiomatic, so I won't argue with your choice.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D93553

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


  1   2   >