[PATCH] D112013: [clang][ASTImporter] Fix for importing functions with EST_Unevaluated prototype.

2021-10-21 Thread Balázs Kéri via Phabricator via cfe-commits
balazske marked 4 inline comments as done.
balazske added inline comments.



Comment at: clang/unittests/AST/ASTImporterTest.cpp:6189
+  // Check if the import was correct.
+  CXXConstructorDecl *ToCtor = *ToL->ctor_begin();
+  const auto *ToFPT = ToCtor->getType()->getAs();

steakhal wrote:
> Please assert that the number of constructors is correct.
> I would rather recommend doing so in the //from// case as well.
Here the goal is only to get a copy constructor, not to test if all 
constructors are imported. To get the constructor count relatively much 
additional code is needed (there is no function for it).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112013

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


[PATCH] D112158: mips: fix search path for multilib o32

2021-10-21 Thread Simon Atanasyan via Phabricator via cfe-commits
atanasyan added a comment.

- Does this problem exist on all versions of Debian or starting from specific 
version only?
- This fix needs test cases. Take a look at "Check linker invocation on Debian 
6 MIPS 32/64-bit" in the `clang/test/Driver/linux-ld.c` for example.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112158

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


[PATCH] D111870: [clangd] Add a way to enable IncludeCleaner through config

2021-10-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 381157.
kbobyrev added a comment.

Elaborate a bit more on Strict mode for UnusedHeaders.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111870

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/Diagnostics.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1464,6 +1464,45 @@
   AllOf(Diag(Test.range("deprecated"), "'bar' is deprecated"),
 WithTag(DiagnosticTag::Deprecated;
 }
+
+TEST(DiagnosticsTest, IncludeCleaner) {
+  Annotations Test(R"cpp(
+$fix[[  $diag[[#include "unused.h"]]
+]]  #include "used.h"
+
+  void foo() {
+used();
+  }
+  )cpp");
+  TestTU TU;
+  TU.Code = Test.code().str();
+  TU.AdditionalFiles["unused.h"] = R"cpp(
+void unused() {}
+  )cpp";
+  TU.AdditionalFiles["used.h"] = R"cpp(
+void used() {}
+  )cpp";
+  // Off by default.
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+  Config Cfg;
+  Cfg.Diagnostics.IncludeCleaner.UnusedHeaders =
+  Config::UnusedHeadersPolicy::Strict;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  UnorderedElementsAre(
+  AllOf(Diag(Test.range("diag"), "included header is not used"),
+WithTag(DiagnosticTag::Unnecessary), DiagSource(Diag::Clangd),
+WithFix(Fix(Test.range("fix"), "", "remove unused header");
+  Cfg.Diagnostics.SuppressAll = true;
+  WithContextValue SuppressAllWithCfg(Config::Key, std::move(Cfg));
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+  Cfg.Diagnostics.SuppressAll = false;
+  Cfg.Diagnostics.Suppress = {"clangd-unused-header"};
+  WithContextValue SuppressFilterWithCfg(Config::Key, std::move(Cfg));
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -67,6 +67,8 @@
 CheckOptions:
   IgnoreMacros: true
   example-check.ExampleOption: 0
+  IncludeCleaner:
+UnusedHeaders: Strict
   )yaml";
   auto Results = Fragment::parseYAML(YAML, "config.yaml", Diags.callback());
   EXPECT_THAT(Diags.Diagnostics, IsEmpty());
@@ -83,6 +85,9 @@
   EXPECT_THAT(Results[3].Diagnostics.ClangTidy.CheckOptions,
   ElementsAre(PairVal("IgnoreMacros", "true"),
   PairVal("example-check.ExampleOption", "0")));
+  EXPECT_TRUE(Results[3].Diagnostics.IncludeCleaner.UnusedHeaders);
+  EXPECT_EQ("Strict",
+*Results[3].Diagnostics.IncludeCleaner.UnusedHeaders.getValue());
 }
 
 TEST(ParseYAML, Locations) {
Index: clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
@@ -244,6 +244,25 @@
   }
 }
 
+TEST_F(ConfigCompileTests, DiagnosticsIncludeCleaner) {
+  // Defaults to None.
+  EXPECT_TRUE(compileAndApply());
+  EXPECT_EQ(Conf.Diagnostics.IncludeCleaner.UnusedHeaders,
+Config::UnusedHeadersPolicy::None);
+
+  Frag = {};
+  Frag.Diagnostics.IncludeCleaner.UnusedHeaders.emplace("None");
+  EXPECT_TRUE(compileAndApply());
+  EXPECT_EQ(Conf.Diagnostics.IncludeCleaner.UnusedHeaders,
+Config::UnusedHeadersPolicy::None);
+
+  Frag = {};
+  Frag.Diagnostics.IncludeCleaner.UnusedHeaders.emplace("Strict");
+  EXPECT_TRUE(compileAndApply());
+  EXPECT_EQ(Conf.Diagnostics.IncludeCleaner.UnusedHeaders,
+Config::UnusedHeadersPolicy::Strict);
+}
+
 TEST_F(ConfigCompileTests, DiagnosticSuppression) {
   Frag.Diagnostics.Suppress.emplace_back("bugprone-use-after-move");
   Frag.Diagnostics.Suppress.emplace_back("unreachable-code");
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -18,6 +18,7 @@
 #include "FeatureModule.

[PATCH] D112013: [clang][ASTImporter] Fix for importing functions with EST_Unevaluated prototype.

2021-10-21 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.

I love it.




Comment at: clang/unittests/AST/ASTImporterTest.cpp:6189
+  // Check if the import was correct.
+  CXXConstructorDecl *ToCtor = *ToL->ctor_begin();
+  const auto *ToFPT = ToCtor->getType()->getAs();

balazske wrote:
> steakhal wrote:
> > Please assert that the number of constructors is correct.
> > I would rather recommend doing so in the //from// case as well.
> Here the goal is only to get a copy constructor, not to test if all 
> constructors are imported. To get the constructor count relatively much 
> additional code is needed (there is no function for it).
I see. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112013

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


[PATCH] D106681: [analyzer][NFCI] Move a block from `getBindingForElement` to separate functions

2021-10-21 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added inline comments.



Comment at: clang/test/Analysis/initialization.c:103
+void glob_arr_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}

ASDenysPetrov wrote:
> ASDenysPetrov wrote:
> > steakhal wrote:
> > > martong wrote:
> > > > ASDenysPetrov wrote:
> > > > > steakhal wrote:
> > > > > > I'm pretty sure we should not get `Unknown` for simply loading from 
> > > > > > a global variable.
> > > > > > That would imply that loading two times subsequently we could not 
> > > > > > prove that the value remained the same.
> > > > > > But that should remain the same, thus compare equal unless some 
> > > > > > other code modifier that memory region.
> > > > > > 
> > > > > > That could happen for two reasons:
> > > > > > 1) There is a racecondition, and another thread modified that 
> > > > > > location. But that would be UB, so that could not happen.
> > > > > > 2) The global variable is //volatile//, so the hardware might 
> > > > > > changed its content- but this global is not volatile so this does 
> > > > > > not apply.
> > > > > > 
> > > > > > That being said, this load should have resulted in a //fresh// 
> > > > > > conjured symbolic value instead of //unknown//.
> > > > > > Could you please check if it did result in //unknown// before your 
> > > > > > patch, or you did introduce this behavior?
> > > > > I'm not sure I caught your thoughts.
> > > > > But I think the things is much simplier:
> > > > > `clang_analyzer_eval` can only produce `UNKNOWN` or `TRUE` or 
> > > > > `FALSE`. If we know the constraint of `glob_arr_no_init[2]` we return 
> > > > > `TRUE` or `FALSE`, and `UNKNOWN` otherwise.
> > > > > But in fact I should use `clang_analyzer_dump` here instead of 
> > > > > `clang_analyzer_eval`. This is actually my fault. I'll update this.
> > > > > Could you please check if it did result in unknown before your patch, 
> > > > > or you did introduce this behavior?
> > > > 
> > > > I've just checked it, it was `Unknown` before this patch as well. 
> > > > And actually, that is wrong because the array has static storage 
> > > > duration and as such, we know that it is initialized with zeros 
> > > > according to the C standard. But, that should be addressed in a 
> > > > follow-up patch (if someone has the capacity).
> > > > https://stackoverflow.com/questions/32708161/value-of-uninitialized-elements-in-array-of-c-language/32708288
> > > Oh true. I was actually tricked by the `initialization.cpp:38`, where I 
> > > actually caught this. And in that case, you use `dump()` yet you get 
> > > `Unknown` as a result. But the issue remains the same.
> > C++ also states about zero-initialization for static storage lifetime 
> > duration: http://eel.is/c++draft/basic.start.static#2
> > I think it will be among my next patches.
> > And in that case, you use dump() yet you get Unknown as a result. But the 
> > issue remains the same.
> I just realized that I was confused as well :) The `dump` returns a symbolic 
> value like `reg_$0`, **not** 
> `Unknown`. So my intention of using `eval` was deliberate. Anyway we should 
> improve this to produce `FALSE` instead of `UNKNOWN`, since it has a //static 
> storage//.
It's a really complex topic. I would highly recommend taking baby steps to 
improve this area.

In C, you might have a chance to accomplish something, but in C++ static 
globals might be initialized by running a constructor, which means arbitrary 
user-defined code. This is actually why we disabled similar logic in the 
`RegionStore::getInitialStore()`. I highly recommend taking a look.

Consider this code:
```lang=C++
// TU 1:
#include 
static int a;  // zero-initialized initially
int *p2a = &a; // escapes the address of 'a'

int main() {
  printf("%d\n", a); // reports 42
}

// TU 2:
extern int *p2a;
static bool sentinel = (*p2a = 42, false);
```


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

https://reviews.llvm.org/D106681

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


[PATCH] D90996: [clang-format] Add --staged/--cached option to git-clang-format

2021-10-21 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

FYI I doubt you'll get a response from the original clang-format code owners as 
they have moved on. But I can take a look

Before giving this the ok, I'd like to understand a little more.

if I make a (bad)formatting change in a file which is not already staged and 
run `git clang-format` it will say

  $ git clang-format
  The following files would be modified but have unstaged changes:
  M   clang/lib/Format/Format.cpp
  Please commit, stage, or stash them first.

If I make a formatting change to a file that is untracked in the current 
directory, then it will NOT format those files

I have to do `git add Format.cpp`  for it tol format my file

  $ git clang-format
  changed files:
  clang/lib/Format/Format.cpp

i.e. I seem to ALWAYS have to stage files in order to have `git clang-format` 
do anything

So I'm kind of unclear as to what doing --staged will do differently? (is it to 
simply ignore the `The following files would be modified but have unstaged 
changes:` warning?

Did I misunderstand?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90996

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


[PATCH] D110833: [clang-format] Refactor SpaceBeforeParens to add flags

2021-10-21 Thread Christian Rayroud via Phabricator via cfe-commits
crayroud updated this revision to Diff 381168.
crayroud added a comment.

This new version adds the possibility to configure space before opening 
parentheses independently from one another. Instead of creating a new SBPO_ 
mode for each combinations.


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

https://reviews.llvm.org/D110833

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -14133,6 +14133,64 @@
   verifyFormat("X A::operator++ (T);", SomeSpace);
   verifyFormat("int x = int (y);", SomeSpace);
   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
+
+  FormatStyle SomeSpace2 = getLLVMStyle();
+  SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  SomeSpace2.SpaceBeforeParensFlags = {}; // Reset all flags to false
+  SomeSpace2.SpaceBeforeParensFlags.AfterControlStatements = true;
+  SomeSpace2.SpaceBeforeParensFlags.AfterFunctionDefinitionName = true;
+
+  verifyFormat("int f();", SomeSpace2);
+  verifyFormat("void f (int a, T b) {\n"
+   "  while (true)\n"
+   "continue;\n"
+   "}",
+   SomeSpace2);
+  verifyFormat("if (true)\n"
+   "  f();\n"
+   "else if (true)\n"
+   "  f();",
+   SomeSpace2);
+  verifyFormat("do {\n"
+   "  do_something();\n"
+   "} while (something());",
+   SomeSpace2);
+  verifyFormat("switch (x) {\n"
+   "default:\n"
+   "  break;\n"
+   "}",
+   SomeSpace2);
+  verifyFormat("A::A () : a(1) {}", SomeSpace2);
+  verifyFormat("void f() __attribute__((asdf));", SomeSpace2);
+  verifyFormat("*(&a + 1);\n"
+   "&((&a)[1]);\n"
+   "a[(b + c) * d];\n"
+   "(((a + 1) * 2) + 3) * 4;",
+   SomeSpace2);
+  verifyFormat("#define A(x) x", SomeSpace2);
+  verifyFormat("#define A (x) x", SomeSpace2);
+  verifyFormat("#if defined(x)\n"
+   "#endif",
+   SomeSpace2);
+  verifyFormat("auto i = std::make_unique(5);", SomeSpace2);
+  verifyFormat("size_t x = sizeof(x);", SomeSpace2);
+  verifyFormat("auto f(int x) -> decltype(x);", SomeSpace2);
+  verifyFormat("auto f(int x) -> typeof(x);", SomeSpace2);
+  verifyFormat("auto f(int x) -> _Atomic(x);", SomeSpace2);
+  verifyFormat("auto f(int x) -> __underlying_type(x);", SomeSpace2);
+  verifyFormat("int f(T x) noexcept(x.create());", SomeSpace2);
+  verifyFormat("alignas(128) char a[128];", SomeSpace2);
+  verifyFormat("size_t x = alignof(MyType);", SomeSpace2);
+  verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
+   SomeSpace2);
+  verifyFormat("int f() throw(Deprecated);", SomeSpace2);
+  verifyFormat("typedef void (*cb)(int);", SomeSpace2);
+  verifyFormat("T A::operator()();", SomeSpace2);
+  verifyFormat("X A::operator++(T);", SomeSpace2);
+  verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
+  verifyFormat("int x = int(y);", SomeSpace2);
+  verifyFormat("M (std::size_t R, std::size_t C) : C(C), data(R) {}",
+   SomeSpace2);
 }
 
 TEST_F(FormatTest, SpaceAfterLogicalNot) {
@@ -18631,6 +18689,8 @@
   FormatStyle::SBPO_ControlStatementsExceptControlMacros);
   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
   FormatStyle::SBPO_NonEmptyParentheses);
+  CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
+  FormatStyle::SBPO_Custom);
   // For backward compatibility:
   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
   FormatStyle::SBPO_Never);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2906,7 +2906,7 @@
 
 bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
   return Style.SpaceBeforeParens == FormatStyle::SBPO_Always ||
- (Style.SpaceBeforeParens == FormatStyle::SBPO_NonEmptyParentheses &&
+ (Style.SpaceBeforeParensFlags.BeforeNonEmptyParentheses &&
   Right.ParameterCount > 0);
 }
 
@@ -3134,33 +3134,64 @@
   // e.g. template  [[nodiscard]] ...
   if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeSquare))
 return true;
+  // Space before parentheses common for all languages
   if (Right.is(tok::l_paren)) {
 if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
   return true;
-if (Style.SpaceBeforeParens ==
-FormatStyle::SBPO_ControlStatementsEx

[PATCH] D112158: mips: fix search path for multilib o32

2021-10-21 Thread YunQiang Su via Phabricator via cfe-commits
wzssyqa added a comment.

In D112158#3077049 , @atanasyan wrote:

> - Does this problem exist on all versions of Debian or starting from specific 
> version only?

This feature starts from llvm-8. And this problem is since then.

> - This fix needs test cases. Take a look at "Check linker invocation on 
> Debian 6 MIPS 32/64-bit" in the `clang/test/Driver/linux-ld.c` for example.

I will do so.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112158

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


[PATCH] D90996: [clang-format] Add --staged/--cached option to git-clang-format

2021-10-21 Thread Erik Larsson via Phabricator via cfe-commits
ortogonal added a comment.

Thanks for looking into this!

The feature `--staged` adds the possibility to ONLY run clang format on what is 
staged.

Lets say you have main.cpp where you have done two changes. You stage one of 
them using:

  $ git add -p main.cpp

You now have a state were one of the changes is staged for commit but not the 
other.

  $ git status
  On branch master
  Changes to be committed:
(use "git restore --staged ..." to unstage)
  modified:   main.cpp
  
  Changes not staged for commit:
(use "git add ..." to update what will be committed)
(use "git restore ..." to discard changes in working directory)
  modified:   main.cpp

If you now run `git-clang-format` it will format all changes in main.cpp, but 
at this stage adding `--staged` to git-clang-format lets you only format what 
is staged in that file.

I use this together with a git pre-commit-hook to make sure that all my code 
changes are formatted correctly before I commit. But without the `--staged` 
option I end up in situations were my pre-commit-hook fails because I have part 
of a files staged and a formatting error in the part of the file that is not 
staged.

Does this make the need for `--staged` clearer?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90996

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


[PATCH] D112143: [X86][ABI] Do not return float/double from x87 registers when x87 is disabled

2021-10-21 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei updated this revision to Diff 381179.
pengfei added a comment.

Fix bugs. Ready for review now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112143

Files:
  clang/include/clang/Driver/Options.td
  clang/test/Driver/x86-target-features.c
  llvm/lib/Target/X86/X86CallingConv.td
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/test/CodeGen/X86/no-ret-in-x87-reg.ll

Index: llvm/test/CodeGen/X86/no-ret-in-x87-reg.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/no-ret-in-x87-reg.ll
@@ -0,0 +1,102 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=i686-- | FileCheck %s -check-prefix=X87
+; RUN: llc < %s -mtriple=i686-- -mattr=-x87 | FileCheck %s -check-prefixes=NOX87,NOSSE-NOX87
+; RUN: llc < %s -mtriple=i686-- -mattr=-x87,-sse2 | FileCheck %s -check-prefixes=NOX87,NOSSE-NOX87
+; RUN: llc < %s -mtriple=i686-- -mattr=-x87,+sse2 | FileCheck %s -check-prefixes=NOX87,SSE-NOX87
+
+define float @f1(float %a, float %b) nounwind {
+; X87-LABEL: f1:
+; X87:   # %bb.0: # %entry
+; X87-NEXT:flds {{[0-9]+}}(%esp)
+; X87-NEXT:retl
+;
+; NOSSE-NOX87-LABEL: f1:
+; NOSSE-NOX87:   # %bb.0: # %entry
+; NOSSE-NOX87-NEXT:movl {{[0-9]+}}(%esp), %eax
+; NOSSE-NOX87-NEXT:retl
+;
+; SSE-NOX87-LABEL: f1:
+; SSE-NOX87:   # %bb.0: # %entry
+; SSE-NOX87-NEXT:movd {{.*#+}} xmm0 = mem[0],zero,zero,zero
+; SSE-NOX87-NEXT:movd %xmm0, %eax
+; SSE-NOX87-NEXT:retl
+entry:
+  ret float %b
+}
+
+define double @f2(double %a, double %b) nounwind {
+; X87-LABEL: f2:
+; X87:   # %bb.0: # %entry
+; X87-NEXT:fldl {{[0-9]+}}(%esp)
+; X87-NEXT:retl
+;
+; NOX87-LABEL: f2:
+; NOX87:   # %bb.0: # %entry
+; NOX87-NEXT:movl {{[0-9]+}}(%esp), %eax
+; NOX87-NEXT:movl {{[0-9]+}}(%esp), %edx
+; NOX87-NEXT:retl
+entry:
+  ret double %b
+}
+
+define float @f3(float %a, float %b) nounwind {
+; X87-LABEL: f3:
+; X87:   # %bb.0: # %entry
+; X87-NEXT:flds {{[0-9]+}}(%esp)
+; X87-NEXT:fadds {{[0-9]+}}(%esp)
+; X87-NEXT:retl
+;
+; NOSSE-NOX87-LABEL: f3:
+; NOSSE-NOX87:   # %bb.0: # %entry
+; NOSSE-NOX87-NEXT:pushl {{[0-9]+}}(%esp)
+; NOSSE-NOX87-NEXT:pushl {{[0-9]+}}(%esp)
+; NOSSE-NOX87-NEXT:calll __addsf3
+; NOSSE-NOX87-NEXT:addl $8, %esp
+; NOSSE-NOX87-NEXT:retl
+;
+; SSE-NOX87-LABEL: f3:
+; SSE-NOX87:   # %bb.0: # %entry
+; SSE-NOX87-NEXT:movss {{.*#+}} xmm0 = mem[0],zero,zero,zero
+; SSE-NOX87-NEXT:addss {{[0-9]+}}(%esp), %xmm0
+; SSE-NOX87-NEXT:movd %xmm0, %eax
+; SSE-NOX87-NEXT:retl
+entry:
+  %0 = fadd float %a, %b
+  ret float %0
+}
+
+define double @f4(double %a, double %b) nounwind {
+; X87-LABEL: f4:
+; X87:   # %bb.0: # %entry
+; X87-NEXT:fldl {{[0-9]+}}(%esp)
+; X87-NEXT:faddl {{[0-9]+}}(%esp)
+; X87-NEXT:retl
+;
+; NOSSE-NOX87-LABEL: f4:
+; NOSSE-NOX87:   # %bb.0: # %entry
+; NOSSE-NOX87-NEXT:pushl {{[0-9]+}}(%esp)
+; NOSSE-NOX87-NEXT:pushl {{[0-9]+}}(%esp)
+; NOSSE-NOX87-NEXT:pushl {{[0-9]+}}(%esp)
+; NOSSE-NOX87-NEXT:pushl {{[0-9]+}}(%esp)
+; NOSSE-NOX87-NEXT:calll __adddf3
+; NOSSE-NOX87-NEXT:addl $16, %esp
+; NOSSE-NOX87-NEXT:retl
+;
+; SSE-NOX87-LABEL: f4:
+; SSE-NOX87:   # %bb.0: # %entry
+; SSE-NOX87-NEXT:pushl %ebp
+; SSE-NOX87-NEXT:movl %esp, %ebp
+; SSE-NOX87-NEXT:andl $-8, %esp
+; SSE-NOX87-NEXT:subl $8, %esp
+; SSE-NOX87-NEXT:movsd {{.*#+}} xmm0 = mem[0],zero
+; SSE-NOX87-NEXT:addsd 16(%ebp), %xmm0
+; SSE-NOX87-NEXT:movsd %xmm0, (%esp)
+; SSE-NOX87-NEXT:movl (%esp), %eax
+; SSE-NOX87-NEXT:movl {{[0-9]+}}(%esp), %edx
+; SSE-NOX87-NEXT:movl %ebp, %esp
+; SSE-NOX87-NEXT:popl %ebp
+; SSE-NOX87-NEXT:retl
+entry:
+  %0 = fadd double %a, %b
+  ret double %0
+}
Index: llvm/lib/Target/X86/X86ISelLowering.cpp
===
--- llvm/lib/Target/X86/X86ISelLowering.cpp
+++ llvm/lib/Target/X86/X86ISelLowering.cpp
@@ -2367,6 +2367,10 @@
   if (VT == MVT::v3f16 && Subtarget.hasFP16())
 return MVT::v8f16;
 
+  // We will use 2 GPRs for f64 on 32 bits when x87 is disabled.
+  if (VT == MVT::f64 && !Subtarget.is64Bit() && !Subtarget.hasX87())
+return MVT::i32;
+
   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
 }
 
@@ -2390,6 +2394,10 @@
   if (VT == MVT::v3f16 && Subtarget.hasFP16())
 return 1;
 
+  // We have to split f64 into 2 registers on 32 bits if x87 is disabled.
+  if (VT == MVT::f64 && !Subtarget.is64Bit() && !Subtarget.hasX87())
+return 2;
+
   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
 }
 
Index: llvm/lib/Target/X86/X86CallingConv.td
===
--- llvm/lib/Target/X86/X86CallingConv.td
+++ llvm/lib/Target/X86/X86CallingConv.td
@@ -273,7 +2

[clang] b471e25 - [clang] Support __float128 on DragonFlyBSD.

2021-10-21 Thread Frederic Cambus via cfe-commits

Author: Frederic Cambus
Date: 2021-10-21T11:18:52+02:00
New Revision: b471e25a59241b6b60e75494ca7b8d775a4131a2

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

LOG: [clang] Support __float128 on DragonFlyBSD.

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

Added: 


Modified: 
clang/lib/Basic/Targets/OSTargets.h

Removed: 




diff  --git a/clang/lib/Basic/Targets/OSTargets.h 
b/clang/lib/Basic/Targets/OSTargets.h
index 3adb12568eea..f49e2200cd5b 100644
--- a/clang/lib/Basic/Targets/OSTargets.h
+++ b/clang/lib/Basic/Targets/OSTargets.h
@@ -179,6 +179,8 @@ class LLVM_LIBRARY_VISIBILITY DragonFlyBSDTargetInfo
 Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
 Builder.defineMacro("__tune_i386__");
 DefineStd(Builder, "unix", Opts);
+if (this->HasFloat128)
+  Builder.defineMacro("__FLOAT128__");
   }
 
 public:
@@ -188,6 +190,7 @@ class LLVM_LIBRARY_VISIBILITY DragonFlyBSDTargetInfo
 default:
 case llvm::Triple::x86:
 case llvm::Triple::x86_64:
+  this->HasFloat128 = true;
   this->MCountName = ".mcount";
   break;
 }



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


[PATCH] D111760: [clang] Support __float128 on DragonFlyBSD.

2021-10-21 Thread Frederic Cambus via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb471e25a5924: [clang] Support __float128 on DragonFlyBSD. 
(authored by fcambus).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111760

Files:
  clang/lib/Basic/Targets/OSTargets.h


Index: clang/lib/Basic/Targets/OSTargets.h
===
--- clang/lib/Basic/Targets/OSTargets.h
+++ clang/lib/Basic/Targets/OSTargets.h
@@ -179,6 +179,8 @@
 Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
 Builder.defineMacro("__tune_i386__");
 DefineStd(Builder, "unix", Opts);
+if (this->HasFloat128)
+  Builder.defineMacro("__FLOAT128__");
   }
 
 public:
@@ -188,6 +190,7 @@
 default:
 case llvm::Triple::x86:
 case llvm::Triple::x86_64:
+  this->HasFloat128 = true;
   this->MCountName = ".mcount";
   break;
 }


Index: clang/lib/Basic/Targets/OSTargets.h
===
--- clang/lib/Basic/Targets/OSTargets.h
+++ clang/lib/Basic/Targets/OSTargets.h
@@ -179,6 +179,8 @@
 Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
 Builder.defineMacro("__tune_i386__");
 DefineStd(Builder, "unix", Opts);
+if (this->HasFloat128)
+  Builder.defineMacro("__FLOAT128__");
   }
 
 public:
@@ -188,6 +190,7 @@
 default:
 case llvm::Triple::x86:
 case llvm::Triple::x86_64:
+  this->HasFloat128 = true;
   this->MCountName = ".mcount";
   break;
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D90996: [clang-format] Add --staged/--cached option to git-clang-format

2021-10-21 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.
This revision is now accepted and ready to land.

Much, thank you for seeing this over the line,

This LGTM, lets wait a bit in case any of the others have a comment.

I assume you need help committing this? if so we need your name and your email 
address so we can commit it on your behalf


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90996

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


[PATCH] D90996: [clang-format] Add --staged/--cached option to git-clang-format

2021-10-21 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a subscriber: lodato.
MyDeveloperDay added a comment.

@lodato if you are still around (I see no changes since 2017), we may be able 
to add you as a "Co-author" I'm not sure of the policy, (again I would need 
your name and email address)

Co-authored-by: name 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90996

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


[PATCH] D90996: [clang-format] Add --staged/--cached option to git-clang-format

2021-10-21 Thread Erik Larsson via Phabricator via cfe-commits
ortogonal added a comment.

Thanks for all your help (superfast as well)

Yes I need help commiting.

My name: Erik Larsson
My email: karl.erik.lars...@gmail.com


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90996

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


[PATCH] D90996: [clang-format] Add --staged/--cached option to git-clang-format

2021-10-21 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

No problem, I hope your ok if @lodato  gets back to us, I think we should 
probably try and credit them a least a little.

Like I said let us wait a bit for people to have a chance to take a look (I'm 
not in the US hence why I've seen it already),

I doubt there will be a problem as @klimek approved @lodato work (I'm not sure 
why it didn't get landed), but sometimes it just needs someone to be 
persistent, for that I thank you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90996

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


[PATCH] D110833: [clang-format] Refactor SpaceBeforeParens to add flags

2021-10-21 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Fundamentally this looks ok to me, the biggest concern is fathoming out the 
change in TokenAnnotator.cpp to mean the same thing, but I think that is what 
the tests should be for I think.

One think I do is use the output of this

https://clang.llvm.org/docs/ClangFormattedStatus.html

it creates a file in `clang/docs/tools/clang-formatted-files.txt` these are all 
the files that when we last checked were 100% clang-formatted (all 7949) of 
them..

Now be careful because people don't always maintain that clean status (naughty 
them!), but I use to ensure I'm not breaking clang-format (for at least the 
default LLVM style)

so build your own clang-format and then in the llvm-project directory I run

  clang-format -verbose -n -files clang/docs/tools/clang-formatted-files.txt

This will check all the files (reasonably quickly YMMV)

  $ clang-format -verbose -n -files clang/docs/tools/clang-formatted-files.txt
  Clang-formating 7950 files
  Formatting [1/7949] clang/bindings/python/tests/cindex/INPUTS/header1.h
  Formatting [2/7949] clang/bindings/python/tests/cindex/INPUTS/header2.h
  Formatting [3/7949] clang/bindings/python/tests/cindex/INPUTS/header3.h
  Formatting [4/7949] clang/examples/Attribute/Attribute.cpp
  Formatting [5/7949] clang/examples/CallSuperAttribute/CallSuperAttrInfo.cpp
  Formatting [6/7949] clang/include/clang/Analysis/AnalysisDiagnostic.h
  Formatting [7/7949] clang/include/clang/Analysis/BodyFarm.h
  

if your (or they more likely) have broken anything then you'll get a warning 
(in this case it was their fault)

  Formatting [134/7949] 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
  
clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h:19:16: 
warning: code should be clang-formatted [-Wclang-format-violations]
  namespace clang{

But this is a good way of giving clang-format a quick check to ensure its not 
broken anything (over large code base) - You will get failures (as this file is 
out of date)




Comment at: clang/docs/ClangFormatStyleOptions.rst:3708
+SpaceBeforeParens: Custom
+SpaceBeforeParensFlags:
+  AfterFunctionDefinitionName: true

I'm not a massive fan of the use of 'Flags' in the config (I know we use it as 
the typename), naming things is hard!



Comment at: clang/include/clang/Format/Format.h:3416
+  /// \version 14
+  SpaceBeforeParensCustom SpaceBeforeParensFlags;
+

I'm not a massive fan of the word `Flags` here and thoughts?



Comment at: clang/unittests/Format/FormatTest.cpp:14193
+  verifyFormat("M (std::size_t R, std::size_t C) : C(C), data(R) {}",
+   SomeSpace2);
 }

IMHO I think we should see tests for the other combinations of custom (I know 
it might be repeated)


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

https://reviews.llvm.org/D110833

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


[PATCH] D111870: [clangd] Add a way to enable IncludeCleaner through config

2021-10-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 381190.
kbobyrev added a comment.

[clangd] IncludeCleaner: Implement more complicated rules for considering enums 
forward declarations "used"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111870

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/Diagnostics.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -103,6 +103,34 @@
   "struct ^X { enum ^Language { ^CXX = 42, Python = 9000}; };",
   "int Lang = X::CXX;",
   },
+  {
+  "enum class Color;",
+  "enum class Color {};",
+  },
+  {
+  "enum class ^Color : int;",
+  "enum class Color : int {};",
+  },
+  {
+  "enum class Color : int {};",
+  "enum class Color : int;",
+  },
+  {
+  "enum class Color;",
+  "enum class Color {}; Color c;",
+  },
+  {
+  "enum class ^Color : char;",
+  "Color c;",
+  },
+  {
+  "enum class ^Color : char {};",
+  "Color c;",
+  },
+  {
+  "enum class ^Color;",
+  "Color c;",
+  },
   {
   // When a type is resolved via a using declaration, the
   // UsingShadowDecl is not referenced in the AST.
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1464,6 +1464,45 @@
   AllOf(Diag(Test.range("deprecated"), "'bar' is deprecated"),
 WithTag(DiagnosticTag::Deprecated;
 }
+
+TEST(DiagnosticsTest, IncludeCleaner) {
+  Annotations Test(R"cpp(
+$fix[[  $diag[[#include "unused.h"]]
+]]  #include "used.h"
+
+  void foo() {
+used();
+  }
+  )cpp");
+  TestTU TU;
+  TU.Code = Test.code().str();
+  TU.AdditionalFiles["unused.h"] = R"cpp(
+void unused() {}
+  )cpp";
+  TU.AdditionalFiles["used.h"] = R"cpp(
+void used() {}
+  )cpp";
+  // Off by default.
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+  Config Cfg;
+  Cfg.Diagnostics.IncludeCleaner.UnusedHeaders =
+  Config::UnusedHeadersPolicy::Strict;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  UnorderedElementsAre(
+  AllOf(Diag(Test.range("diag"), "included header is not used"),
+WithTag(DiagnosticTag::Unnecessary), DiagSource(Diag::Clangd),
+WithFix(Fix(Test.range("fix"), "", "remove unused header");
+  Cfg.Diagnostics.SuppressAll = true;
+  WithContextValue SuppressAllWithCfg(Config::Key, std::move(Cfg));
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+  Cfg.Diagnostics.SuppressAll = false;
+  Cfg.Diagnostics.Suppress = {"clangd-unused-header"};
+  WithContextValue SuppressFilterWithCfg(Config::Key, std::move(Cfg));
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -67,6 +67,8 @@
 CheckOptions:
   IgnoreMacros: true
   example-check.ExampleOption: 0
+  IncludeCleaner:
+UnusedHeaders: Strict
   )yaml";
   auto Results = Fragment::parseYAML(YAML, "config.yaml", Diags.callback());
   EXPECT_THAT(Diags.Diagnostics, IsEmpty());
@@ -83,6 +85,9 @@
   EXPECT_THAT(Results[3].Diagnostics.ClangTidy.CheckOptions,
   ElementsAre(PairVal("IgnoreMacros", "true"),
   PairVal("example-check.ExampleOption", "0")));
+  EXPECT_TRUE(Results[3].Diagnostics.IncludeCleaner.UnusedHeaders);
+  EXPECT_EQ("Strict",
+*Results[3].Diagnostics.IncludeCleaner.UnusedHeaders.getValue());
 }
 
 TEST(ParseYAML, Locations) {
Index: clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
===
--

[PATCH] D111870: [clangd] Add a way to enable IncludeCleaner through config

2021-10-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 381192.
kbobyrev added a comment.

Prevent accidental changes from getting into this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111870

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/Diagnostics.cpp
  clang-tools-extra/clangd/Diagnostics.h
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
  clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp

Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1464,6 +1464,45 @@
   AllOf(Diag(Test.range("deprecated"), "'bar' is deprecated"),
 WithTag(DiagnosticTag::Deprecated;
 }
+
+TEST(DiagnosticsTest, IncludeCleaner) {
+  Annotations Test(R"cpp(
+$fix[[  $diag[[#include "unused.h"]]
+]]  #include "used.h"
+
+  void foo() {
+used();
+  }
+  )cpp");
+  TestTU TU;
+  TU.Code = Test.code().str();
+  TU.AdditionalFiles["unused.h"] = R"cpp(
+void unused() {}
+  )cpp";
+  TU.AdditionalFiles["used.h"] = R"cpp(
+void used() {}
+  )cpp";
+  // Off by default.
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+  Config Cfg;
+  Cfg.Diagnostics.IncludeCleaner.UnusedHeaders =
+  Config::UnusedHeadersPolicy::Strict;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+  EXPECT_THAT(
+  *TU.build().getDiagnostics(),
+  UnorderedElementsAre(
+  AllOf(Diag(Test.range("diag"), "included header is not used"),
+WithTag(DiagnosticTag::Unnecessary), DiagSource(Diag::Clangd),
+WithFix(Fix(Test.range("fix"), "", "remove unused header");
+  Cfg.Diagnostics.SuppressAll = true;
+  WithContextValue SuppressAllWithCfg(Config::Key, std::move(Cfg));
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+  Cfg.Diagnostics.SuppressAll = false;
+  Cfg.Diagnostics.Suppress = {"clangd-unused-header"};
+  WithContextValue SuppressFilterWithCfg(Config::Key, std::move(Cfg));
+  EXPECT_THAT(*TU.build().getDiagnostics(), IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigYAMLTests.cpp
@@ -67,6 +67,8 @@
 CheckOptions:
   IgnoreMacros: true
   example-check.ExampleOption: 0
+  IncludeCleaner:
+UnusedHeaders: Strict
   )yaml";
   auto Results = Fragment::parseYAML(YAML, "config.yaml", Diags.callback());
   EXPECT_THAT(Diags.Diagnostics, IsEmpty());
@@ -83,6 +85,9 @@
   EXPECT_THAT(Results[3].Diagnostics.ClangTidy.CheckOptions,
   ElementsAre(PairVal("IgnoreMacros", "true"),
   PairVal("example-check.ExampleOption", "0")));
+  EXPECT_TRUE(Results[3].Diagnostics.IncludeCleaner.UnusedHeaders);
+  EXPECT_EQ("Strict",
+*Results[3].Diagnostics.IncludeCleaner.UnusedHeaders.getValue());
 }
 
 TEST(ParseYAML, Locations) {
Index: clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
===
--- clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
+++ clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp
@@ -244,6 +244,25 @@
   }
 }
 
+TEST_F(ConfigCompileTests, DiagnosticsIncludeCleaner) {
+  // Defaults to None.
+  EXPECT_TRUE(compileAndApply());
+  EXPECT_EQ(Conf.Diagnostics.IncludeCleaner.UnusedHeaders,
+Config::UnusedHeadersPolicy::None);
+
+  Frag = {};
+  Frag.Diagnostics.IncludeCleaner.UnusedHeaders.emplace("None");
+  EXPECT_TRUE(compileAndApply());
+  EXPECT_EQ(Conf.Diagnostics.IncludeCleaner.UnusedHeaders,
+Config::UnusedHeadersPolicy::None);
+
+  Frag = {};
+  Frag.Diagnostics.IncludeCleaner.UnusedHeaders.emplace("Strict");
+  EXPECT_TRUE(compileAndApply());
+  EXPECT_EQ(Conf.Diagnostics.IncludeCleaner.UnusedHeaders,
+Config::UnusedHeadersPolicy::Strict);
+}
+
 TEST_F(ConfigCompileTests, DiagnosticSuppression) {
   Frag.Diagnostics.Suppress.emplace_back("bugprone-use-after-move");
   Frag.Diagnostics.Suppress.emplace_back("unreachable-code");
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -18,6 +18,7 @@
 #include "FeatureModul

[PATCH] D112209: [clangd] IncludeCleaner: Complicated rules for enum usage

2021-10-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
kbobyrev requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112209

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -103,6 +103,34 @@
   "struct ^X { enum ^Language { ^CXX = 42, Python = 9000}; };",
   "int Lang = X::CXX;",
   },
+  {
+  "enum class Color;",
+  "enum class Color {};",
+  },
+  {
+  "enum class ^Color : int;",
+  "enum class Color : int {};",
+  },
+  {
+  "enum class Color : int {};",
+  "enum class Color : int;",
+  },
+  {
+  "enum class Color;",
+  "enum class Color {}; Color c;",
+  },
+  {
+  "enum class ^Color : char;",
+  "Color c;",
+  },
+  {
+  "enum class ^Color : char {};",
+  "Color c;",
+  },
+  {
+  "enum class ^Color;",
+  "Color c;",
+  },
   {
   // When a type is resolved via a using declaration, the
   // UsingShadowDecl is not referenced in the AST.
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -35,6 +35,16 @@
   }
 
   bool VisitTagType(TagType *TT) {
+// For enumerations we will require only the definition if it's present and
+// the underlying type is not specified.
+if (TT->isEnumeralType()) {
+  const auto *Enum = llvm::dyn_cast(TT->getDecl());
+  assert(Enum);
+  if (!Enum->getIntegerTypeSourceInfo() && TT->getDecl()->getDefinition()) {
+Result.insert(TT->getDecl()->getDefinition()->getLocation());
+return true;
+  }
+}
 add(TT->getDecl());
 return true;
   }
@@ -67,29 +77,35 @@
   }
 
   bool TraverseType(QualType T) {
-if (isNew(T.getTypePtrOrNull())) { // don't care about quals
+if (isNew(T.getTypePtrOrNull())) // don't care about quals
   Base::TraverseType(T);
-}
 return true;
   }
 
   bool VisitUsingDecl(UsingDecl *D) {
-for (const auto *Shadow : D->shadows()) {
+for (const auto *Shadow : D->shadows())
   add(Shadow->getTargetDecl());
-}
 return true;
   }
 
+  // Require redeclarations only for definitions and only when the underlying
+  // type is specified.
+  bool VisitEnumDecl(EnumDecl *D) {
+if (D != D->getDefinition() || !D->getIntegerTypeSourceInfo())
+  return false;
+for (const auto *Redecl : D->redecls())
+  Result.insert(Redecl->getLocation());
+return false;
+  }
+
 private:
   using Base = RecursiveASTVisitor;
 
   void add(const Decl *D) {
-if (!D || !isNew(D->getCanonicalDecl())) {
+if (!D || !isNew(D->getCanonicalDecl()))
   return;
-}
-for (const Decl *Redecl : D->redecls()) {
+for (const Decl *Redecl : D->redecls())
   Result.insert(Redecl->getLocation());
-}
   }
 
   bool isNew(const void *P) { return P && Visited.insert(P).second; }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112209: [clangd] IncludeCleaner: Complicated rules for enum usage

2021-10-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 381195.
kbobyrev added a comment.

Remove unwanted (though good) formatting changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112209

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -103,6 +103,34 @@
   "struct ^X { enum ^Language { ^CXX = 42, Python = 9000}; };",
   "int Lang = X::CXX;",
   },
+  {
+  "enum class Color;",
+  "enum class Color {};",
+  },
+  {
+  "enum class ^Color : int;",
+  "enum class Color : int {};",
+  },
+  {
+  "enum class Color : int {};",
+  "enum class Color : int;",
+  },
+  {
+  "enum class Color;",
+  "enum class Color {}; Color c;",
+  },
+  {
+  "enum class ^Color : char;",
+  "Color c;",
+  },
+  {
+  "enum class ^Color : char {};",
+  "Color c;",
+  },
+  {
+  "enum class ^Color;",
+  "Color c;",
+  },
   {
   // When a type is resolved via a using declaration, the
   // UsingShadowDecl is not referenced in the AST.
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -35,6 +35,16 @@
   }
 
   bool VisitTagType(TagType *TT) {
+// For enumerations we will require only the definition if it's present and
+// the underlying type is not specified.
+if (TT->isEnumeralType()) {
+  const auto *Enum = llvm::dyn_cast(TT->getDecl());
+  assert(Enum);
+  if (!Enum->getIntegerTypeSourceInfo() && TT->getDecl()->getDefinition()) 
{
+Result.insert(TT->getDecl()->getDefinition()->getLocation());
+return true;
+  }
+}
 add(TT->getDecl());
 return true;
   }
@@ -80,6 +90,16 @@
 return true;
   }
 
+  // Require redeclarations only for definitions and only when the underlying
+  // type is specified.
+  bool VisitEnumDecl(EnumDecl *D) {
+if (D != D->getDefinition() || !D->getIntegerTypeSourceInfo())
+  return false;
+for (const auto *Redecl : D->redecls())
+  Result.insert(Redecl->getLocation());
+return false;
+  }
+
 private:
   using Base = RecursiveASTVisitor;
 


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -103,6 +103,34 @@
   "struct ^X { enum ^Language { ^CXX = 42, Python = 9000}; };",
   "int Lang = X::CXX;",
   },
+  {
+  "enum class Color;",
+  "enum class Color {};",
+  },
+  {
+  "enum class ^Color : int;",
+  "enum class Color : int {};",
+  },
+  {
+  "enum class Color : int {};",
+  "enum class Color : int;",
+  },
+  {
+  "enum class Color;",
+  "enum class Color {}; Color c;",
+  },
+  {
+  "enum class ^Color : char;",
+  "Color c;",
+  },
+  {
+  "enum class ^Color : char {};",
+  "Color c;",
+  },
+  {
+  "enum class ^Color;",
+  "Color c;",
+  },
   {
   // When a type is resolved via a using declaration, the
   // UsingShadowDecl is not referenced in the AST.
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -35,6 +35,16 @@
   }
 
   bool VisitTagType(TagType *TT) {
+// For enumerations we will require only the definition if it's present and
+// the underlying type is not specified.
+if (TT->isEnumeralType()) {
+  const auto *Enum = llvm::dyn_cast(TT->getDecl());
+  assert(Enum);
+  if (!Enum->getIntegerTypeSourceInfo() && TT->getDecl()->getDefinition()) {
+Result.insert(TT->getDecl()->getDefinition()->getLocation());
+return true;
+  }
+}
 add(TT->getDecl());
 return true;
   }
@@ -80,6 +90,16 @@
 return true;
   }
 
+  // Require redeclarations only for definitions and only when the underlying
+  // type is specified.
+  bool VisitEnumDecl(EnumDecl *D) {
+if (D != D->getDefinition() || !D->getIntegerTypeSourceInfo())
+  return false;
+for (const auto *Redecl : D->redecls())
+  Result.insert(Redecl->getLocation()

[PATCH] D112209: [clangd] IncludeCleaner: Complicated rules for enum usage

2021-10-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 381198.
kbobyrev added a comment.

Add one more test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112209

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -103,6 +103,38 @@
   "struct ^X { enum ^Language { ^CXX = 42, Python = 9000}; };",
   "int Lang = X::CXX;",
   },
+  {
+  "enum class Color;",
+  "enum class Color {};",
+  },
+  {
+  "enum class ^Color : int;",
+  "enum class Color : int {};",
+  },
+  {
+  "enum class Color : int {};",
+  "enum class Color : int;",
+  },
+  {
+  "enum class Color;",
+  "enum class Color {}; Color c;",
+  },
+  {
+  "enum class ^Color : int;",
+  "enum class Color : int {}; Color c;",
+  },
+  {
+  "enum class ^Color : char;",
+  "Color c;",
+  },
+  {
+  "enum class ^Color : char {};",
+  "Color c;",
+  },
+  {
+  "enum class ^Color;",
+  "Color c;",
+  },
   {
   // When a type is resolved via a using declaration, the
   // UsingShadowDecl is not referenced in the AST.
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -35,6 +35,16 @@
   }
 
   bool VisitTagType(TagType *TT) {
+// For enumerations we will require only the definition if it's present and
+// the underlying type is not specified.
+if (TT->isEnumeralType()) {
+  const auto *Enum = llvm::dyn_cast(TT->getDecl());
+  assert(Enum);
+  if (!Enum->getIntegerTypeSourceInfo() && TT->getDecl()->getDefinition()) 
{
+Result.insert(TT->getDecl()->getDefinition()->getLocation());
+return true;
+  }
+}
 add(TT->getDecl());
 return true;
   }
@@ -80,6 +90,16 @@
 return true;
   }
 
+  // Require redeclarations only for definitions and only when the underlying
+  // type is specified.
+  bool VisitEnumDecl(EnumDecl *D) {
+if (D != D->getDefinition() || !D->getIntegerTypeSourceInfo())
+  return false;
+for (const auto *Redecl : D->redecls())
+  Result.insert(Redecl->getLocation());
+return false;
+  }
+
 private:
   using Base = RecursiveASTVisitor;
 


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -103,6 +103,38 @@
   "struct ^X { enum ^Language { ^CXX = 42, Python = 9000}; };",
   "int Lang = X::CXX;",
   },
+  {
+  "enum class Color;",
+  "enum class Color {};",
+  },
+  {
+  "enum class ^Color : int;",
+  "enum class Color : int {};",
+  },
+  {
+  "enum class Color : int {};",
+  "enum class Color : int;",
+  },
+  {
+  "enum class Color;",
+  "enum class Color {}; Color c;",
+  },
+  {
+  "enum class ^Color : int;",
+  "enum class Color : int {}; Color c;",
+  },
+  {
+  "enum class ^Color : char;",
+  "Color c;",
+  },
+  {
+  "enum class ^Color : char {};",
+  "Color c;",
+  },
+  {
+  "enum class ^Color;",
+  "Color c;",
+  },
   {
   // When a type is resolved via a using declaration, the
   // UsingShadowDecl is not referenced in the AST.
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -35,6 +35,16 @@
   }
 
   bool VisitTagType(TagType *TT) {
+// For enumerations we will require only the definition if it's present and
+// the underlying type is not specified.
+if (TT->isEnumeralType()) {
+  const auto *Enum = llvm::dyn_cast(TT->getDecl());
+  assert(Enum);
+  if (!Enum->getIntegerTypeSourceInfo() && TT->getDecl()->getDefinition()) {
+Result.insert(TT->getDecl()->getDefinition()->getLocation());
+return true;
+  }
+}
 add(TT->getDecl());
 return true;
   }
@@ -80,6 +90,16 @@
 return true;
   }
 
+  // Require redeclarations only for definitions and only when the underlying
+  // type is specified.
+  bool VisitEnumDecl(EnumDe

[PATCH] D110833: [clang-format] Refactor SpaceBeforeParens to add flags

2021-10-21 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/include/clang/Format/Format.h:3341
+/// \endcode
+bool AfterFunctionDeclarationName;
+/// If ``true``, put a space between function definition name and opening

Could you sort these? AfterControlStatements e.g. would be in front of this.



Comment at: clang/include/clang/Format/Format.h:3361
+/// \endcode
+bool AfterOperators;
+/// If ``true``, put space between if macros and opening parentheses.

Should `new` be handled differently than the other operators? But at least add 
an operator example which is not `new`, and keep this one.



Comment at: clang/include/clang/Format/Format.h:3405
+  ///
+  /// If ``SpaceBeforeParens`` is set to ``SBPO_Custom``, use this to specify
+  /// how each individual space before parentheses case should be handled.

Custom



Comment at: clang/include/clang/Format/Format.h:3416
+  /// \version 14
+  SpaceBeforeParensCustom SpaceBeforeParensFlags;
+

MyDeveloperDay wrote:
> I'm not a massive fan of the word `Flags` here and thoughts?
Yeah, neither, but Options is taken.

But Flags indicate that these will always be booleans, and we know that may 
change in the future.

Is it possible the reuse SpaceBeforeParensOptions as struct and still parse the 
old enum? (Yes of course, but is it feasible in terms of needed work?)



Comment at: clang/include/clang/Format/Format.h:3422
   ///true:  false:
-  ///for (auto v : values) {}   vs. for(auto v: values) {}
+  ///for (auto v : values) {}   vs. for (auto v: values) {}
   /// \endcode

Please remove again. :)



Comment at: clang/lib/Format/Format.cpp:1221
   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
+  LLVMStyle.SpaceBeforeParensFlags.AfterControlStatements = true;
+  LLVMStyle.SpaceBeforeParensFlags.AfterOperators = true;

Is this needed? Shouldn't the expand take care of that?


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

https://reviews.llvm.org/D110833

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


[PATCH] D111790: [AArch64][Driver][SVE] Allow -msve-vector-bits=+ syntax to mean no maximum vscale

2021-10-21 Thread Peter Waller via Phabricator via cfe-commits
peterwaller-arm added a comment.

(Accept, but please run clang format)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111790

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


RE: [PATCH] D111109: AddGlobalAnnotations for function with or without function body.

2021-10-21 Thread stan li via cfe-commits
Hi Alex,
I’ll take a look. Not sure how long it takes though.
Please revert it. I don’t have the permission to commit yet.

Could you share more information about the crash?
What is the command line to repro the crash and which environment it crashed.

Thanks
Xiang
Sent from Mail for Windows

From: Alexander Kornienko via Phabricator
Sent: Wednesday, October 20, 2021 2:19 PM
To: python3k...@outlook.com; 
mizve...@gmail.com; 
blitzrak...@gmail.com; 
notst...@gmail.com; 
shen...@google.com; 
rich...@metafoo.co.uk; 
bhuvanendra.kum...@amd.com; 
mlek...@skidmore.edu; 
jlero...@apple.com; 
chris.biene...@me.com; 
aaron.ball...@gmail.com
Cc: ale...@google.com; 
ndesaulni...@google.com; 
cfe-commits@lists.llvm.org; 
david.gr...@arm.com; 
ruiling.s...@amd.com
Subject: [PATCH] D09: AddGlobalAnnotations for function with or without 
function body.

alexfh added a comment.

Reduced test case:

  template  void b(a);
  template  class d {
  public:
class e {
public:
  c *f();
};
e *g();
  };
  template  class j;
  template  class j {
  public:
class k {
public:
  k(int *);
  ~k();
};
int n();
d l;
  };
  template  int j::n() {
auto m = l.g()->f();
k a(*m);
b(a);
  }
  template 
  j::k::~k() __attribute__((annotate(""))) {}
  class o {
int m_fn4();
j p;
  };
  int o::m_fn4() { p.n(); }

Please revert the commit if there is no quick and obvious solution. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D09

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


RE: [PATCH] D111109: AddGlobalAnnotations for function with or without function body.

2021-10-21 Thread stan li via cfe-commits
Hi Alex,
I tried compile your repro on Windows with
clang -S
But it didn’t crash.

Could you share the command line and environment to repro the crash?

Thanks
Xiang

Sent from Mail for Windows


From: Alexander Kornienko via Phabricator 
Sent: Wednesday, October 20, 2021 4:10:42 PM
To: python3k...@outlook.com ; mizve...@gmail.com 
; blitzrak...@gmail.com ; 
notst...@gmail.com ; shen...@google.com 
; rich...@metafoo.co.uk ; 
bhuvanendra.kum...@amd.com ; mlek...@skidmore.edu 
; jlero...@apple.com ; 
chris.biene...@me.com ; aaron.ball...@gmail.com 

Cc: ale...@google.com ; ndesaulni...@google.com 
; cfe-commits@lists.llvm.org 
; david.gr...@arm.com ; 
ruiling.s...@amd.com 
Subject: [PATCH] D09: AddGlobalAnnotations for function with or without 
function body.

alexfh added a comment.

Reduced the test further to:

  struct k {
~k() __attribute__((annotate(""))) {}
  };
  void m() { k(); }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D09

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


[clang] aad244d - Revert "AddGlobalAnnotations for function with or without function body."

2021-10-21 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-10-21T07:08:18-04:00
New Revision: aad244dfc566236e9d3ef48c7aea3616bb6aab14

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

LOG: Revert "AddGlobalAnnotations for function with or without function body."

This reverts commit 121b2252de0eed68f2ddf5f09e924a6c35423d47.

The following code causes a crash in some circumstances:

  struct k {
~k() __attribute__((annotate(""))) {}
  };
  void m() { k(); }

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGen/annotations-global.c
clang/test/CodeGenCXX/attr-annotate.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index e53a8a36974ae..74c4490d5422e 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2200,9 +2200,6 @@ void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 
llvm::Function *F,
CalleeIdx, PayloadIndices,
/* VarArgsArePassed */ 
false)}));
   }
-
-  if (FD->hasAttr())
-AddGlobalAnnotations(FD, F);
 }
 
 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
@@ -4900,6 +4897,8 @@ void 
CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
 AddGlobalCtor(Fn, CA->getPriority());
   if (const DestructorAttr *DA = D->getAttr())
 AddGlobalDtor(Fn, DA->getPriority(), true);
+  if (D->hasAttr())
+AddGlobalAnnotations(D, Fn);
 }
 
 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {

diff  --git a/clang/test/CodeGen/annotations-global.c 
b/clang/test/CodeGen/annotations-global.c
index 454680fa57d66..2a5c847fd9602 100644
--- a/clang/test/CodeGen/annotations-global.c
+++ b/clang/test/CodeGen/annotations-global.c
@@ -4,19 +4,15 @@
 // RUN: FileCheck --check-prefix=BAR %s < %t1
 // RUN: FileCheck --check-prefix=FOOS %s < %t1
 // RUN: FileCheck --check-prefix=ADDRSPACE %s < %t1
-// RUN: FileCheck --check-prefix=DECL %s < %t1
 // RUN: %clang_cc1 %s -triple r600 -emit-llvm -o - | FileCheck %s 
--check-prefix AS1-GLOBALS
 // END.
 
 static __attribute((annotate("sfoo_0"))) __attribute((annotate("sfoo_1"))) 
char sfoo;
 __attribute((annotate("foo_0"))) __attribute((annotate("foo_1"))) char foo;
 
-void __attribute((annotate("ann_decl_0"))) 
__attribute((annotate("ann_decl_1")))  decl(char *a);
-
 void __attribute((annotate("ann_a_0"))) __attribute((annotate("ann_a_1"))) 
__attribute((annotate("ann_a_2"))) __attribute((annotate("ann_a_3"))) a(char 
*a);
 void __attribute((annotate("ann_a_0"))) __attribute((annotate("ann_a_1"))) 
a(char *a) {
   __attribute__((annotate("bar_0"))) __attribute__((annotate("bar_1"))) static 
char bar;
-  decl(a);
   sfoo = 0;
 }
 
@@ -26,13 +22,13 @@ __attribute((address_space(1))) 
__attribute__((annotate("addrspace1_ann"))) char
 // FOOS: private unnamed_addr constant [7 x i8] c"sfoo_{{.}}\00", section 
"llvm.metadata"
 // FOOS: private unnamed_addr constant [7 x i8] c"sfoo_{{.}}\00", section 
"llvm.metadata"
 // FOOS-NOT: sfoo_
-// FOOS: @llvm.global.annotations = appending global [13 x { i8*, i8*, i8*, 
i32, i8* }] {{.*}}i8* @sfoo{{.*}}i8* @sfoo{{.*}}, section "llvm.metadata"
+// FOOS: @llvm.global.annotations = appending global [11 x { i8*, i8*, i8*, 
i32, i8* }] {{.*}}i8* @sfoo{{.*}}i8* @sfoo{{.*}}, section "llvm.metadata"
 
 // FOO: target triple
 // FOO: private unnamed_addr constant [6 x i8] c"foo_{{.}}\00", section 
"llvm.metadata"
 // FOO: private unnamed_addr constant [6 x i8] c"foo_{{.}}\00", section 
"llvm.metadata"
 // FOO-NOT: foo_
-// FOO: @llvm.global.annotations = appending global [13 x { i8*, i8*, i8*, 
i32, i8* }] {{.*}}i8* @foo{{.*}}i8* @foo{{.*}}, section "llvm.metadata"
+// FOO: @llvm.global.annotations = appending global [11 x { i8*, i8*, i8*, 
i32, i8* }] {{.*}}i8* @foo{{.*}}i8* @foo{{.*}}, section "llvm.metadata"
 
 // A: target triple
 // A: private unnamed_addr constant [8 x i8] c"ann_a_{{.}}\00", section 
"llvm.metadata"
@@ -40,24 +36,18 @@ __attribute((address_space(1))) 
__attribute__((annotate("addrspace1_ann"))) char
 // A: private unnamed_addr constant [8 x i8] c"ann_a_{{.}}\00", section 
"llvm.metadata"
 // A: private unnamed_addr constant [8 x i8] c"ann_a_{{.}}\00", section 
"llvm.metadata"
 // A-NOT: ann_a_
-// A: @llvm.global.annotations = appending global [13 x { i8*, i8*, i8*, i32, 
i8* }] {{.*}}i8* bitcast (void (i8*)* @a to i8*){{.*}}i8* bitcast (void (i8*)* 
@a to i8*){{.*}}i8* bitcast (void (i8*)* @a to i8*){{.*}}i8* bitcast (void 
(i8*)* @a to i8*){{.*}}, section "llvm.metadata"
+// A: @llvm.global.annotations = appending global [11 x { i8*, i8*, i8*, i32, 
i8* }] {{.*}}i8* bitcast (void (i8*)* @a to i8*){{.*}}i8* bitcast (void (i8*)* 
@a to i8*){{.*}}i8* bitcast (void (i8*)*

Re: [PATCH] D111109: AddGlobalAnnotations for function with or without function body.

2021-10-21 Thread Aaron Ballman via cfe-commits
On Wed, Oct 20, 2021 at 5:28 PM stan li  wrote:
>
> Hi Alex,
>
> I’ll take a look. Not sure how long it takes though.
>
> Please revert it. I don’t have the permission to commit yet.

I've reverted in aad244dfc566236e9d3ef48c7aea3616bb6aab14 while the
crash is being investigated.

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


[PATCH] D108366: [clang][deps] Make resource directory deduction configurable

2021-10-21 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 381210.
jansvoboda11 added a comment.

Add `REQUIRES: shell` to the test, rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108366

Files:
  clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json.template
  clang/test/ClangScanDeps/Inputs/resource_directory/compiler
  clang/test/ClangScanDeps/Inputs/resource_directory/mod.h
  clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap
  clang/test/ClangScanDeps/Inputs/resource_directory/tu.c
  clang/test/ClangScanDeps/resource_directory.c
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -204,6 +204,25 @@
 llvm::cl::desc("the module of which the dependencies are to be computed"),
 llvm::cl::cat(DependencyScannerCategory));
 
+enum ResourceDirRecipeKind {
+  RDRK_ModifyCompilerPath,
+  RDRK_InvokeCompiler,
+};
+
+static llvm::cl::opt ResourceDirRecipe(
+"resource-dir-recipe",
+llvm::cl::desc("How to produce missing '-resource-dir' argument"),
+llvm::cl::values(
+clEnumValN(RDRK_ModifyCompilerPath, "modify-compiler-path",
+   "Construct the resource directory from the compiler path in "
+   "the compilation database. This assumes it's part of the "
+   "same toolchain as this clang-scan-deps. (default)"),
+clEnumValN(RDRK_InvokeCompiler, "invoke-compiler",
+   "Invoke the compiler with '-print-resource-dir' and use the "
+   "reported path as the resource directory. (deprecated)")),
+llvm::cl::init(RDRK_ModifyCompilerPath),
+llvm::cl::cat(DependencyScannerCategory));
+
 llvm::cl::opt Verbose("v", llvm::cl::Optional,
 llvm::cl::desc("Use verbose output."),
 llvm::cl::init(false),
@@ -495,7 +514,7 @@
   AdjustedArgs.push_back("/clang:" + LastO);
 }
 
-if (!HasResourceDir) {
+if (!HasResourceDir && ResourceDirRecipe == RDRK_InvokeCompiler) {
   StringRef ResourceDir =
   ResourceDirCache.findResourceDir(Args, ClangCLMode);
   if (!ResourceDir.empty()) {
Index: clang/test/ClangScanDeps/resource_directory.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/resource_directory.c
@@ -0,0 +1,25 @@
+// REQUIRES: shell
+
+// RUN: rm -rf %t && mkdir %t
+// RUN: cp %S/Inputs/resource_directory/* %t
+
+// Deduce the resource directory from the compiler path.
+//
+// RUN: sed -e "s|CLANG|/our/custom/bin/clang|g" -e "s|DIR|%/t|g" \
+// RUN:   %S/Inputs/resource_directory/cdb.json.template > %t/cdb_path.json
+// RUN: clang-scan-deps -compilation-database %t/cdb_path.json --format experimental-full \
+// RUN:   --resource-dir-recipe modify-compiler-path > %t/result_path.json
+// RUN: cat %t/result_path.json | sed 's:\?:/:g' | FileCheck %s --check-prefix=CHECK-PATH
+// CHECK-PATH:  "-resource-dir"
+// CHECK-PATH-NEXT: "/our/custom/lib{{.*}}"
+
+// Run the compiler and ask it for the resource directory.
+//
+// RUN: chmod +x %t/compiler
+// RUN: sed -e "s|CLANG|%/t/compiler|g" -e "s|DIR|%/t|g" \
+// RUN:   %S/Inputs/resource_directory/cdb.json.template > %t/cdb_invocation.json
+// RUN: clang-scan-deps -compilation-database %t/cdb_invocation.json --format experimental-full \
+// RUN:   --resource-dir-recipe invoke-compiler > %t/result_invocation.json
+// RUN: cat %t/result_invocation.json | sed 's:\?:/:g' | FileCheck %s --check-prefix=CHECK-INVOCATION
+// CHECK-INVOCATION:  "-resource-dir"
+// CHECK-INVOCATION-NEXT: "/custom/compiler/resources"
Index: clang/test/ClangScanDeps/Inputs/resource_directory/tu.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/Inputs/resource_directory/tu.c
@@ -0,0 +1 @@
+#include "mod.h"
Index: clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap
===
--- /dev/null
+++ clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap
@@ -0,0 +1 @@
+module mod { header "mod.h" }
Index: clang/test/ClangScanDeps/Inputs/resource_directory/compiler
===
--- /dev/null
+++ clang/test/ClangScanDeps/Inputs/resource_directory/compiler
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+echo "/custom/compiler/resources"
Index: clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json.template
===
--- /dev/null
+++ clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json.template
@@ -0,0 +1,7 @@
+[
+  {
+"directory": "DIR",
+"comman

[PATCH] D110127: [Clang] Support typedef with btf_decl_tag attributes

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110127

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


[PATCH] D112013: [clang][ASTImporter] Fix for importing functions with EST_Unevaluated prototype.

2021-10-21 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.

Thanks for updating the test case!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112013

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


[PATCH] D112159: Relax assert in ExprConstant to a return None.

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

I checked the call sites to see if any were missed and I did not spot uses that 
should also be changed. LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112159

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


[PATCH] D111720: [clang][deps] Ensure reported context hash is strict

2021-10-21 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp:56-58
+  // Ensure the reported context hash is strict.
+  CI.getHeaderSearchOpts().ModulesStrictContextHash = true;
+

dexonsmith wrote:
> jansvoboda11 wrote:
> > jansvoboda11 wrote:
> > > dexonsmith wrote:
> > > > IIUC, explicit modules don't really have/need a context hash. Can 
> > > > related options be stripped out when serializing to `-cc1` when 
> > > > `ImplicitModules` is false?
> > > > 
> > > > Basically, I'm asking if `ModulesStrictContextHash` is a no-op when 
> > > > `ImplicitModules` is false. If not, can we make it a no-op?
> > > > (If we can, then maybe rename the field to 
> > > > `ImplicitModulesStrictContextHash` and audit that no one reads it when 
> > > > `ImplicitModules` is off...)
> > > Let me clarify this a bit. You're right that when building explicit 
> > > modules, we don't care about context hash.
> > > 
> > > We do care about using **strict** context hash during the scan though - 
> > > it's an implementation detail through which we prevent mixing 
> > > incompatible modules/TUs. (This strict context hash is enabled elsewhere 
> > > in the dependency scanner.)
> > > 
> > > At the end of the scan, we take discovered modules and modify/prune their 
> > > `CompilerInvocation` (in this function). This can essentially "merge" 
> > > multiple versions of the same module into one, which is very desirable. 
> > > But we still want to do it according to the **strict** context hash. We 
> > > don't want to merge versions with different search paths for example 
> > > (non-strict context hash). That's what this change ensures.
> > > 
> > > Note that we don't **need** to report context hashes to scanner clients. 
> > > Any other identifier derived from a strict context hash would work.
> > I think the rename you're suggesting is valid.
> > 
> > We //could// strip the `ModulesStrictContextHash` in the scanner: after we 
> > generate the strict context hash and before we generate the command-line. I 
> > think that can be done in a NFC follow-up.
> I think I understand the problem now. I hadn't really put together that the 
> implicit modules context hash machinery was being used to decide the artifact 
> location for the explicit module.
> 
> I'm concerned this is too subtle and fragile. I'm wondering if the following 
> more naive solution would work:
> - Prune/canonicalize the CompilerInvocation (as now).
> - Write/modify any fields to use placeholders for fields the client has 
> control over. (Besides `OutputFile`, what else is there?)
> - Generate the `-cc1` and hash it. That's now the context hash. Return it to 
> the client.
> 
> But maybe that's the whole point of the strict context hash, and if there are 
> bugs where this would behave differently, we should fix the strict context 
> hash?
> 
> ...
> 
> Stepping back, please go ahead and commit this incremental improvement, after 
> expanding the comment to:
> 1. More fully explain the context: that the context hash will be generated 
> from the CompilerInvocation and sent to the client, which then uses it to 
> decide where to store the artifact. We need to make sure it's strict.
> 2. Explain why `assert(ModulesStrictContextHash)` would fail, even though the 
> scan used a strict context hash. (Maybe it'd makes sense to make that change 
> in a follow-up...?)
> I'm concerned this is too subtle and fragile. I'm wondering if the following 
> more naive solution would work:
> - Prune/canonicalize the CompilerInvocation (as now).
> - Write/modify any fields to use placeholders for fields the client has 
> control over. (Besides `OutputFile`, what else is there?)

In general, we don't know much about the intended filesystem paths. Off the top 
of my head, we don't know the PCM output file (and values for 
`-fmodule-file=`), input file (and values for `-fmodule-map-file=`: module map 
used for building might have different location during the scan), serialized 
diagnostics file (we can't use the file for a TU that discovered the module 
first).

> - Generate the `-cc1` and hash it. That's now the context hash. Return it to 
> the client.
>
> But maybe that's the whole point of the strict context hash, and if there are 
> bugs where this would behave differently, we should fix the strict context 
> hash?

I think that's a valid approach. Just wondering why you see it being less 
subtle and fragile than strict context hash?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111720

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


[clang] 954d77b - [clang][deps] Ensure reported context hash is strict

2021-10-21 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-10-21T13:49:47+02:00
New Revision: 954d77b98dd69c6bcf808e3dac871171d4832bad

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

LOG: [clang][deps] Ensure reported context hash is strict

One of main goals of the dependency scanner is to be strict about module 
compatibility. This is achieved through strict context hash. This patch ensures 
that strict context hash is enabled not only during the scan itself (and its 
minimized implicit build), but also when actually reporting the dependency.

Reviewed By: dexonsmith

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

Added: 
clang/test/ClangScanDeps/Inputs/modules-context-hash/a/dep.h
clang/test/ClangScanDeps/Inputs/modules-context-hash/b/dep.h
clang/test/ClangScanDeps/Inputs/modules-context-hash/cdb.json.template
clang/test/ClangScanDeps/Inputs/modules-context-hash/mod.h
clang/test/ClangScanDeps/Inputs/modules-context-hash/module.modulemap
clang/test/ClangScanDeps/Inputs/modules-context-hash/tu.c
clang/test/ClangScanDeps/modules-context-hash.c

Modified: 
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index 919c7d175362d..8144f25d145ce 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -55,6 +55,14 @@ CompilerInvocation 
ModuleDepCollector::makeInvocationForModuleBuildWithoutPaths(
 
   Optimize(CI);
 
+  // The original invocation probably didn't have strict context hash enabled.
+  // We will use the context hash of this invocation to distinguish between
+  // multiple incompatible versions of the same module and will use it when
+  // reporting dependencies to the clients. Let's make sure we're using
+  // **strict** context hash in order to prevent accidental sharing of
+  // incompatible modules (e.g. with 
diff erences in search paths).
+  CI.getHeaderSearchOpts().ModulesStrictContextHash = true;
+
   return CI;
 }
 

diff  --git a/clang/test/ClangScanDeps/Inputs/modules-context-hash/a/dep.h 
b/clang/test/ClangScanDeps/Inputs/modules-context-hash/a/dep.h
new file mode 100644
index 0..e69de29bb2d1d

diff  --git a/clang/test/ClangScanDeps/Inputs/modules-context-hash/b/dep.h 
b/clang/test/ClangScanDeps/Inputs/modules-context-hash/b/dep.h
new file mode 100644
index 0..e69de29bb2d1d

diff  --git 
a/clang/test/ClangScanDeps/Inputs/modules-context-hash/cdb.json.template 
b/clang/test/ClangScanDeps/Inputs/modules-context-hash/cdb.json.template
new file mode 100644
index 0..81f7084ca8854
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/modules-context-hash/cdb.json.template
@@ -0,0 +1,12 @@
+[
+  {
+"directory": "DIR",
+"command": "clang -c DIR/tu.c -fmodules -fmodules-cache-path=DIR/cache 
-IDIR/a -o DIR/tu_a.o",
+"file": "DIR/tu.c"
+  },
+  {
+"directory": "DIR",
+"command": "clang -c DIR/tu.c -fmodules -fmodules-cache-path=DIR/cache 
-IDIR/b -o DIR/tu_b.o",
+"file": "DIR/tu.c"
+  }
+]

diff  --git a/clang/test/ClangScanDeps/Inputs/modules-context-hash/mod.h 
b/clang/test/ClangScanDeps/Inputs/modules-context-hash/mod.h
new file mode 100644
index 0..075cfb1252c83
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/modules-context-hash/mod.h
@@ -0,0 +1 @@
+#include "dep.h"

diff  --git 
a/clang/test/ClangScanDeps/Inputs/modules-context-hash/module.modulemap 
b/clang/test/ClangScanDeps/Inputs/modules-context-hash/module.modulemap
new file mode 100644
index 0..03cbffaeb1fb5
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/modules-context-hash/module.modulemap
@@ -0,0 +1 @@
+module mod { header "mod.h" }

diff  --git a/clang/test/ClangScanDeps/Inputs/modules-context-hash/tu.c 
b/clang/test/ClangScanDeps/Inputs/modules-context-hash/tu.c
new file mode 100644
index 0..01f145835c765
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/modules-context-hash/tu.c
@@ -0,0 +1 @@
+#include "mod.h"

diff  --git a/clang/test/ClangScanDeps/modules-context-hash.c 
b/clang/test/ClangScanDeps/modules-context-hash.c
new file mode 100644
index 0..0b9a3e085ee6b
--- /dev/null
+++ b/clang/test/ClangScanDeps/modules-context-hash.c
@@ -0,0 +1,89 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: cp -r %S/Inputs/modules-context-hash/* %t
+
+// Check that the scanner reports the same module as distinct dependencies when
+// a single translation unit gets compiled with multiple command-lines that
+// produce 
diff erent **strict** context hashes.
+
+// RUN: sed "s|DIR|%/t|g" %S/Inputs/modules-context-hash/cdb.json.template > 
%t/cdb.json
+// RUN: 

[PATCH] D111720: [clang][deps] Ensure reported context hash is strict

2021-10-21 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG954d77b98dd6: [clang][deps] Ensure reported context hash is 
strict (authored by jansvoboda11).

Changed prior to commit:
  https://reviews.llvm.org/D111720?vs=379397&id=381213#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111720

Files:
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/Inputs/modules-context-hash/a/dep.h
  clang/test/ClangScanDeps/Inputs/modules-context-hash/b/dep.h
  clang/test/ClangScanDeps/Inputs/modules-context-hash/cdb.json.template
  clang/test/ClangScanDeps/Inputs/modules-context-hash/mod.h
  clang/test/ClangScanDeps/Inputs/modules-context-hash/module.modulemap
  clang/test/ClangScanDeps/Inputs/modules-context-hash/tu.c
  clang/test/ClangScanDeps/modules-context-hash.c

Index: clang/test/ClangScanDeps/modules-context-hash.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-context-hash.c
@@ -0,0 +1,89 @@
+// RUN: rm -rf %t && mkdir %t
+// RUN: cp -r %S/Inputs/modules-context-hash/* %t
+
+// Check that the scanner reports the same module as distinct dependencies when
+// a single translation unit gets compiled with multiple command-lines that
+// produce different **strict** context hashes.
+
+// RUN: sed "s|DIR|%/t|g" %S/Inputs/modules-context-hash/cdb.json.template > %t/cdb.json
+// RUN: echo -%t > %t/result.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full -j 1 >> %t/result.json
+// RUN: cat %t/result.json | sed 's:\?:/:g' | FileCheck %s -check-prefix=CHECK
+
+// CHECK:  -[[PREFIX:.*]]
+// CHECK-NEXT: {
+// CHECK-NEXT:   "modules": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1"
+// CHECK:  "-emit-module"
+// CHECK:  "-I"
+// CHECK:  "[[PREFIX]]/a"
+// CHECK:  "-fmodule-name=mod"
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "[[HASH_MOD_A:.*]]",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/a/dep.h",
+// CHECK-NEXT: "[[PREFIX]]/mod.h",
+// CHECK-NEXT: "[[PREFIX]]/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "mod"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-module-deps": [],
+// CHECK-NEXT:   "clang-modulemap-file": "[[PREFIX]]/module.modulemap",
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-cc1"
+// CHECK:  "-emit-module"
+// CHECK:  "-I"
+// CHECK:  "[[PREFIX]]/b"
+// CHECK:  "-fmodule-name=mod"
+// CHECK:],
+// CHECK-NEXT:   "context-hash": "[[HASH_MOD_B:.*]]",
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/b/dep.h",
+// CHECK-NEXT: "[[PREFIX]]/mod.h",
+// CHECK-NEXT: "[[PREFIX]]/module.modulemap"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "name": "mod"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "translation-units": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-context-hash": "{{.*}}",
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "[[HASH_MOD_A]]",
+// CHECK-NEXT:   "module-name": "mod"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-fno-implicit-modules",
+// CHECK-NEXT: "-fno-implicit-module-maps"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/tu.c"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "input-file": "[[PREFIX]]/tu.c"
+// CHECK-NEXT: },
+// CHECK-NEXT: {
+// CHECK-NEXT:   "clang-context-hash": "{{.*}}",
+// CHECK-NEXT:   "clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "[[HASH_MOD_B]]",
+// CHECK-NEXT:   "module-name": "mod"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "command-line": [
+// CHECK-NEXT: "-fno-implicit-modules",
+// CHECK-NEXT: "-fno-implicit-module-maps"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "file-deps": [
+// CHECK-NEXT: "[[PREFIX]]/tu.c"
+// CHECK-NEXT:   ],
+// CHECK-NEXT:   "input-file": "[[PREFIX]]/tu.c"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ]
+// CHECK-NEXT: }
Index: clang/test/ClangScanDeps/Inputs/modules-context-hash/tu.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/Inputs/modules-context-hash/tu.c
@@ -0,0 +1 @@
+#include "mod.h"
Index: clang/test/ClangScanDeps/Inputs/modules-context-hash/module.modulemap

[PATCH] D107347: [Sema] haveSameParameterTypes - replace repeated isNull() test with assertions

2021-10-21 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added a comment.

FYI, it seems like a branch containing this patch was accidentally pushed to 
GitHub: https://github.com/llvm/llvm-project/tree/5357a98c823a


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107347

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


[PATCH] D112190: [clang] Don't clear AST if we have consumers running after the main action

2021-10-21 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.

lgtm


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112190

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


[clang] 2461666 - [clang][deps] NFC: Remove redundant CompilerInstance reference

2021-10-21 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-10-21T13:50:46+02:00
New Revision: 24616664afd455d7fde9cf4c631ff30347196bbc

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

LOG: [clang][deps] NFC: Remove redundant CompilerInstance reference

The `ModuleDepCollectorPP` class holds a reference to `ModuleDepCollector` as 
well as `ModuleDepCollector`'s `CompilerInstance`. The fact that these refer to 
the same object is non-obvious.

This patch removes the `CompilerInvocation` reference from 
`ModuleDepCollectorPP` and accesses it through `ModuleDepCollector` instead.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index a15353dbf11b6..29c33ecb491ef 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -141,8 +141,7 @@ class ModuleDepCollector;
 /// \c DependencyConsumer of the parent \c ModuleDepCollector.
 class ModuleDepCollectorPP final : public PPCallbacks {
 public:
-  ModuleDepCollectorPP(CompilerInstance &I, ModuleDepCollector &MDC)
-  : Instance(I), MDC(MDC) {}
+  ModuleDepCollectorPP(ModuleDepCollector &MDC) : MDC(MDC) {}
 
   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
@@ -159,8 +158,6 @@ class ModuleDepCollectorPP final : public PPCallbacks {
   void EndOfMainFile() override;
 
 private:
-  /// The compiler instance for the current translation unit.
-  CompilerInstance &Instance;
   /// The parent dependency collector.
   ModuleDepCollector &MDC;
   /// Working set of direct modular dependencies.

diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index 8144f25d145ce..c6cbec1a4279f 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -138,11 +138,11 @@ void ModuleDepCollectorPP::FileChanged(SourceLocation Loc,
   // This has to be delayed as the context hash can change at the start of
   // `CompilerInstance::ExecuteAction`.
   if (MDC.ContextHash.empty()) {
-MDC.ContextHash = Instance.getInvocation().getModuleHash();
+MDC.ContextHash = MDC.Instance.getInvocation().getModuleHash();
 MDC.Consumer.handleContextHash(MDC.ContextHash);
   }
 
-  SourceManager &SM = Instance.getSourceManager();
+  SourceManager &SM = MDC.Instance.getSourceManager();
 
   // Dependency generation really does want to go all the way to the
   // file entry for a source location to find out what is depended on.
@@ -185,12 +185,13 @@ void ModuleDepCollectorPP::handleImport(const Module 
*Imported) {
 }
 
 void ModuleDepCollectorPP::EndOfMainFile() {
-  FileID MainFileID = Instance.getSourceManager().getMainFileID();
+  FileID MainFileID = MDC.Instance.getSourceManager().getMainFileID();
   MDC.MainFile = std::string(
-  Instance.getSourceManager().getFileEntryForID(MainFileID)->getName());
+  
MDC.Instance.getSourceManager().getFileEntryForID(MainFileID)->getName());
 
-  if (!Instance.getPreprocessorOpts().ImplicitPCHInclude.empty())
-MDC.FileDeps.push_back(Instance.getPreprocessorOpts().ImplicitPCHInclude);
+  if (!MDC.Instance.getPreprocessorOpts().ImplicitPCHInclude.empty())
+MDC.FileDeps.push_back(
+MDC.Instance.getPreprocessorOpts().ImplicitPCHInclude);
 
   for (const Module *M : DirectModularDeps) {
 // A top-level module might not be actually imported as a module when
@@ -229,7 +230,7 @@ ModuleID ModuleDepCollectorPP::handleTopLevelModule(const 
Module *M) {
   MD.ImplicitModulePCMPath = std::string(M->getASTFile()->getName());
   MD.IsSystem = M->IsSystem;
 
-  const FileEntry *ModuleMap = Instance.getPreprocessor()
+  const FileEntry *ModuleMap = MDC.Instance.getPreprocessor()
.getHeaderSearchInfo()
.getModuleMap()
.getModuleMapFileForUniquing(M);
@@ -319,7 +320,7 @@ ModuleDepCollector::ModuleDepCollector(
   OriginalInvocation(std::move(OriginalCI)), OptimizeArgs(OptimizeArgs) {}
 
 void ModuleDepCollector::attachToPreprocessor(Preprocessor &PP) {
-  PP.addPPCallbacks(std::make_unique(Instance, *this));
+  PP.addPPCallbacks(std::make_unique(*this));
 }
 
 void ModuleDepCollector::attachToASTReader(ASTReader &R) {}



_

[clang] 207e9fd - [clang][deps] NFC: Rename scanning CompilerInstance

2021-10-21 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-10-21T13:51:00+02:00
New Revision: 207e9fdea704dd8c6db077971d958abb8b4d6d84

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

LOG: [clang][deps] NFC: Rename scanning CompilerInstance

The dependency scanner works with multiple instances of 
`Compiler{Instance,Invocation}`. From names of the variables/members, their 
purpose is not obvious.

This patch gives a distinct name to the `CompilerInstance` that's used to run 
the implicit build during dependency scan.

Depends on D111724.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index 29c33ecb491ef..6966ed8a1bde9 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -190,7 +190,7 @@ class ModuleDepCollectorPP final : public PPCallbacks {
 class ModuleDepCollector final : public DependencyCollector {
 public:
   ModuleDepCollector(std::unique_ptr Opts,
- CompilerInstance &I, DependencyConsumer &C,
+ CompilerInstance &ScanInstance, DependencyConsumer &C,
  CompilerInvocation &&OriginalCI, bool OptimizeArgs);
 
   void attachToPreprocessor(Preprocessor &PP) override;
@@ -199,8 +199,8 @@ class ModuleDepCollector final : public DependencyCollector 
{
 private:
   friend ModuleDepCollectorPP;
 
-  /// The compiler instance for the current translation unit.
-  CompilerInstance &Instance;
+  /// The compiler instance for scanning the current translation unit.
+  CompilerInstance &ScanInstance;
   /// The consumer of collected dependency information.
   DependencyConsumer &Consumer;
   /// Path to the main source file.

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index 2a0943c16d88c..7fdc49271791a 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -165,34 +165,34 @@ class DependencyScanningAction : public 
tooling::ToolAction {
 CompilerInvocation OriginalInvocation(*Invocation);
 
 // Create a compiler instance to handle the actual work.
-CompilerInstance Compiler(std::move(PCHContainerOps));
-Compiler.setInvocation(std::move(Invocation));
+CompilerInstance ScanInstance(std::move(PCHContainerOps));
+ScanInstance.setInvocation(std::move(Invocation));
 
 // Create the compiler's actual diagnostics engine.
-sanitizeDiagOpts(Compiler.getDiagnosticOpts());
-Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
-if (!Compiler.hasDiagnostics())
+sanitizeDiagOpts(ScanInstance.getDiagnosticOpts());
+ScanInstance.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
+if (!ScanInstance.hasDiagnostics())
   return false;
 
-Compiler.getPreprocessorOpts().AllowPCHWithDifferentModulesCachePath = 
true;
+ScanInstance.getPreprocessorOpts().AllowPCHWithDifferentModulesCachePath =
+true;
 
 FileMgr->getFileSystemOpts().WorkingDir = std::string(WorkingDirectory);
-Compiler.setFileManager(FileMgr);
-Compiler.createSourceManager(*FileMgr);
+ScanInstance.setFileManager(FileMgr);
+ScanInstance.createSourceManager(*FileMgr);
 
 llvm::StringSet<> PrebuiltModulesInputFiles;
 // Store the list of prebuilt module files into header search options. This
 // will prevent the implicit build to create duplicate modules and will
 // force reuse of the existing prebuilt module files instead.
-if (!Compiler.getPreprocessorOpts().ImplicitPCHInclude.empty())
+if (!ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty())
   visitPrebuiltModule(
-  Compiler.getPreprocessorOpts().ImplicitPCHInclude, Compiler,
-  Compiler.getHeaderSearchOpts().PrebuiltModuleFiles,
+  ScanInstance.getPreprocessorOpts().ImplicitPCHInclude, ScanInstance,
+  ScanInstance.getHeaderSearchOpts().PrebuiltModuleFiles,
   PrebuiltModulesInputFiles, /*VisitInputFiles=*/DepFS != nullptr);
 
 // Use the dependency scanning optimized file system if requested to do so.
 if (DepFS) {
-  const CompilerInvocation &CI = Compiler.getInvocation();
   DepFS->clearIgnoredFiles();
   // Ignore any fil

[clang] c62220f - [clang][deps] NFC: Rename building CompilerInvocation

2021-10-21 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-10-21T13:51:27+02:00
New Revision: c62220f9623dde699b88baf47c0a3dca400767fb

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

LOG: [clang][deps] NFC: Rename building CompilerInvocation

The dependency scanner works with multiple instances of 
`Compiler{Instance,Invocation}`. From names of the variables/members, their 
purpose is not obvious.

This patch gives descriptive name to the generated `CompilerInvocation` that 
can be used to derive the command-line to build a modular dependency.

Depends on D111725.

Reviewed By: dexonsmith

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

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index 6966ed8a1bde9..e61147d6f2b0a 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -101,7 +101,7 @@ struct ModuleDeps {
   bool ImportedByMainFile = false;
 
   /// Compiler invocation that can be used to build this module (without 
paths).
-  CompilerInvocation Invocation;
+  CompilerInvocation BuildInvocation;
 
   /// Gets the canonical command line suitable for passing to clang.
   ///

diff  --git a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp 
b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
index cb04bc1a9d829..0e419ab4e2918 100644
--- a/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ b/clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -84,7 +84,7 @@ serializeCompilerInvocation(const CompilerInvocation &CI) {
 std::vector ModuleDeps::getCanonicalCommandLine(
 std::function LookupPCMPath,
 std::function LookupModuleDeps) const {
-  CompilerInvocation CI(Invocation);
+  CompilerInvocation CI(BuildInvocation);
   FrontendOptions &FrontendOpts = CI.getFrontendOpts();
 
   InputKind ModuleMapInputKind(FrontendOpts.DashX.getLanguage(),
@@ -101,7 +101,7 @@ std::vector 
ModuleDeps::getCanonicalCommandLine(
 
 std::vector
 ModuleDeps::getCanonicalCommandLineWithoutModulePaths() const {
-  return serializeCompilerInvocation(Invocation);
+  return serializeCompilerInvocation(BuildInvocation);
 }
 
 void dependencies::detail::collectPCMAndModuleMapPaths(
@@ -260,13 +260,13 @@ ModuleID ModuleDepCollectorPP::handleTopLevelModule(const 
Module *M) {
   llvm::DenseSet SeenModules;
   addAllSubmodulePrebuiltDeps(M, MD, SeenModules);
 
-  MD.Invocation = MDC.makeInvocationForModuleBuildWithoutPaths(
-  MD, [&](CompilerInvocation &CI) {
+  MD.BuildInvocation = MDC.makeInvocationForModuleBuildWithoutPaths(
+  MD, [&](CompilerInvocation &BuildInvocation) {
 if (MDC.OptimizeArgs)
-  optimizeHeaderSearchOpts(CI.getHeaderSearchOpts(),
+  optimizeHeaderSearchOpts(BuildInvocation.getHeaderSearchOpts(),
*MDC.ScanInstance.getASTReader(), *MF);
   });
-  MD.ID.ContextHash = MD.Invocation.getModuleHash();
+  MD.ID.ContextHash = MD.BuildInvocation.getModuleHash();
 
   llvm::DenseSet AddedModules;
   addAllSubmoduleDeps(M, MD, AddedModules);

diff  --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index b77abeacc195f..450a4efead099 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -362,7 +362,7 @@ class FullDeps {
 SmallString<256> ExplicitPCMPath(
 !ModuleFilesDir.empty()
 ? ModuleFilesDir
-: MD.Invocation.getHeaderSearchOpts().ModuleCachePath);
+: MD.BuildInvocation.getHeaderSearchOpts().ModuleCachePath);
 llvm::sys::path::append(ExplicitPCMPath, MD.ID.ContextHash, Filename);
 return std::string(ExplicitPCMPath);
   }



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


[PATCH] D111724: [clang][deps] NFC: Remove redundant CompilerInstance reference

2021-10-21 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG24616664afd4: [clang][deps] NFC: Remove redundant 
CompilerInstance reference (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111724

Files:
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp


Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -138,11 +138,11 @@
   // This has to be delayed as the context hash can change at the start of
   // `CompilerInstance::ExecuteAction`.
   if (MDC.ContextHash.empty()) {
-MDC.ContextHash = Instance.getInvocation().getModuleHash();
+MDC.ContextHash = MDC.Instance.getInvocation().getModuleHash();
 MDC.Consumer.handleContextHash(MDC.ContextHash);
   }
 
-  SourceManager &SM = Instance.getSourceManager();
+  SourceManager &SM = MDC.Instance.getSourceManager();
 
   // Dependency generation really does want to go all the way to the
   // file entry for a source location to find out what is depended on.
@@ -185,12 +185,13 @@
 }
 
 void ModuleDepCollectorPP::EndOfMainFile() {
-  FileID MainFileID = Instance.getSourceManager().getMainFileID();
+  FileID MainFileID = MDC.Instance.getSourceManager().getMainFileID();
   MDC.MainFile = std::string(
-  Instance.getSourceManager().getFileEntryForID(MainFileID)->getName());
+  
MDC.Instance.getSourceManager().getFileEntryForID(MainFileID)->getName());
 
-  if (!Instance.getPreprocessorOpts().ImplicitPCHInclude.empty())
-MDC.FileDeps.push_back(Instance.getPreprocessorOpts().ImplicitPCHInclude);
+  if (!MDC.Instance.getPreprocessorOpts().ImplicitPCHInclude.empty())
+MDC.FileDeps.push_back(
+MDC.Instance.getPreprocessorOpts().ImplicitPCHInclude);
 
   for (const Module *M : DirectModularDeps) {
 // A top-level module might not be actually imported as a module when
@@ -229,7 +230,7 @@
   MD.ImplicitModulePCMPath = std::string(M->getASTFile()->getName());
   MD.IsSystem = M->IsSystem;
 
-  const FileEntry *ModuleMap = Instance.getPreprocessor()
+  const FileEntry *ModuleMap = MDC.Instance.getPreprocessor()
.getHeaderSearchInfo()
.getModuleMap()
.getModuleMapFileForUniquing(M);
@@ -319,7 +320,7 @@
   OriginalInvocation(std::move(OriginalCI)), OptimizeArgs(OptimizeArgs) {}
 
 void ModuleDepCollector::attachToPreprocessor(Preprocessor &PP) {
-  PP.addPPCallbacks(std::make_unique(Instance, *this));
+  PP.addPPCallbacks(std::make_unique(*this));
 }
 
 void ModuleDepCollector::attachToASTReader(ASTReader &R) {}
Index: clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
===
--- clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -141,8 +141,7 @@
 /// \c DependencyConsumer of the parent \c ModuleDepCollector.
 class ModuleDepCollectorPP final : public PPCallbacks {
 public:
-  ModuleDepCollectorPP(CompilerInstance &I, ModuleDepCollector &MDC)
-  : Instance(I), MDC(MDC) {}
+  ModuleDepCollectorPP(ModuleDepCollector &MDC) : MDC(MDC) {}
 
   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
@@ -159,8 +158,6 @@
   void EndOfMainFile() override;
 
 private:
-  /// The compiler instance for the current translation unit.
-  CompilerInstance &Instance;
   /// The parent dependency collector.
   ModuleDepCollector &MDC;
   /// Working set of direct modular dependencies.


Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -138,11 +138,11 @@
   // This has to be delayed as the context hash can change at the start of
   // `CompilerInstance::ExecuteAction`.
   if (MDC.ContextHash.empty()) {
-MDC.ContextHash = Instance.getInvocation().getModuleHash();
+MDC.ContextHash = MDC.Instance.getInvocation().getModuleHash();
 MDC.Consumer.handleContextHash(MDC.ContextHash);
   }
 
-  SourceManager &SM = Instance.getSourceManager();
+  SourceManager &SM = MDC.Instance.getSourceManager();
 
   // Dependency generation really does want to go all the way to the
   // file entry for a source location to find out what is depended on.
@@ -185,12 +185,13 @@
 }
 
 void ModuleDepCollectorPP::EndOfMainFile() {
-  FileID MainFileID = Instance.getSourceManager().getMainFileI

[PATCH] D111725: [clang][deps] NFC: Rename scanning CompilerInstance

2021-10-21 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG207e9fdea704: [clang][deps] NFC: Rename scanning 
CompilerInstance (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111725

Files:
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp

Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -134,15 +134,15 @@
FileID PrevFID) {
   if (Reason != PPCallbacks::EnterFile)
 return;
-  
+
   // This has to be delayed as the context hash can change at the start of
   // `CompilerInstance::ExecuteAction`.
   if (MDC.ContextHash.empty()) {
-MDC.ContextHash = MDC.Instance.getInvocation().getModuleHash();
+MDC.ContextHash = MDC.ScanInstance.getInvocation().getModuleHash();
 MDC.Consumer.handleContextHash(MDC.ContextHash);
   }
 
-  SourceManager &SM = MDC.Instance.getSourceManager();
+  SourceManager &SM = MDC.ScanInstance.getSourceManager();
 
   // Dependency generation really does want to go all the way to the
   // file entry for a source location to find out what is depended on.
@@ -185,13 +185,14 @@
 }
 
 void ModuleDepCollectorPP::EndOfMainFile() {
-  FileID MainFileID = MDC.Instance.getSourceManager().getMainFileID();
-  MDC.MainFile = std::string(
-  MDC.Instance.getSourceManager().getFileEntryForID(MainFileID)->getName());
+  FileID MainFileID = MDC.ScanInstance.getSourceManager().getMainFileID();
+  MDC.MainFile = std::string(MDC.ScanInstance.getSourceManager()
+ .getFileEntryForID(MainFileID)
+ ->getName());
 
-  if (!MDC.Instance.getPreprocessorOpts().ImplicitPCHInclude.empty())
+  if (!MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude.empty())
 MDC.FileDeps.push_back(
-MDC.Instance.getPreprocessorOpts().ImplicitPCHInclude);
+MDC.ScanInstance.getPreprocessorOpts().ImplicitPCHInclude);
 
   for (const Module *M : DirectModularDeps) {
 // A top-level module might not be actually imported as a module when
@@ -230,15 +231,16 @@
   MD.ImplicitModulePCMPath = std::string(M->getASTFile()->getName());
   MD.IsSystem = M->IsSystem;
 
-  const FileEntry *ModuleMap = MDC.Instance.getPreprocessor()
+  const FileEntry *ModuleMap = MDC.ScanInstance.getPreprocessor()
.getHeaderSearchInfo()
.getModuleMap()
.getModuleMapFileForUniquing(M);
   MD.ClangModuleMapFile = std::string(ModuleMap ? ModuleMap->getName() : "");
 
   serialization::ModuleFile *MF =
-  MDC.Instance.getASTReader()->getModuleManager().lookup(M->getASTFile());
-  MDC.Instance.getASTReader()->visitInputFiles(
+  MDC.ScanInstance.getASTReader()->getModuleManager().lookup(
+  M->getASTFile());
+  MDC.ScanInstance.getASTReader()->visitInputFiles(
   *MF, true, true, [&](const serialization::InputFile &IF, bool isSystem) {
 // __inferred_module.map is the result of the way in which an implicit
 // module build handles inferred modules. It adds an overlay VFS with
@@ -262,7 +264,7 @@
   MD, [&](CompilerInvocation &CI) {
 if (MDC.OptimizeArgs)
   optimizeHeaderSearchOpts(CI.getHeaderSearchOpts(),
-   *MDC.Instance.getASTReader(), *MF);
+   *MDC.ScanInstance.getASTReader(), *MF);
   });
   MD.ID.ContextHash = MD.Invocation.getModuleHash();
 
@@ -314,9 +316,10 @@
 }
 
 ModuleDepCollector::ModuleDepCollector(
-std::unique_ptr Opts, CompilerInstance &I,
-DependencyConsumer &C, CompilerInvocation &&OriginalCI, bool OptimizeArgs)
-: Instance(I), Consumer(C), Opts(std::move(Opts)),
+std::unique_ptr Opts,
+CompilerInstance &ScanInstance, DependencyConsumer &C,
+CompilerInvocation &&OriginalCI, bool OptimizeArgs)
+: ScanInstance(ScanInstance), Consumer(C), Opts(std::move(Opts)),
   OriginalInvocation(std::move(OriginalCI)), OptimizeArgs(OptimizeArgs) {}
 
 void ModuleDepCollector::attachToPreprocessor(Preprocessor &PP) {
@@ -328,7 +331,7 @@
 bool ModuleDepCollector::isPrebuiltModule(const Module *M) {
   std::string Name(M->getTopLevelModuleName());
   const auto &PrebuiltModuleFiles =
-  Instance.getHeaderSearchOpts().PrebuiltModuleFiles;
+  ScanInstance.getHeaderSearchOpts().PrebuiltModuleFiles;
   auto PrebuiltModuleFileIt = PrebuiltModuleFiles.find(Name);
   if (PrebuiltModuleFileIt == PrebuiltModuleFiles.end())
 return false;
Index: clang/l

[PATCH] D111728: [clang][deps] NFC: Rename building CompilerInvocation

2021-10-21 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc62220f9623d: [clang][deps] NFC: Rename building 
CompilerInvocation (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111728

Files:
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/tools/clang-scan-deps/ClangScanDeps.cpp


Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -362,7 +362,7 @@
 SmallString<256> ExplicitPCMPath(
 !ModuleFilesDir.empty()
 ? ModuleFilesDir
-: MD.Invocation.getHeaderSearchOpts().ModuleCachePath);
+: MD.BuildInvocation.getHeaderSearchOpts().ModuleCachePath);
 llvm::sys::path::append(ExplicitPCMPath, MD.ID.ContextHash, Filename);
 return std::string(ExplicitPCMPath);
   }
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -84,7 +84,7 @@
 std::vector ModuleDeps::getCanonicalCommandLine(
 std::function LookupPCMPath,
 std::function LookupModuleDeps) const {
-  CompilerInvocation CI(Invocation);
+  CompilerInvocation CI(BuildInvocation);
   FrontendOptions &FrontendOpts = CI.getFrontendOpts();
 
   InputKind ModuleMapInputKind(FrontendOpts.DashX.getLanguage(),
@@ -101,7 +101,7 @@
 
 std::vector
 ModuleDeps::getCanonicalCommandLineWithoutModulePaths() const {
-  return serializeCompilerInvocation(Invocation);
+  return serializeCompilerInvocation(BuildInvocation);
 }
 
 void dependencies::detail::collectPCMAndModuleMapPaths(
@@ -260,13 +260,13 @@
   llvm::DenseSet SeenModules;
   addAllSubmodulePrebuiltDeps(M, MD, SeenModules);
 
-  MD.Invocation = MDC.makeInvocationForModuleBuildWithoutPaths(
-  MD, [&](CompilerInvocation &CI) {
+  MD.BuildInvocation = MDC.makeInvocationForModuleBuildWithoutPaths(
+  MD, [&](CompilerInvocation &BuildInvocation) {
 if (MDC.OptimizeArgs)
-  optimizeHeaderSearchOpts(CI.getHeaderSearchOpts(),
+  optimizeHeaderSearchOpts(BuildInvocation.getHeaderSearchOpts(),
*MDC.ScanInstance.getASTReader(), *MF);
   });
-  MD.ID.ContextHash = MD.Invocation.getModuleHash();
+  MD.ID.ContextHash = MD.BuildInvocation.getModuleHash();
 
   llvm::DenseSet AddedModules;
   addAllSubmoduleDeps(M, MD, AddedModules);
Index: clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
===
--- clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -101,7 +101,7 @@
   bool ImportedByMainFile = false;
 
   /// Compiler invocation that can be used to build this module (without 
paths).
-  CompilerInvocation Invocation;
+  CompilerInvocation BuildInvocation;
 
   /// Gets the canonical command line suitable for passing to clang.
   ///


Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -362,7 +362,7 @@
 SmallString<256> ExplicitPCMPath(
 !ModuleFilesDir.empty()
 ? ModuleFilesDir
-: MD.Invocation.getHeaderSearchOpts().ModuleCachePath);
+: MD.BuildInvocation.getHeaderSearchOpts().ModuleCachePath);
 llvm::sys::path::append(ExplicitPCMPath, MD.ID.ContextHash, Filename);
 return std::string(ExplicitPCMPath);
   }
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -84,7 +84,7 @@
 std::vector ModuleDeps::getCanonicalCommandLine(
 std::function LookupPCMPath,
 std::function LookupModuleDeps) const {
-  CompilerInvocation CI(Invocation);
+  CompilerInvocation CI(BuildInvocation);
   FrontendOptions &FrontendOpts = CI.getFrontendOpts();
 
   InputKind ModuleMapInputKind(FrontendOpts.DashX.getLanguage(),
@@ -101,7 +101,7 @@
 
 std::vector
 ModuleDeps::getCanonicalCommandLineWithoutModulePaths() const {
-  return serializeCompilerInvocation(Invocation);
+  return serializeCompilerInvocation(BuildInvocation);
 }
 
 void dependencies::detail::collectPCMAndModuleMapPaths(
@@ -260,13 +260,13 @@
   llvm::DenseSet SeenModules;
   addAllSubmodulePrebuiltDeps(M, MD, SeenModules);
 
-  MD.Invocation =

[clang] b8b14b6 - [clang][deps] Make resource directory deduction configurable

2021-10-21 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-10-21T14:06:52+02:00
New Revision: b8b14b682c339c9ab85360d24ba9b888d52fdfbb

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

LOG: [clang][deps] Make resource directory deduction configurable

The `clang-scan-deps` CLI tool invokes the compiler with `-print-resource-dir` 
in case the `-resource-dir` argument is missing from the compilation command 
line. This is to enable running the tool on compilation databases that use 
compiler from a different toolchain than `clang-scan-deps` itself. While this 
doesn't make sense when scanning modular builds (due to the `-cc1` arguments 
the tool generates), the tool can can be used to efficiently scan for file 
dependencies of non-modular builds too.

This patch stops deducing the resource directory by invoking the compiler by 
default. This mode can still be enabled by invoking `clang-scan-deps` with 
`--resource-dir-recipe invoke-compiler`. The new default is 
`--resource-dir-recipe modify-compiler-path` which relies on the resource 
directory deduction taking place in `Driver::Driver` which is based on the 
compiler path. This makes the default more aligned with the intended usage of 
the tool while still allowing it to serve other use-cases.

Note that this functionality was also influenced by D108979, where the 
dependency scanner stopped going through `ClangTool::run`. The function tried 
to deduce the resource directory based on the current executable path, which 
might not be what the users expect when invoked from within a shared library.

Depends on D108979.

Reviewed By: dexonsmith

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

Added: 
clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json.template
clang/test/ClangScanDeps/Inputs/resource_directory/compiler
clang/test/ClangScanDeps/Inputs/resource_directory/mod.h
clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap
clang/test/ClangScanDeps/Inputs/resource_directory/tu.c
clang/test/ClangScanDeps/resource_directory.c

Modified: 
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 




diff  --git 
a/clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json.template 
b/clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json.template
new file mode 100644
index 0..b9f413db96af5
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json.template
@@ -0,0 +1,7 @@
+[
+  {
+"directory": "DIR",
+"command": "CLANG -fmodules -gmodules -fimplicit-module-maps 
-fmodules-cache-path=DIR/cache -c DIR/tu.c -o DIR/tu.o",
+"file": "DIR/tu.c"
+  }
+]

diff  --git a/clang/test/ClangScanDeps/Inputs/resource_directory/compiler 
b/clang/test/ClangScanDeps/Inputs/resource_directory/compiler
new file mode 100755
index 0..edeb2a2fd0009
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/resource_directory/compiler
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+echo "/custom/compiler/resources"

diff  --git a/clang/test/ClangScanDeps/Inputs/resource_directory/mod.h 
b/clang/test/ClangScanDeps/Inputs/resource_directory/mod.h
new file mode 100644
index 0..e69de29bb2d1d

diff  --git 
a/clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap 
b/clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap
new file mode 100644
index 0..03cbffaeb1fb5
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap
@@ -0,0 +1 @@
+module mod { header "mod.h" }

diff  --git a/clang/test/ClangScanDeps/Inputs/resource_directory/tu.c 
b/clang/test/ClangScanDeps/Inputs/resource_directory/tu.c
new file mode 100644
index 0..01f145835c765
--- /dev/null
+++ b/clang/test/ClangScanDeps/Inputs/resource_directory/tu.c
@@ -0,0 +1 @@
+#include "mod.h"

diff  --git a/clang/test/ClangScanDeps/resource_directory.c 
b/clang/test/ClangScanDeps/resource_directory.c
new file mode 100644
index 0..6912aa9a19952
--- /dev/null
+++ b/clang/test/ClangScanDeps/resource_directory.c
@@ -0,0 +1,25 @@
+// REQUIRES: shell
+
+// RUN: rm -rf %t && mkdir %t
+// RUN: cp %S/Inputs/resource_directory/* %t
+
+// Deduce the resource directory from the compiler path.
+//
+// RUN: sed -e "s|CLANG|/our/custom/bin/clang|g" -e "s|DIR|%/t|g" \
+// RUN:   %S/Inputs/resource_directory/cdb.json.template > %t/cdb_path.json
+// RUN: clang-scan-deps -compilation-database %t/cdb_path.json --format 
experimental-full \
+// RUN:   --resource-dir-recipe modify-compiler-path > %t/result_path.json
+// RUN: cat %t/result_path.json | sed 's:\?:/:g' | FileCheck %s 
--check-prefix=CHECK-PATH
+// CHECK-PATH:  "-resource-dir"
+// CHECK-PATH-NEXT: "/our/custom/lib{{.*}}"
+
+// Run the compiler and ask it for the resource directory.
+//
+// RUN: chmod +x %

[PATCH] D108366: [clang][deps] Make resource directory deduction configurable

2021-10-21 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb8b14b682c33: [clang][deps] Make resource directory 
deduction configurable (authored by jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D108366

Files:
  clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json.template
  clang/test/ClangScanDeps/Inputs/resource_directory/compiler
  clang/test/ClangScanDeps/Inputs/resource_directory/mod.h
  clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap
  clang/test/ClangScanDeps/Inputs/resource_directory/tu.c
  clang/test/ClangScanDeps/resource_directory.c
  clang/tools/clang-scan-deps/ClangScanDeps.cpp

Index: clang/tools/clang-scan-deps/ClangScanDeps.cpp
===
--- clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -204,6 +204,25 @@
 llvm::cl::desc("the module of which the dependencies are to be computed"),
 llvm::cl::cat(DependencyScannerCategory));
 
+enum ResourceDirRecipeKind {
+  RDRK_ModifyCompilerPath,
+  RDRK_InvokeCompiler,
+};
+
+static llvm::cl::opt ResourceDirRecipe(
+"resource-dir-recipe",
+llvm::cl::desc("How to produce missing '-resource-dir' argument"),
+llvm::cl::values(
+clEnumValN(RDRK_ModifyCompilerPath, "modify-compiler-path",
+   "Construct the resource directory from the compiler path in "
+   "the compilation database. This assumes it's part of the "
+   "same toolchain as this clang-scan-deps. (default)"),
+clEnumValN(RDRK_InvokeCompiler, "invoke-compiler",
+   "Invoke the compiler with '-print-resource-dir' and use the "
+   "reported path as the resource directory. (deprecated)")),
+llvm::cl::init(RDRK_ModifyCompilerPath),
+llvm::cl::cat(DependencyScannerCategory));
+
 llvm::cl::opt Verbose("v", llvm::cl::Optional,
 llvm::cl::desc("Use verbose output."),
 llvm::cl::init(false),
@@ -495,7 +514,7 @@
   AdjustedArgs.push_back("/clang:" + LastO);
 }
 
-if (!HasResourceDir) {
+if (!HasResourceDir && ResourceDirRecipe == RDRK_InvokeCompiler) {
   StringRef ResourceDir =
   ResourceDirCache.findResourceDir(Args, ClangCLMode);
   if (!ResourceDir.empty()) {
Index: clang/test/ClangScanDeps/resource_directory.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/resource_directory.c
@@ -0,0 +1,25 @@
+// REQUIRES: shell
+
+// RUN: rm -rf %t && mkdir %t
+// RUN: cp %S/Inputs/resource_directory/* %t
+
+// Deduce the resource directory from the compiler path.
+//
+// RUN: sed -e "s|CLANG|/our/custom/bin/clang|g" -e "s|DIR|%/t|g" \
+// RUN:   %S/Inputs/resource_directory/cdb.json.template > %t/cdb_path.json
+// RUN: clang-scan-deps -compilation-database %t/cdb_path.json --format experimental-full \
+// RUN:   --resource-dir-recipe modify-compiler-path > %t/result_path.json
+// RUN: cat %t/result_path.json | sed 's:\?:/:g' | FileCheck %s --check-prefix=CHECK-PATH
+// CHECK-PATH:  "-resource-dir"
+// CHECK-PATH-NEXT: "/our/custom/lib{{.*}}"
+
+// Run the compiler and ask it for the resource directory.
+//
+// RUN: chmod +x %t/compiler
+// RUN: sed -e "s|CLANG|%/t/compiler|g" -e "s|DIR|%/t|g" \
+// RUN:   %S/Inputs/resource_directory/cdb.json.template > %t/cdb_invocation.json
+// RUN: clang-scan-deps -compilation-database %t/cdb_invocation.json --format experimental-full \
+// RUN:   --resource-dir-recipe invoke-compiler > %t/result_invocation.json
+// RUN: cat %t/result_invocation.json | sed 's:\?:/:g' | FileCheck %s --check-prefix=CHECK-INVOCATION
+// CHECK-INVOCATION:  "-resource-dir"
+// CHECK-INVOCATION-NEXT: "/custom/compiler/resources"
Index: clang/test/ClangScanDeps/Inputs/resource_directory/tu.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/Inputs/resource_directory/tu.c
@@ -0,0 +1 @@
+#include "mod.h"
Index: clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap
===
--- /dev/null
+++ clang/test/ClangScanDeps/Inputs/resource_directory/module.modulemap
@@ -0,0 +1 @@
+module mod { header "mod.h" }
Index: clang/test/ClangScanDeps/Inputs/resource_directory/compiler
===
--- /dev/null
+++ clang/test/ClangScanDeps/Inputs/resource_directory/compiler
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+echo "/custom/compiler/resources"
Index: clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json.template
===
--- /dev/null
+++ clang/test/ClangScanDeps/Inputs/resource_directory/cdb.json

[PATCH] D112159: Relax assert in ExprConstant to a return None.

2021-10-21 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added a comment.

Thanks! Lots of call sites to check, appreciate the check


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112159

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


[clang] 7ff4f48 - Relax assert in ExprConstant to a return None.

2021-10-21 Thread Jon Chesterfield via cfe-commits

Author: Jon Chesterfield
Date: 2021-10-21T13:09:56+01:00
New Revision: 7ff4f48adb26429086d6fd85a14336e57cd340dc

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

LOG: Relax assert in ExprConstant to a return None.

Fixes a compiler assert on passing a compile time integer to atomic builtins.

Assert introduced in D61522
Function changed from ->bool to ->Optional in D76646
Simplifies call sites to getIntegerConstantExpr to elide the now-redundant
isValueDependent checks.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/lib/Sema/SemaAttr.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaExprCXX.cpp
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/lib/Sema/SemaType.cpp
clang/test/SemaTemplate/atomics.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 59943d19a3e42..c74e4c96f7b0f 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -15501,8 +15501,10 @@ bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
 Optional Expr::getIntegerConstantExpr(const ASTContext &Ctx,
 SourceLocation *Loc,
 bool isEvaluated) const {
-  assert(!isValueDependent() &&
- "Expression evaluator can't be called on a dependent expression.");
+  if (isValueDependent()) {
+// Expression evaluator can't succeed on a dependent expression.
+return None;
+  }
 
   APSInt Value;
 

diff  --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index 40d8beab76057..100f8e36a9b86 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -340,7 +340,7 @@ void Sema::ActOnPragmaPack(SourceLocation PragmaLoc, 
PragmaMsStackAction Action,
 
 // pack(0) is like pack(), which just works out since that is what
 // we use 0 for in PackAttr.
-if (Alignment->isTypeDependent() || Alignment->isValueDependent() || !Val 
||
+if (Alignment->isTypeDependent() || !Val ||
 !(*Val == 0 || Val->isPowerOf2()) || Val->getZExtValue() > 16) {
   Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
   return; // Ignore

diff  --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 5b9568c1ed95f..9c4e3ca103624 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -216,7 +216,7 @@ static bool checkUInt32Argument(Sema &S, const AttrInfo 
&AI, const Expr *Expr,
 uint32_t &Val, unsigned Idx = UINT_MAX,
 bool StrictlyUnsigned = false) {
   Optional I = llvm::APSInt(32);
-  if (Expr->isTypeDependent() || Expr->isValueDependent() ||
+  if (Expr->isTypeDependent() ||
   !(I = Expr->getIntegerConstantExpr(S.Context))) {
 if (Idx != UINT_MAX)
   S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
@@ -308,7 +308,7 @@ static bool checkFunctionOrMethodParameterIndex(
   (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
 
   Optional IdxInt;
-  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
+  if (IdxExpr->isTypeDependent() ||
   !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) {
 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
@@ -2860,8 +2860,7 @@ static void handleSentinelAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   if (AL.getNumArgs() > 0) {
 Expr *E = AL.getArgAsExpr(0);
 Optional Idx = llvm::APSInt(32);
-if (E->isTypeDependent() || E->isValueDependent() ||
-!(Idx = E->getIntegerConstantExpr(S.Context))) {
+if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) 
{
   S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
   << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
   return;
@@ -2880,8 +2879,7 @@ static void handleSentinelAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   if (AL.getNumArgs() > 1) {
 Expr *E = AL.getArgAsExpr(1);
 Optional Idx = llvm::APSInt(32);
-if (E->isTypeDependent() || E->isValueDependent() ||
-!(Idx = E->getIntegerConstantExpr(S.Context))) {
+if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) 
{
   S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
   << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
   return;

diff  --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 0f3f50c8f6c6f..571b790b31eaa 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp

[PATCH] D112159: Relax assert in ExprConstant to a return None.

2021-10-21 Thread Jon Chesterfield via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7ff4f48adb26: Relax assert in ExprConstant to a return None. 
(authored by JonChesterfield).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112159

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/SemaTemplate/atomics.cpp

Index: clang/test/SemaTemplate/atomics.cpp
===
--- clang/test/SemaTemplate/atomics.cpp
+++ clang/test/SemaTemplate/atomics.cpp
@@ -15,3 +15,13 @@
   }
   void h() { g(0); }
 }
+
+// Can pass value dependent integer to atomic builtin
+template 
+void fetchAdd(int *A, int V) {
+  __atomic_fetch_add(A, V, Order);
+}
+
+void fetchAddUse(int *A, int V) {
+  fetchAdd<__ATOMIC_ACQ_REL>(A, V);
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -7814,7 +7814,7 @@
 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
llvm::APSInt &Result) {
   const auto *AttrExpr = Attr.getArgAsExpr(0);
-  if (!AttrExpr->isTypeDependent() && !AttrExpr->isValueDependent()) {
+  if (!AttrExpr->isTypeDependent()) {
 if (Optional Res =
 AttrExpr->getIntegerConstantExpr(S.Context)) {
   Result = *Res;
Index: clang/lib/Sema/SemaTemplateDeduction.cpp
===
--- clang/lib/Sema/SemaTemplateDeduction.cpp
+++ clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -2169,11 +2169,10 @@
   }
 
   Expr *ArgExpr = (ArgDepMatrix->*GetArgDimensionExpr)();
-  if (!ArgExpr->isValueDependent())
-if (Optional ArgConst =
-ArgExpr->getIntegerConstantExpr(S.Context))
-  if (*ArgConst == *ParamConst)
-return Sema::TDK_Success;
+  if (Optional ArgConst =
+  ArgExpr->getIntegerConstantExpr(S.Context))
+if (*ArgConst == *ParamConst)
+  return Sema::TDK_Success;
   return Sema::TDK_NonDeducedMismatch;
 }
 
Index: clang/lib/Sema/SemaExprCXX.cpp
===
--- clang/lib/Sema/SemaExprCXX.cpp
+++ clang/lib/Sema/SemaExprCXX.cpp
@@ -2137,39 +2137,38 @@
 // Let's see if this is a constant < 0. If so, we reject it out of hand,
 // per CWG1464. Otherwise, if it's not a constant, we must have an
 // unparenthesized array type.
-if (!(*ArraySize)->isValueDependent()) {
-  // We've already performed any required implicit conversion to integer or
-  // unscoped enumeration type.
-  // FIXME: Per CWG1464, we are required to check the value prior to
-  // converting to size_t. This will never find a negative array size in
-  // C++14 onwards, because Value is always unsigned here!
-  if (Optional Value =
-  (*ArraySize)->getIntegerConstantExpr(Context)) {
-if (Value->isSigned() && Value->isNegative()) {
-  return ExprError(Diag((*ArraySize)->getBeginLoc(),
-diag::err_typecheck_negative_array_size)
-   << (*ArraySize)->getSourceRange());
-}
-
-if (!AllocType->isDependentType()) {
-  unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits(
-  Context, AllocType, *Value);
-  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
-return ExprError(
-Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
-<< toString(*Value, 10) << (*ArraySize)->getSourceRange());
-}
 
-KnownArraySize = Value->getZExtValue();
-  } else if (TypeIdParens.isValid()) {
-// Can't have dynamic array size when the type-id is in parentheses.
-Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
-<< (*ArraySize)->getSourceRange()
-<< FixItHint::CreateRemoval(TypeIdParens.getBegin())
-<< FixItHint::CreateRemoval(TypeIdParens.getEnd());
+// We've already performed any required implicit conversion to integer or
+// unscoped enumeration type.
+// FIXME: Per CWG1464, we are required to check the value prior to
+// converting to size_t. This will never find a negative array size in
+// C++14 onwards, because Value is always unsigned here!
+if (Optional Value =
+(*ArraySize)->getIntegerConstantExpr(Context)) {
+  if (Value->isSigned() && Value->isNegative()) {
+return ExprError(Diag((*ArraySize)->getBeginLoc(),

[PATCH] D112059: Fix inline builtin handling in case of redefinition

2021-10-21 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:1302
   // in case the function pointer is referenced somewhere.
-  if (FD->isInlineBuiltinDeclaration() && Fn) {
+  if (Fn) {
 std::string FDInlineName = (Fn->getName() + ".inline").str();

nickdesaulniers wrote:
> I don't think we want to do all this work if just `Fn`; ie. create a new 
> `std::string` with `.inline` suffix for every function we're going to 
> generate code (IR) for.  How about we add an additional unlikely guard:
> 
> `if (FD->getBuiltinID() && FN) {`
> 
> Because in the usual case, `FD` both has a builtin ID and is an inline 
> builtin declaration, while in the exceptional case that this patch addresses, 
> `FD` has a builtin ID but is not an inline builtin declaration.
Is it correct to gate this on whether it's a builtin or not? I thought that 
builtin-like (e.g., the usual pile of attributes) user code should also have 
the same effect, shouldn't it?



Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:1319-1321
+// everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
+// to detect that situation before we reach codegen, so do some late
+// replacement.

nickdesaulniers wrote:
> Perhaps in `Sema::CheckFunctionDeclaration`?  I see there is where we detect 
> redeclarations. The calls from there to 
> `FunctionDecl::setPreviousDeclaration()` seem to set up the redecl chain.  
> Perhaps this exceptional case (or both cases, even) would be handled better 
> there?
> 
> cc @rsmith @aaron.ballman in case they have feedback/tips/cycles.
I don't know that it's a good idea to modify the redeclaration chain in this 
case. The comments on the chain are pretty clear that it's a temporal chain 
where "previous" means previously declared in relation to the current 
declaration. @rsmith may feel differently, however.


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

https://reviews.llvm.org/D112059

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


Re: [PATCH] D111109: AddGlobalAnnotations for function with or without function body.

2021-10-21 Thread Alexander Kornienko via cfe-commits
On Thu, Oct 21, 2021 at 8:49 AM stan li  wrote:

> Hi Alex,
>
> I tried compile your repro on Windows with
>
> clang -S
>
> But it didn’t crash.
>
>
>
> Could you share the command line and environment to repro the crash?
>

I'm seeing the crash on linux on x86 with just `clang q.cc`. However, on
other platforms one may need cc1 arguments. The important ones seem to be:
$ clang++ -cc1 -triple x86_64-unknown-linux-gnu -emit-obj
 -mconstructor-aliases q.cc
PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash
backtrace, preprocessed source, and associated run script.
Stack dump:
0.  Program arguments: clang++ -cc1 -triple x86_64-unknown-linux-gnu
-emit-obj -mconstructor-aliases q.cc
1.   parser at end of file
2.  Optimizer
 #0 0x04d910ec llvm::sys::PrintStackTrace(llvm::raw_ostream&, int)
/usr/local/google/home/alexfh/work/llvm-project/llvm/lib/Support/Unix/Signals.inc:565:11
 #1 0x04d912bb PrintStackTraceSignalHandler(void*)
/usr/local/google/home/alexfh/work/llvm-project/llvm/lib/Support/Unix/Signals.inc:632:1
 #2 0x04d8f826 llvm::sys::RunSignalHandlers()
/usr/local/google/home/alexfh/work/llvm-project/llvm/lib/Support/Signals.cpp:96:5
 #3 0x04d91a47 SignalHandler(int)
/usr/local/google/home/alexfh/work/llvm-project/llvm/lib/Support/Unix/Signals.inc:407:1
 #4 0x7f76f967d8e0 __restore_rt
(/lib/x86_64-linux-gnu/libpthread.so.0+0x138e0)
 #5 0x014c09dc llvm::Value::getValueID() const
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/IR/Value.h:533:12
 #6 0x014c0be5 llvm::isa_impl::doit(llvm::Value const&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/IR/Value.h:952:29
 #7 0x014c0bc5 llvm::isa_impl_cl::doit(llvm::Value const*)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/Support/Casting.h:105:5
 #8 0x014c0b28 llvm::isa_impl_wrap::doit(llvm::Value const* const&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/Support/Ca
sting.h:131:5
 #9 0x014c0b02 llvm::isa_impl_wrap::doit(llvm::Value* const&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/Support/Casting.
h:121:5
#10 0x014c0ab5 bool llvm::isa(llvm::Value* const&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/Support/Casting.h:142:3
#11 0x014c0a15 llvm::cast_retty::ret_type llvm::cast(llvm::Value*)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/Support/
Casting.h:0:3
#12 0x03494a39
llvm::LazyCallGraph::visitReferences(llvm::SmallVectorImpl&,
llvm::SmallPtrSetImpl&, llvm::function_ref) /usr/local/google/home
/alexfh/work/llvm-project/llvm/lib/Analysis/LazyCallGraph.cpp:2000:19
#13 0x034952c4 llvm::LazyCallGraph::LazyCallGraph(llvm::Module&,
llvm::function_ref)
/usr/local/google/home/alexfh/work/llvm-project/llvm/lib/Analysis/LazyC
allGraph.cpp:208:1
#14 0x06a03ed9 llvm::LazyCallGraphAnalysis::run(llvm::Module&,
llvm::AnalysisManager&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/Analysis/LazyCallGraph.h:1257:12
#15 0x06a03d58 llvm::detail::AnalysisPassModel::Invalidator>::run(llvm::Module&,
llvm::AnalysisM
anager&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/IR/PassManagerInternal.h:323:12
#16 0x0412519b
llvm::AnalysisManager::getResultImpl(llvm::AnalysisKey*,
llvm::Module&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/IR/PassManagerImpl.h:73:35
#17 0x033b8c43 llvm::LazyCallGraphAnalysis::Result&
llvm::AnalysisManager::getResult(llvm::Module&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/incl
ude/llvm/IR/PassManager.h:786:21
#18 0x033adc08
llvm::InnerAnalysisManagerProxy, llvm::Module>::run(llvm::Module&,
llvm::AnalysisManager&) /usr/local
/google/home/alexfh/work/llvm-project/llvm/lib/Analysis/CGSCCPassManager.cpp:673:30
#19 0x06a73537 llvm::detail::AnalysisPassModel, llvm::Module>, llvm::PreservedAnalys
es, llvm::AnalysisManager::Invalidator>::run(llvm::Module&,
llvm::AnalysisManager&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/IR/PassManagerInternal.h:324:1
4
#20 0x0412519b
llvm::AnalysisManager::getResultImpl(llvm::AnalysisKey*,
llvm::Module&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/IR/PassManagerImpl.h:73:35
#21 0x033b8b73
llvm::InnerAnalysisManagerProxy, llvm::Module>::Result&
llvm::AnalysisManager::getResult, llvm::Module> >(llvm::Module&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/IR/PassManager.h:786
:21
#22 0x033ab373
llvm::ModuleToPostOrderCGSCCPassAdaptor::run(llvm::Module&,
llvm::AnalysisManager&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/lib/Analysis/CGSCCPassManager.cpp:
144:56
#23 0x04302e9b llvm::detail::PassModel >::run(llvm::Module&,
llvm::AnalysisManager&)
/usr/local/google/home/alexfh/work/llvm-project/llvm/include/llvm/IR/PassManagerInternal

[PATCH] D111790: [AArch64][Driver][SVE] Allow -msve-vector-bits=+ syntax to mean no maximum vscale

2021-10-21 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm added inline comments.



Comment at: clang/lib/Basic/Targets/AArch64.cpp:454
 
-  if (Opts.ArmSveVectorBits) {
-Builder.defineMacro("__ARM_FEATURE_SVE_BITS", 
Twine(Opts.ArmSveVectorBits));
+  if (Opts.VScaleMin) {
+Builder.defineMacro("__ARM_FEATURE_SVE_BITS", Twine(Opts.VScaleMin * 128));

Similar to my previous comment these must only be defined when both 
`Opts.VScaleMin` and `Opts.VScaleMax` have the same non-zero value.



Comment at: clang/lib/Basic/Targets/AArch64.cpp:467
 AArch64TargetInfo::getVScaleRange(const LangOptions &LangOpts) const {
-  if (LangOpts.ArmSveVectorBits) {
-unsigned VScale = LangOpts.ArmSveVectorBits / 128;
-return std::pair(VScale, VScale);
-  }
+  if (LangOpts.VScaleMin)
+return std::pair(LangOpts.VScaleMin,

Should this be `LangOpts.VScaleMin || LangOpts.VScaleMax` to be more future 
proof?



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:1828
+Val.equals("2048+")) {
+  int Bits = 0;
+  if (Val.endswith("+"))

I looks like this should be `unsigned` to ensure the correct version of 
getAsInteger is called.



Comment at: clang/lib/Driver/ToolChains/Clang.cpp:1829-1833
+  if (Val.endswith("+"))
+Val = Val.substr(0, Val.size() - 1);
+  else {
+bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
+assert(!Invalid && "Failed to parse value");

I'm wondering if with the extra complexity if it's worth parsing `Val` first 
before dealing with the numerical values.  For example:

```
if (!Val.equals("scalable")) {
  if (Val.endswith("+")) {
MinOnly = true;
Val = Val.substr(0, Val.size() - 1);
  }

  if (Val.getAsInteger(10, Bits) &&
  (Bits == 128 || (Bits == 256...)) {
Args.MakeArgString("-mvscale-min=", Bits)
if (!MinOnly)
  Args.MakeArgString("-mvscale-max=", Bits)
  } else
D.Diag(diag::err_drv_unsupported_option_argument
}
```
After writing this I'm not sure it's actually any better, so just something to 
consider.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111790

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


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

2021-10-21 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

This patch seems to case a new crash, details are at 
https://bugs.llvm.org/show_bug.cgi?id=52250.


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

https://reviews.llvm.org/D70172

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


[PATCH] D99797: [analyzer] Implemented RangeSet::Factory::unite function to handle intersections and adjacency

2021-10-21 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

I think, the visual comments that we have in `intersect` makes the code of 
`intersect` a lot easier to follow. Could you please add similar visual 
comments here? Also, I find `First` and `Second` in `intersect` way more better 
naming than `I1` and `I2`, could you please update?




Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:169
+
+  iterator I1 = LHS.begin();
+  iterator E1 = LHS.end();

I think, the naming conventions we have in `intersect` are easier to follow. 
Could we call `I1` as `First` and `I2` as `Second`?



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:181
+  // Append the rest of the ranges from another range set to the Result
+  // and return the later.
+  auto AppendRest = [&Result](iterator I, iterator E) {





Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:188
+  // Handle a corner case first when both range sets start from MIN.
+  // This helps to avoid complicated conditions below.
+  if (Min == I1->From() && Min == I2->From()) {

It is not clear what is the complicated condition that you'd like to avoid. 
Could you please elaborate?



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:189-201
+  if (Min == I1->From() && Min == I2->From()) {
+if (I1->To() > I2->To()) {
+  // The second range is entirely inside the first one. Skip it.
+  // Check for the end of the range for every incrementation.
+  if (++I2 == E2)
+return AppendRest(I1, E1);
+} else {

I'd like to see similar visual comments that we have in `intersect`.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:204-205
+  while (true) {
+// I1->From() shall be lower than I2->From().
+// Otherwise, swap the iterators.
+if (I1->From() > I2->From()) {

Let's reuse as much as possible from `intersect`, both code and comments.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:207-208
+if (I1->From() > I2->From()) {
+  std::swap(I1, I2);
+  std::swap(E1, E2);
+}

We could reuse `SwapIterators` from `intersect`. Of course for that we need to 
make a real function out of the lambda.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:211
+
+// At this point, the next range surely starts with I1->From().
+F = &I1->From();





Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:212
+// At this point, the next range surely starts with I1->From().
+F = &I1->From();
+

Let's be consistent with `intersect`. Also, you could introduce the variable 
here, and it is not needed to declare that at L176.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:214
+
+// Build a new range.
+while (true) {





Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:242
+  // Every next range of the first set always go after the second range.
+  // So swap the iterators without any check.
+  std::swap(I1, I2);




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

https://reviews.llvm.org/D99797

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


[PATCH] D112024: [clang] diagnose_as attribute for Fortify diagnosing like builtins.

2021-10-21 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/Attr.td:3822
+def DiagnoseAs : InheritableAttr {
+  let Spellings = [Clang<"diagnose_as">];
+  let Args = [ExprArgument<"Function">,

george.burgess.iv wrote:
> purely subjective nit: `diagnose_as` feels a bit too generic. if you agree, 
> does `diagnose_as_builtin` sound potentially better?
Agreed on it being a bit generic -- it sounds like this is only useful for 
Fortify, so I wonder if I'm wrong about that or whether we should name it 
`fortify_diagnose_as_builtin` or `fortify_diagnostic`, etc.



Comment at: clang/include/clang/Basic/AttrDocs.td:5936-5937
+applied to the called function as if it were the function specified by the
+attribute. The function whose diagnostics to mimic as well as the correct order
+of arguments must be specified.
+

I think we should go into more detail about what the correct order of arguments 
actually means. The example doesn't make it particularly clear what's going on.



Comment at: clang/lib/Sema/SemaChecking.cpp:602-605
+DeclRefExpr *F = dyn_cast_or_null(DAIAttr->getFunction());
+if (!F)
+  return;
+FunctionDecl *AttrDecl = dyn_cast_or_null(F->getFoundDecl());

george.burgess.iv wrote:
> It seems that this is serving as implicit validation of this attribute's 
> members (e.g., if we can't figure out the Function that this DAIAttr is 
> pointing to, we exit gracefully, etc.)
> 
> Would it be better to instead do this validation in `handleDiagnoseAsAttr`, 
> and store the results (which we can then presume are valid here) in the 
> `DiagnoseAsAttr`?
> 
> In that case, it might be easiest to simply store the `FunctionDecl` that's 
> being referenced, rather than a DRE to it.




Comment at: clang/lib/Sema/SemaChecking.cpp:653
 
-const Expr *ObjArg = TheCall->getArg(Index);
+auto IndexOptional = TranslateIndex(Index);
+if (!IndexOptional)





Comment at: clang/lib/Sema/SemaChecking.cpp:668
   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional {
-Expr *ObjArg = TheCall->getArg(Index);
+auto IndexOptional = TranslateIndex(Index);
+if (!IndexOptional)





Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1018-1019
+if (!checkUInt32Argument(S, AL, IndexExpr, Index, UINT_MAX, false)) {
+  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
+  << AL << I << IndexExpr->getSourceRange();
+  return;

This diagnostic looks incorrect to me -- the call to `checkUInt32Argument()` 
diagnoses if the expression is not an appropriately-sized integer. This 
diagnostic is about the value received being out of bounds.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:1026-1030
+  if (!AL.isArgExpr(0)) {
+S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
+<< AL << AANT_ArgumentConstantExpr;
+return;
+  }

This also seems a bit wrong -- we don't expect a constant expression, we expect 
a builtin function ID. You may need to use a new diagnostic here instead of 
reusing an existing one. Also, we should check that we got an actual builtin 
function as the expression, shouldn't we?



Comment at: clang/test/Sema/warn-fortify-source.c:184
 
+void *test_memcpy(const void *src, size_t c, void *dst) 
__attribute__((diagnose_as(__builtin_memcpy, 3, 1, 2))) {
+  return __builtin_memcpy(dst, src, c);

george.burgess.iv wrote:
> we generally try to extensively test error cases around new attributes. i'd 
> recommend the following cases:
> 
> - `diagnose_as(__function_that_doesnt_exist)`
> - `diagnose_as(function_i_predeclared_but_which_isnt_a_builtin)`
> - `diagnose_as(__builtin_memcpy, 1, 2, 3, 4)` (too many args) 
> - `diagnose_as(__builtin_memcpy, 1, 2)` (too few args)
> - `diagnose_as(__builtin_memcpy, "abc", 2, 3)` 
> - `void test_memcpy(double, double, double) 
> __attribute__((diagnose_as(__builtin_memcpy, 1, 2, 3));` (mismatched param 
> types)
> -  `diagnose_as(__some_overloaded_function_name)`
> 
> there're probably more that might be nice, but those seem like a good 
> foundation :)
Additional tests:

`diagnose_as(some_templated_function, 1, 2, 3)`
`diagnose_as(some_templated_function_instantiation, 1, 2, 3)`
`diagnose_as("123", 1, 2, 3)`

Also interesting to test is redeclaration behavior:
```
void my_awesome_func(const char *);

void use1() {
  my_awesome_func(0);
}

[[clang::diagnose_as(__builtin_strlen, 1)]] void my_awesome_func(const char 
*str) {}

void use2() {
  my_awesome_func(0);
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112024

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

[PATCH] D90996: [clang-format] Add --staged/--cached option to git-clang-format

2021-10-21 Thread Mark Lodato via Phabricator via cfe-commits
lodato requested changes to this revision.
lodato added a comment.
This revision now requires changes to proceed.

Thanks for pushing this through, @ortogonal! The change LGTM, except the two 
minor issues listed.

Name: Mark Lodato
Email: lod...@google.com




Comment at: clang/tools/clang-format/git-clang-format:140
 if not opts.diff:
   die('--diff is required when two commits are given')
   else:

Does there need to be an equivalent check that --staged requires --diff? Could 
you test to make sure that works as expected?



Comment at: clang/tools/clang-format/git-clang-format:299
   The return value's `stdin` file object will produce a patch with the
-  differences between the working directory and the first commit if a single
+  differences between the working/cached directory and the first commit if a 
single
   one was specified, or the difference between both specified commits, filtered

nit: probably more clear to say "working directory (or stage if `staged`)" or 
something like that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90996

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


[PATCH] D111993: [libomptarget][WIP] Patch amdgpu DeviceRTL until it compiles

2021-10-21 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield abandoned this revision.
JonChesterfield added a comment.

Going to discard this and recreate as a new patch which includes the two cmake 
ones (D111983  and D111987 
)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111993

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


[PATCH] D106681: [analyzer][NFCI] Move a block from `getBindingForElement` to separate functions

2021-10-21 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 381240.
ASDenysPetrov added a comment.

Added a comment to //initialization.c//, that we can reason about values of 
constant array which doesn't have an initializer. This is not such simple for 
C++, since there are much more ways to initialize the array.


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

https://reviews.llvm.org/D106681

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.c
  clang/test/Analysis/initialization.cpp

Index: clang/test/Analysis/initialization.cpp
===
--- clang/test/Analysis/initialization.cpp
+++ clang/test/Analysis/initialization.cpp
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -std=c++14 -triple i386-apple-darwin10 -analyze -analyzer-config eagerly-assume=false -analyzer-checker=core.uninitialized.Assign,core.builtin,debug.ExprInspection,core.uninitialized.UndefReturn -verify %s
 
+template 
+void clang_analyzer_dump(T x);
 void clang_analyzer_eval(int);
 
 struct S {
@@ -32,6 +34,10 @@
   auto x = ptr[idx]; // expected-warning{{garbage or undefined}}
 }
 
+void glob_symbolic_index1(int idx) {
+  clang_analyzer_dump(glob_arr1[idx]); // expected-warning{{Unknown}}
+}
+
 int const glob_arr2[4] = {1, 2};
 void glob_ptr_index1() {
   int const *ptr = glob_arr2;
@@ -128,3 +134,15 @@
   // FIXME: Should warn {{garbage or undefined}}.
   auto x = ptr[idx]; // // no-warning
 }
+
+extern const int glob_arr_no_init[10];
+void glob_array_index4() {
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
+
+struct S2 {
+  static const int arr_no_init[10];
+};
+void struct_arr_index1() {
+  clang_analyzer_eval(S2::arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -97,3 +97,9 @@
   // FIXME: Should warn {{garbage or undefined}}.
   int res = glob_arr2[x][y]; // no-warning
 }
+
+const int glob_arr_no_init[10];
+void glob_arr_index4() {
+  // FIXME: Should warn {{FALSE}}, since the array has a static storage.
+  clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -437,6 +437,10 @@
 
   RegionBindingsRef removeSubRegionBindings(RegionBindingsConstRef B,
 const SubRegion *R);
+  Optional getConstantValFromConstArrayInitializer(
+  RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R);
+  Optional getSValFromInitListExpr(const InitListExpr *ILE,
+ uint64_t Offset, QualType ElemT);
 
 public: // Part of public interface to class.
 
@@ -1625,6 +1629,95 @@
   return Result;
 }
 
+Optional RegionStoreManager::getConstantValFromConstArrayInitializer(
+RegionBindingsConstRef B, const VarRegion *VR, const ElementRegion *R) {
+  assert(R && VR && "Regions should not be null");
+
+  // Check if the containing array has an initialized value that we can trust.
+  // We can trust a const value or a value of a global initializer in main().
+  const VarDecl *VD = VR->getDecl();
+  if (!VD->getType().isConstQualified() &&
+  !R->getElementType().isConstQualified() &&
+  (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
+return None;
+
+  // Array's declaration should have an initializer.
+  const Expr *Init = VD->getAnyInitializer();
+  if (!Init)
+return None;
+
+  // Array's declaration should have ConstantArrayType type, because only this
+  // type contains an array extent.
+  const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(VD->getType());
+  if (!CAT)
+return None;
+
+  // Array should be one-dimensional.
+  // TODO: Support multidimensional array.
+  if (isa(CAT->getElementType())) // is multidimensional
+return None;
+
+  // Array's offset should be a concrete value.
+  // Return Unknown value if symbolic index presented.
+  // FIXME: We also need to take ElementRegions with symbolic
+  // indexes into account.
+  const auto OffsetVal = R->getIndex().getAs();
+  if (!OffsetVal.hasValue())
+return UnknownVal();
+
+  // Check offset for being out of bounds.
+  // C++20 [expr.add] 7.6.6.4 (excerpt):
+  //   If P points to an array element i of an array object x with n
+  //   elements, where i < 0 or i > n, the behavior is undefined.
+  //   Dereferencing is not allowed on the "one past the last
+  //   element", when i == n.
+  // Example:
+  //   const int arr[4] = {1, 2};
+  //   const int *ptr = arr;
+  //   int x0 = ptr[0];  // 1
+  //   int x1 = ptr[1];  // 2
+  //   int x2 = ptr[2];  // 0
+  //   int x3 = ptr[3];  // 0
+  //   int x4 = 

[PATCH] D111542: [analyzer] Retrieve incomplete array extent from its redeclaration.

2021-10-21 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1649-1653
+  // NOTE: `VD` is always non-null if `Init` is non-null, so we can check for
+  // null only one of them.
+  const Expr *Init = VD->getAnyInitializer(VD);
   if (!Init)
 return None;

martong wrote:
> steakhal wrote:
> > Wait. But if `VD` is null, you get a null-dereference.
> > But you already dereferenced `VD` multiple times, so it cannot be null.
> > 
> > Oh, but the `getAnyInitializer()` will overwrite it! That's a surprise.
> > TBH I would rather pass a fresh uninitialized pointer if you really need 
> > the exact decl which actually provided the initialized expression to make 
> > this behavior explicit.
> > 
> > That way, with a properly chosen name you could spare the NOTE comment as 
> > well.
> Yes I agree, probably it is easier to follow the code if you make it explicit 
> that `VD` is overwritten here.
> Wait. But if VD is null, you get a null-dereference.
We have an assertion above.
> Oh, but the getAnyInitializer() will overwrite it! That's a surprise.
So was for me :) I'll add a NOTE in the comment.


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

https://reviews.llvm.org/D111542

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


[PATCH] D110436: Add %n format specifier warning to clang-tidy

2021-10-21 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/PercentNFormatSpecifierCheck.cpp:26-27
+  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
+ const char *startSpecifier,
+ unsigned specifierLen) override {
+const analyze_printf::PrintfConversionSpecifier &CS =





Comment at: 
clang-tools-extra/clang-tidy/bugprone/PercentNFormatSpecifierCheck.cpp:43-57
+  auto PrintfDecl = functionDecl(hasName("::printf"));
+  auto FprintfDecl = functionDecl(hasName("::fprintf"));
+  auto VfprintfDecl = functionDecl(hasName("::vfprintf"));
+  auto SprintfDecl = functionDecl(hasName("::sprintf"));
+  auto SnprintfDecl = functionDecl(hasName("::snprintf"));
+  auto VprintfDecl = functionDecl(hasName("::vprintf"));
+  auto VsprintfDecl = functionDecl(hasName("::vsprintf"));

Rather than separate all these into individual matchers, I think it's better to 
use `hasAnyName()`. e.g.,
```
  Finder->addMatcher(
  callExpr(callee(functionDecl(
   hasAnyName("::printf", "::vprintf", "::scanf", "::vscanf"))),
   hasArgument(0, stringLiteral().bind("StringLiteral"))),
  this);
```
Also, it looks like this misses the `wchar_t` variants.

One additional design question is whether we should consider user-specified 
functions which use the `format` attribute in general. Using that attribute 
implies the function handles format specifier strings, so it seems like those 
functions would also want to flag %n for this particular check.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/PercentNFormatSpecifierCheck.cpp:89
+Result.Context->getTargetInfo());
+diag(loc, "usage of %%n can lead to unsafe writing to memory");
+  }

FWIW, this diagnostic sounds more scary than I think it should. This implies to 
me that tidy has found an unsafe usage when in fact, tidy is only identifying 
that you have used the feature at all.

Personally, I think it's more useful to limit the check to problematic 
situations. Use of `%n` by itself is not unsafe (in fact, I cannot think of a 
situation where use of `%n` in a *string literal* format specifier is ever a 
problem by itself. Generally, the safety concerns come from having a *non 
string literal* format specifier where an attacker can insert their own `%n`.

If you want this check to be "did you use `%n` at all", then I think the 
diagnostic should read more along the lines of `'%n' used as a format 
specifier` instead. However, I question whether "bugprone" is the right place 
for it at that point, because it's not really pointing out buggy code.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone-percent-n-format-specifier.rst:7-8
+Finds any usage of the %n format specifier inside the format string
+of a call to printf, scanf, or any of their derivatives. The %n format
+specifier can lead to unsafe writing to memory.
+

Similar concerns about overselling the safety aspect of using `%n`.


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

https://reviews.llvm.org/D110436

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


[PATCH] D110925: [clangd] Follow-up on rGdea48079b90d

2021-10-21 Thread ntfshard via Phabricator via cfe-commits
ntfshard added a comment.

It seems I faced with degradation in compile time.




Comment at: llvm/include/llvm/Support/FileSystem/UniqueID.h:68
+return hash_value(
+std::pair(Tag.getDevice(), Tag.getFile()));
+  }

In this line a narrow conversion, and MSVC compiler can't build it with 
warnings as error key. 
getDevice and getFile returns uint64_t but pair expects unsigned ints.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110925

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


[PATCH] D111542: [analyzer] Retrieve incomplete array extent from its redeclaration.

2021-10-21 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 381252.
ASDenysPetrov added a comment.

Rebased. Updated comment for obscure behaviour of `getAnyInitializer` function.


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

https://reviews.llvm.org/D111542

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.c


Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -103,3 +103,42 @@
   // FIXME: Should warn {{FALSE}}, since the array has a static storage.
   clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
 }
+
+const int glob_arr3[];  // IncompleteArrayType
+const int glob_arr3[4] = {1, 2, 3}; // ConstantArrayType
+void glob_arr_index5() {
+  clang_analyzer_eval(glob_arr3[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index5() {
+  int x = 42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index6() {
+  int x = -42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+const int glob_arr4[];  // IncompleteArrayType
+const int glob_arr4[4] = {1, 2, 3}; // ConstantArrayType
+const int glob_arr4[];  // ConstantArrayType (according to AST)
+void glob_arr_index6() {
+  clang_analyzer_eval(glob_arr4[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index7() {
+  int x = 42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index8() {
+  int x = -42;
+  int res = glob_arr4[x]; // expected-warning{{garbage or undefined}}
+}
Index: clang/lib/StaticAnalyzer/Core/RegionStore.cpp
===
--- clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1641,8 +1641,17 @@
   (!B.isMainAnalysis() || !VD->hasGlobalStorage()))
 return None;
 
-  // Array's declaration should have an initializer.
-  const Expr *Init = VD->getAnyInitializer();
+  // Array's declaration should have `ConstantArrayType` type, because only 
this
+  // type contains an array extent. It may happen that array type can be of
+  // `IncompleteArrayType` type. To get the declaration of `ConstantArrayType`
+  // type, we should find the declaration in the redeclarations chain that has
+  // the initialization expression.
+  // NOTE: `getAnyInitializer` has an out-parameter, which returns a new `VD`
+  // from which an initializer is obtained. We replace current `VD` with the 
new
+  // `VD`.
+  const Expr *Init = VD->getAnyInitializer(VD);
+  // NOTE: If `Init` is non-null, then a new `VD` is non-null for sure. So 
check
+  // `Init` for null only and don't worry about the replaced `VD`.
   if (!Init)
 return None;
 


Index: clang/test/Analysis/initialization.c
===
--- clang/test/Analysis/initialization.c
+++ clang/test/Analysis/initialization.c
@@ -103,3 +103,42 @@
   // FIXME: Should warn {{FALSE}}, since the array has a static storage.
   clang_analyzer_eval(glob_arr_no_init[2]); // expected-warning{{UNKNOWN}}
 }
+
+const int glob_arr3[];  // IncompleteArrayType
+const int glob_arr3[4] = {1, 2, 3}; // ConstantArrayType
+void glob_arr_index5() {
+  clang_analyzer_eval(glob_arr3[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr3[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index5() {
+  int x = 42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index6() {
+  int x = -42;
+  int res = glob_arr3[x]; // expected-warning{{garbage or undefined}}
+}
+
+const int glob_arr4[];  // IncompleteArrayType
+const int glob_arr4[4] = {1, 2, 3}; // ConstantArrayType
+const int glob_arr4[];  // ConstantArrayType (according to AST)
+void glob_arr_index6() {
+  clang_analyzer_eval(glob_arr4[0] == 1); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[1] == 2); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[2] == 3); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr4[3] == 0); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index7() {
+  int x = 42;
+  int res = glob_arr4[x]; // expected-warning{{g

Re: [clang] 2edb89c - Lex arguments for __has_cpp_attribute and friends as expanded tokens

2021-10-21 Thread Aaron Ballman via cfe-commits
On Mon, Oct 18, 2021 at 4:13 PM Richard Smith  wrote:
>
> On Mon, 18 Oct 2021 at 12:56, Aaron Ballman  wrote:
>>
>> On Mon, Oct 18, 2021 at 3:52 PM Richard Smith  wrote:
>> >
>> >  On Mon, 18 Oct 2021 at 12:48, Aaron Ballman  
>> > wrote:
>> >>
>> >> On Mon, Oct 18, 2021 at 3:33 PM Richard Smith  
>> >> wrote:
>> >> >
>> >> > On Sun, 17 Oct 2021 at 04:58, Aaron Ballman via cfe-commits 
>> >> >  wrote:
>> >> >>
>> >> >>
>> >> >> Author: Aaron Ballman
>> >> >> Date: 2021-10-17T07:54:48-04:00
>> >> >> New Revision: 2edb89c746848c52964537268bf03e7906bf2542
>> >> >>
>> >> >> URL: 
>> >> >> https://github.com/llvm/llvm-project/commit/2edb89c746848c52964537268bf03e7906bf2542
>> >> >> DIFF: 
>> >> >> https://github.com/llvm/llvm-project/commit/2edb89c746848c52964537268bf03e7906bf2542.diff
>> >> >>
>> >> >> LOG: Lex arguments for __has_cpp_attribute and friends as expanded 
>> >> >> tokens
>> >> >>
>> >> >> The C and C++ standards require the argument to __has_cpp_attribute and
>> >> >> __has_c_attribute to be expanded ([cpp.cond]p5). It would make little 
>> >> >> sense
>> >> >> to expand the argument to those operators but not expand the argument 
>> >> >> to
>> >> >> __has_attribute and __has_declspec, so those were both also changed in 
>> >> >> this
>> >> >> patch.
>> >> >>
>> >> >> Note that it might make sense for the other builtins to also expand 
>> >> >> their
>> >> >> argument, but it wasn't as clear to me whether the behavior would be 
>> >> >> correct
>> >> >> there, and so they were left for a future revision.
>> >> >>
>> >> >> Added:
>> >> >> clang/test/Preprocessor/has_attribute_errors.cpp
>> >> >>
>> >> >> Modified:
>> >> >> clang/docs/ReleaseNotes.rst
>> >> >> clang/lib/Lex/PPMacroExpansion.cpp
>> >> >> clang/test/Preprocessor/has_attribute.c
>> >> >> clang/test/Preprocessor/has_attribute.cpp
>> >> >> clang/test/Preprocessor/has_c_attribute.c
>> >> >>
>> >> >> Removed:
>> >> >>
>> >> >>
>> >> >>
>> >> >> 
>> >> >> diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
>> >> >> index 6501a4870e2a6..263eae83036df 100644
>> >> >> --- a/clang/docs/ReleaseNotes.rst
>> >> >> +++ b/clang/docs/ReleaseNotes.rst
>> >> >> @@ -110,6 +110,13 @@ Attribute Changes in Clang
>> >> >>attribute is handled instead, e.g. in ``handleDeclAttribute``.
>> >> >>(This was changed in order to better support attributes in code 
>> >> >> completion).
>> >> >>
>> >> >> +- __has_cpp_attribute, __has_c_attribute, __has_attribute, and 
>> >> >> __has_declspec
>> >> >> +  will now macro expand their argument. This causes a change in 
>> >> >> behavior for
>> >> >> +  code using ``__has_cpp_attribute(__clang__::attr)`` (and same for
>> >> >> +  ``__has_c_attribute``) where it would previously expand to ``0`` 
>> >> >> for all
>> >> >> +  attributes, but will now issue an error due to the expansion of the
>> >> >> +  predefined ``__clang__`` macro.
>> >> >> +
>> >> >>  Windows Support
>> >> >>  ---
>> >> >>
>> >> >>
>> >> >> diff  --git a/clang/lib/Lex/PPMacroExpansion.cpp 
>> >> >> b/clang/lib/Lex/PPMacroExpansion.cpp
>> >> >> index bf19f538647e6..5a0fa5184e38b 100644
>> >> >> --- a/clang/lib/Lex/PPMacroExpansion.cpp
>> >> >> +++ b/clang/lib/Lex/PPMacroExpansion.cpp
>> >> >> @@ -1293,7 +1293,7 @@ static bool EvaluateHasIncludeNext(Token &Tok,
>> >> >>  /// integer values.
>> >> >>  static void 
>> >> >> EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
>> >> >>  Token &Tok, 
>> >> >> IdentifierInfo *II,
>> >> >> -Preprocessor &PP,
>> >> >> +Preprocessor &PP, bool 
>> >> >> ExpandArgs,
>> >> >>  llvm::function_ref<
>> >> >>int(Token &Tok,
>> >> >>bool 
>> >> >> &HasLexedNextTok)> Op) {
>> >> >> @@ -1319,7 +1319,10 @@ static void 
>> >> >> EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
>> >> >>bool SuppressDiagnostic = false;
>> >> >>while (true) {
>> >> >>  // Parse next token.
>> >> >> -PP.LexUnexpandedToken(Tok);
>> >> >> +if (ExpandArgs)
>> >> >> +  PP.Lex(Tok);
>> >> >> +else
>> >> >> +  PP.LexUnexpandedToken(Tok);
>> >> >
>> >> >
>> >> > How does this handle things like:
>> >> >
>> >> > #define RPAREN )
>> >> > #if __has_attribute(clang::fallthrough RPAREN
>> >> >
>> >> > ? I think that should be an error: the ) token should not be produced 
>> >> > by macro expansion, analogous to the behavior of function-like macros. 
>> >> > But I imagine unless we're careful here, we'll allow that macro 
>> >> > expansion to terminate the "macro".
>> >>
>> >> I agree, I think that should be an error. We handle it reasonably too; I 
>> >> get:
>> >>
>> >> error: missing ')'

[PATCH] D110925: [clangd] Follow-up on rGdea48079b90d

2021-10-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev marked an inline comment as done.
kbobyrev added inline comments.



Comment at: llvm/include/llvm/Support/FileSystem/UniqueID.h:68
+return hash_value(
+std::pair(Tag.getDevice(), Tag.getFile()));
+  }

ntfshard wrote:
> In this line a narrow conversion, and MSVC compiler can't build it with 
> warnings as error key. 
> getDevice and getFile returns uint64_t but pair expects unsigned ints.
> 
> 
Thank you for noticing! Fixed in 
https://github.com/llvm/llvm-project/commit/88303693ce97cf842f0714068c2cae44cd6515e1


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110925

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


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

2021-10-21 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked an inline comment as done.
yaxunl added a comment.

In D70172#3077696 , @hokein wrote:

> This patch seems to cause a new crash, details are at 
> https://bugs.llvm.org/show_bug.cgi?id=52250.

I will take a look. Thanks.


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

https://reviews.llvm.org/D70172

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


[PATCH] D112221: Mark ATOMIC_VAR_INIT and ATOMIC_FLAG_INIT as deprecated

2021-10-21 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: rsmith, ldionne, cjdb, erichkeane.
aaron.ballman requested review of this revision.
Herald added a project: clang.

C17 deprecated `ATOMIC_VAR_INIT` with the resolution of DR 485. C++ followed 
suit when adopting P0883R2 for C++20, but additionally chose to deprecate 
`ATOMIC_FLAG_INIT` at the same time despite the macro still being required in 
C. This patch marks both macros as deprecated when appropriate to do so.

It does so by using `#pragma clang deprecated` and this patch presumes we don't 
have to guard those uses of the pragma with compiler or compiler version checks.

I believe libc++ will need some changes to address the deprecation as it seems 
it is using these macros. I'm not a libc++ maintainer and so I've added a few 
libc++ folks to the review so they can weigh in on whether libc++ should change 
first or can react to the changes in this patch. If libc++ needs to change 
first and you'd like me to drive those changes, I'd appreciate knowing what 
changes the maintainers would like to see there (I believe that removing the 
ATOMIC_VAR_INIT and using direct initialization would be appropriate, but I 
have no idea if the maintainers agree).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112221

Files:
  clang/lib/Headers/stdatomic.h
  clang/test/Headers/stdatomic-deprecations.c


Index: clang/test/Headers/stdatomic-deprecations.c
===
--- /dev/null
+++ clang/test/Headers/stdatomic-deprecations.c
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c11 %s -verify=okay
+// RUN: %clang_cc1 -fsyntax-only -std=c17 %s -verify
+// RUN: %clang_cc1 -fsyntax-only -std=c++11 -x c++ %s -verify=okay
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -x c++ %s -verify=cxx,expected
+
+// okay-no-diagnostics
+
+#include 
+
+void func(void) {
+  (void)ATOMIC_VAR_INIT(12); // expected-warning {{macro 'ATOMIC_VAR_INIT' has 
been marked as deprecated}}
+  #if defined(ATOMIC_FLAG_INIT) // cxx-warning {{macro 'ATOMIC_FLAG_INIT' has 
been marked as deprecated}}
+  #endif
+}
+
Index: clang/lib/Headers/stdatomic.h
===
--- clang/lib/Headers/stdatomic.h
+++ clang/lib/Headers/stdatomic.h
@@ -40,6 +40,10 @@
 /* 7.17.2 Initialization */
 
 #define ATOMIC_VAR_INIT(value) (value)
+#if __STDC_VERSION__ >= 201710L || __cplusplus >= 202002L
+/* ATOMIC_VAR_INIT was deprecated in C17 and C++20. */
+#pragma clang deprecated(ATOMIC_VAR_INIT)
+#endif
 #define atomic_init __c11_atomic_init
 
 /* 7.17.3 Order and consistency */
@@ -149,6 +153,10 @@
 typedef struct atomic_flag { atomic_bool _Value; } atomic_flag;
 
 #define ATOMIC_FLAG_INIT { 0 }
+#if __cplusplus >= 202002L
+/* ATOMIC_FLAG_INIT was deprecated in C++20 but is not deprecated in C. */
+#pragma clang deprecated(ATOMIC_FLAG_INIT)
+#endif
 
 /* These should be provided by the libc implementation. */
 #ifdef __cplusplus


Index: clang/test/Headers/stdatomic-deprecations.c
===
--- /dev/null
+++ clang/test/Headers/stdatomic-deprecations.c
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c11 %s -verify=okay
+// RUN: %clang_cc1 -fsyntax-only -std=c17 %s -verify
+// RUN: %clang_cc1 -fsyntax-only -std=c++11 -x c++ %s -verify=okay
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -x c++ %s -verify=cxx,expected
+
+// okay-no-diagnostics
+
+#include 
+
+void func(void) {
+  (void)ATOMIC_VAR_INIT(12); // expected-warning {{macro 'ATOMIC_VAR_INIT' has been marked as deprecated}}
+  #if defined(ATOMIC_FLAG_INIT) // cxx-warning {{macro 'ATOMIC_FLAG_INIT' has been marked as deprecated}}
+  #endif
+}
+
Index: clang/lib/Headers/stdatomic.h
===
--- clang/lib/Headers/stdatomic.h
+++ clang/lib/Headers/stdatomic.h
@@ -40,6 +40,10 @@
 /* 7.17.2 Initialization */
 
 #define ATOMIC_VAR_INIT(value) (value)
+#if __STDC_VERSION__ >= 201710L || __cplusplus >= 202002L
+/* ATOMIC_VAR_INIT was deprecated in C17 and C++20. */
+#pragma clang deprecated(ATOMIC_VAR_INIT)
+#endif
 #define atomic_init __c11_atomic_init
 
 /* 7.17.3 Order and consistency */
@@ -149,6 +153,10 @@
 typedef struct atomic_flag { atomic_bool _Value; } atomic_flag;
 
 #define ATOMIC_FLAG_INIT { 0 }
+#if __cplusplus >= 202002L
+/* ATOMIC_FLAG_INIT was deprecated in C++20 but is not deprecated in C. */
+#pragma clang deprecated(ATOMIC_FLAG_INIT)
+#endif
 
 /* These should be provided by the libc implementation. */
 #ifdef __cplusplus
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D90996: [clang-format] Add --staged/--cached option to git-clang-format

2021-10-21 Thread Erik Larsson via Phabricator via cfe-commits
ortogonal updated this revision to Diff 381269.
ortogonal added a comment.

Update description on function `compute_diff`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90996

Files:
  clang/tools/clang-format/git-clang-format


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -32,12 +32,13 @@
 import subprocess
 import sys
 
-usage = 'git clang-format [OPTIONS] [] [] [--] [...]'
+usage = ('git clang-format [OPTIONS] [] [|--staged] '
+ '[--] [...]')
 
 desc = '''
 If zero or one commits are given, run clang-format on all lines that differ
 between the working directory and , which defaults to HEAD.  Changes 
are
-only applied to the working directory.
+only applied to the working directory, or in the stage/index.
 
 If two commits are given (requires --diff), run clang-format on all lines in 
the
 second  that differ from the first .
@@ -112,6 +113,8 @@
  help='select hunks interactively')
   p.add_argument('-q', '--quiet', action='count', default=0,
  help='print less information')
+  p.add_argument('--staged', '--cached', action='store_true',
+ help='format lines in the stage instead of the working dir')
   p.add_argument('--style',
  default=config.get('clangformat.style', None),
  help='passed to clang-format'),
@@ -131,12 +134,14 @@
 
   commits, files = interpret_args(opts.args, dash_dash, opts.commit)
   if len(commits) > 1:
+if opts.staged:
+  die('--staged is not allowed when two commits are given')
 if not opts.diff:
   die('--diff is required when two commits are given')
   else:
 if len(commits) > 2:
   die('at most two commits allowed; %d given' % len(commits))
-  changed_lines = compute_diff_and_extract_lines(commits, files)
+  changed_lines = compute_diff_and_extract_lines(commits, files, opts.staged)
   if opts.verbose >= 1:
 ignored_files = set(changed_lines)
   filter_by_extension(changed_lines, opts.extensions.lower().split(','))
@@ -275,9 +280,9 @@
   return convert_string(stdout.strip())
 
 
-def compute_diff_and_extract_lines(commits, files):
+def compute_diff_and_extract_lines(commits, files, staged):
   """Calls compute_diff() followed by extract_lines()."""
-  diff_process = compute_diff(commits, files)
+  diff_process = compute_diff(commits, files, staged)
   changed_lines = extract_lines(diff_process.stdout)
   diff_process.stdout.close()
   diff_process.wait()
@@ -287,17 +292,21 @@
   return changed_lines
 
 
-def compute_diff(commits, files):
+def compute_diff(commits, files, staged):
   """Return a subprocess object producing the diff from `commits`.
 
   The return value's `stdin` file object will produce a patch with the
-  differences between the working directory and the first commit if a single
-  one was specified, or the difference between both specified commits, filtered
-  on `files` (if non-empty).  Zero context lines are used in the patch."""
+  differences between the working directory (or stage if --staged is used) and
+  the first commit if a single one was specified, or the difference between
+  both specified commits, filtered on `files` (if non-empty).
+  Zero context lines are used in the patch."""
   git_tool = 'diff-index'
+  extra_args = []
   if len(commits) > 1:
 git_tool = 'diff-tree'
-  cmd = ['git', git_tool, '-p', '-U0'] + commits + ['--']
+  elif staged:
+extra_args += ['--cached']
+  cmd = ['git', git_tool, '-p', '-U0'] + extra_args + commits + ['--']
   cmd.extend(files)
   p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
   p.stdin.close()


Index: clang/tools/clang-format/git-clang-format
===
--- clang/tools/clang-format/git-clang-format
+++ clang/tools/clang-format/git-clang-format
@@ -32,12 +32,13 @@
 import subprocess
 import sys
 
-usage = 'git clang-format [OPTIONS] [] [] [--] [...]'
+usage = ('git clang-format [OPTIONS] [] [|--staged] '
+ '[--] [...]')
 
 desc = '''
 If zero or one commits are given, run clang-format on all lines that differ
 between the working directory and , which defaults to HEAD.  Changes are
-only applied to the working directory.
+only applied to the working directory, or in the stage/index.
 
 If two commits are given (requires --diff), run clang-format on all lines in the
 second  that differ from the first .
@@ -112,6 +113,8 @@
  help='select hunks interactively')
   p.add_argument('-q', '--quiet', action='count', default=0,
  help='print less information')
+  p.add_argument('--staged', '--cached', action='store_true',
+ help='format lines in the stage instead of the working dir')
   p.add_argument('--styl

[PATCH] D111100: enable plugins for clang-tidy

2021-10-21 Thread Jameson Nash via Phabricator via cfe-commits
vtjnash added a comment.

bump?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D00

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


[PATCH] D90996: [clang-format] Add --staged/--cached option to git-clang-format

2021-10-21 Thread Erik Larsson via Phabricator via cfe-commits
ortogonal added inline comments.



Comment at: clang/tools/clang-format/git-clang-format:140
 if not opts.diff:
   die('--diff is required when two commits are given')
   else:

lodato wrote:
> Does there need to be an equivalent check that --staged requires --diff? 
> Could you test to make sure that works as expected?
Sorry, new to this system. I wrote a reply to this, but it seemed to get lost 
when uploading. Let me try again :)

The check that you can't use `--staged` with two commits is enough. For example 
it you do:
```
git clang-format --diff --staged 53f64aa089c5fd335b1337cab7eaa99d072a25fc 
273e318e1ff0fae58ec7ed248ee3c9c73da8c00e
error: --staged is not allowed when two commits are given
```

But you are allowed to run just `git clang-format --staged`. It you do:
```
$ git add foo.cc
$ git clang-format --staged
changed files:
foo.cc
```
This will run clang-format on the staged changes on foo.cc.

It this what you meant or did I misunderstand you.

Thanks for your review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D90996

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


[PATCH] D107339: [analyzer] Retrieve a character from StringLiteral as an initializer for constant arrays.

2021-10-21 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov updated this revision to Diff 381274.
ASDenysPetrov added a comment.

Rebased. Improved behavior to make `glob_invalid_index8` case passed and some 
other cases. Added more tests. Added tests for universal characters.


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

https://reviews.llvm.org/D107339

Files:
  clang/lib/StaticAnalyzer/Core/RegionStore.cpp
  clang/test/Analysis/initialization.cpp

Index: clang/test/Analysis/initialization.cpp
===
--- clang/test/Analysis/initialization.cpp
+++ clang/test/Analysis/initialization.cpp
@@ -146,3 +146,105 @@
 void struct_arr_index1() {
   clang_analyzer_eval(S2::arr_no_init[2]); // expected-warning{{UNKNOWN}}
 }
+
+char const glob_arr6[5] = "123";
+void glob_array_index5() {
+  clang_analyzer_eval(glob_arr6[0] == '1');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr6[1] == '2');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr6[2] == '3');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr6[3] == '\0'); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr6[4] == '\0'); // expected-warning{{TRUE}}
+}
+
+void glob_ptr_index3() {
+  char const *ptr = glob_arr6;
+  clang_analyzer_eval(ptr[-42] == '\0'); // expected-warning{{UNDEFINED}}
+  clang_analyzer_eval(ptr[0] == '1');// expected-warning{{TRUE}}
+  clang_analyzer_eval(ptr[1] == '2');// expected-warning{{TRUE}}
+  clang_analyzer_eval(ptr[2] == '3');// expected-warning{{TRUE}}
+  clang_analyzer_eval(ptr[3] == '\0');   // expected-warning{{TRUE}}
+  clang_analyzer_eval(ptr[4] == '\0');   // expected-warning{{TRUE}}
+  clang_analyzer_eval(ptr[5] == '\0');   // expected-warning{{UNDEFINED}}
+  clang_analyzer_eval(ptr[6] == '\0');   // expected-warning{{UNDEFINED}}
+}
+
+void glob_invalid_index7() {
+  int idx = -42;
+  auto x = glob_arr6[idx]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index8() {
+  const char *ptr = glob_arr6;
+  int idx = 42;
+  auto x = ptr[idx]; // expected-warning{{garbage or undefined}}
+}
+
+char const glob_arr7[5] = {"123"};
+void glob_array_index6() {
+  clang_analyzer_eval(glob_arr7[0] == '1');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr7[1] == '2');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr7[2] == '3');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr7[3] == '\0'); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_arr7[4] == '\0'); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index9() {
+  int idx = -42;
+  auto x = glob_arr7[idx]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index10() {
+  const char *ptr = glob_arr7;
+  int idx = 42;
+  auto x = ptr[idx]; // expected-warning{{garbage or undefined}}
+}
+
+char const *const glob_ptr8 = "123";
+void glob_ptr_index4() {
+  clang_analyzer_eval(glob_ptr8[0] == '1');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr8[1] == '2');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr8[2] == '3');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr8[3] == '\0'); // expected-warning{{TRUE}}
+}
+
+void glob_invalid_index11() {
+  int idx = -42;
+  auto x = glob_ptr8[idx]; // expected-warning{{garbage or undefined}}
+}
+
+void glob_invalid_index12() {
+  int idx = 42;
+  auto x = glob_ptr8[idx]; // expected-warning{{garbage or undefined}}
+}
+
+const char16_t *const glob_ptr9 = u"абв";
+void glob_ptr_index5() {
+  clang_analyzer_eval(glob_ptr9[0] == u'а'); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr9[1] == u'б'); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr9[2] == u'в'); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr9[3] == '\0'); // expected-warning{{TRUE}}
+}
+
+const char32_t *const glob_ptr10 = U"\U0001F607\U0001F608\U0001F609";
+void glob_ptr_index6() {
+  clang_analyzer_eval(glob_ptr10[0] == U'\U0001F607'); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr10[1] == U'\U0001F608'); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr10[2] == U'\U0001F609'); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr10[3] == '\0');  // expected-warning{{TRUE}}
+}
+
+const wchar_t *const glob_ptr11 = L"\123\u0041\xFF";
+void glob_ptr_index7() {
+  clang_analyzer_eval(glob_ptr11[0] == L'\123');   // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr11[1] == L'\u0041'); // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr11[2] == L'\xFF');   // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr11[3] == L'\0'); // expected-warning{{TRUE}}
+}
+
+const char *const glob_ptr12 = u8"abc";
+void glob_ptr_index8() {
+  clang_analyzer_eval(glob_ptr12[0] == 'a');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr12[1] == 'b');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr12[2] == 'c');  // expected-warning{{TRUE}}
+  clang_analyzer_eval(glob_ptr12[3] == '\0')

[PATCH] D112227: [libomptarget] Build DeviceRTL for amdgpu

2021-10-21 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield created this revision.
Herald added subscribers: kerbowa, t-tye, tpr, dstuttard, yaxunl, mgorny, 
nhaehnle, jvesely, kzhuravl.
JonChesterfield requested review of this revision.
Herald added subscribers: openmp-commits, cfe-commits, sstefan1, wdng.
Herald added a reviewer: jdoerfert.
Herald added projects: clang, OpenMP.

Doesn't pass tests yet.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112227

Files:
  clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp
  openmp/libomptarget/DeviceRTL/CMakeLists.txt
  openmp/libomptarget/DeviceRTL/src/Configuration.cpp
  openmp/libomptarget/DeviceRTL/src/Synchronization.cpp

Index: openmp/libomptarget/DeviceRTL/src/Synchronization.cpp
===
--- openmp/libomptarget/DeviceRTL/src/Synchronization.cpp
+++ openmp/libomptarget/DeviceRTL/src/Synchronization.cpp
@@ -68,8 +68,23 @@
 ///{
 #pragma omp begin declare variant match(device = {arch(amdgcn)})
 
-uint32_t atomicInc(uint32_t *Address, uint32_t Val, int Ordering) {
-  return __builtin_amdgcn_atomic_inc32(Address, Val, Ordering, "");
+uint32_t atomicInc(uint32_t *A, uint32_t V, int Ordering) {
+  // builtin_amdgcn_atomic_inc32 should expand to this switch when
+  // passed a runtime value, but does not do so yet. Workaround here.
+  switch (Ordering) {
+  default:
+__builtin_unreachable();
+  case __ATOMIC_RELAXED:
+return __builtin_amdgcn_atomic_inc32(A, V, __ATOMIC_RELAXED, "");
+  case __ATOMIC_ACQUIRE:
+return __builtin_amdgcn_atomic_inc32(A, V, __ATOMIC_ACQUIRE, "");
+  case __ATOMIC_RELEASE:
+return __builtin_amdgcn_atomic_inc32(A, V, __ATOMIC_RELEASE, "");
+  case __ATOMIC_ACQ_REL:
+return __builtin_amdgcn_atomic_inc32(A, V, __ATOMIC_ACQ_REL, "");
+  case __ATOMIC_SEQ_CST:
+return __builtin_amdgcn_atomic_inc32(A, V, __ATOMIC_SEQ_CST, "");
+  }
 }
 
 uint32_t SHARED(namedBarrierTracker);
@@ -126,17 +141,64 @@
   fence::team(__ATOMIC_RELEASE);
 }
 
+// sema checking of amdgcn_fence is aggressive. Intention is to patch clang
+// so that it is usable within a template environment and so that a runtime
+// value of the memory order is expanded to this switch within clang/llvm.
+void fenceTeam(int Ordering) {
+  switch (Ordering) {
+  default:
+__builtin_unreachable();
+  case __ATOMIC_ACQUIRE:
+return __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup");
+  case __ATOMIC_RELEASE:
+return __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup");
+  case __ATOMIC_ACQ_REL:
+return __builtin_amdgcn_fence(__ATOMIC_ACQ_REL, "workgroup");
+  case __ATOMIC_SEQ_CST:
+return __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup");
+  }
+}
+void fenceKernel(int Ordering) {
+  switch (Ordering) {
+  default:
+__builtin_unreachable();
+  case __ATOMIC_ACQUIRE:
+return __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
+  case __ATOMIC_RELEASE:
+return __builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
+  case __ATOMIC_ACQ_REL:
+return __builtin_amdgcn_fence(__ATOMIC_ACQ_REL, "agent");
+  case __ATOMIC_SEQ_CST:
+return __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "agent");
+  }
+}
+void fenceSystem(int Ordering) {
+  switch (Ordering) {
+  default:
+__builtin_unreachable();
+  case __ATOMIC_ACQUIRE:
+return __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "");
+  case __ATOMIC_RELEASE:
+return __builtin_amdgcn_fence(__ATOMIC_RELEASE, "");
+  case __ATOMIC_ACQ_REL:
+return __builtin_amdgcn_fence(__ATOMIC_ACQ_REL, "");
+  case __ATOMIC_SEQ_CST:
+return __builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "");
+  }
+}
+
 void syncWarp(__kmpc_impl_lanemask_t) {
   // AMDGCN doesn't need to sync threads in a warp
 }
 
 void syncThreads() { __builtin_amdgcn_s_barrier(); }
 
-void fenceTeam(int Ordering) { __builtin_amdgcn_fence(Ordering, "workgroup"); }
-
-void fenceKernel(int Ordering) { __builtin_amdgcn_fence(Ordering, "agent"); }
-
-void fenceSystem(int Ordering) { __builtin_amdgcn_fence(Ordering, ""); }
+// TODO: Don't have wavefront lane locks. Possibly can't have them.
+void unsetLock(omp_lock_t *) { __builtin_trap(); }
+int testLock(omp_lock_t *) { __builtin_trap(); }
+void initLock(omp_lock_t *) { __builtin_trap(); }
+void destroyLock(omp_lock_t *) { __builtin_trap(); }
+void setLock(omp_lock_t *) { __builtin_trap(); }
 
 #pragma omp end declare variant
 ///}
@@ -238,7 +300,7 @@
 }
 
 void atomic::store(uint32_t *Addr, uint32_t V, int Ordering) {
-   impl::atomicStore(Addr, V, Ordering);
+  impl::atomicStore(Addr, V, Ordering);
 }
 
 uint32_t atomic::inc(uint32_t *Addr, uint32_t V, int Ordering) {
Index: openmp/libomptarget/DeviceRTL/src/Configuration.cpp
===
--- openmp/libomptarget/DeviceRTL/src/Configuration.cpp
+++ openmp/libomptarget/DeviceRTL/src/Configuration.cpp
@@ -20,14 +20,14 @@
 
 #pragma omp declare target
 
-extern uint32_t __omp_rtl_debug_kind;
+// extern uint32_t __omp_rtl_debug_kind;
 
 // TOOD: We want to 

[PATCH] D112227: [libomptarget] Build DeviceRTL for amdgpu

2021-10-21 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: openmp/libomptarget/DeviceRTL/src/Configuration.cpp:23
 
-extern uint32_t __omp_rtl_debug_kind;
+// extern uint32_t __omp_rtl_debug_kind;
 

Otherwise the missing symbols prevents linking, not clear why it works on 
nvptx64



Comment at: openmp/libomptarget/DeviceRTL/src/Synchronization.cpp:71
 
-uint32_t atomicInc(uint32_t *Address, uint32_t Val, int Ordering) {
-  return __builtin_amdgcn_atomic_inc32(Address, Val, Ordering, "");
+uint32_t atomicInc(uint32_t *A, uint32_t V, int Ordering) {
+  // builtin_amdgcn_atomic_inc32 should expand to this switch when

This is not good, need to revise sema checking on these intrinsics and add some 
lowering in clang/llvm that builds the switch. Written longhand here to get 
things running.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112227

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


[PATCH] D111566: [SYCL] Fix function pointer address space

2021-10-21 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: rjmccall, erichkeane, Anastasia.
aaron.ballman added a comment.

Adding a few more reviewers with more familiarity with codegen and address 
spaces to make sure we've not missed something here outside of SYCL.




Comment at: clang/lib/CodeGen/CodeGenTypes.cpp:636-638
+unsigned AS = PointeeType->isFunctionTy()
+  ? getDataLayout().getProgramAddressSpace()
+  : Context.getTargetAddressSpace(ETy);

The review summary says that this is a fix for SYCL, but the fix itself happens 
for all targets, not just SYCL. If that's intentional, are we sure it's correct?


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

https://reviews.llvm.org/D111566

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


[clang] b396010 - [Clang] Support typedef with btf_decl_tag attributes

2021-10-21 Thread Yonghong Song via cfe-commits

Author: Yonghong Song
Date: 2021-10-21T08:41:49-07:00
New Revision: b396010240cda92f5fcfa30cba1b9ad905561eae

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

LOG: [Clang] Support typedef with btf_decl_tag attributes

Previously, btf_del_tag attribute supports record, field, global variable,
function and function parameter ([1], [2]). This patch added support for 
typedef.
The main reason is for typedef of an anonymous struct/union, we can only apply
btf_decl_tag attribute to the anonymous struct/union like below:
  typedef struct { ... } __btf_decl_tag target_type
In this case, the __btf_decl_tag attribute applies to anonymous struct,
which increases downstream implementation complexity. But if
typedef with btf_decl_tag attribute is supported, we can have
  typedef struct { ... } target_type __btf_decl_tag
which applies __btf_decl_tag to typedef "target_type" which make it
easier to directly associate btf_decl_tag with a named type.
This patch permitted btf_decl_tag with typedef types with this reason.

 [1] https://reviews.llvm.org/D106614
 [2] https://reviews.llvm.org/D111588

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

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/test/Misc/pragma-attribute-supported-attributes-list.test
clang/test/Sema/attr-btf_tag.c

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index e94466bd6121a..f58217f8f44ae 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1839,7 +1839,8 @@ def BPFPreserveAccessIndex : InheritableAttr,
 def BTFDeclTag : InheritableAttr {
   let Spellings = [Clang<"btf_decl_tag">];
   let Args = [StringArgument<"BTFDeclTag">];
-  let Subjects = SubjectList<[Var, Function, Record, Field], ErrorDiag>;
+  let Subjects = SubjectList<[Var, Function, Record, Field, TypedefName],
+ ErrorDiag>;
   let Documentation = [BTFDeclTagDocs];
   let LangOpts = [COnly];
 }

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 3a70f88eff0a2..71f947687a08f 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -2016,9 +2016,10 @@ def BTFDeclTagDocs : Documentation {
   let Content = [{
 Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for
 all targets. This attribute may be attached to a struct/union, struct/union
-field, function, function parameter or variable declaration. If -g is 
specified,
-the ``ARGUMENT`` info will be preserved in IR and be emitted to dwarf.
-For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF section too.
+field, function, function parameter, variable or typedef declaration. If -g is
+specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to
+dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF
+section too.
   }];
 }
 

diff  --git a/clang/test/Misc/pragma-attribute-supported-attributes-list.test 
b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
index d4cd73f5e9bce..199934b2791da 100644
--- a/clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ b/clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -22,7 +22,7 @@
 // CHECK-NEXT: Assumption (SubjectMatchRule_function, 
SubjectMatchRule_objc_method)
 // CHECK-NEXT: Availability ((SubjectMatchRule_record, SubjectMatchRule_enum, 
SubjectMatchRule_enum_constant, SubjectMatchRule_field, 
SubjectMatchRule_function, SubjectMatchRule_namespace, 
SubjectMatchRule_objc_category, SubjectMatchRule_objc_implementation, 
SubjectMatchRule_objc_interface, SubjectMatchRule_objc_method, 
SubjectMatchRule_objc_property, SubjectMatchRule_objc_protocol, 
SubjectMatchRule_record, SubjectMatchRule_type_alias, 
SubjectMatchRule_variable))
 // CHECK-NEXT: BPFPreserveAccessIndex (SubjectMatchRule_record)
-// CHECK-NEXT: BTFDeclTag (SubjectMatchRule_variable, 
SubjectMatchRule_function, SubjectMatchRule_record, SubjectMatchRule_field)
+// CHECK-NEXT: BTFDeclTag (SubjectMatchRule_variable, 
SubjectMatchRule_function, SubjectMatchRule_record, SubjectMatchRule_field, 
SubjectMatchRule_type_alias)
 // CHECK-NEXT: BuiltinAlias (SubjectMatchRule_function)
 // CHECK-NEXT: CFAuditedTransfer (SubjectMatchRule_function)
 // CHECK-NEXT: CFConsumed (SubjectMatchRule_variable_is_parameter)

diff  --git a/clang/test/Sema/attr-btf_tag.c b/clang/test/Sema/attr-btf_tag.c
index 4f2a5dd57ad93..d33ccdf962825 100644
--- a/clang/test/Sema/attr-btf_tag.c
+++ b/clang/test/Sema/attr-btf_tag.c
@@ -25,18 +25,26 @@ int i1 __invalid; // expected-error {{'btf_decl_tag' 
attribute requires a string
 
 enum e1 {
   E1
-} __tag1;

[PATCH] D110127: [Clang] Support typedef with btf_decl_tag attributes

2021-10-21 Thread Yonghong Song via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb396010240cd: [Clang] Support typedef with btf_decl_tag 
attributes (authored by yonghong-song).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110127

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/attr-btf_tag.c


Index: clang/test/Sema/attr-btf_tag.c
===
--- clang/test/Sema/attr-btf_tag.c
+++ clang/test/Sema/attr-btf_tag.c
@@ -25,18 +25,26 @@
 
 enum e1 {
   E1
-} __tag1; // expected-error {{'btf_decl_tag' attribute only applies to 
variables, functions, structs, unions, classes, and non-static data members}}
+} __tag1; // expected-error {{'btf_decl_tag' attribute only applies to 
variables, functions, structs, unions, classes, non-static data members, and 
typedefs}}
 
 enum e2 {
   E2
-} __tag_no_arg; // expected-error {{'btf_decl_tag' attribute only applies to 
variables, functions, structs, unions, classes, and non-static data members}}
+} __tag_no_arg; // expected-error {{'btf_decl_tag' attribute only applies to 
variables, functions, structs, unions, classes, non-static data members, and 
typedefs}}
 
 enum e3 {
   E3
-} __tag_2_arg; // expected-error {{'btf_decl_tag' attribute only applies to 
variables, functions, structs, unions, classes, and non-static data members}}
+} __tag_2_arg; // expected-error {{'btf_decl_tag' attribute only applies to 
variables, functions, structs, unions, classes, non-static data members, and 
typedefs}}
 
 int __tag1 __tag2 foo(struct t1 *arg, struct t2 *arg2);
 int __tag2 __tag3 foo(struct t1 *arg, struct t2 *arg2);
 int __tag1 foo(struct t1 *arg __tag1, struct t2 *arg2) {
   return arg->a + arg2->a;
 }
+
+typedef unsigned * __u1 __tag1 __tag2;
+typedef struct {
+  int a;
+} __t2 __tag1 __tag2;
+int convert2(__t2 *arg) {
+  return arg->a;
+}
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -22,7 +22,7 @@
 // CHECK-NEXT: Assumption (SubjectMatchRule_function, 
SubjectMatchRule_objc_method)
 // CHECK-NEXT: Availability ((SubjectMatchRule_record, SubjectMatchRule_enum, 
SubjectMatchRule_enum_constant, SubjectMatchRule_field, 
SubjectMatchRule_function, SubjectMatchRule_namespace, 
SubjectMatchRule_objc_category, SubjectMatchRule_objc_implementation, 
SubjectMatchRule_objc_interface, SubjectMatchRule_objc_method, 
SubjectMatchRule_objc_property, SubjectMatchRule_objc_protocol, 
SubjectMatchRule_record, SubjectMatchRule_type_alias, 
SubjectMatchRule_variable))
 // CHECK-NEXT: BPFPreserveAccessIndex (SubjectMatchRule_record)
-// CHECK-NEXT: BTFDeclTag (SubjectMatchRule_variable, 
SubjectMatchRule_function, SubjectMatchRule_record, SubjectMatchRule_field)
+// CHECK-NEXT: BTFDeclTag (SubjectMatchRule_variable, 
SubjectMatchRule_function, SubjectMatchRule_record, SubjectMatchRule_field, 
SubjectMatchRule_type_alias)
 // CHECK-NEXT: BuiltinAlias (SubjectMatchRule_function)
 // CHECK-NEXT: CFAuditedTransfer (SubjectMatchRule_function)
 // CHECK-NEXT: CFConsumed (SubjectMatchRule_variable_is_parameter)
Index: clang/include/clang/Basic/AttrDocs.td
===
--- clang/include/clang/Basic/AttrDocs.td
+++ clang/include/clang/Basic/AttrDocs.td
@@ -2016,9 +2016,10 @@
   let Content = [{
 Clang supports the ``__attribute__((btf_decl_tag("ARGUMENT")))`` attribute for
 all targets. This attribute may be attached to a struct/union, struct/union
-field, function, function parameter or variable declaration. If -g is 
specified,
-the ``ARGUMENT`` info will be preserved in IR and be emitted to dwarf.
-For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF section too.
+field, function, function parameter, variable or typedef declaration. If -g is
+specified, the ``ARGUMENT`` info will be preserved in IR and be emitted to
+dwarf. For BPF targets, the ``ARGUMENT`` info will be emitted to .BTF ELF
+section too.
   }];
 }
 
Index: clang/include/clang/Basic/Attr.td
===
--- clang/include/clang/Basic/Attr.td
+++ clang/include/clang/Basic/Attr.td
@@ -1839,7 +1839,8 @@
 def BTFDeclTag : InheritableAttr {
   let Spellings = [Clang<"btf_decl_tag">];
   let Args = [StringArgument<"BTFDeclTag">];
-  let Subjects = SubjectList<[Var, Function, Record, Field], ErrorDiag>;
+  let Subjects = SubjectList<[Var, Function, Record, Field, TypedefName],
+ ErrorDiag>;
   let Documentation = [BTFDeclTagDocs];
   let LangOpts = [COnly];
 }


Index: clang/test/Sema/attr-btf_tag.

[PATCH] D112229: Reapply [ORC-RT] Configure the ORC runtime for more architectures and platforms

2021-10-21 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir created this revision.
benlangmuir added a reviewer: lhames.
Herald added subscribers: kristof.beyls, mgorny.
benlangmuir requested review of this revision.
Herald added projects: clang, Sanitizers.
Herald added subscribers: Sanitizers, cfe-commits.

Reapply 5692ed0cce8c95 
, but with 
the ORC runtime disabled explicitly on CrossWinToARMLinux to match the other 
compiler-rt runtime libraries.

  

---

Enable building the ORC runtime for 64-bit and 32-bit ARM architectures, and 
for all Darwin embedded platforms (iOS, tvOS, and watchOS). This covers 
building the cross-platform code, but does not add TLV runtime support for the 
new architectures, which can be added independently.

Incidentally, stop building the Mach-O TLS support file unnecessarily on other 
platforms.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112229

Files:
  clang/cmake/caches/CrossWinToARMLinux.cmake
  compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
  compiler-rt/cmake/config-ix.cmake
  compiler-rt/lib/orc/CMakeLists.txt
  compiler-rt/lib/orc/elfnix_tls.x86-64.S
  compiler-rt/lib/orc/macho_tlv.x86-64.S
  compiler-rt/lib/orc/simple_packed_serialization.h

Index: compiler-rt/lib/orc/simple_packed_serialization.h
===
--- compiler-rt/lib/orc/simple_packed_serialization.h
+++ compiler-rt/lib/orc/simple_packed_serialization.h
@@ -396,10 +396,12 @@
 uint64_t Size;
 if (!SPSArgList::deserialize(IB, Size))
   return false;
+if (Size > std::numeric_limits::max())
+  return false;
 Data = IB.data();
 if (!IB.skip(Size))
   return false;
-S = {Data, Size};
+S = {Data, static_cast(Size)};
 return true;
   }
 };
Index: compiler-rt/lib/orc/macho_tlv.x86-64.S
===
--- compiler-rt/lib/orc/macho_tlv.x86-64.S
+++ compiler-rt/lib/orc/macho_tlv.x86-64.S
@@ -10,6 +10,9 @@
 //
 //===--===//
 
+// The content of this file is x86_64-only
+#if defined(__x86_64__)
+
 #define REGISTER_SAVE_SPACE_SIZE512
 
 .text
@@ -66,3 +69,5 @@
 addq$REGISTER_SAVE_SPACE_SIZE, %rsp
 popq%rbp
 ret
+
+#endif // defined(__x86_64__)
Index: compiler-rt/lib/orc/elfnix_tls.x86-64.S
===
--- compiler-rt/lib/orc/elfnix_tls.x86-64.S
+++ compiler-rt/lib/orc/elfnix_tls.x86-64.S
@@ -11,6 +11,9 @@
 //
 //===--===//
 
+// The content of this file is x86_64-only
+#if defined(__x86_64__)
+
 #define REGISTER_SAVE_SPACE_SIZE512
 
 .text
@@ -57,3 +60,5 @@
 addq$REGISTER_SAVE_SPACE_SIZE, %rsp
 popq%rbp
 ret
+
+#endif // defined(__x86_64__)
Index: compiler-rt/lib/orc/CMakeLists.txt
===
--- compiler-rt/lib/orc/CMakeLists.txt
+++ compiler-rt/lib/orc/CMakeLists.txt
@@ -10,8 +10,7 @@
   )
 
 # Implementation files for all ORC architectures.
-set(x86_64_SOURCES
-# x86-64 specific assembly files will go here.
+set(ALL_ORC_ASM_SOURCES
   macho_tlv.x86-64.S
   elfnix_tls.x86-64.S
 )
@@ -36,7 +35,7 @@
 # consumption by tests.
 set(ORC_ALL_SOURCE_FILES
   ${ORC_SOURCES}
-  ${x86_64_SOURCES}
+  ${ALL_ORC_ASM_SOURCES}
   ${ORC_IMPL_HEADERS}
   )
 
@@ -61,17 +60,16 @@
 endif()
 
 if (APPLE)
-   add_asm_sources(ORC_ASM_SOURCES macho_tlv.x86-64.S)
+  add_asm_sources(ORC_ASM_SOURCES macho_tlv.x86-64.S)
 
   add_compiler_rt_object_libraries(RTOrc
 OS ${ORC_SUPPORTED_OS}
 ARCHS ${ORC_SUPPORTED_ARCH}
-SOURCES ${ORC_SOURCES} ${x86_64_SOURCES}
+SOURCES ${ORC_SOURCES} ${ORC_ASM_SOURCES}
 ADDITIONAL_HEADERS ${ORC_IMPL_HEADERS}
 CFLAGS ${ORC_CFLAGS}
 DEPS ${ORC_DEPS})
 
-  # We only support running on osx for now.
   add_compiler_rt_runtime(clang_rt.orc
 STATIC
 OS ${ORC_SUPPORTED_OS}
@@ -82,13 +80,16 @@
 LINK_LIBS ${ORC_LINK_LIBS}
 PARENT_TARGET orc)
 else() # not Apple
+  add_asm_sources(ORC_ASM_SOURCES elfnix_tls.x86-64.S)
+
   foreach(arch ${ORC_SUPPORTED_ARCH})
 if(NOT CAN_TARGET_${arch})
   continue()
 endif()
+
 add_compiler_rt_object_libraries(RTOrc
   ARCHS ${arch}
-  SOURCES ${ORC_SOURCES} ${${arch}_SOURCES}
+  SOURCES ${ORC_SOURCES} ${ORC_ASM_SOURCES}
   ADDITIONAL_HEADERS ${ORC_IMPL_HEADERS}
   CFLAGS ${ORC_CFLAGS}
   DEPS ${ORC_DEPS})
Index: compiler-rt/cmake/config-ix.cmake
===
--- compiler-rt/cmake/config-ix.cmake
+++ compiler-rt/cmake/config-ix.cmake
@@ -480,6 +480,7 @@
   list(APPEND PROFILE_SUPPORTED_OS ${platform}sim)
   list(APPEND TSAN_SUPPORTED_OS ${platform}sim)
   li

[PATCH] D112229: Reapply [ORC-RT] Configure the ORC runtime for more architectures and platforms

2021-10-21 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir added inline comments.



Comment at: clang/cmake/caches/CrossWinToARMLinux.cmake:104
 set(COMPILER_RT_BUILD_CRT   OFF CACHE BOOL "")
+set(COMPILER_RT_BUILD_ORC   OFF CACHE BOOL "")
 set(COMPILER_RT_DEFAULT_TARGET_ONLY ON CACHE BOOL "")

This is the only change since the last time.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112229

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


[PATCH] D112229: Reapply [ORC-RT] Configure the ORC runtime for more architectures and platforms

2021-10-21 Thread Lang Hames via Phabricator via cfe-commits
lhames accepted this revision.
lhames added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks Ben.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112229

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


[PATCH] D107339: [analyzer] Retrieve a character from StringLiteral as an initializer for constant arrays.

2021-10-21 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D107339#3075306 , @steakhal wrote:

> Why does `glob_invalid_index7()` and `glob_invalid_index8()` differ in 
> behavior?
> I would expect that the analyzer produces the same `Loc` symbolic value for 
> both cases thus, the array access should result in the same behavior 
> regardless if `glob_arr6` is used, or acquired a pointer and using that in a 
> subsequent operation.
> Could you elaborate on this?

You're right about //the same Loc//. There were just limitations of the 
previous implementation. I've fixed it.




Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1642
+  //
+  // Previous check for `Idx < 0` guarantee that `Idx` is non-negative.
+  const auto I = static_cast(Idx.getExtValue());

steakhal wrote:
> Instead of this comment, you can put an `assert(Idx.isStrictlyPositive())` 
> here.
I reworked this case and we don't need it anymore.


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

https://reviews.llvm.org/D107339

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


[clang] f6811ce - [DebugInfo] Support typedef with btf_decl_tag attributes

2021-10-21 Thread Yonghong Song via cfe-commits

Author: Yonghong Song
Date: 2021-10-21T08:42:58-07:00
New Revision: f6811cec84218912d1c7c9b0b8d308834e6e24e3

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

LOG: [DebugInfo] Support typedef with btf_decl_tag attributes

Clang patch ([1]) added support for btf_decl_tag attributes with typedef
types. This patch added llvm support including dwarf generation.
For example, for typedef
   typedef unsigned * __u __attribute__((btf_decl_tag("tag1")));
   __u u;
the following shows llvm-dwarfdump result:
   0x0033:   DW_TAG_typedef
   DW_AT_type  (0x0048 "unsigned int *")
   DW_AT_name  ("__u")
   DW_AT_decl_file ("/home/yhs/work/tests/llvm/btf_tag/t.c")
   DW_AT_decl_line (1)

   0x003e: DW_TAG_LLVM_annotation
 DW_AT_name("btf_decl_tag")
 DW_AT_const_value ("tag1")

   0x0047: NULL

  [1] https://reviews.llvm.org/D110127

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

Added: 
clang/test/CodeGen/attr-btf_tag-typedef.c
llvm/test/Bitcode/attr-btf_tag-typedef.ll
llvm/test/DebugInfo/X86/attr-btf_tag-typedef.ll

Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp
llvm/include/llvm/IR/DIBuilder.h
llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
llvm/lib/IR/DIBuilder.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 132b5c28e8f55..6e477d40b83e6 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1276,9 +1276,11 @@ llvm::DIType *CGDebugInfo::CreateType(const TypedefType 
*Ty,
 
   uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
   // Typedefs are derived from some other type.
+  llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());
   return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
 getOrCreateFile(Loc), getLineNumber(Loc),
-getDeclContextDescriptor(Ty->getDecl()), 
Align);
+getDeclContextDescriptor(Ty->getDecl()), Align,
+Annotations);
 }
 
 static unsigned getDwarfCC(CallingConv CC) {

diff  --git a/clang/test/CodeGen/attr-btf_tag-typedef.c 
b/clang/test/CodeGen/attr-btf_tag-typedef.c
new file mode 100644
index 0..57aafde15893d
--- /dev/null
+++ b/clang/test/CodeGen/attr-btf_tag-typedef.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -triple %itanium_abi_triple -debug-info-kind=limited -S 
-emit-llvm -o - %s | FileCheck %s
+
+#define __tag1 __attribute__((btf_decl_tag("tag1")))
+typedef struct { int a; } __s __tag1;
+typedef unsigned * __u __tag1;
+__s a;
+__u u;
+
+// CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "__u", file: ![[#]], line: 
[[#]], baseType: ![[#]], annotations: ![[ANNOT:[0-9]+]])
+// CHECK: ![[ANNOT]] = !{![[TAG1:[0-9]+]]}
+// CHECK: ![[TAG1]] = !{!"btf_decl_tag", !"tag1"}
+
+// CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "__s", file: ![[#]], line: 
[[#]], baseType: ![[#]], annotations: ![[ANNOT]])

diff  --git a/llvm/include/llvm/IR/DIBuilder.h 
b/llvm/include/llvm/IR/DIBuilder.h
index 28c70877aa2e8..90165095bb0c0 100644
--- a/llvm/include/llvm/IR/DIBuilder.h
+++ b/llvm/include/llvm/IR/DIBuilder.h
@@ -250,9 +250,11 @@ namespace llvm {
 /// \param LineNo  Line number.
 /// \param Context The surrounding context for the typedef.
 /// \param AlignInBits Alignment. (optional)
+/// \param Annotations Annotations. (optional)
 DIDerivedType *createTypedef(DIType *Ty, StringRef Name, DIFile *File,
  unsigned LineNo, DIScope *Context,
- uint32_t AlignInBits = 0);
+ uint32_t AlignInBits = 0,
+ DINodeArray Annotations = nullptr);
 
 /// Create debugging information entry for a 'friend'.
 DIDerivedType *createFriend(DIType *Ty, DIType *FriendTy);

diff  --git a/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp 
b/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
index d4a7808b9d1e3..f1af9e2373f81 100644
--- a/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
@@ -754,6 +754,8 @@ void DwarfUnit::constructTypeDIE(DIE &Buffer, const 
DIDerivedType *DTy) {
   if (!Name.empty())
 addString(Buffer, dwarf::DW_AT_name, Name);
 
+  addAnnotation(Buffer, DTy->getAnnotations());
+
   // If alignment is specified for a typedef , create and insert 
DW_AT_alignment
   // attribute in DW_TAG_typedef DIE.
   if (Tag == dwarf::DW_TAG_typedef && DD->getDwarfVersion() >= 5) {

diff  --git a/llvm/lib/IR/DIBuilder.cpp b/llvm/lib/IR/DIBuilder.cpp
index 8ff4c21

[PATCH] D110129: [DebugInfo] Support typedef with btf_decl_tag attributes

2021-10-21 Thread Yonghong Song 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 rGf6811cec8421: [DebugInfo] Support typedef with btf_decl_tag 
attributes (authored by yonghong-song).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110129

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/attr-btf_tag-typedef.c
  llvm/include/llvm/IR/DIBuilder.h
  llvm/lib/CodeGen/AsmPrinter/DwarfUnit.cpp
  llvm/lib/IR/DIBuilder.cpp
  llvm/test/Bitcode/attr-btf_tag-typedef.ll
  llvm/test/DebugInfo/X86/attr-btf_tag-typedef.ll

Index: llvm/test/DebugInfo/X86/attr-btf_tag-typedef.ll
===
--- /dev/null
+++ llvm/test/DebugInfo/X86/attr-btf_tag-typedef.ll
@@ -0,0 +1,69 @@
+; RUN: llc -mtriple=x86_64-linux -filetype=obj -o %t %s
+; RUN: llvm-dwarfdump -debug-info %t | FileCheck %s
+;
+; Source:
+;   #define __tag1 __attribute__((btf_decl_tag("tag1")))
+;   typedef struct { int a; } __s __tag1;
+;   typedef unsigned * __u __tag1;
+;   __s a;
+;   __u u;
+; Compilation flag:
+;   clang -S -g -emit-llvm typedef.c
+
+%struct.__s = type { i32 }
+
+@a = dso_local global %struct.__s zeroinitializer, align 4, !dbg !0
+@u = dso_local global i32* null, align 8, !dbg !5
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!17, !18, !19, !20, !21}
+!llvm.ident = !{!22}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "a", scope: !2, file: !3, line: 4, type: !12, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW_LANG_C99, file: !3, producer: "clang version 14.0.0 (https://github.com/llvm/llvm-project.git b9757992b73e823edf1fa699372ff9cd29db6cb7)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, globals: !4, splitDebugInlining: false, nameTableKind: None)
+!3 = !DIFile(filename: "typedef.c", directory: "/home/yhs/work/tests/llvm/btf_tag")
+!4 = !{!0, !5}
+!5 = !DIGlobalVariableExpression(var: !6, expr: !DIExpression())
+!6 = distinct !DIGlobalVariable(name: "u", scope: !2, file: !3, line: 5, type: !7, isLocal: false, isDefinition: true)
+!7 = !DIDerivedType(tag: DW_TAG_typedef, name: "__u", file: !3, line: 3, baseType: !8, annotations: !10)
+!8 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !9, size: 64)
+!9 = !DIBasicType(name: "unsigned int", size: 32, encoding: DW_ATE_unsigned)
+!10 = !{!11}
+!11 = !{!"btf_decl_tag", !"tag1"}
+!12 = !DIDerivedType(tag: DW_TAG_typedef, name: "__s", file: !3, line: 2, baseType: !13, annotations: !10)
+!13 = distinct !DICompositeType(tag: DW_TAG_structure_type, file: !3, line: 2, size: 32, elements: !14)
+!14 = !{!15}
+!15 = !DIDerivedType(tag: DW_TAG_member, name: "a", scope: !13, file: !3, line: 2, baseType: !16, size: 32)
+!16 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
+
+; CHECK:DW_TAG_typedef
+; CHECK-NEXT: DW_AT_type
+; CHECK-NEXT: DW_AT_name  ("__s")
+; CHECK-NEXT: DW_AT_decl_file
+; CHECK-NEXT: DW_AT_decl_line
+; CHECK-EMPTY:
+; CHECK-NEXT: DW_TAG_LLVM_annotation
+; CHECK-NEXT:   DW_AT_name("btf_decl_tag")
+; CHECK-NEXT:   DW_AT_const_value ("tag1")
+; CHECK-EMPTY:
+; CHECK-NEXT: NULL
+
+; CHECK:DW_TAG_typedef
+; CHECK-NEXT: DW_AT_type
+; CHECK-NEXT: DW_AT_name  ("__u")
+; CHECK-NEXT: DW_AT_decl_file
+; CHECK-NEXT: DW_AT_decl_line
+; CHECK-EMPTY:
+; CHECK-NEXT: DW_TAG_LLVM_annotation
+; CHECK-NEXT:   DW_AT_name("btf_decl_tag")
+; CHECK-NEXT:   DW_AT_const_value ("tag1")
+; CHECK-EMPTY:
+; CHECK-NEXT: NULL
+
+!17 = !{i32 7, !"Dwarf Version", i32 4}
+!18 = !{i32 2, !"Debug Info Version", i32 3}
+!19 = !{i32 1, !"wchar_size", i32 4}
+!20 = !{i32 7, !"uwtable", i32 1}
+!21 = !{i32 7, !"frame-pointer", i32 2}
+!22 = !{!"clang version 14.0.0 (https://github.com/llvm/llvm-project.git b9757992b73e823edf1fa699372ff9cd29db6cb7)"}
Index: llvm/test/Bitcode/attr-btf_tag-typedef.ll
===
--- /dev/null
+++ llvm/test/Bitcode/attr-btf_tag-typedef.ll
@@ -0,0 +1,54 @@
+; RUN: llvm-as < %s | llvm-dis | FileCheck %s
+;
+; Source:
+;   #define __tag1 __attribute__((btf_decl_tag("tag1")))
+;   typedef struct { int a; } __s __tag1;
+;   typedef unsigned * __u __tag1;
+;   __s a;
+;   __u u;
+; Compilation flag:
+;   clang -S -g -emit-llvm typedef.c
+
+%struct.__s = type { i32 }
+
+@a = dso_local global %struct.__s zeroinitializer, align 4, !dbg !0
+@u = dso_local global i32* null, align 8, !dbg !5
+
+!llvm.dbg.cu = !{!2}
+!llvm.module.flags = !{!17, !18, !19, !20, !21}
+!llvm.ident = !{!22}
+
+!0 = !DIGlobalVariableExpression(var: !1, expr: !DIExpression())
+!1 = distinct !DIGlobalVariable(name: "a", scope: !2, file: !3, line: 4, type: !12, isLocal: false, isDefinition: true)
+!2 = distinct !DICompileUnit(language: DW

[PATCH] D111566: [SYCL] Fix function pointer address space

2021-10-21 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added inline comments.



Comment at: clang/lib/CodeGen/CodeGenTypes.cpp:636-638
+unsigned AS = PointeeType->isFunctionTy()
+  ? getDataLayout().getProgramAddressSpace()
+  : Context.getTargetAddressSpace(ETy);

aaron.ballman wrote:
> The review summary says that this is a fix for SYCL, but the fix itself 
> happens for all targets, not just SYCL. If that's intentional, are we sure 
> it's correct?
Yes this affects all targets. To be honest, I'm not sure if this change is 
correct for CUDA/openCL, etc. My first patch (which I didn't upload) restricted 
the change to SYCL. However, I saw the same thing was done in a generic manner 
for function pointers  - 
https://github.com/llvm/llvm-project/commit/57fd86de879cf2b4c7001b6d0a09df60877ce24d,
 and so followed the same logic. I'm hoping reviewers more familiar with 
address spaces can help here. 


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

https://reviews.llvm.org/D111566

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


[PATCH] D107339: [analyzer] Retrieve a character from StringLiteral as an initializer for constant arrays.

2021-10-21 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

@martong

> I am close to accepting this. However, D111542 
>  should be its parent patch. I think 
> similar issues could arise here as well, so, redecl chain tests would be 
> really beneficial.

I think I'm done. You can proceed the review.


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

https://reviews.llvm.org/D107339

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


[PATCH] D111199: [Clang][LLVM][Attr] support btf_type_tag attribute

2021-10-21 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

I reviewed this a bit, but I think it might be heading in a slightly wrong 
direction. I think you should be using an `AttributedType` but I don't think we 
need to add `AttributedBTFType` as a subclass to do this. An `AttributedType` 
holds the type kind information in it, but you should be able to access an 
`AttributedTypeLoc` object to get to the semantic attribute to access the 
string argument to the attribute. Generally, you'd call `getTypeSourceInfo()` 
on the declaration to get the type source info for its type, you can call 
`getTypeLoc()` on that object to get a generic `TypeLoc` object, and then call 
`getAs()` on that to turn it into an `AttributedTypeLoc` and 
from there you can call `getAttr()` to get the `Attr *` for the semantic 
attribute.




Comment at: clang/include/clang/AST/ASTContext.h:1562-1563
 
+  QualType getAttributedBTFType(attr::Kind attrKind, QualType modifiedType,
+QualType equivalentType, StringRef BTFTypeTag);
+





Comment at: clang/include/clang/AST/PropertiesBase.td:134
   def ExprRef : SubclassPropertyType<"Expr", StmtRef>;
+def String : PropertyType<"std::string">;
 def TemplateArgument : PropertyType;

Is `std::string` really the correct type to be using for AST serialization? Can 
we use `StringRef` here as well?



Comment at: clang/include/clang/AST/Type.h:4779-4783
+  AttributedBTFType(QualType canon, attr::Kind attrKind, QualType modified,
+QualType equivalent, StringRef BTFTypeTag)
+  : AttributedType(AttributedBTF, canon, attrKind, modified, equivalent) {
+this->BTFTypeTag = BTFTypeTag;
+  }





Comment at: clang/include/clang/AST/TypeLoc.h:896
+: public InheritingConcreteTypeLoc {};
+

Is this actually needed? I would have assumed the `AttributedTypeLoc` would 
suffice.



Comment at: clang/include/clang/Basic/Attr.td:1850
+  let Args = [StringArgument<"BTFTypeTag">];
+  let Documentation = [Undocumented];
+  let LangOpts = [COnly];

No new, undocumented attributes please.



Comment at: clang/include/clang/Serialization/ASTRecordWriter.h:286-287
 
+  void writeString(StringRef Str) { return AddString(Str); }
+
   /// Emit a path.

This appears to be unused, can be removed?



Comment at: clang/lib/AST/ASTContext.cpp:4636-4656
+QualType ASTContext::getAttributedBTFType(attr::Kind attrKind,
+  QualType modifiedType,
+  QualType equivalentType,
+  StringRef BTFTypeTag) {
+  llvm::FoldingSetNodeID id;
+  AttributedBTFType::Profile(id, attrKind, modifiedType, equivalentType,
+ BTFTypeTag);





Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:1152
+  StringRef BTFTypeTag = AT->getBTFTypeTag();
+  if (BTFTypeTag[0]) {
+llvm::Metadata *Ops[2] = {

Should this be checking `!BTFTypeTag.empty()` instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D99

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


[PATCH] D112227: [libomptarget] Build DeviceRTL for amdgpu

2021-10-21 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: openmp/libomptarget/DeviceRTL/src/Configuration.cpp:23
 
-extern uint32_t __omp_rtl_debug_kind;
+// extern uint32_t __omp_rtl_debug_kind;
 

JonChesterfield wrote:
> Otherwise the missing symbols prevents linking, not clear why it works on 
> nvptx64
linking what? Clang emits the symbol, maybe just not for amdgpu.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112227

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


[clang] dccfadd - [clang] Use StringRef::contains (NFC)

2021-10-21 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2021-10-21T08:58:19-07:00
New Revision: dccfaddc6bcc711bd972b43bff5ce6d71c1b39dc

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

LOG: [clang] Use StringRef::contains (NFC)

Added: 


Modified: 
clang/lib/ARCMigrate/ObjCMT.cpp
clang/lib/ARCMigrate/TransUnbridgedCasts.cpp
clang/lib/ARCMigrate/Transforms.cpp
clang/lib/AST/Expr.cpp
clang/lib/ASTMatchers/ASTMatchersInternal.cpp
clang/lib/Analysis/RetainSummaryManager.cpp
clang/lib/CodeGen/CodeGenFunction.cpp
clang/lib/CodeGen/TargetInfo.cpp
clang/lib/Lex/HeaderSearch.cpp
clang/lib/Lex/LiteralSupport.cpp
clang/lib/Rewrite/Rewriter.cpp
clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
clang/utils/TableGen/NeonEmitter.cpp
clang/utils/TableGen/RISCVVEmitter.cpp

Removed: 




diff  --git a/clang/lib/ARCMigrate/ObjCMT.cpp b/clang/lib/ARCMigrate/ObjCMT.cpp
index c8a389d1f2e5a..e99c6435062fb 100644
--- a/clang/lib/ARCMigrate/ObjCMT.cpp
+++ b/clang/lib/ARCMigrate/ObjCMT.cpp
@@ -487,9 +487,8 @@ static void rewriteToObjCProperty(const ObjCMethodDecl 
*Getter,
 
   // Short circuit 'delegate' properties that contain the name "delegate" or
   // "dataSource", or have exact name "target" to have 'assign' attribute.
-  if (PropertyName.equals("target") ||
-  (PropertyName.find("delegate") != StringRef::npos) ||
-  (PropertyName.find("dataSource") != StringRef::npos)) {
+  if (PropertyName.equals("target") || PropertyName.contains("delegate") ||
+  PropertyName.contains("dataSource")) {
 QualType QT = Getter->getReturnType();
 if (!QT->isRealType())
   append_attr(PropertyString, "assign", LParenAdded);

diff  --git a/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp 
b/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp
index b14364509a0bf..40220a2eef491 100644
--- a/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp
+++ b/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp
@@ -146,9 +146,8 @@ class UnbridgedCastRewriter : public 
RecursiveASTVisitor{
 ento::cocoa::isRefType(E->getSubExpr()->getType(), "CF",
FD->getIdentifier()->getName())) {
   StringRef fname = FD->getIdentifier()->getName();
-  if (fname.endswith("Retain") ||
-  fname.find("Create") != StringRef::npos ||
-  fname.find("Copy") != StringRef::npos) {
+  if (fname.endswith("Retain") || fname.contains("Create") ||
+  fname.contains("Copy")) {
 // Do not migrate to couple of bridge transfer casts which
 // cancel each other out. Leave it unchanged so error gets user
 // attention instead.
@@ -168,7 +167,7 @@ class UnbridgedCastRewriter : public 
RecursiveASTVisitor{
 return;
   }
 
-  if (fname.find("Get") != StringRef::npos) {
+  if (fname.contains("Get")) {
 castToObjCObject(E, /*retained=*/false);
 return;
   }

diff  --git a/clang/lib/ARCMigrate/Transforms.cpp 
b/clang/lib/ARCMigrate/Transforms.cpp
index e274a540e4083..ca48160d9c856 100644
--- a/clang/lib/ARCMigrate/Transforms.cpp
+++ b/clang/lib/ARCMigrate/Transforms.cpp
@@ -95,11 +95,9 @@ bool trans::isPlusOne(const Expr *E) {
   ento::cocoa::isRefType(callE->getType(), "CF",
  FD->getIdentifier()->getName())) {
 StringRef fname = FD->getIdentifier()->getName();
-if (fname.endswith("Retain") ||
-fname.find("Create") != StringRef::npos ||
-fname.find("Copy") != StringRef::npos) {
+if (fname.endswith("Retain") || fname.contains("Create") ||
+fname.contains("Copy"))
   return true;
-}
   }
 }
   }

diff  --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index f0c195c08ccba..e9ee624e499da 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -4116,7 +4116,7 @@ bool ExtVectorElementExpr::containsDuplicateElements() 
const {
 Comp = Comp.substr(1);
 
   for (unsigned i = 0, e = Comp.size(); i != e; ++i)
-if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos)
+if (Comp.substr(i + 1).contains(Comp[i]))
 return true;
 
   return false;

diff  --git a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp 
b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
index 12e3c488d61a3..b7622e3b51f1e 100644
--- a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -468,8 +468,8 @@ hasAnyOverloadedOperatorNameFunc(ArrayRef NameRefs) {
 }
 
 HasNameMatcher::HasNameMatcher(std::vector N)
-: UseUnqualifiedMatch(llvm::all_of(
-  N, [](StringRef Name) { return Name.find("::") == Name.npos; })),
+: UseUnqualifiedMatch(
+  llvm::all_of(N, [](Str

[clang] b8da594 - Reapply [ORC-RT] Configure the ORC runtime for more architectures and platforms

2021-10-21 Thread Ben Langmuir via cfe-commits

Author: Ben Langmuir
Date: 2021-10-21T09:00:18-07:00
New Revision: b8da594750762f811283820c19b02cedfb6632d4

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

LOG: Reapply [ORC-RT] Configure the ORC runtime for more architectures and 
platforms

Reapply 5692ed0cce8c95, but with the ORC runtime disabled explicitly on
CrossWinToARMLinux to match the other compiler-rt runtime libraries.

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

---

Enable building the ORC runtime for 64-bit and 32-bit ARM architectures,
and for all Darwin embedded platforms (iOS, tvOS, and watchOS). This
covers building the cross-platform code, but does not add TLV runtime
support for the new architectures, which can be added independently.

Incidentally, stop building the Mach-O TLS support file unnecessarily on
other platforms.

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

Added: 


Modified: 
clang/cmake/caches/CrossWinToARMLinux.cmake
compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
compiler-rt/cmake/config-ix.cmake
compiler-rt/lib/orc/CMakeLists.txt
compiler-rt/lib/orc/elfnix_tls.x86-64.S
compiler-rt/lib/orc/macho_tlv.x86-64.S
compiler-rt/lib/orc/simple_packed_serialization.h

Removed: 




diff  --git a/clang/cmake/caches/CrossWinToARMLinux.cmake 
b/clang/cmake/caches/CrossWinToARMLinux.cmake
index 778494ee9f104..63b49bc569ed0 100644
--- a/clang/cmake/caches/CrossWinToARMLinux.cmake
+++ b/clang/cmake/caches/CrossWinToARMLinux.cmake
@@ -101,6 +101,7 @@ set(COMPILER_RT_BUILD_XRAY  OFF CACHE BOOL 
"")
 set(COMPILER_RT_BUILD_LIBFUZZER OFF CACHE BOOL "")
 set(COMPILER_RT_BUILD_PROFILE   OFF CACHE BOOL "")
 set(COMPILER_RT_BUILD_CRT   OFF CACHE BOOL "")
+set(COMPILER_RT_BUILD_ORC   OFF CACHE BOOL "")
 set(COMPILER_RT_DEFAULT_TARGET_ONLY ON CACHE BOOL "")
 set(COMPILER_RT_INCLUDE_TESTS   ON CACHE BOOL "")
 

diff  --git a/compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake 
b/compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
index 882e12ada0279..86fa3bb5527fa 100644
--- a/compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
+++ b/compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
@@ -78,5 +78,5 @@ endif()
 set(ALL_SHADOWCALLSTACK_SUPPORTED_ARCH ${ARM64})
 
 if (UNIX)
-set(ALL_ORC_SUPPORTED_ARCH ${X86_64})
+set(ALL_ORC_SUPPORTED_ARCH ${X86_64} ${ARM64} ${ARM32})
 endif()

diff  --git a/compiler-rt/cmake/config-ix.cmake 
b/compiler-rt/cmake/config-ix.cmake
index e2985dccc645f..7624605cf1f86 100644
--- a/compiler-rt/cmake/config-ix.cmake
+++ b/compiler-rt/cmake/config-ix.cmake
@@ -480,6 +480,7 @@ if(APPLE)
   list(APPEND PROFILE_SUPPORTED_OS ${platform}sim)
   list(APPEND TSAN_SUPPORTED_OS ${platform}sim)
   list(APPEND FUZZER_SUPPORTED_OS ${platform}sim)
+  list(APPEND ORC_SUPPORTED_OS ${platform}sim)
 endif()
 foreach(arch ${DARWIN_${platform}sim_ARCHS})
   list(APPEND COMPILER_RT_SUPPORTED_ARCH ${arch})
@@ -510,6 +511,7 @@ if(APPLE)
 list(APPEND TSAN_SUPPORTED_OS ${platform})
   endif()
   list(APPEND FUZZER_SUPPORTED_OS ${platform})
+  list(APPEND ORC_SUPPORTED_OS ${platform})
 endif()
 foreach(arch ${DARWIN_${platform}_ARCHS})
   list(APPEND COMPILER_RT_SUPPORTED_ARCH ${arch})

diff  --git a/compiler-rt/lib/orc/CMakeLists.txt 
b/compiler-rt/lib/orc/CMakeLists.txt
index 7259f953f3112..cc57707a64799 100644
--- a/compiler-rt/lib/orc/CMakeLists.txt
+++ b/compiler-rt/lib/orc/CMakeLists.txt
@@ -10,8 +10,7 @@ set(ORC_SOURCES
   )
 
 # Implementation files for all ORC architectures.
-set(x86_64_SOURCES
-# x86-64 specific assembly files will go here.
+set(ALL_ORC_ASM_SOURCES
   macho_tlv.x86-64.S
   elfnix_tls.x86-64.S
 )
@@ -36,7 +35,7 @@ set(ORC_IMPL_HEADERS
 # consumption by tests.
 set(ORC_ALL_SOURCE_FILES
   ${ORC_SOURCES}
-  ${x86_64_SOURCES}
+  ${ALL_ORC_ASM_SOURCES}
   ${ORC_IMPL_HEADERS}
   )
 
@@ -61,17 +60,16 @@ if (TARGET cxx-headers OR HAVE_LIBCXX)
 endif()
 
 if (APPLE)
-   add_asm_sources(ORC_ASM_SOURCES macho_tlv.x86-64.S)
+  add_asm_sources(ORC_ASM_SOURCES macho_tlv.x86-64.S)
 
   add_compiler_rt_object_libraries(RTOrc
 OS ${ORC_SUPPORTED_OS}
 ARCHS ${ORC_SUPPORTED_ARCH}
-SOURCES ${ORC_SOURCES} ${x86_64_SOURCES}
+SOURCES ${ORC_SOURCES} ${ORC_ASM_SOURCES}
 ADDITIONAL_HEADERS ${ORC_IMPL_HEADERS}
 CFLAGS ${ORC_CFLAGS}
 DEPS ${ORC_DEPS})
 
-  # We only support running on osx for now.
   add_compiler_rt_runtime(clang_rt.orc
 STATIC
 OS ${ORC_SUPPORTED_OS}
@@ -82,13 +80,16 @@ if (APPLE)
 LINK_LIBS ${ORC_LINK_LIBS}
 PARENT_TARGET orc)
 else() # not Apple
+  add_asm_sources(ORC_ASM_SOURCES elfnix_tls.x86-

[PATCH] D112229: Reapply [ORC-RT] Configure the ORC runtime for more architectures and platforms

2021-10-21 Thread Ben Langmuir 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 rGb8da59475076: Reapply [ORC-RT] Configure the ORC runtime for 
more architectures and platforms (authored by benlangmuir).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112229

Files:
  clang/cmake/caches/CrossWinToARMLinux.cmake
  compiler-rt/cmake/Modules/AllSupportedArchDefs.cmake
  compiler-rt/cmake/config-ix.cmake
  compiler-rt/lib/orc/CMakeLists.txt
  compiler-rt/lib/orc/elfnix_tls.x86-64.S
  compiler-rt/lib/orc/macho_tlv.x86-64.S
  compiler-rt/lib/orc/simple_packed_serialization.h

Index: compiler-rt/lib/orc/simple_packed_serialization.h
===
--- compiler-rt/lib/orc/simple_packed_serialization.h
+++ compiler-rt/lib/orc/simple_packed_serialization.h
@@ -396,10 +396,12 @@
 uint64_t Size;
 if (!SPSArgList::deserialize(IB, Size))
   return false;
+if (Size > std::numeric_limits::max())
+  return false;
 Data = IB.data();
 if (!IB.skip(Size))
   return false;
-S = {Data, Size};
+S = {Data, static_cast(Size)};
 return true;
   }
 };
Index: compiler-rt/lib/orc/macho_tlv.x86-64.S
===
--- compiler-rt/lib/orc/macho_tlv.x86-64.S
+++ compiler-rt/lib/orc/macho_tlv.x86-64.S
@@ -10,6 +10,9 @@
 //
 //===--===//
 
+// The content of this file is x86_64-only
+#if defined(__x86_64__)
+
 #define REGISTER_SAVE_SPACE_SIZE512
 
 .text
@@ -66,3 +69,5 @@
 addq$REGISTER_SAVE_SPACE_SIZE, %rsp
 popq%rbp
 ret
+
+#endif // defined(__x86_64__)
Index: compiler-rt/lib/orc/elfnix_tls.x86-64.S
===
--- compiler-rt/lib/orc/elfnix_tls.x86-64.S
+++ compiler-rt/lib/orc/elfnix_tls.x86-64.S
@@ -11,6 +11,9 @@
 //
 //===--===//
 
+// The content of this file is x86_64-only
+#if defined(__x86_64__)
+
 #define REGISTER_SAVE_SPACE_SIZE512
 
 .text
@@ -57,3 +60,5 @@
 addq$REGISTER_SAVE_SPACE_SIZE, %rsp
 popq%rbp
 ret
+
+#endif // defined(__x86_64__)
Index: compiler-rt/lib/orc/CMakeLists.txt
===
--- compiler-rt/lib/orc/CMakeLists.txt
+++ compiler-rt/lib/orc/CMakeLists.txt
@@ -10,8 +10,7 @@
   )
 
 # Implementation files for all ORC architectures.
-set(x86_64_SOURCES
-# x86-64 specific assembly files will go here.
+set(ALL_ORC_ASM_SOURCES
   macho_tlv.x86-64.S
   elfnix_tls.x86-64.S
 )
@@ -36,7 +35,7 @@
 # consumption by tests.
 set(ORC_ALL_SOURCE_FILES
   ${ORC_SOURCES}
-  ${x86_64_SOURCES}
+  ${ALL_ORC_ASM_SOURCES}
   ${ORC_IMPL_HEADERS}
   )
 
@@ -61,17 +60,16 @@
 endif()
 
 if (APPLE)
-   add_asm_sources(ORC_ASM_SOURCES macho_tlv.x86-64.S)
+  add_asm_sources(ORC_ASM_SOURCES macho_tlv.x86-64.S)
 
   add_compiler_rt_object_libraries(RTOrc
 OS ${ORC_SUPPORTED_OS}
 ARCHS ${ORC_SUPPORTED_ARCH}
-SOURCES ${ORC_SOURCES} ${x86_64_SOURCES}
+SOURCES ${ORC_SOURCES} ${ORC_ASM_SOURCES}
 ADDITIONAL_HEADERS ${ORC_IMPL_HEADERS}
 CFLAGS ${ORC_CFLAGS}
 DEPS ${ORC_DEPS})
 
-  # We only support running on osx for now.
   add_compiler_rt_runtime(clang_rt.orc
 STATIC
 OS ${ORC_SUPPORTED_OS}
@@ -82,13 +80,16 @@
 LINK_LIBS ${ORC_LINK_LIBS}
 PARENT_TARGET orc)
 else() # not Apple
+  add_asm_sources(ORC_ASM_SOURCES elfnix_tls.x86-64.S)
+
   foreach(arch ${ORC_SUPPORTED_ARCH})
 if(NOT CAN_TARGET_${arch})
   continue()
 endif()
+
 add_compiler_rt_object_libraries(RTOrc
   ARCHS ${arch}
-  SOURCES ${ORC_SOURCES} ${${arch}_SOURCES}
+  SOURCES ${ORC_SOURCES} ${ORC_ASM_SOURCES}
   ADDITIONAL_HEADERS ${ORC_IMPL_HEADERS}
   CFLAGS ${ORC_CFLAGS}
   DEPS ${ORC_DEPS})
Index: compiler-rt/cmake/config-ix.cmake
===
--- compiler-rt/cmake/config-ix.cmake
+++ compiler-rt/cmake/config-ix.cmake
@@ -480,6 +480,7 @@
   list(APPEND PROFILE_SUPPORTED_OS ${platform}sim)
   list(APPEND TSAN_SUPPORTED_OS ${platform}sim)
   list(APPEND FUZZER_SUPPORTED_OS ${platform}sim)
+  list(APPEND ORC_SUPPORTED_OS ${platform}sim)
 endif()
 foreach(arch ${DARWIN_${platform}sim_ARCHS})
   list(APPEND COMPILER_RT_SUPPORTED_ARCH ${arch})
@@ -510,6 +511,7 @@
 list(APPEND TSAN_SUPPORTED_OS ${platform})
   endif()
   list(APPEND FUZZER_SUPPORTED_OS ${platform})
+  list(APPEND ORC_SUPPORTED_OS ${platform})
 endif()
 foreach(arch ${DARWIN_${platform}_ARCHS})
   list(APPEND COM

[PATCH] D112230: [OpenCL] Add support of __opencl_c_device_enqueue feature macro.

2021-10-21 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov created this revision.
azabaznov added reviewers: Anastasia, yaxunl, svenvh.
Herald added a subscriber: ldrumm.
azabaznov requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This feature requires support of __opencl_c_generic_address_space,
so diagnostics for that is provided as well.

The main problem with device enqueue feature is that block literal for block
with no captures emitted in global address space. This is not correct if feature
for program scope, global variables are not supported. This patch:

- Disables generation blocks with constant address space (yet) if feature for 
program scope global variables is not supported,

since such blocks always have no captures. Global blocks are not allowed in any 
other address space then constant
if feature for program scope global variables is not supported.

- For local blocks without captures, generate block literal is local scope with 
use of generic address space.

This is achieved adding checks during code generation and not treating block 
literal with no captures as constant expressions.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112230

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Basic/OpenCLOptions.cpp
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/CodeGen/CGBlocks.cpp
  clang/lib/CodeGen/CGOpenCLRuntime.cpp
  clang/lib/CodeGen/CGOpenCLRuntime.h
  clang/lib/Headers/opencl-c-base.h
  clang/lib/Headers/opencl-c.h
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CodeGenOpenCL/address-spaces-mangling.cl
  clang/test/CodeGenOpenCL/address-spaces.cl
  clang/test/CodeGenOpenCL/blocks.cl
  clang/test/CodeGenOpenCL/blocks_no_global_literal.cl
  clang/test/Frontend/opencl.cl
  clang/test/Misc/opencl-c-3.0.incorrect_options.cl
  clang/test/SemaOpenCL/constant-blocks-unsupported-cl3.0.cl
  clang/test/SemaOpenCL/invalid-block.cl
  clang/test/SemaOpenCL/invalid-device-enqueue-types-cl3.0.cl
  clang/test/SemaOpenCL/invalid-pipes-cl1.2.cl
  clang/test/SemaOpenCL/storageclass.cl

Index: clang/test/SemaOpenCL/storageclass.cl
===
--- clang/test/SemaOpenCL/storageclass.cl
+++ clang/test/SemaOpenCL/storageclass.cl
@@ -1,10 +1,10 @@
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL1.2
-// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 -cl-ext=-__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes
-// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 -cl-ext=+__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 -cl-ext=-__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes,-__opencl_c_device_enqueue
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 -cl-ext=+__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes,-__opencl_c_device_enqueue
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 -cl-ext=-__opencl_c_program_scope_global_variables,+__opencl_c_generic_address_space
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 -cl-ext=+__opencl_c_program_scope_global_variables,+__opencl_c_generic_address_space
-// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=clc++2021 -cl-ext=-__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes
-// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=clc++2021 -cl-ext=+__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=clc++2021 -cl-ext=-__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes,-__opencl_c_device_enqueue
+// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=clc++2021 -cl-ext=+__opencl_c_program_scope_global_variables,-__opencl_c_generic_address_space,-__opencl_c_pipes,-__opencl_c_device_enqueue
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=clc++2021 -cl-ext=-__opencl_c_program_scope_global_variables,+__opencl_c_generic_address_space
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=clc++2021 -cl-ext=+__opencl_c_program_scope_global_variables,+__opencl_c_generic_address_space
 static constant int G1 = 0;
Index: clang/test/SemaOpenCL/invalid-pipes-cl1.2.cl
===
--- clang/test/SemaOpenCL/invalid-pipes-cl1.2.cl
+++ clang/test/SemaOpenCL/invalid-pipes-cl1.2.cl
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL1.2
-// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=CL3.0 -cl-ext=-__opencl_c_pipes,-__open

[PATCH] D112227: [libomptarget] Build DeviceRTL for amdgpu

2021-10-21 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added inline comments.



Comment at: openmp/libomptarget/DeviceRTL/src/Configuration.cpp:23
 
-extern uint32_t __omp_rtl_debug_kind;
+// extern uint32_t __omp_rtl_debug_kind;
 

jdoerfert wrote:
> JonChesterfield wrote:
> > Otherwise the missing symbols prevents linking, not clear why it works on 
> > nvptx64
> linking what? Clang emits the symbol, maybe just not for amdgpu.
Where? The only reference I can find to it is here, and it's marked extern.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112227

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


[PATCH] D112190: [clang] Don't clear AST if we have consumers running after the main action

2021-10-21 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added inline comments.



Comment at: clang/test/Misc/clear-ast-before-backend-plugins.c:3-8
+// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend 
-emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext %s 2>&1 
| FileCheck %s --check-prefix=YES
+// YES: Clearing AST
+
+// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend 
-emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext 
-add-plugin print-fns -plugin-arg-print-fns help %s 2>&1 | FileCheck %s 
--check-prefix=NO
+// NO-NOT: Clearing AST
+

dblaikie wrote:
> Can you test that the "consumers running after the main action" are actually 
> running here in a relatively lightweight manner? (ie: in a way that depends 
> on as little details of their behavior as possible, just that they ran)
I don't think so, the only observable behavior is anything the plugin does, and 
this plugin only prints things. Clang on its own doesn't do much debug logging.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112190

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


[clang] 2dcad77 - [clang] Don't clear AST if we have consumers running after the main action

2021-10-21 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2021-10-21T09:03:57-07:00
New Revision: 2dcad7754a204d5dbb78fef8f6b13cd005456e33

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

LOG: [clang] Don't clear AST if we have consumers running after the main action

Downstream users may have Clang plugins. By default these plugins run
after the main action if they are specified on the command line.

Since these plugins are ASTConsumers, presumably they inspect the AST.
So we shouldn't clear it if any plugins run after the main action.

Reviewed By: dblaikie, hans

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

Added: 
clang/test/Misc/clear-ast-before-backend-plugins.c

Modified: 
clang/lib/Frontend/FrontendAction.cpp

Removed: 




diff  --git a/clang/lib/Frontend/FrontendAction.cpp 
b/clang/lib/Frontend/FrontendAction.cpp
index b56db78d3e71a..089f40b36089a 100644
--- a/clang/lib/Frontend/FrontendAction.cpp
+++ b/clang/lib/Frontend/FrontendAction.cpp
@@ -217,8 +217,13 @@ FrontendAction::CreateWrappedASTConsumer(CompilerInstance 
&CI,
 
   // Add to Consumers the main consumer, then all the plugins that go after it
   Consumers.push_back(std::move(Consumer));
-  for (auto &C : AfterConsumers) {
-Consumers.push_back(std::move(C));
+  if (!AfterConsumers.empty()) {
+// If we have plugins after the main consumer, which may be the codegen
+// action, they likely will need the ASTContext, so don't clear it in the
+// codegen action.
+CI.getCodeGenOpts().ClearASTBeforeBackend = false;
+for (auto &C : AfterConsumers)
+  Consumers.push_back(std::move(C));
   }
 
   return std::make_unique(std::move(Consumers));

diff  --git a/clang/test/Misc/clear-ast-before-backend-plugins.c 
b/clang/test/Misc/clear-ast-before-backend-plugins.c
new file mode 100644
index 0..c00bee4450d98
--- /dev/null
+++ b/clang/test/Misc/clear-ast-before-backend-plugins.c
@@ -0,0 +1,9 @@
+// REQUIRES: plugins, examples, asserts
+
+// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend 
-emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext %s 2>&1 
| FileCheck %s --check-prefix=YES
+// YES: Clearing AST
+
+// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend 
-emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext 
-add-plugin print-fns -plugin-arg-print-fns help %s 2>&1 | FileCheck %s 
--check-prefix=NO
+// NO-NOT: Clearing AST
+
+void f() {}



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


[PATCH] D112190: [clang] Don't clear AST if we have consumers running after the main action

2021-10-21 Thread Arthur Eubanks via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2dcad7754a20: [clang] Don't clear AST if we have 
consumers running after the main action (authored by aeubanks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112190

Files:
  clang/lib/Frontend/FrontendAction.cpp
  clang/test/Misc/clear-ast-before-backend-plugins.c


Index: clang/test/Misc/clear-ast-before-backend-plugins.c
===
--- /dev/null
+++ clang/test/Misc/clear-ast-before-backend-plugins.c
@@ -0,0 +1,9 @@
+// REQUIRES: plugins, examples, asserts
+
+// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend 
-emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext %s 2>&1 
| FileCheck %s --check-prefix=YES
+// YES: Clearing AST
+
+// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend 
-emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext 
-add-plugin print-fns -plugin-arg-print-fns help %s 2>&1 | FileCheck %s 
--check-prefix=NO
+// NO-NOT: Clearing AST
+
+void f() {}
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -217,8 +217,13 @@
 
   // Add to Consumers the main consumer, then all the plugins that go after it
   Consumers.push_back(std::move(Consumer));
-  for (auto &C : AfterConsumers) {
-Consumers.push_back(std::move(C));
+  if (!AfterConsumers.empty()) {
+// If we have plugins after the main consumer, which may be the codegen
+// action, they likely will need the ASTContext, so don't clear it in the
+// codegen action.
+CI.getCodeGenOpts().ClearASTBeforeBackend = false;
+for (auto &C : AfterConsumers)
+  Consumers.push_back(std::move(C));
   }
 
   return std::make_unique(std::move(Consumers));


Index: clang/test/Misc/clear-ast-before-backend-plugins.c
===
--- /dev/null
+++ clang/test/Misc/clear-ast-before-backend-plugins.c
@@ -0,0 +1,9 @@
+// REQUIRES: plugins, examples, asserts
+
+// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend -emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext %s 2>&1 | FileCheck %s --check-prefix=YES
+// YES: Clearing AST
+
+// RUN: %clang_cc1 -mllvm -debug-only=codegenaction -clear-ast-before-backend -emit-obj -o /dev/null -load %llvmshlibdir/PrintFunctionNames%pluginext -add-plugin print-fns -plugin-arg-print-fns help %s 2>&1 | FileCheck %s --check-prefix=NO
+// NO-NOT: Clearing AST
+
+void f() {}
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -217,8 +217,13 @@
 
   // Add to Consumers the main consumer, then all the plugins that go after it
   Consumers.push_back(std::move(Consumer));
-  for (auto &C : AfterConsumers) {
-Consumers.push_back(std::move(C));
+  if (!AfterConsumers.empty()) {
+// If we have plugins after the main consumer, which may be the codegen
+// action, they likely will need the ASTContext, so don't clear it in the
+// codegen action.
+CI.getCodeGenOpts().ClearASTBeforeBackend = false;
+for (auto &C : AfterConsumers)
+  Consumers.push_back(std::move(C));
   }
 
   return std::make_unique(std::move(Consumers));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112230: [OpenCL] Add support of __opencl_c_device_enqueue feature macro.

2021-10-21 Thread Anton Zabaznov via Phabricator via cfe-commits
azabaznov added a comment.

@Anastasia, @yaxunl, do you think it's possible to refactor code generation for 
blocks such that block literal for global blocks (with no captures) would be 
emitted in constant address space? Now it's emitted in global address space 
(for example @__block_literal_global in https://godbolt.org/z/4z8hGj7hz).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112230

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


[PATCH] D112227: [libomptarget] Build DeviceRTL for amdgpu

2021-10-21 Thread Jon Chesterfield via Phabricator via cfe-commits
JonChesterfield added subscribers: ronlieb, pdhaliwal, carlo.bertolli, 
gregrodgers, dpalermo.
JonChesterfield added a comment.

Subscribed some AMD people to this. I wanted to apply this patch as-is to 
amd-stg-open to feed it to the internal testing, but it doesn't apply because 
Driver/ToolChains/AMDGPUOpenMP.cpp in rocm is significantly different to trunk 
(in particular the call to addOpenMPDeviceRTL is commented out)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112227

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


[clang] cfca2ae - Update the C++ and C status pages now that Clang 13 has been released

2021-10-21 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-10-21T12:13:19-04:00
New Revision: cfca2ae1f5babaf0877bbd3ce8665b9db3344411

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

LOG: Update the C++ and C status pages now that Clang 13 has been released

Added: 


Modified: 
clang/www/c_status.html
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/www/c_status.html b/clang/www/c_status.html
index d61e4af47501e..10b41c451d0c2 100644
--- a/clang/www/c_status.html
+++ b/clang/www/c_status.html
@@ -784,7 +784,7 @@ C2x implementation status
 
   Allow duplicate attributes
   http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2557.pdf";>N2557
-  Clang 13
+  Clang 13
 
 
   Character encoding of diagnostic text

diff  --git a/clang/www/cxx_status.html b/clang/www/cxx_status.html
index 9c3688d1dd6c3..aa5dd57e8ce02 100755
--- a/clang/www/cxx_status.html
+++ b/clang/www/cxx_status.html
@@ -111,7 +111,7 @@ C++11 implementation status
   Clang 2.9

 https://wg21.link/p1825r0";>P1825R0 (DR)
-Clang 13
+Clang 13
   
 
 
@@ -1220,7 +1220,7 @@ C++20 implementation status
 
   using enum
   https://wg21.link/p1099r5";>P1099R5
-  Clang 13
+  Clang 13
 
 
   Class template argument deduction for aggregates
@@ -1254,7 +1254,7 @@ C++20 implementation status
 
   More implicit moves
   https://wg21.link/p1825r0";>P1825R0 (DR)
-  Clang 13
+  Clang 13
 
 
 
@@ -1285,18 +1285,18 @@ C++2b implementation status
 
   Literal suffix uz, z for size_t, 
ssize_t
   https://wg21.link/p0330r8";>P0330R8
-  Clang 13
+  Clang 13
 
 
 
   Make () in lambdas optional in all cases
   https://wg21.link/p1102r2";>P1102R2
-  Clang 13
+  Clang 13
 
 
   Simpler implicit move
   https://wg21.link/p2266r1";>P2266R1
-  Clang 13
+  Clang 13
 
 
   if consteval
@@ -1306,7 +1306,7 @@ C++2b implementation status
 
   Allow duplicate attributes
   https://wg21.link/P2156R1";>P2156R1
-  Clang 13
+  Clang 13
 
 
   Narrowing contextual conversions to bool



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


[clang] acfe7d8 - Update the title and encoding for the C++ status page

2021-10-21 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2021-10-21T12:14:44-04:00
New Revision: acfe7d895d2f0897fe8f79151a491e75a7a99a25

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

LOG: Update the title and encoding for the C++ status page

Added: 


Modified: 
clang/www/cxx_status.html

Removed: 




diff  --git a/clang/www/cxx_status.html b/clang/www/cxx_status.html
index aa5dd57e8ce0..6894ca1b1ea6 100755
--- a/clang/www/cxx_status.html
+++ b/clang/www/cxx_status.html
@@ -1,8 +1,8 @@
 
 
 
-  
-  Clang - C++20, C++17, C++14, C++11 and C++98 Status
+  
+  Clang - C++ Programming Language Status
   
   
   

[PATCH] D110436: Add %n format specifier warning to clang-tidy

2021-10-21 Thread Jayson Yan via Phabricator via cfe-commits
Jaysonyan added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/PercentNFormatSpecifierCheck.cpp:43-57
+  auto PrintfDecl = functionDecl(hasName("::printf"));
+  auto FprintfDecl = functionDecl(hasName("::fprintf"));
+  auto VfprintfDecl = functionDecl(hasName("::vfprintf"));
+  auto SprintfDecl = functionDecl(hasName("::sprintf"));
+  auto SnprintfDecl = functionDecl(hasName("::snprintf"));
+  auto VprintfDecl = functionDecl(hasName("::vprintf"));
+  auto VsprintfDecl = functionDecl(hasName("::vsprintf"));

aaron.ballman wrote:
> Rather than separate all these into individual matchers, I think it's better 
> to use `hasAnyName()`. e.g.,
> ```
>   Finder->addMatcher(
>   callExpr(callee(functionDecl(
>hasAnyName("::printf", "::vprintf", "::scanf", 
> "::vscanf"))),
>hasArgument(0, stringLiteral().bind("StringLiteral"))),
>   this);
> ```
> Also, it looks like this misses the `wchar_t` variants.
> 
> One additional design question is whether we should consider user-specified 
> functions which use the `format` attribute in general. Using that attribute 
> implies the function handles format specifier strings, so it seems like those 
> functions would also want to flag %n for this particular check.
Thanks! Will change to use `hasAnyName()` and will add the `wchar_t` variants.

Regarding the matching user-specified functions, I was interested in doing that 
but I'm struggling to find a way to match it. Do you have any suggestions? 



Comment at: 
clang-tools-extra/clang-tidy/bugprone/PercentNFormatSpecifierCheck.cpp:89
+Result.Context->getTargetInfo());
+diag(loc, "usage of %%n can lead to unsafe writing to memory");
+  }

aaron.ballman wrote:
> FWIW, this diagnostic sounds more scary than I think it should. This implies 
> to me that tidy has found an unsafe usage when in fact, tidy is only 
> identifying that you have used the feature at all.
> 
> Personally, I think it's more useful to limit the check to problematic 
> situations. Use of `%n` by itself is not unsafe (in fact, I cannot think of a 
> situation where use of `%n` in a *string literal* format specifier is ever a 
> problem by itself. Generally, the safety concerns come from having a *non 
> string literal* format specifier where an attacker can insert their own `%n`.
> 
> If you want this check to be "did you use `%n` at all", then I think the 
> diagnostic should read more along the lines of `'%n' used as a format 
> specifier` instead. However, I question whether "bugprone" is the right place 
> for it at that point, because it's not really pointing out buggy code.
I think that's fair and changing the wording to just calling out the usage of 
the feature makes sense. The original motivation behind this change was because 
Fuchsia plans to disable usage of `%n` altogether. So we could possibly move 
this check to be under "fuchsia" rather than "bugprone".

That being said, I don't have full context behind the motivation to disable 
usage of `%n` but I believe that even explicit usage of the `%n` can be 
considered "bugprone" since it's difficult to guarantee that the pointer you 
are writing to comes from a reliable source.


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

https://reviews.llvm.org/D110436

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


[clang] 19b07ec - Reland [clang] Pass -clear-ast-before-backend in Clang::ConstructJob()

2021-10-21 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2021-10-21T09:25:53-07:00
New Revision: 19b07ec00062daffcb2fb132f4ac0f2484ff44fa

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

LOG: Reland [clang] Pass -clear-ast-before-backend in Clang::ConstructJob()

This clears the memory used for the Clang AST before we run LLVM passes.

https://llvm-compile-time-tracker.com/compare.php?from=d0a5f61c4f6fccec87fd5207e3fcd9502dd59854&to=b7437fee79e04464dd968e1a29185495f3590481&stat=max-rss
shows significant memory savings with no slowdown (in fact -O0 slightly speeds 
up).

For more background, see
https://lists.llvm.org/pipermail/cfe-dev/2021-September/068930.html.

Turn this off for the interpreter since it does codegen multiple times.

Relanding with fix for -print-stats: D111973

Relanding with fix for plugins: D112190

If you'd like to use this even with plugins, consider using the features
introduced in D112096.

This can be turned off with -Xclang -no-clear-ast-before-backend.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Interpreter/Interpreter.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 8dabfff64f80a..d5b5e3bb0bb84 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4675,6 +4675,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   // cleanup.
   if (!C.isForDiagnostics())
 CmdArgs.push_back("-disable-free");
+  CmdArgs.push_back("-clear-ast-before-backend");
 
 #ifdef NDEBUG
   const bool IsAssertBuild = false;

diff  --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 02b3025297b67..d14940d2e1321 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -113,6 +113,10 @@ CreateCI(const llvm::opt::ArgStringList &Argv) {
 
   Clang->getTarget().adjust(Clang->getDiagnostics(), Clang->getLangOpts());
 
+  // Don't clear the AST before backend codegen since we do codegen multiple
+  // times, reusing the same AST.
+  Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
+
   return std::move(Clang);
 }
 



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


[PATCH] D107339: [analyzer] Retrieve a character from StringLiteral as an initializer for constant arrays.

2021-10-21 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1708-1710
+  // Handle StringLiteral.
+  if (const auto *SL = dyn_cast(Init))
+return getSValFromStringLiteral(SL, Offset, R->getElementType());

I am wondering why this hunk is needed? `getSValFromInitListExpr` is handling 
this case at L1725, isn't it?


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

https://reviews.llvm.org/D107339

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


[PATCH] D110925: [clangd] Follow-up on rGdea48079b90d

2021-10-21 Thread ntfshard via Phabricator via cfe-commits
ntfshard added a comment.

Still not sure, getHashValue function returns unsigned, but seems it should 
return hash_code or result of operator size_t()


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110925

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


  1   2   >