[clang-tools-extra] aa1ac2a - [clangd] Flush stderr after signal handlers run, so we always get the full stack/crash info

2021-10-25 Thread Sam McCall via cfe-commits
Author: Sam McCall
Date: 2021-10-26T01:08:36+02:00
New Revision: aa1ac2ae451e54dfa19dce2794800bbd034e2194

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

LOG: [clangd] Flush stderr after signal handlers run, so we always get the full 
stack/crash info

Added: 


Modified: 
clang-tools-extra/clangd/tool/ClangdMain.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp 
b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index 2e48bfb433f0c..4f8895b5d605c 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -681,7 +681,12 @@ int main(int argc, char *argv[]) {
   llvm::InitializeAllTargetInfos();
   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   llvm::sys::AddSignalHandler(
-  [](void *) { ThreadCrashReporter::runCrashHandlers(); }, nullptr);
+  [](void *) {
+ThreadCrashReporter::runCrashHandlers();
+// Ensure ThreadCrashReporter and PrintStackTrace output is visible.
+llvm::errs().flush();
+  },
+  nullptr);
   llvm::sys::SetInterruptFunction(&requestShutdown);
   llvm::cl::SetVersionPrinter([](llvm::raw_ostream &OS) {
 OS << versionString() << "\n"



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


[PATCH] D112498: [Lex] Remove timer from #pragma clang __debug crash handler

2021-10-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: kadircet, aganea.
sammccall requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This seems to be temporary code for testing 
28ad9fc20823678881baa0d723834b88ea9e8e3a 

which was never removed


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112498

Files:
  clang/lib/Lex/Pragma.cpp


Index: clang/lib/Lex/Pragma.cpp
===
--- clang/lib/Lex/Pragma.cpp
+++ clang/lib/Lex/Pragma.cpp
@@ -45,7 +45,6 @@
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/Timer.h"
 #include 
 #include 
 #include 
@@ -1108,8 +1107,6 @@
   if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
 llvm_unreachable("This is an assertion!");
 } else if (II->isStr("crash")) {
-  llvm::Timer T("crash", "pragma crash");
-  llvm::TimeRegion R(&T);
   if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
 LLVM_BUILTIN_TRAP;
 } else if (II->isStr("parser_crash")) {


Index: clang/lib/Lex/Pragma.cpp
===
--- clang/lib/Lex/Pragma.cpp
+++ clang/lib/Lex/Pragma.cpp
@@ -45,7 +45,6 @@
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/Timer.h"
 #include 
 #include 
 #include 
@@ -1108,8 +1107,6 @@
   if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
 llvm_unreachable("This is an assertion!");
 } else if (II->isStr("crash")) {
-  llvm::Timer T("crash", "pragma crash");
-  llvm::TimeRegion R(&T);
   if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
 LLVM_BUILTIN_TRAP;
 } else if (II->isStr("parser_crash")) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D108696: [Coroutines] [Frontend] Lookup in std namespace first

2021-10-25 Thread Lewis Baker via Phabricator via cfe-commits
lewissbaker added a comment.

So am I correct in understanding that the main issue with the chicken/egg 
problem for updating both the compiler to use the new stdlib facilities and 
updating the stdlib facilities is that we don't want to issue warnings about 
using `` and telling users to use `` instead 
if there is no `` header.

I wonder if a suitable transition approach here might be to have the compiler 
do:

- try lookup of std::coroutine_handle/coroutine_traits; if found try to 
instantiate the expression (e.g. await-suspend) using the std:: type
- if not found then try lookup of 
std::experimental::coroutine_handle/coroutine_traits; and if found try to 
instantiate the expression using the std::experimental:: type; and if 
successful, then;
  - if std:: type was found but instantiating the expression failed, then issue 
a warning about using deprecated std::experimental:: types
  - otherwise if std:: type was not found, try to find  header and 
if present then issue a warning suggesting using  instead of 


Then you should be able to land the compiler change and it should continue to 
have the same behaviour for existing code using std::experimental:: types with 
the existing stdlib.
It is only once the stdlib changes that land which add the  header 
that users would start seeing the warnings about using  instead of 


Note that there are still some potential breakages for code that could go on 
here, however.

Imagine that some header I included has been updated to use  while 
my current header is still using  so that both are in 
scope.

I might have defined an awaitable type that looks like the following:

  c++
  #include  // which transitively includes 
  #include 
  
  struct my_awaitable {
bool await_ready();
void await_suspend(std::experimental::coroutine_handle<> coro);
void await_resume();
  };

In this case, the compiler would find the `std::coroutine_handle<>` and try to 
instantiate the await-suspend expression with that type, which would fail 
because `await_suspend()` is not callable with a `std::coroutine_handle`.
The compiler would need to fall back to instantiating the expression with 
`std::experimental::coroutine_handle`.

There is also the variation where await_suspend() is a template function that 
deduces the promise-type argument.
e.g.

  c++
  template
  void await_suspend(std::experimental::coroutine_handle coro);

There are also cases where the template parameter to await_suspend() is 
unconstrained.
e.g.

  c++
  struct promise_type {
...
std::experimental::coroutine_handle<> continuation;
  };
  
  struct my_awaitable {
bool await_ready();
template
auto await_suspend(CoroHandle handle) {
  coro.promise().continuation = handle;
  return coro;
}
void await_resume();
  
std::experimental::coroutine_handle coro;
  };

Such a type would successfully deduce the template parameter using 
std::coroutine_handle and so the await-suspend expression would be valid, but 
the instantiation of the await_suspend() body would fail as a 
std::coroutine_handle cannot be assigned to an lvalue of type 
`std::experimentl::coroutine_handle<>`. This would not produce a 
SFINAE-friendly error that the compiler could retry with std::experimental 
types.

I'm not sure if there's a great way of keeping such code working in a mixed 
`` and `` world.
Maybe the cost of doing so is not worth the benefit?

The only way I can think of making this work is to just make 
`std::experimental::*` an alias for `std::*`.
But that only works for `std::experimental::coroutine_handle`. It doesn't work 
for `std::experimental::coroutine_traits` as you can't add specialisations 
through an alias.


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

https://reviews.llvm.org/D108696

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


[PATCH] D112498: [Lex] Remove timer from #pragma clang __debug crash handler

2021-10-25 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added a comment.

This Timer is actually the test coverage for that commit. If we don’t want it 
here, I guess you could move it to the Support unit tests?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112498

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


[PATCH] D110869: [X86] Implement -fzero-call-used-regs option

2021-10-25 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 382155.
void added a comment.

Count sub/super registers as "uses" in terminating instructions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110869

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/zero-call-used-regs.c
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/Sema/zero_call_used_regs.c
  llvm/include/llvm/Support/CodeGen.h
  llvm/lib/Target/X86/X86FrameLowering.cpp
  llvm/lib/Target/X86/X86FrameLowering.h
  llvm/lib/Target/X86/X86RegisterInfo.cpp
  llvm/lib/Target/X86/X86RegisterInfo.h
  llvm/test/CodeGen/X86/zero-call-used-regs-all-arg.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-all-gpr-arg.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-all-gpr.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-all.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-fmod.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-skip.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-smoke-tests.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-used-arg.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr-arg.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr.ll
  llvm/test/CodeGen/X86/zero-call-used-regs-used.ll

Index: llvm/test/CodeGen/X86/zero-call-used-regs-used.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/zero-call-used-regs-used.ll
@@ -0,0 +1,28 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu | FileCheck %s
+
+@result = dso_local global i32 0, align 4
+
+define dso_local i32 @foo(i32 returned %x) local_unnamed_addr #0 {
+; CHECK-LABEL: foo:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movl %edi, %eax
+; CHECK-NEXT:xorl %edi, %edi
+; CHECK-NEXT:retq
+entry:
+  ret i32 %x
+}
+
+define dso_local i32 @main() local_unnamed_addr #1 {
+; CHECK-LABEL: main:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movl $2, result(%rip)
+; CHECK-NEXT:xorl %eax, %eax
+; CHECK-NEXT:retq
+entry:
+  store volatile i32 2, i32* @result, align 4
+  ret i32 0
+}
+
+attributes #0 = { mustprogress nofree norecurse nosync nounwind readnone uwtable willreturn "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" "zero-call-used-regs"="used" }
+attributes #1 = { nofree norecurse nounwind uwtable "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" "zero-call-used-regs"="used" }
Index: llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr.ll
@@ -0,0 +1,28 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu | FileCheck %s
+
+@result = dso_local global i32 0, align 4
+
+define dso_local i32 @foo(i32 returned %x) local_unnamed_addr #0 {
+; CHECK-LABEL: foo:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movl %edi, %eax
+; CHECK-NEXT:xorl %edi, %edi
+; CHECK-NEXT:retq
+entry:
+  ret i32 %x
+}
+
+define dso_local i32 @main() local_unnamed_addr #1 {
+; CHECK-LABEL: main:
+; CHECK:   # %bb.0: # %entry
+; CHECK-NEXT:movl $2, result(%rip)
+; CHECK-NEXT:xorl %eax, %eax
+; CHECK-NEXT:retq
+entry:
+  store volatile i32 2, i32* @result, align 4
+  ret i32 0
+}
+
+attributes #0 = { mustprogress nofree norecurse nosync nounwind readnone uwtable willreturn "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" "zero-call-used-regs"="used-gpr" }
+attributes #1 = { nofree norecurse nounwind uwtable "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" "zero-call-used-regs"="used-gpr" }
Index: llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr-arg.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/zero-call-used-regs-used-gpr-arg.ll
@@ -0,0 +1,28 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu | FileCheck %s
+
+@result = 

[PATCH] D112498: [Lex] Remove timer from #pragma clang __debug crash handler

2021-10-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D112498#3086029 , @aganea wrote:

> This Timer is actually the test coverage for that commit.

Ah, our issue is that it runs in production as well as in the tests. Each time 
the parser sees the crash pragma it dumps a bunch of output to stderr, even if 
the pragma is disabled in PP opts.

> If we don’t want it here, I guess you could move it to the Support unit tests?

Makes sense. Do I understand right that we want to a crash recovery context, a 
timer region within it, and then `abort()` within that?
And we're just verifying we can do that a couple of times without crashing?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112498

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


[PATCH] D110092: [clang][NFC] encapsulate global method list in GlobalMethodPool

2021-10-25 Thread Richard Howell via Phabricator via cfe-commits
rmaz abandoned this revision.
rmaz added a comment.

Abandoning in favor of D110123 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110092

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


[PATCH] D109632: [clang] de-duplicate methods from AST files

2021-10-25 Thread Richard Howell via Phabricator via cfe-commits
rmaz abandoned this revision.
rmaz added a comment.

@vsapsai i'll abandon this diff then, thanks for your extensive feedback on the 
approach. Is D110123  shippable already, or 
are there some more corner cases to cover?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109632

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


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

2021-10-25 Thread Nico Weber via cfe-commits
Was this reviewed anywhere?

I'll note that some internal project apparently used to check `#if
__has_attribute(__unsafe_unretained)`. That used to silently (and
incorrectly I think) always return 0 as far as I can tell, but now it fails
with:

```
$ out/gn/bin/clang -c foo.mm
foo.mm:1:21: error: missing ')' after '__attribute__'
#if __has_attribute(__unsafe_unretained)
^~~
:350:42: note: expanded from here
#define __unsafe_unretained __attribute__((objc_ownership(none)))
~^
foo.mm:1:20: note: to match this '('
#if __has_attribute(__unsafe_unretained)
   ^
1 error generated.
```

That's arguably a progression and I'm still finding out what the intent
there was (maybe `#ifdef __unsafe_unretained`?).

So nothing to do here I think, but I thought I'd mention it.

On Sun, Oct 17, 2021 at 7:58 AM Aaron Ballman via cfe-commits <
cfe-commits@lists.llvm.org> 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);
>
>  already_lexed:
>  switch (Tok.getKind()) {
> @@ -1609,21 +1612,21 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
>  OS << CounterValue++;
>  Tok.setKind(tok::numeric_constant);
>} else if (II == Ident__has_feature) {
> -EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
> +EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
>[this](Token &Tok, bool &HasLexedNextToken) -> int {
>  IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
>
> diag::err_feature_check_malformed);
>  return II && HasFeature(*this, II->getName());
>});
>} else if (II == Ident__has_extension) {
> -EvaluateFeatureLikeBuiltin

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

2021-10-25 Thread Nico Weber via cfe-commits
Looks like the reason for this check was that
https://github.com/llvm/llvm-project/blob/3b42fc8a07c37e47efae80c931eff7e63103e0e9/clang/include/clang/Basic/Attr.td#L1946
contains __unsafe_unretained despite it just being a macro here:
http://llvm-cs.pcc.me.uk/tools/clang/lib/Frontend/InitPreprocessor.cpp#1019

Is that Attr.td entry incorrect?

On Mon, Oct 25, 2021 at 8:40 PM Nico Weber  wrote:

> Was this reviewed anywhere?
>
> I'll note that some internal project apparently used to check `#if
> __has_attribute(__unsafe_unretained)`. That used to silently (and
> incorrectly I think) always return 0 as far as I can tell, but now it fails
> with:
>
> ```
> $ out/gn/bin/clang -c foo.mm
> foo.mm:1:21: error: missing ')' after '__attribute__'
> #if __has_attribute(__unsafe_unretained)
> ^~~
> :350:42: note: expanded from here
> #define __unsafe_unretained __attribute__((objc_ownership(none)))
> ~^
> foo.mm:1:20: note: to match this '('
> #if __has_attribute(__unsafe_unretained)
>^
> 1 error generated.
> ```
>
> That's arguably a progression and I'm still finding out what the intent
> there was (maybe `#ifdef __unsafe_unretained`?).
>
> So nothing to do here I think, but I thought I'd mention it.
>
> On Sun, Oct 17, 2021 at 7:58 AM Aaron Ballman via cfe-commits <
> cfe-commits@lists.llvm.org> 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);
>>
>>  already_lexed:
>>  switch (Tok.getKind()) {
>> @@ -1609,21 +1612,21 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok)
>> {
>>  O

[PATCH] D112399: Get Bazel building `//clang` on Windows with clang-cl.

2021-10-25 Thread Nico Weber via Phabricator via cfe-commits
thakis added inline comments.



Comment at: clang/include/clang/Basic/Builtins.def:1059
+#undef strcasecmp
+#undef strncasecmp
+

Why do we need this with bazel but not with other windows builds?


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

https://reviews.llvm.org/D112399

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


[PATCH] D112498: [Lex] Remove timer from #pragma clang __debug crash handler

2021-10-25 Thread Alexandre Ganea via Phabricator via cfe-commits
aganea added a comment.

That sounds right. You can test that scenario in a debugger, by putting a 
breakpoint before BuryPointer in clang/tools/driver/driver.cpp and verifying 
that the TimerGroup still has a pointer to the deleted stack frames, after the 
CrashRecoveryContext has successfully catches the abort().


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112498

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


[PATCH] D112399: Get Bazel building `//clang` on Windows with clang-cl.

2021-10-25 Thread Chandler Carruth via Phabricator via cfe-commits
chandlerc added inline comments.



Comment at: clang/include/clang/Basic/Builtins.def:1059
+#undef strcasecmp
+#undef strncasecmp
+

thakis wrote:
> Why do we need this with bazel but not with other windows builds?
I don't know how this never was hit by other builders. I don't usually develop 
on Windows so I have very little experience with different builds there.

My guess is that it is the particular way that Bazel+clang-cl compile on 
Windows causes sligthtly more to be transitively included with `#include 
` and that grows the number of functions hit with this. I thought 
about trying to "fix" that, but the existing `#undef` lines made me think it 
wouldn't be completely successful.

Are you worried about the change? Looking for a different fix?



Comment at: 
utils/bazel/llvm-project-overlay/clang/include/clang/Config/config.h:78
 /* Define if we have sys/resource.h (rlimits) */
-#define CLANG_HAVE_RLIMITS 1
+/* CLANG_HAVE_RLIMITS defined in Bazel */
 

GMNGeoffrey wrote:
> Hmm I think we probably should have a change-detector for this config as well 
> as the LLVM ones
Yeah, but didn't want to try to add that in this change.

IMO, the better thing would be for this to go away as it is almost entirely 
redundant already But agin, not this change



Comment at: utils/bazel/llvm-project-overlay/llvm/cc_plugin_library.bzl:33
+for impl_name in [dll_name, dylib_name, so_name]:
+cc_binary(
+name = impl_name,

GMNGeoffrey wrote:
> What about this makes `binary_alias` no longer work?
The `output_group` in the subsequent `filegroup`. It requires the actions in 
the sources to have a correctly named `output_group`, which `cc_binary` with 
`linkshared` does.

It's possible that I could just rename things enough by adding multiple layers 
of file groups and maybe some added "copy this file" rules... But I'm worried 
that wouldn't work well long term. For example, it seems reasonable for the 
`.lib` file to *name* the `.dll` file that should be loaded. And so if we build 
it with `cc_binary` that has the wrong name, I'm worried things won't work as 
expected. I have higher confidence in this arrangement where the `cc_binary` 
directly produces the desired name.

Something like that actually happened when I tried a different way of wiring 
this up that still used the `binary_alias` on Linux -- it ended up actually 
loading `liblibclang_impl.so` and not `libclang.so`. That was a different 
setup, so maaaybe I wouldn't hit that exact situation, but its the kind of 
thing that inclined me towards this model.


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

https://reviews.llvm.org/D112399

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


[PATCH] D112504: [OpenMP] Wrap (v)printf in the new RT and use same handling for AMD

2021-10-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert created this revision.
jdoerfert added reviewers: JonChesterfield, tianshilei1992, jhuber6.
Herald added subscribers: guansong, bollu, yaxunl.
jdoerfert requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added projects: clang, OpenMP.

To support `printf` NVPTX and AMD targets are handled differently. The
latter performs host calls, which we don't really want in OpenMP, the
former translates `printf` calls to `vprintf` calls as the NVIDIA
runtime provides an implementation for the device of `vprintf`. This
patch unifies the AMD and NVPTX handling and emits for both calls to the
`vprintf` wrapper `__llvm_omp_vprintf` which we define in our new device
runtime. The main benefit of this wrapper is that we can more easily
control (and profile) the emission of `printf` calls in device code.

Note: Tests are coming.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112504

Files:
  clang/lib/CodeGen/CGGPUBuiltin.cpp
  openmp/libomptarget/DeviceRTL/include/Debug.h
  openmp/libomptarget/DeviceRTL/include/Interface.h
  openmp/libomptarget/DeviceRTL/src/Debug.cpp

Index: openmp/libomptarget/DeviceRTL/src/Debug.cpp
===
--- openmp/libomptarget/DeviceRTL/src/Debug.cpp
+++ openmp/libomptarget/DeviceRTL/src/Debug.cpp
@@ -38,6 +38,15 @@
  assertion);
   __builtin_trap();
 }
+
+// We do not have a vprintf implementation for AMD GPU yet so we use a stub.
+#pragma omp begin declare variant match(device = {arch(amdgcn)})
+int32_t vprintf(const char *, void *) { return 0; }
+#pragma omp end declare variant
+
+int32_t __llvm_omp_vprintf(const char *Format, void *Arguments) {
+  return vprintf(Format, Arguments);
+}
 }
 
 /// Current indentation level for the function trace. Only accessed by thread 0.
Index: openmp/libomptarget/DeviceRTL/include/Interface.h
===
--- openmp/libomptarget/DeviceRTL/include/Interface.h
+++ openmp/libomptarget/DeviceRTL/include/Interface.h
@@ -340,6 +340,9 @@
 int32_t __kmpc_shuffle_int32(int32_t val, int16_t delta, int16_t size);
 int64_t __kmpc_shuffle_int64(int64_t val, int16_t delta, int16_t size);
 ///}
+
+/// Printf
+int32_t __llvm_omp_vprintf(const char *Format, void *Arguments);
 }
 
 #endif
Index: openmp/libomptarget/DeviceRTL/include/Debug.h
===
--- openmp/libomptarget/DeviceRTL/include/Debug.h
+++ openmp/libomptarget/DeviceRTL/include/Debug.h
@@ -46,17 +46,12 @@
 /// macro.
 /// {
 
-#ifndef __AMDGCN__
 extern "C" {
 int printf(const char *format, ...);
 }
 
 #define PRINTF(fmt, ...) (void)printf(fmt, __VA_ARGS__)
 #define PRINT(str) PRINTF("%s", str)
-#else
-#define PRINTF(fmt, ...)
-#define PRINT(str)
-#endif
 
 #define WARN(fmt, ...) PRINTF("WARNING: " #fmt, __VA_ARGS__)
 
Index: clang/lib/CodeGen/CGGPUBuiltin.cpp
===
--- clang/lib/CodeGen/CGGPUBuiltin.cpp
+++ clang/lib/CodeGen/CGGPUBuiltin.cpp
@@ -21,24 +21,30 @@
 using namespace clang;
 using namespace CodeGen;
 
-static llvm::Function *GetVprintfDeclaration(llvm::Module &M) {
+static llvm::Function *GetVprintfDeclaration(CodeGenModule &CGM) {
+  bool UsesNewOpenMPDeviceRuntime = CGM.getLangOpts().OpenMPIsDevice &&
+CGM.getLangOpts().OpenMPTargetNewRuntime;
+  const char *Name =
+  UsesNewOpenMPDeviceRuntime ? "__llvm_omp_vprintf" : "vprintf";
+  llvm::Module &M = CGM.getModule();
   llvm::Type *ArgTypes[] = {llvm::Type::getInt8PtrTy(M.getContext()),
 llvm::Type::getInt8PtrTy(M.getContext())};
   llvm::FunctionType *VprintfFuncType = llvm::FunctionType::get(
   llvm::Type::getInt32Ty(M.getContext()), ArgTypes, false);
 
-  if (auto* F = M.getFunction("vprintf")) {
+  if (auto *F = M.getFunction(Name)) {
 // Our CUDA system header declares vprintf with the right signature, so
 // nobody else should have been able to declare vprintf with a bogus
-// signature.
+// signature. The OpenMP device runtime provides a wrapper around vprintf
+// which we use here. The signature should match though.
 assert(F->getFunctionType() == VprintfFuncType);
 return F;
   }
 
-  // vprintf doesn't already exist; create a declaration and insert it into the
-  // module.
+  // vprintf, or for OpenMP device offloading the vprintf wrapper, doesn't
+  // already exist; create a declaration and insert it into the module.
   return llvm::Function::Create(
-  VprintfFuncType, llvm::GlobalVariable::ExternalLinkage, "vprintf", &M);
+  VprintfFuncType, llvm::GlobalVariable::ExternalLinkage, Name, &M);
 }
 
 // Transforms a call to printf into a call to the NVPTX vprintf syscall (which
@@ -117,7 +123,7 @@
   }
 
   // Invoke vprintf and return.
-  llvm::Function* VprintfFunc = GetVprintfDeclaration(CGM.getModule());
+  llvm::Function *Vpr

[PATCH] D109506: [clangd] Print current request context along with the stack trace

2021-10-25 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

This doesn't build on windows: http://45.33.8.238/win/47615/step_4.txt

Please take a look and revert for now if it takes a while to fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109506

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


[PATCH] D108696: [Coroutines] [Frontend] Lookup in std namespace first

2021-10-25 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

In D108696#3086011 , @lewissbaker 
wrote:

> So am I correct in understanding that the main issue with the chicken/egg 
> problem for updating both the compiler to use the new stdlib facilities and 
> updating the stdlib facilities is that we don't want to issue warnings about 
> using `` and telling users to use `` 
> instead if there is no `` header.
>
> I wonder if a suitable transition approach here might be to have the compiler 
> do:
>
> - try lookup of std::coroutine_handle/coroutine_traits; if found try to 
> instantiate the expression (e.g. await-suspend) using the std:: type
> - if not found then try lookup of 
> std::experimental::coroutine_handle/coroutine_traits; and if found try to 
> instantiate the expression using the std::experimental:: type; and if 
> successful, then;
>   - if std:: type was found but instantiating the expression failed, then 
> issue a warning about using deprecated std::experimental:: types
>   - otherwise if std:: type was not found, try to find  header and 
> if present then issue a warning suggesting using  instead of 
> 
>
> Then you should be able to land the compiler change and it should continue to 
> have the same behaviour for existing code using std::experimental:: types 
> with the existing stdlib.
> It is only once the stdlib changes that land which add the  header 
> that users would start seeing the warnings about using  instead of 
> 

It looks odd for me with the sentence:

> otherwise if std:: type was not found, try to find  header and if 
> present then issue a warning suggesting using  instead of 
> 

If we could find the  header, we should be able to find `std::coro*` 
types. Otherwise, the  header is fake.

My transition plan would be:

- Land this.
- Land D109433 , it is the change who added 
.
- Land another patch in clang to issue a warning for the deprecated use of 
. The reason why we need to split this with the first 
step is that we don't want to trigger the CI system for libc++. (It's the 
reason this patch is rejected before).
- Remove  in libcxx in LLVM15.
- Remove the support for `std::experimental::coro*` in clang in LLVM16.



> Note that there are still some potential breakages for code that could go on 
> here, however.
>
> Imagine that some header I included has been updated to use  while 
> my current header is still using  so that both are in 
> scope.
>
> I might have defined an awaitable type that looks like the following:
>
>   c++
>   #include  // which transitively includes 
>   #include 
>   
>   struct my_awaitable {
> bool await_ready();
> void await_suspend(std::experimental::coroutine_handle<> coro);
> void await_resume();
>   };
>
> In this case, the compiler would find the `std::coroutine_handle<>` and try 
> to instantiate the await-suspend expression with that type, which would fail 
> because `await_suspend()` is not callable with a `std::coroutine_handle`.
> The compiler would need to fall back to instantiating the expression with 
> `std::experimental::coroutine_handle`.

My personal opinion is that this case should fail instead of requiring the 
compiler to fall back to instantiating with `std::experimental::coro*`. There 
are two reasons:

- It is not easy to implement such fall back to instantiating logics. It would 
make the current search process much more complex.
- It is not worth to do so in my opinion. Since  is the 
deprecated use. It is odd for me that we need to do extra work to conform it.

> There is also the variation where await_suspend() is a template function that 
> deduces the promise-type argument.
> e.g.
>
>   c++
>   template
>   void await_suspend(std::experimental::coroutine_handle coro);
>
> There are also cases where the template parameter to await_suspend() is 
> unconstrained.
> e.g.
>
>   c++
>   struct promise_type {
> ...
> std::experimental::coroutine_handle<> continuation;
>   };
>   
>   struct my_awaitable {
> bool await_ready();
> template
> auto await_suspend(CoroHandle handle) {
>   coro.promise().continuation = handle;
>   return coro;
> }
> void await_resume();
>   
> std::experimental::coroutine_handle coro;
>   };
>
> Such a type would successfully deduce the template parameter using 
> std::coroutine_handle and so the await-suspend expression would be valid, but 
> the instantiation of the await_suspend() body would fail as a 
> std::coroutine_handle cannot be assigned to an lvalue of type 
> `std::experimentl::coroutine_handle<>`. This would not produce a 
> SFINAE-friendly error that the compiler could retry with std::experimental 
> types.
>
> I'm not sure if there's a great way of keeping such code working in a mixed 
> `` and `` world.
> Maybe the cost of doing so is not worth the benefit?

Thanks for offering these examples. It is valuable. But I think the root cause 
may be the mixed use for `` and ``. It is 

[clang-tools-extra] ba94b8b - [clangd] Attempt to fix buildbots

2021-10-25 Thread Shoaib Meenai via cfe-commits
Author: Shoaib Meenai
Date: 2021-10-25T20:16:59-07:00
New Revision: ba94b8bdffb4c65d5475746a6ba43d279683e5bd

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

LOG: [clangd] Attempt to fix buildbots

http://45.33.8.238/win/47615/step_4.txt is a sample error; I believe it
just needs the right header to be included.

Added: 


Modified: 
clang-tools-extra/clangd/support/ThreadCrashReporter.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/support/ThreadCrashReporter.cpp 
b/clang-tools-extra/clangd/support/ThreadCrashReporter.cpp
index e67900e6916d9..b0386ba0089d0 100644
--- a/clang-tools-extra/clangd/support/ThreadCrashReporter.cpp
+++ b/clang-tools-extra/clangd/support/ThreadCrashReporter.cpp
@@ -9,6 +9,7 @@
 #include "support/ThreadCrashReporter.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/ThreadLocal.h"
+#include 
 
 namespace clang {
 namespace clangd {



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


[PATCH] D109506: [clangd] Print current request context along with the stack trace

2021-10-25 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added a comment.

In D109506#3086183 , @thakis wrote:

> This doesn't build on windows: http://45.33.8.238/win/47615/step_4.txt
>
> Please take a look and revert for now if it takes a while to fix.

I pushed rGba94b8bdffb4 
 as a 
speculative fix. I'll keep an eye on that bot. Thanks for the heads up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109506

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


[PATCH] D112504: [OpenMP] Wrap (v)printf in the new RT and use same handling for AMD

2021-10-25 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 382171.
jdoerfert added a comment.

Actually use the new wrapper for OpenMP offload targeting AMD (and the new RT)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112504

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGGPUBuiltin.cpp
  openmp/libomptarget/DeviceRTL/include/Debug.h
  openmp/libomptarget/DeviceRTL/include/Interface.h
  openmp/libomptarget/DeviceRTL/src/Debug.cpp

Index: openmp/libomptarget/DeviceRTL/src/Debug.cpp
===
--- openmp/libomptarget/DeviceRTL/src/Debug.cpp
+++ openmp/libomptarget/DeviceRTL/src/Debug.cpp
@@ -38,6 +38,15 @@
  assertion);
   __builtin_trap();
 }
+
+// We do not have a vprintf implementation for AMD GPU yet so we use a stub.
+#pragma omp begin declare variant match(device = {arch(amdgcn)})
+int32_t vprintf(const char *, void *) { return 0; }
+#pragma omp end declare variant
+
+int32_t __llvm_omp_vprintf(const char *Format, void *Arguments) {
+  return vprintf(Format, Arguments);
+}
 }
 
 /// Current indentation level for the function trace. Only accessed by thread 0.
Index: openmp/libomptarget/DeviceRTL/include/Interface.h
===
--- openmp/libomptarget/DeviceRTL/include/Interface.h
+++ openmp/libomptarget/DeviceRTL/include/Interface.h
@@ -340,6 +340,9 @@
 int32_t __kmpc_shuffle_int32(int32_t val, int16_t delta, int16_t size);
 int64_t __kmpc_shuffle_int64(int64_t val, int16_t delta, int16_t size);
 ///}
+
+/// Printf
+int32_t __llvm_omp_vprintf(const char *Format, void *Arguments);
 }
 
 #endif
Index: openmp/libomptarget/DeviceRTL/include/Debug.h
===
--- openmp/libomptarget/DeviceRTL/include/Debug.h
+++ openmp/libomptarget/DeviceRTL/include/Debug.h
@@ -46,17 +46,12 @@
 /// macro.
 /// {
 
-#ifndef __AMDGCN__
 extern "C" {
 int printf(const char *format, ...);
 }
 
 #define PRINTF(fmt, ...) (void)printf(fmt, __VA_ARGS__)
 #define PRINT(str) PRINTF("%s", str)
-#else
-#define PRINTF(fmt, ...)
-#define PRINT(str)
-#endif
 
 #define WARN(fmt, ...) PRINTF("WARNING: " #fmt, __VA_ARGS__)
 
Index: clang/lib/CodeGen/CGGPUBuiltin.cpp
===
--- clang/lib/CodeGen/CGGPUBuiltin.cpp
+++ clang/lib/CodeGen/CGGPUBuiltin.cpp
@@ -21,24 +21,30 @@
 using namespace clang;
 using namespace CodeGen;
 
-static llvm::Function *GetVprintfDeclaration(llvm::Module &M) {
+static llvm::Function *GetVprintfDeclaration(CodeGenModule &CGM) {
+  bool UsesNewOpenMPDeviceRuntime = CGM.getLangOpts().OpenMPIsDevice &&
+CGM.getLangOpts().OpenMPTargetNewRuntime;
+  const char *Name =
+  UsesNewOpenMPDeviceRuntime ? "__llvm_omp_vprintf" : "vprintf";
+  llvm::Module &M = CGM.getModule();
   llvm::Type *ArgTypes[] = {llvm::Type::getInt8PtrTy(M.getContext()),
 llvm::Type::getInt8PtrTy(M.getContext())};
   llvm::FunctionType *VprintfFuncType = llvm::FunctionType::get(
   llvm::Type::getInt32Ty(M.getContext()), ArgTypes, false);
 
-  if (auto* F = M.getFunction("vprintf")) {
+  if (auto *F = M.getFunction(Name)) {
 // Our CUDA system header declares vprintf with the right signature, so
 // nobody else should have been able to declare vprintf with a bogus
-// signature.
+// signature. The OpenMP device runtime provides a wrapper around vprintf
+// which we use here. The signature should match though.
 assert(F->getFunctionType() == VprintfFuncType);
 return F;
   }
 
-  // vprintf doesn't already exist; create a declaration and insert it into the
-  // module.
+  // vprintf, or for OpenMP device offloading the vprintf wrapper, doesn't
+  // already exist; create a declaration and insert it into the module.
   return llvm::Function::Create(
-  VprintfFuncType, llvm::GlobalVariable::ExternalLinkage, "vprintf", &M);
+  VprintfFuncType, llvm::GlobalVariable::ExternalLinkage, Name, &M);
 }
 
 // Transforms a call to printf into a call to the NVPTX vprintf syscall (which
@@ -117,7 +123,7 @@
   }
 
   // Invoke vprintf and return.
-  llvm::Function* VprintfFunc = GetVprintfDeclaration(CGM.getModule());
+  llvm::Function *VprintfFunc = GetVprintfDeclaration(CGM);
   return RValue::get(Builder.CreateCall(
   VprintfFunc, {Args[0].getRValue(*this).getScalarVal(), BufferPtr}));
 }
@@ -130,6 +136,12 @@
  E->getBuiltinCallee() == Builtin::BI__builtin_printf);
   assert(E->getNumArgs() >= 1); // printf always has at least one arg.
 
+  // For OpenMP target offloading we go with a modified nvptx printf method.
+  // Basically creating calls to __llvm_omp_vprintf with the arguments and
+  // dealing with the details in the device runtime itself.
+  if (getLangOpts().OpenMPIsDevice && getLangOpts().OpenMPTargetNewRuntime)
+  

[clang] 1ff1bca - [AIX][ZOS] Disable tests due to lack of Objective-C support

2021-10-25 Thread Jake Egan via cfe-commits
Author: Jake Egan
Date: 2021-10-25T23:32:13-04:00
New Revision: 1ff1bcab970afaef49e2ab8ab7681a12d11ad17d

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

LOG: [AIX][ZOS] Disable tests due to lack of Objective-C support

AIX and z/OS lack Objective-C support, so mark these tests as unsupported for 
AIX and z/OS.

This patch follows the same reasoning as D109060.

Reviewed By: jsji

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

Added: 


Modified: 
clang/test/Modules/ModuleDebugInfo.cpp
clang/test/Modules/ModuleDebugInfo.m
clang/test/Modules/clang_module_file_info.m
clang/test/Modules/debug-info-moduleimport-in-module.m
clang/test/Modules/module-debuginfo-prefix.m
llvm/test/DebugInfo/X86/objc_direct.ll

Removed: 




diff  --git a/clang/test/Modules/ModuleDebugInfo.cpp 
b/clang/test/Modules/ModuleDebugInfo.cpp
index 836f0d28fb2a2..433002c6cdbe3 100644
--- a/clang/test/Modules/ModuleDebugInfo.cpp
+++ b/clang/test/Modules/ModuleDebugInfo.cpp
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that (the same) debug info is emitted for an Objective-C++
 // module and a C++ precompiled header.
 

diff  --git a/clang/test/Modules/ModuleDebugInfo.m 
b/clang/test/Modules/ModuleDebugInfo.m
index ed576e441e5da..5493d6edc581c 100644
--- a/clang/test/Modules/ModuleDebugInfo.m
+++ b/clang/test/Modules/ModuleDebugInfo.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that debug info is emitted for an Objective-C module and
 // a precompiled header.
 

diff  --git a/clang/test/Modules/clang_module_file_info.m 
b/clang/test/Modules/clang_module_file_info.m
index b949c68c63903..8ae7483639661 100644
--- a/clang/test/Modules/clang_module_file_info.m
+++ b/clang/test/Modules/clang_module_file_info.m
@@ -1,4 +1,4 @@
-
+// UNSUPPORTED: -zos, -aix
 @import DependsOnModule;
 
 // RUN: rm -rf %t %t-obj

diff  --git a/clang/test/Modules/debug-info-moduleimport-in-module.m 
b/clang/test/Modules/debug-info-moduleimport-in-module.m
index cde46115d288a..71b863e8bce15 100644
--- a/clang/test/Modules/debug-info-moduleimport-in-module.m
+++ b/clang/test/Modules/debug-info-moduleimport-in-module.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that an @import inside a module is not represented in the debug info.
 
 // REQUIRES: asserts

diff  --git a/clang/test/Modules/module-debuginfo-prefix.m 
b/clang/test/Modules/module-debuginfo-prefix.m
index da5d86abefd08..5a6f924bf60e7 100644
--- a/clang/test/Modules/module-debuginfo-prefix.m
+++ b/clang/test/Modules/module-debuginfo-prefix.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // REQUIRES: asserts
 
 // Modules:

diff  --git a/llvm/test/DebugInfo/X86/objc_direct.ll 
b/llvm/test/DebugInfo/X86/objc_direct.ll
index c29dec14a4488..87e0f08241a3e 100644
--- a/llvm/test/DebugInfo/X86/objc_direct.ll
+++ b/llvm/test/DebugInfo/X86/objc_direct.ll
@@ -1,3 +1,4 @@
+; UNSUPPORTED: -zos, -aix
 ; RUN: llc < %s -filetype=obj -o %t
 ; RUN: llvm-dwarfdump -v %t | FileCheck %s
 



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


[PATCH] D112390: [AIX][ZOS] Disable tests due to lack of Objective-C support

2021-10-25 Thread Jake Egan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1ff1bcab970a: [AIX][ZOS] Disable tests due to lack of 
Objective-C support (authored by Jake-Egan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112390

Files:
  clang/test/Modules/ModuleDebugInfo.cpp
  clang/test/Modules/ModuleDebugInfo.m
  clang/test/Modules/clang_module_file_info.m
  clang/test/Modules/debug-info-moduleimport-in-module.m
  clang/test/Modules/module-debuginfo-prefix.m
  llvm/test/DebugInfo/X86/objc_direct.ll


Index: llvm/test/DebugInfo/X86/objc_direct.ll
===
--- llvm/test/DebugInfo/X86/objc_direct.ll
+++ llvm/test/DebugInfo/X86/objc_direct.ll
@@ -1,3 +1,4 @@
+; UNSUPPORTED: -zos, -aix
 ; RUN: llc < %s -filetype=obj -o %t
 ; RUN: llvm-dwarfdump -v %t | FileCheck %s
 
Index: clang/test/Modules/module-debuginfo-prefix.m
===
--- clang/test/Modules/module-debuginfo-prefix.m
+++ clang/test/Modules/module-debuginfo-prefix.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // REQUIRES: asserts
 
 // Modules:
Index: clang/test/Modules/debug-info-moduleimport-in-module.m
===
--- clang/test/Modules/debug-info-moduleimport-in-module.m
+++ clang/test/Modules/debug-info-moduleimport-in-module.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that an @import inside a module is not represented in the debug info.
 
 // REQUIRES: asserts
Index: clang/test/Modules/clang_module_file_info.m
===
--- clang/test/Modules/clang_module_file_info.m
+++ clang/test/Modules/clang_module_file_info.m
@@ -1,4 +1,4 @@
-
+// UNSUPPORTED: -zos, -aix
 @import DependsOnModule;
 
 // RUN: rm -rf %t %t-obj
Index: clang/test/Modules/ModuleDebugInfo.m
===
--- clang/test/Modules/ModuleDebugInfo.m
+++ clang/test/Modules/ModuleDebugInfo.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that debug info is emitted for an Objective-C module and
 // a precompiled header.
 
Index: clang/test/Modules/ModuleDebugInfo.cpp
===
--- clang/test/Modules/ModuleDebugInfo.cpp
+++ clang/test/Modules/ModuleDebugInfo.cpp
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that (the same) debug info is emitted for an Objective-C++
 // module and a C++ precompiled header.
 


Index: llvm/test/DebugInfo/X86/objc_direct.ll
===
--- llvm/test/DebugInfo/X86/objc_direct.ll
+++ llvm/test/DebugInfo/X86/objc_direct.ll
@@ -1,3 +1,4 @@
+; UNSUPPORTED: -zos, -aix
 ; RUN: llc < %s -filetype=obj -o %t
 ; RUN: llvm-dwarfdump -v %t | FileCheck %s
 
Index: clang/test/Modules/module-debuginfo-prefix.m
===
--- clang/test/Modules/module-debuginfo-prefix.m
+++ clang/test/Modules/module-debuginfo-prefix.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // REQUIRES: asserts
 
 // Modules:
Index: clang/test/Modules/debug-info-moduleimport-in-module.m
===
--- clang/test/Modules/debug-info-moduleimport-in-module.m
+++ clang/test/Modules/debug-info-moduleimport-in-module.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that an @import inside a module is not represented in the debug info.
 
 // REQUIRES: asserts
Index: clang/test/Modules/clang_module_file_info.m
===
--- clang/test/Modules/clang_module_file_info.m
+++ clang/test/Modules/clang_module_file_info.m
@@ -1,4 +1,4 @@
-
+// UNSUPPORTED: -zos, -aix
 @import DependsOnModule;
 
 // RUN: rm -rf %t %t-obj
Index: clang/test/Modules/ModuleDebugInfo.m
===
--- clang/test/Modules/ModuleDebugInfo.m
+++ clang/test/Modules/ModuleDebugInfo.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that debug info is emitted for an Objective-C module and
 // a precompiled header.
 
Index: clang/test/Modules/ModuleDebugInfo.cpp
===
--- clang/test/Modules/ModuleDebugInfo.cpp
+++ clang/test/Modules/ModuleDebugInfo.cpp
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that (the same) debug info is emitted for an Objective-C++
 // module and a C++ precompiled header.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] b43a2ae - [clang-tidy] Suppress readability-static-access-through-instance for CUDA built-in variables

2021-10-25 Thread Carlos Galvez via cfe-commits
Author: Carlos Galvez
Date: 2021-10-26T05:45:25Z
New Revision: b43a2aee4ee946d8897880e824f4b09fe4c46143

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

LOG: [clang-tidy] Suppress readability-static-access-through-instance for CUDA 
built-in variables

clang-tidy can be used to statically analyze CUDA code,
thanks to clang being able to compile CUDA code natively.
This makes clang-tidy the one and only open-source
static analyzer for CUDA.

However it currently warns for native CUDA built-in
variables, like threadIdx, due to the way they
are implemented in clang.

Users don't need to know the details of the clang
implementation, and they should continue to write
idiomatic code. Therefore, suppress the warning
if a CUDA built-in variable is encountered.

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-static-accessed-through-instance/__clang_cuda_builtin_vars.h

Modified: 

clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp

clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
 
b/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
index df4a39e11ce43..f2c1b0f5ec49b 100644
--- 
a/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/readability/StaticAccessedThroughInstanceCheck.cpp
@@ -9,6 +9,7 @@
 #include "StaticAccessedThroughInstanceCheck.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/StringRef.h"
 
 using namespace clang::ast_matchers;
 
@@ -54,7 +55,7 @@ void StaticAccessedThroughInstanceCheck::check(
 
   const Expr *BaseExpr = MemberExpression->getBase();
 
-  // Do not warn for overlaoded -> operators.
+  // Do not warn for overloaded -> operators.
   if (isa(BaseExpr))
 return;
 
@@ -70,6 +71,10 @@ void StaticAccessedThroughInstanceCheck::check(
   std::string BaseTypeName =
   BaseType.getAsString(PrintingPolicyWithSupressedTag);
 
+  // Do not warn for CUDA built-in variables.
+  if (StringRef(BaseTypeName).startswith("__cuda_builtin_"))
+return;
+
   SourceLocation MemberExprStartLoc = MemberExpression->getBeginLoc();
   auto Diag =
   diag(MemberExprStartLoc, "static member accessed through instance");

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-static-accessed-through-instance/__clang_cuda_builtin_vars.h
 
b/clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-static-accessed-through-instance/__clang_cuda_builtin_vars.h
new file mode 100644
index 0..63eb17303c6e8
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/Inputs/readability-static-accessed-through-instance/__clang_cuda_builtin_vars.h
@@ -0,0 +1,36 @@
+//===--- __clang_cuda_builtin_vars.h - Stub header for tests *- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef ___CLANG_CUDA_BUILTIN_VARS_H_
+#define ___CLANG_CUDA_BUILTIN_VARS_H_
+
+#define __CUDA_DEVICE_BUILTIN(FIELD) \
+  static unsigned int FIELD;
+
+struct __cuda_builtin_threadIdx_t {
+  __CUDA_DEVICE_BUILTIN(x);
+};
+
+struct __cuda_builtin_blockIdx_t {
+  __CUDA_DEVICE_BUILTIN(x);
+};
+
+struct __cuda_builtin_blockDim_t {
+  __CUDA_DEVICE_BUILTIN(x);
+};
+
+struct __cuda_builtin_gridDim_t {
+  __CUDA_DEVICE_BUILTIN(x);
+};
+
+__cuda_builtin_threadIdx_t threadIdx;
+__cuda_builtin_blockIdx_t blockIdx;
+__cuda_builtin_blockDim_t blockDim;
+__cuda_builtin_gridDim_t gridDim;
+
+#endif // ___CLANG_CUDA_BUILTIN_VARS_H_

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
index 9de96ae3a9d35..cd8d198c3d47d 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability-static-accessed-through-instance.cpp
@@ -1,4 +1,5 @@
-// RUN: %check_clang_tidy %s readability-static-accessed-through-instance %t
+// RUN: %check_clang_tidy %s readability-static-accessed-through-instance %t 
-- -- -isystem %S/Inputs/readability-static-accessed-through-instance
+#include <__clang_cuda_builtin_vars.h>
 
 struct C {
   static void foo();
@@ -248,3 +249,17 @@ void use_inline() {

[PATCH] D112334: [clang-tidy] Suppress readability-static-access-through-instance for CUDA built-in variables

2021-10-25 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

Thanks for the review! I forgot to mention the Differential Revision in the 
commit message after pushing so this review stays open, is there any way I can 
add it now in some other way? I suppose we don't want force-push?


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

https://reviews.llvm.org/D112334

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


[PATCH] D111866: [RISCV] Support Zfhmin extension

2021-10-25 Thread Shao-Ce SUN via Phabricator via cfe-commits
achieveartificialintelligence updated this revision to Diff 382195.
achieveartificialintelligence added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111866

Files:
  clang/test/Driver/riscv-arch.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVISelLowering.cpp
  llvm/lib/Target/RISCV/RISCVInstrInfoZfh.td
  llvm/lib/Target/RISCV/RISCVSubtarget.h
  llvm/test/CodeGen/RISCV/attributes.ll
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/rv32zfhmin-invalid.s
  llvm/test/MC/RISCV/rv32zfhmin-valid.s

Index: llvm/test/MC/RISCV/rv32zfhmin-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv32zfhmin-valid.s
@@ -0,0 +1,62 @@
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zfhmin,+d -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zfhmin,+d -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zfhmin,+d < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zfhmin,+d -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zfhmin,+d < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zfhmin,+d -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+
+# CHECK-ASM-AND-OBJ: flh ft0, 12(a0)
+# CHECK-ASM: encoding: [0x07,0x10,0xc5,0x00]
+flh f0, 12(a0)
+# CHECK-ASM-AND-OBJ: flh ft1, 4(ra)
+# CHECK-ASM: encoding: [0x87,0x90,0x40,0x00]
+flh f1, +4(ra)
+# CHECK-ASM-AND-OBJ: flh ft2, -2048(a3)
+# CHECK-ASM: encoding: [0x07,0x91,0x06,0x80]
+flh f2, -2048(x13)
+# CHECK-ASM-AND-OBJ: flh ft3, -2048(s1)
+# CHECK-ASM: encoding: [0x87,0x91,0x04,0x80]
+flh f3, %lo(2048)(s1)
+# CHECK-ASM-AND-OBJ: flh ft4, 2047(s2)
+# CHECK-ASM: encoding: [0x07,0x12,0xf9,0x7f]
+flh f4, 2047(s2)
+# CHECK-ASM-AND-OBJ: flh ft5, 0(s3)
+# CHECK-ASM: encoding: [0x87,0x92,0x09,0x00]
+flh f5, 0(s3)
+
+# CHECK-ASM-AND-OBJ: fsh ft6, 2047(s4)
+# CHECK-ASM: encoding: [0xa7,0x1f,0x6a,0x7e]
+fsh f6, 2047(s4)
+# CHECK-ASM-AND-OBJ: fsh ft7, -2048(s5)
+# CHECK-ASM: encoding: [0x27,0x90,0x7a,0x80]
+fsh f7, -2048(s5)
+# CHECK-ASM-AND-OBJ: fsh fs0, -2048(s6)
+# CHECK-ASM: encoding: [0x27,0x10,0x8b,0x80]
+fsh f8, %lo(2048)(s6)
+# CHECK-ASM-AND-OBJ: fsh fs1, 999(s7)
+# CHECK-ASM: encoding: [0xa7,0x93,0x9b,0x3e]
+fsh f9, 999(s7)
+
+# CHECK-ASM-AND-OBJ: fmv.x.h a2, fs7
+# CHECK-ASM: encoding: [0x53,0x86,0x0b,0xe4]
+fmv.x.h a2, fs7
+# CHECK-ASM-AND-OBJ: fmv.h.x ft1, a6
+# CHECK-ASM: encoding: [0xd3,0x00,0x08,0xf4]
+fmv.h.x ft1, a6
+
+# CHECK-ASM-AND-OBJ: fcvt.s.h fa0, ft0
+# CHECK-ASM: encoding: [0x53,0x05,0x20,0x40]
+fcvt.s.h fa0, ft0
+# CHECK-ASM-AND-OBJ: fcvt.h.s ft2, fa2
+# CHECK-ASM: encoding: [0x53,0x71,0x06,0x44]
+fcvt.h.s ft2, fa2
+# CHECK-ASM-AND-OBJ: fcvt.d.h fa0, ft0
+# CHECK-ASM: encoding: [0x53,0x05,0x20,0x42]
+fcvt.d.h fa0, ft0
+# CHECK-ASM-AND-OBJ: fcvt.h.d ft2, fa2
+# CHECK-ASM: encoding: [0x53,0x71,0x16,0x44]
+fcvt.h.d ft2, fa2
Index: llvm/test/MC/RISCV/rv32zfhmin-invalid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/rv32zfhmin-invalid.s
@@ -0,0 +1,23 @@
+# RUN: not llvm-mc -triple riscv32 -mattr=+experimental-zfhmin < %s 2>&1 | \
+# RUN:   FileCheck %s
+
+# Out of range immediates
+## simm12
+flh ft1, -2049(a0) # CHECK: :[[@LINE]]:10: error: operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an integer in the range [-2048, 2047]
+fsh ft2, 2048(a1) # CHECK: :[[@LINE]]:10: error: operand must be a symbol with %lo/%pcrel_lo/%tprel_lo modifier or an integer in the range [-2048, 2047]
+
+# Memory operand not formatted correctly
+flh ft1, a0, -200 # CHECK: :[[@LINE]]:14: error: invalid operand for instruction
+
+# Invalid register names
+flh ft15, 100(a0) # CHECK: :[[@LINE]]:5: error: invalid operand for instruction
+flh ft1, 100(a10) # CHECK: :[[@LINE]]:14: error: expected register
+
+# Integer registers where FP regs are expected
+fmv.x.h fs7, a2 # CHECK: :[[@LINE]]:9: error: invalid operand for instruction
+
+# FP registers where integer regs are expected
+fmv.h.x a8, ft2 # CHECK: :[[@LINE]]:9: error: invalid operand for instruction
+
+# Zfh instructions
+fmadd.h f10, f11, f12, f13, dyn # CHECK: :[[@LINE]]:1: error: instruction requires the following: 'Zfh' (Half-Precision Floating-Point)
Index: llvm/test/MC/RISCV/attribute-arch.s
===
--- llvm/test/MC/RISCV/attribute-arch.s
+++ llvm/test/MC/RISCV/attribute-arch.s
@@ -66,8 +66,11 @@
 .attribute arch, "rv32izbt"
 # CHECK: attribute  5, "rv32i2p0_zbt0p93"
 
+.attribute arch, "rv32ifzfhmi

[PATCH] D112504: [OpenMP] Wrap (v)printf in the new RT and use same handling for AMD

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

That's an interesting approach.

Do you happen to know where I can find details of the data format behind that 
void*? Have been meaning to look at writing printf for amdgpu as host side 
decoding of that buffer. If the compiler knows how long it is, that would be a 
useful third argument.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112504

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


[PATCH] D112284: [Clang][NFC] Clang CUDA codegen: a dyn_cast -> cast instance + clang-tidy fixes

2021-10-25 Thread Uday Bondhugula via Phabricator via cfe-commits
bondhugula marked an inline comment as done.
bondhugula added a comment.

In D112284#3085086 , @tra wrote:

> The description is a bit misleading. The dyn_cast->cast appears to be a minor 
> part of this patch.
> I'd separate clang-tidy cleanups into a separate patch or would just describe 
> all of these changes as a clean-up. dyn_cast->cast is an NFC change here, 
> too, considering that we're operating on a type of `FunctionDecl 
> *cudaLaunchKernelFD`.

I agree. I've done the latter.




Comment at: clang/lib/CodeGen/CGCUDANV.cpp:240
 llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
-  } else {
-// cudaError_t cudaLaunch(char *);
-return CGM.CreateRuntimeFunction(
-llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
   }
+  // cudaError_t cudaLaunch(char *);

tra wrote:
> Nit: you could remove these `{...}` now, too.
I retained this part due to the extra comment in line with LLVM style:
https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements
"//We consider that readability is harmed when omitting the brace in the 
presence of a single statement that is accompanied by a comment (assuming the 
comment can’t be hoisted above the if or loop statement, see below).//"


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112284

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


[PATCH] D112284: [Clang][NFC] Clang CUDA codegen clean-up

2021-10-25 Thread Uday Bondhugula via Phabricator via cfe-commits
bondhugula updated this revision to Diff 382201.
bondhugula marked an inline comment as done.
bondhugula retitled this revision from "[Clang][NFC] Clang CUDA codegen: a 
dyn_cast -> cast instance + clang-tidy fixes" to "[Clang][NFC] Clang CUDA 
codegen clean-up".
bondhugula edited the summary of this revision.
bondhugula added a comment.

Address review comments. Update commit title and summary.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112284

Files:
  clang/lib/CodeGen/CGCUDANV.cpp


Index: clang/lib/CodeGen/CGCUDANV.cpp
===
--- clang/lib/CodeGen/CGCUDANV.cpp
+++ clang/lib/CodeGen/CGCUDANV.cpp
@@ -177,7 +177,7 @@
   llvm::Function *finalizeModule() override;
 };
 
-}
+} // end anonymous namespace
 
 std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
   if (CGM.getLangOpts().HIP)
@@ -237,11 +237,10 @@
 // hipError_t hipLaunchByPtr(char *);
 return CGM.CreateRuntimeFunction(
 llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
-  } else {
-// cudaError_t cudaLaunch(char *);
-return CGM.CreateRuntimeFunction(
-llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
   }
+  // cudaError_t cudaLaunch(char *);
+  return CGM.CreateRuntimeFunction(
+  llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
 }
 
 llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
@@ -253,8 +252,8 @@
 }
 
 llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
-  auto CallbackFnTy = getCallbackFnTy();
-  auto RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
+  auto *CallbackFnTy = getCallbackFnTy();
+  auto *RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
   llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy,
   VoidPtrTy, CallbackFnTy->getPointerTo()};
   return llvm::FunctionType::get(VoidTy, Params, false);
@@ -397,7 +396,7 @@
   QualType QT = cudaLaunchKernelFD->getType();
   QualType CQT = QT.getCanonicalType();
   llvm::Type *Ty = CGM.getTypes().ConvertType(CQT);
-  llvm::FunctionType *FTy = dyn_cast(Ty);
+  llvm::FunctionType *FTy = cast(Ty);
 
   const CGFunctionInfo &FI =
   CGM.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);
@@ -590,7 +589,7 @@
   uint64_t VarSize =
   CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
   if (Info.Flags.isManaged()) {
-auto ManagedVar = new llvm::GlobalVariable(
+auto *ManagedVar = new llvm::GlobalVariable(
 CGM.getModule(), Var->getType(),
 /*isConstant=*/false, Var->getLinkage(),
 /*Init=*/Var->isDeclaration()
@@ -823,7 +822,7 @@
 GpuBinaryHandle,
 CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
 {
-  auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
+  auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
   llvm::Constant *Zero =
   llvm::Constant::getNullValue(HandleValue->getType());
   llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
@@ -842,7 +841,7 @@
   CtorBuilder.SetInsertPoint(ExitBlock);
   // Call __hip_register_globals(GpuBinaryHandle);
   if (RegisterGlobalsFunc) {
-auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
+auto *HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
 CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
   }
 }
@@ -958,7 +957,7 @@
 
   Address GpuBinaryAddr(GpuBinaryHandle, CharUnits::fromQuantity(
  GpuBinaryHandle->getAlignment()));
-  auto HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
+  auto *HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
   // There is only one HIP fat binary per linked module, however there are
   // multiple destructor functions. Make sure the fat binary is unregistered
   // only once.
@@ -1071,7 +1070,7 @@
 llvm::GlobalVariable *Var = Info.Var;
 if (Info.Flags.getKind() == DeviceVarFlags::Variable &&
 Info.Flags.isManaged()) {
-  auto ManagedVar = new llvm::GlobalVariable(
+  auto *ManagedVar = new llvm::GlobalVariable(
   CGM.getModule(), Var->getType(),
   /*isConstant=*/false, Var->getLinkage(),
   /*Init=*/Var->isDeclaration()


Index: clang/lib/CodeGen/CGCUDANV.cpp
===
--- clang/lib/CodeGen/CGCUDANV.cpp
+++ clang/lib/CodeGen/CGCUDANV.cpp
@@ -177,7 +177,7 @@
   llvm::Function *finalizeModule() override;
 };
 
-}
+} // end anonymous namespace
 
 std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
   if (CGM.getLangOpts().HIP)
@@ -237,11 +237,10 @@
 // hipError_t hipLaunchByPtr(char *);
 return CGM.CreateRuntimeFunction(
 llvm::FunctionType::get(IntTy, CharPtrTy, 

[PATCH] D112481: [Sema] fix nondeterminism in ASTContext::getDeducedTemplateSpecializationType

2021-10-25 Thread Bruno Cardoso Lopes via Phabricator via cfe-commits
bruno added a reviewer: bruno.
bruno added a comment.

Nice catch, thanks for working on this!




Comment at: clang/lib/AST/ASTContext.cpp:5640
+  DeducedTemplateSpecializationType::Profile(
+  ID, Template, DeducedType, IsDependent || Template.isDependent());
   if (DeducedTemplateSpecializationType *DTST =

Should this be done in the implementation (like done for the ctor)?
```
static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
  QualType Deduced, bool IsDependent) {
Template.Profile(ID);
ID.AddPointer(Deduced.getAsOpaquePtr());
ID.AddBoolean(IsDependent || Template.isDependent());
  }
```



Comment at: clang/lib/AST/ASTContext.cpp:5649
+  DTST->Profile(TempID);
+  assert(ID == TempID && "ID does not match");
   Types.push_back(DTST);

Seems like this assertion is failing in some of the tests above!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112481

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


[PATCH] D112284: [Clang][NFC] Clang CUDA codegen clean-up

2021-10-25 Thread Uday Bondhugula via Phabricator via cfe-commits
bondhugula added a comment.

@tra While on this, I also wanted to ask as to why clang cuda codegen is using 
an argument on the global ctor and the dtor it's generating. The argument is 
unused and I couldn't find any code comments to support it in either 
`CGCUDANV.cpp` or `CodeGenModule.cpp`.  I assume there is a reason because 
`CodeGenModule.cpp` is generating an explicit bitcast and has additional 
utilities to convert the function type to one with no arguments. Without the 
argument, one could just use `appendToGlobalCtors/Dtors` from `ModuleUtils`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112284

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


[PATCH] D110618: [HIPSPV][2/4] Add HIPSPV tool chain

2021-10-25 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki updated this revision to Diff 381854.
linjamaki added a comment.

Rebase and use SPIRV::constructTranslateCommand() to contruct
the LLVM-SPIR-V translation command.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110618

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/lib/Driver/ToolChains/HIPSPV.cpp
  clang/lib/Driver/ToolChains/HIPSPV.h

Index: clang/lib/Driver/ToolChains/HIPSPV.h
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/HIPSPV.h
@@ -0,0 +1,100 @@
+//===--- HIPSPV.h - HIP ToolChain Implementations ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_HIPSPV_H
+#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_HIPSPV_H
+
+#include "SPIRV.h"
+#include "clang/Driver/Tool.h"
+#include "clang/Driver/ToolChain.h"
+
+namespace clang {
+namespace driver {
+namespace tools {
+namespace HIPSPV {
+
+// Runs llvm-link/opt/llc/lld, which links multiple LLVM bitcode, together with
+// device library, then compiles it to SPIR-V in a shared object.
+class LLVM_LIBRARY_VISIBILITY Linker : public Tool {
+public:
+  Linker(const ToolChain &TC) : Tool("HIPSPV::Linker", "hipspv-link", TC) {}
+
+  bool hasIntegratedCPP() const override { return false; }
+
+  void ConstructJob(Compilation &C, const JobAction &JA,
+const InputInfo &Output, const InputInfoList &Inputs,
+const llvm::opt::ArgList &TCArgs,
+const char *LinkingOutput) const override;
+
+private:
+  void constructLinkAndEmitSpirvCommand(Compilation &C, const JobAction &JA,
+const InputInfoList &Inputs,
+const InputInfo &Output,
+const llvm::opt::ArgList &Args) const;
+};
+
+} // namespace HIPSPV
+} // namespace tools
+
+namespace toolchains {
+
+class LLVM_LIBRARY_VISIBILITY HIPSPVToolChain final : public ToolChain {
+public:
+  HIPSPVToolChain(const Driver &D, const llvm::Triple &Triple,
+  const ToolChain &HostTC, const llvm::opt::ArgList &Args);
+
+  const llvm::Triple *getAuxTriple() const override {
+return &HostTC.getTriple();
+  }
+
+  void
+  addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
+llvm::opt::ArgStringList &CC1Args,
+Action::OffloadKind DeviceOffloadKind) const override;
+  void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override;
+  CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override;
+  void
+  AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+llvm::opt::ArgStringList &CC1Args) const override;
+  void AddClangCXXStdlibIncludeArgs(
+  const llvm::opt::ArgList &Args,
+  llvm::opt::ArgStringList &CC1Args) const override;
+  void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+   llvm::opt::ArgStringList &CC1Args) const override;
+  void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+ llvm::opt::ArgStringList &CC1Args) const override;
+  llvm::SmallVector
+  getHIPDeviceLibs(const llvm::opt::ArgList &Args) const override;
+
+  SanitizerMask getSupportedSanitizers() const override;
+
+  VersionTuple
+  computeMSVCVersion(const Driver *D,
+ const llvm::opt::ArgList &Args) const override;
+
+  unsigned GetDefaultDwarfVersion() const override { return 5; }
+  bool IsIntegratedAssemblerDefault() const override { return true; }
+  bool IsMathErrnoDefault() const override { return false; }
+  bool useIntegratedAs() const override { return true; }
+  bool isCrossCompiling() const override { return true; }
+  bool isPICDefault() const override { return false; }
+  bool isPIEDefault() const override { return false; }
+  bool isPICDefaultForced() const override { return false; }
+  bool SupportsProfiling() const override { return false; }
+
+  const ToolChain &HostTC;
+
+protected:
+  Tool *buildLinker() const override;
+};
+
+} // end namespace toolchains
+} // end namespace driver
+} // end namespace clang
+
+#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_HIPSPV_H
Index: clang/lib/Driver/ToolChains/HIPSPV.cpp
===
--- /dev/null
+++ clang/lib/Driver/ToolChains/HIPSPV.cpp
@@ -0,0 +1,293 @@
+//===--- HIPSPV.cpp - HIPSPV ToolChain Implementation ---*- C++ -*-===/

[PATCH] D110622: [HIPSPV][3/4] Enable SPIR-V emission for HIP

2021-10-25 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki updated this revision to Diff 381855.
linjamaki added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110622

Files:
  clang/include/clang/Basic/Cuda.h
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Basic/Cuda.cpp
  clang/lib/Basic/Targets/NVPTX.cpp
  clang/lib/Basic/Targets/NVPTX.h
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/Inputs/hipspv-dev-lib/a/a.bc
  clang/test/Driver/Inputs/hipspv-dev-lib/b/b.bc
  clang/test/Driver/Inputs/hipspv-dev-lib/hipspv-spirv64.bc
  clang/test/Driver/Inputs/hipspv/bin/.hipVersion
  clang/test/Driver/Inputs/hipspv/lib/hip-device-lib/hipspv-spirv64.bc
  clang/test/Driver/Inputs/hipspv/lib/libLLVMHipSpvPasses.so
  clang/test/Driver/Inputs/pass-plugin.so
  clang/test/Driver/hipspv-device-libs.hip
  clang/test/Driver/hipspv-pass-plugin.hip
  clang/test/Driver/hipspv-toolchain-rdc.hip
  clang/test/Driver/hipspv-toolchain.hip
  clang/test/Driver/invalid-offload-options.cpp

Index: clang/test/Driver/invalid-offload-options.cpp
===
--- /dev/null
+++ clang/test/Driver/invalid-offload-options.cpp
@@ -0,0 +1,18 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload= \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=INVALID-TARGET %s
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload=foo   \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=INVALID-TARGET %s
+
+// INVALID-TARGET: error: Invalid or unsupported offload target: '{{.*}}'
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload=foo,bar \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN: 2>&1 | FileCheck --check-prefix=TOO-MANY-TARGETS %s
+
+// TOO-MANY-TARGETS: error: Only one offload target is supported in HIP.
Index: clang/test/Driver/hipspv-toolchain.hip
===
--- /dev/null
+++ clang/test/Driver/hipspv-toolchain.hip
@@ -0,0 +1,37 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -target x86_64-linux-gnu --offload=spirv64 \
+// RUN:   --hip-path=%S/Inputs/hipspv -nohipwrapperinc %s \
+// RUN: 2>&1 | FileCheck %s
+
+// CHECK: [[CLANG:".*clang.*"]] "-cc1" "-triple" "spirv64"
+// CHECK-SAME: "-aux-triple" "{{.*}}" "-emit-llvm-bc"
+// CHECK-SAME: "-fcuda-is-device"
+// CHECK-SAME: "-fcuda-allow-variadic-functions"
+// CHECK-SAME: "-mlink-builtin-bitcode" {{".*/hipspv/lib/hip-device-lib/hipspv-spirv64.bc"}}
+// CHECK-SAME: "-isystem" {{".*/hipspv/include"}}
+// CHECK-SAME: "-fhip-new-launch-api"
+// CHECK-SAME: "-o" [[DEV_BC:".*bc"]]
+// CHECK-SAME: "-x" "hip"
+
+// CHECK: {{".*llvm-link"}} [[DEV_BC]] "-o" [[LINK_BC:".*bc"]]
+
+// CHECK: {{".*opt"}} [[LINK_BC]] "-load-pass-plugin"
+// CHECK-SAME: {{".*/hipspv/lib/libLLVMHipSpvPasses.so"}}
+// CHECK-SAME: "-passes=hip-post-link-passes" "-o" [[LOWER_BC:".*bc"]]
+
+// CHECK: {{".*llvm-spirv"}} "--spirv-max-version=1.1" "--spirv-ext=+all"
+// CHECK-SAME: [[LOWER_BC]] "-o" "[[SPIRV_OUT:.*out]]"
+
+// CHECK: {{".*clang-offload-bundler"}} "-type=o" "-bundle-align=4096"
+// CHECK-SAME: "-targets=host-x86_64-unknown-linux,hip-spirv64generic"
+// CHECK-SAME: "-inputs={{.*}},[[SPIRV_OUT]]" "-outputs=[[BUNDLE:.*hipfb]]"
+
+// CHECK: [[CLANG]] "-cc1" "-triple" {{".*"}} "-aux-triple" "spirv64"
+// CHECK-SAME: "-emit-obj"
+// CHECK-SAME: "-fcuda-include-gpubinary" "[[BUNDLE]]"
+// CHECK-SAME: "-o" [[OBJ_HOST:".*o"]] "-x" "hip"
+
+// CHECK: {{".*ld.*"}} {{.*}}[[OBJ_HOST]]
Index: clang/test/Driver/hipspv-toolchain-rdc.hip
===
--- /dev/null
+++ clang/test/Driver/hipspv-toolchain-rdc.hip
@@ -0,0 +1,63 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -x hip -target x86_64-linux-gnu --offload=spirv64 \
+// RUN:   -fgpu-rdc --hip-path=%S/Inputs/hipspv -nohipwrapperinc \
+// RUN:   %S/Inputs/hip_multiple_inputs/a.cu \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck %s
+
+// Emit objects for host side path
+// CHECK: [[CLANG:".*clang.*"]] "-cc1" "-triple" "x86_64-unknown-linux-gnu"
+// CHECK-SAME: "-aux-triple" "spirv64"
+// CHECK-SAME: "-emit-obj"
+// CHECK-SAME: "-fgpu-rdc"
+// CHECK-SAME: {{.*}} "-o" [[A_OBJ_HOST:".*o"]] "-x" "hip"
+// CHECK-SAME: {{.*}} [[A_SRC:".*a.cu"]]
+
+// CHECK: [[CLANG]] "-cc1" "-triple" "x86_64-unknown-linux-gnu"
+// CHECK-SAME: "-aux-triple" "spirv64"
+// CHECK-SAME: "-emit-obj"
+// CHECK-SAME: "-fg

[PATCH] D110685: [HIPSPV][4/4] Add option to use llc to emit SPIR-V

2021-10-25 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki updated this revision to Diff 381857.
linjamaki added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110685

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/HIPSPV.cpp
  clang/test/Driver/hipspv-options.hip


Index: clang/test/Driver/hipspv-options.hip
===
--- /dev/null
+++ clang/test/Driver/hipspv-options.hip
@@ -0,0 +1,12 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -target x86_64-linux-gnu --offload=spirv64 \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN:   --spirv-use-llc=/foo/bar/llc 2>&1 | FileCheck %s
+
+// CHECK-NOT: llvm-spirv
+// CHECK: "/foo/bar/llc" "--mattr=+spirv1.1" "--filetype=obj" "{{.*}}.bc"
+// CHECK-SAME: "-o" "{{.*}}.out"
+
Index: clang/lib/Driver/ToolChains/HIPSPV.cpp
===
--- clang/lib/Driver/ToolChains/HIPSPV.cpp
+++ clang/lib/Driver/ToolChains/HIPSPV.cpp
@@ -97,6 +97,25 @@
 
   // Emit SPIR-V binary.
 
+  // Use llc. Meant for testing out LLVM SPIR-V backend. Eventually HIPSPV will
+  // switch to use in-tree SPIR-V backend for binary emission.
+  if (auto *A = Args.getLastArg(options::OPT_spirv_use_llc,
+options::OPT_spirv_use_llc_EQ)) {
+assert(A->getNumValues() <= 1);
+const char *LlcExe = nullptr;
+if (A->getNumValues() == 1 && !StringRef(A->getValue()).empty())
+  LlcExe = A->getValue();
+else
+  LlcExe = Args.MakeArgString(getToolChain().GetProgramPath("llc"));
+ArgStringList LlcArgs{"--mattr=+spirv1.1", "--filetype=obj", TempFile, 
"-o",
+  Output.getFilename()};
+C.addCommand(std::make_unique(JA, *this,
+   ResponseFileSupport::None(), LlcExe,
+   LlcArgs, Inputs, Output));
+return;
+  }
+
+  // Use SPIRV-LLVM Translator.
   llvm::opt::ArgStringList TrArgs;
   SPIRV::addTranslatorArgs(Args, TrArgs);
   if (!Args.hasArg(options::OPT_spirv_max_version_EQ))
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -1541,6 +1541,13 @@
 HelpText<"Specify comma separated list of allowed/disallowed SPIR-V "
 "extensions prefixed with '+' or '-'. '+' and '-' allows and disallows "
 "the extension, respectively. Special value 'all' affects all extensions">;
+def spirv_use_llc : Flag<["--"], "spirv-use-llc">, Flags<[HelpHidden]>,
+HelpText<"Use (in-tree) llc to emit SPIR-V. Use for development and "
+"testing only.">;
+def spirv_use_llc_EQ : Joined<["--"], "spirv-use-llc=">,
+MetaVarName<"">, Flags<[HelpHidden]>,
+HelpText<"Use speficied llc to emit SPIR-V. Use for development and "
+"testing only.">;
 
 // Begin sanitizer flags. These should all be core options exposed in all 
driver
 // modes.


Index: clang/test/Driver/hipspv-options.hip
===
--- /dev/null
+++ clang/test/Driver/hipspv-options.hip
@@ -0,0 +1,12 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// UNSUPPORTED: system-windows
+
+// RUN: %clang -### -target x86_64-linux-gnu --offload=spirv64 \
+// RUN:   --hip-path=%S/Inputs/hipspv -nogpuinc -nogpulib %s \
+// RUN:   --spirv-use-llc=/foo/bar/llc 2>&1 | FileCheck %s
+
+// CHECK-NOT: llvm-spirv
+// CHECK: "/foo/bar/llc" "--mattr=+spirv1.1" "--filetype=obj" "{{.*}}.bc"
+// CHECK-SAME: "-o" "{{.*}}.out"
+
Index: clang/lib/Driver/ToolChains/HIPSPV.cpp
===
--- clang/lib/Driver/ToolChains/HIPSPV.cpp
+++ clang/lib/Driver/ToolChains/HIPSPV.cpp
@@ -97,6 +97,25 @@
 
   // Emit SPIR-V binary.
 
+  // Use llc. Meant for testing out LLVM SPIR-V backend. Eventually HIPSPV will
+  // switch to use in-tree SPIR-V backend for binary emission.
+  if (auto *A = Args.getLastArg(options::OPT_spirv_use_llc,
+options::OPT_spirv_use_llc_EQ)) {
+assert(A->getNumValues() <= 1);
+const char *LlcExe = nullptr;
+if (A->getNumValues() == 1 && !StringRef(A->getValue()).empty())
+  LlcExe = A->getValue();
+else
+  LlcExe = Args.MakeArgString(getToolChain().GetProgramPath("llc"));
+ArgStringList LlcArgs{"--mattr=+spirv1.1", "--filetype=obj", TempFile, "-o",
+  Output.getFilename()};
+C.addCommand(std::make_unique(JA, *this,
+   ResponseFileSupport::None(), LlcExe,
+   LlcArgs, Inputs, Output));
+return;
+  }
+
+  // Use SPIRV-LLVM Translator.
   llvm::opt::ArgStringList TrArgs;
   SPI

[PATCH] D111047: CUDA/HIP: Allow __int128 on the host side

2021-10-25 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki updated this revision to Diff 381858.
linjamaki added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111047

Files:
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/SemaCUDA/allow-int128.cu
  clang/test/SemaCUDA/spirv-int128.cu


Index: clang/test/SemaCUDA/spirv-int128.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/spirv-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple spirv64 -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+
+__device__ __int128 d_unused;
+
+// expected-note@+1 {{'d_glb' defined here}}
+__device__ __int128 d_glb;
+
+__device__ __int128 bar() {
+  // expected-error@+1 {{'d_glb' requires 128 bit size '__int128' type 
support, but target 'spirv64' does not support it}}
+  return d_glb;
+}
Index: clang/test/SemaCUDA/allow-int128.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/allow-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+// RUN: %clang_cc1 -triple nvptx \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+// expected-no-diagnostics
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+__device__ __int128 d_unused;
+__device__ __int128 d_glb;
+__device__ __int128 bar() {
+  return d_glb;
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1496,7 +1496,7 @@
   }
   case DeclSpec::TST_int128:
 if (!S.Context.getTargetInfo().hasInt128Type() &&
-!S.getLangOpts().SYCLIsDevice &&
+!S.getLangOpts().SYCLIsDevice && !S.getLangOpts().CUDAIsDevice &&
 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
   S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
 << "__int128";
Index: clang/lib/Sema/Sema.cpp
===
--- clang/lib/Sema/Sema.cpp
+++ clang/lib/Sema/Sema.cpp
@@ -1855,7 +1855,8 @@
 }
 
 void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
-  if (!LangOpts.SYCLIsDevice && !(LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
+  if (!LangOpts.SYCLIsDevice && !(LangOpts.OpenMP && LangOpts.OpenMPIsDevice) 
&&
+  !LangOpts.CUDAIsDevice)
 return;
 
   if (isUnevaluatedContext() || Ty.isNull())


Index: clang/test/SemaCUDA/spirv-int128.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/spirv-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple spirv64 -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+
+__device__ __int128 d_unused;
+
+// expected-note@+1 {{'d_glb' defined here}}
+__device__ __int128 d_glb;
+
+__device__ __int128 bar() {
+  // expected-error@+1 {{'d_glb' requires 128 bit size '__int128' type support, but target 'spirv64' does not support it}}
+  return d_glb;
+}
Index: clang/test/SemaCUDA/allow-int128.cu
===
--- /dev/null
+++ clang/test/SemaCUDA/allow-int128.cu
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+// RUN: %clang_cc1 -triple nvptx \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fcuda-is-device -verify -fsyntax-only %s
+
+// expected-no-diagnostics
+#define __device__ __attribute__((device))
+
+__int128 h_glb;
+__device__ __int128 d_unused;
+__device__ __int128 d_glb;
+__device__ __int128 bar() {
+  return d_glb;
+}
Index: clang/lib/Sema/SemaType.cpp
===
--- clang/lib/Sema/SemaType.cpp
+++ clang/lib/Sema/SemaType.cpp
@@ -1496,7 +1496,7 @@
   }
   case DeclSpec::TST_int128:
 if (!S.Context.getTargetInfo().hasInt128Type() &&
-!S.getLangOpts().SYCLIsDevice &&
+!S.getLangOpts().SYCLIsDevice && !S.getLangOpts().CUDAIsDevice &&
 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
   S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
 << "__int128";
Index: clang/lib/Sema/Sema.cpp
===
--- clang/lib/Sema/Sema.cpp
+++ clang/lib/Sema/Sema.cpp
@@ -1855,7 +1855,8 @@
 }
 
 void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
-  if (!LangOpts.SYCLIsDevice && !(LangOpts.OpenMP && LangOpts.OpenMPIsDevic

[PATCH] D112409: [clang-tidy] Add check 'cert-err33-c'.

2021-10-25 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: carlosgalvezp, steakhal, martong, gamesh411, 
Szelethus, dkrupp, xazax.hun, whisperity.
balazske requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

The CERT rule ERR33-C can be modeled partially by the existing check
'bugprone-unused-return-value'. The existing check is reused with
a fixed set of checked functions.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112409

Files:
  clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
  clang-tools-extra/docs/clang-tidy/checks/bugprone-unused-return-value.rst
  clang-tools-extra/docs/clang-tidy/checks/cert-err33-c.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst

Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -114,6 +114,7 @@
`cert-dcl50-cpp `_,
`cert-dcl58-cpp `_,
`cert-env33-c `_,
+   `cert-err33-c `_,
`cert-err34-c `_,
`cert-err52-cpp `_,
`cert-err58-cpp `_,
Index: clang-tools-extra/docs/clang-tidy/checks/cert-err33-c.rst
===
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/cert-err33-c.rst
@@ -0,0 +1,18 @@
+.. title:: clang-tidy - cert-err33-c
+
+cert-err33-c
+
+
+Warns on unused function return values.
+This check corresponds to (a part of) CERT C Coding Standard rule `ERR33-C.
+Detect and handle standard library errors
+`_.
+The list of checked functions is the same as specified in the rule, with
+following exception:
+
+* These functions are safe if called with NULL argument. The check can not
+  differentiate this case from the others.::
+  
+mblen; mbrlen; mbrtowc; mbtowc; wctomb; wctomb_s
+
+If a custom list of checked functions is needed the check `bugprone-unused-return-value` can be used instead.
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone-unused-return-value.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/bugprone-unused-return-value.rst
+++ clang-tools-extra/docs/clang-tidy/checks/bugprone-unused-return-value.rst
@@ -45,3 +45,6 @@
- ``std::basic_string::empty()`` and ``std::vector::empty()``. Not using the
  return value often indicates that the programmer confused the function with
  ``clear()``.
+
+`cert-err33-c` is a version of this check that checks exactly the functions
+listed in CERT_rule ERR33-C.
\ No newline at end of file
Index: clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
===
--- clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
+++ clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp
@@ -16,6 +16,7 @@
 #include "../bugprone/SpuriouslyWakeUpFunctionsCheck.h"
 #include "../bugprone/SuspiciousMemoryComparisonCheck.h"
 #include "../bugprone/UnhandledSelfAssignmentCheck.h"
+#include "../bugprone/UnusedReturnValueCheck.h"
 #include "../concurrency/ThreadCanceltypeAsynchronousCheck.h"
 #include "../google/UnnamedNamespaceInHeaderCheck.h"
 #include "../misc/NewDeleteOverloadsCheck.h"
@@ -39,6 +40,195 @@
 #include "ThrownExceptionTypeCheck.h"
 #include "VariadicFunctionDefCheck.h"
 
+namespace {
+
+// The following functions are
+// deliberately excluded because they can
+// be called with NULL argument and in
+// this case the check is not applicable:
+// mblen, mbrlen, mbrtowc, mbtowc, wctomb,
+// wctomb_s
+// FIXME: The check can be improved to handle such cases.
+const llvm::StringRef CertErr33CCheckedFunctions = "::aligned_alloc;"
+   "::asctime_s;"
+   "::at_quick_exit;"
+   "::atexit;"
+   "::bsearch;"
+   "::bsearch_s;"
+   "::btowc;"
+   "::c16rtomb;"
+   "::c32rtomb;"
+   "::calloc;"
+   "::clock;"
+   "::cnd_broadcast;"
+   "::cnd_init;"
+   "::cnd_signal;"
+   "::cnd_timedwait;"
+   "::cnd_wait;"
+   "::ctime_s;"
+   "::fc

[PATCH] D112410: [SPIR-V] Add a tool chain for SPIR-V (incomplete)

2021-10-25 Thread Henry Linjamäki via Phabricator via cfe-commits
linjamaki created this revision.
Herald added a subscriber: ThomasRaoux.
linjamaki published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch adds a tool chain (TC) for SPIR-V for demonstration purposes. The TC 
is not complete but it is functional enough for producing SPIR-V assembly*1 and 
object code directly via clang from a language of choice, for example:

  clang -target spirv64 foo.cl -c -o foo.spv
  clang -target spirv64 baz.clcpp -c -o baz.spv
  clang -target spirv64 bar.c -S -o bar.spt

The SPIR-V code is generated by the SPIRV-LLVM translator tool or other 
compatible tool named as `llvm-spirv` that is sought in PATH.

List of things the TC is missing but not limited to:

- Linking and image generation.
- Complete and proper overrides from the base TC.
- Proper SPIR-V assembly output *1.
- Complete command line interface laid out in [1].

*1: The output from the SPIRV-LLVM Translator is its internal text presentation.

Changes in the Driver and base ToolChain and Tool:
Added a mechanism to work with the lack of SPIR-V backend in LLVM for SPIR-V 
TC. Until SPIR-V backend lands on LLVM, compilation phases/actions should be 
bound for SPIR-V in the meantime as following:

- compile -> tools::Clang
- backend -> tools::SPIRV::Translator
- assemble -> tools::SPIRV::Translator

However, Driver’s ToolSelector collapses compile-backend-assemble and 
compile-backend sequences to tools::Clang. To prevent this, added new 
{use,has}IntegratedBackend properties in ToolChain and Tool to which the 
ToolSelector reacts on, and which SPIR-V TC overrides.

We contributed this patch and the previous one in the stack (D112404 
 - [SPIR-V] Add translator tool) to address 
Anastasia’s feedback in (https://reviews.llvm.org/D110618#3062078) and other 
concerns around the SPIR-V tool chain adoption for languages other than HIP. 
However, we do not currently have the resources to allocate for continuing much 
further work in this patch unrelated to the needs of the HIP frontend. Thus, 
please consider this as a potentially useful starting point for further work 
needed to support other frontends, hopefully good enough minimal code to get 
this side started with and our patch set integrated to the master.

[1]: 
https://github.com/KhronosGroup/SPIRV-LLVM-Translator/wiki/SPIRV-Toolchain-for-Clang


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112410

Files:
  clang/include/clang/Driver/Tool.h
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Clang.h
  clang/lib/Driver/ToolChains/SPIRV.cpp
  clang/lib/Driver/ToolChains/SPIRV.h
  clang/test/Driver/spirv-toolchain.c

Index: clang/test/Driver/spirv-toolchain.c
===
--- /dev/null
+++ clang/test/Driver/spirv-toolchain.c
@@ -0,0 +1,57 @@
+// Check object emission.
+// RUN: %clang -### -no-canonical-prefixes -target spirv64 -x cl -c %s 2>&1 | FileCheck --check-prefix=SPV64 %s
+// RUN: %clang -### -no-canonical-prefixes -target spirv64 -x ir -c %s 2>&1 | FileCheck --check-prefix=SPV64 %s
+// RUN: %clang -### -no-canonical-prefixes -target spirv64 -x clcpp -c %s 2>&1 | FileCheck --check-prefix=SPV64 %s
+// RUN: %clang -### -no-canonical-prefixes -target spirv64 -x c -c %s 2>&1 | FileCheck --check-prefix=SPV64 %s
+
+// SPV64: clang{{.*}} "-cc1" "-triple" "spirv64"
+// SPV64-SAME: "-o" [[BC:".*bc"]]
+// SPV64: {{".*llvm-spirv.*"}} [[BC]] "-o" {{".*o"}}
+
+// RUN: %clang -### -no-canonical-prefixes -target spirv32 -x cl -c %s 2>&1 | FileCheck --check-prefix=SPV32 %s
+// RUN: %clang -### -no-canonical-prefixes -target spirv32 -x ir -c %s 2>&1 | FileCheck --check-prefix=SPV32 %s
+// RUN: %clang -### -no-canonical-prefixes -target spirv32 -x clcpp -c %s 2>&1 | FileCheck --check-prefix=SPV32 %s
+// RUN: %clang -### -no-canonical-prefixes -target spirv32 -x c -c %s 2>&1 | FileCheck --check-prefix=SPV32 %s
+
+// SPV32: clang{{.*}} "-cc1" "-triple" "spirv32"
+// SPV32-SAME: "-o" [[BC:".*bc"]]
+// SPV32: {{".*llvm-spirv.*"}} [[BC]] "-o" {{".*o"}}
+
+//-
+// Check Assembly emission.
+// RUN: %clang -### -no-canonical-prefixes -target spirv64 -x cl -S %s 2>&1 | FileCheck --check-prefix=SPT64 %s
+// RUN: %clang -### -no-canonical-prefixes -target spirv64 -x ir -S %s 2>&1 | FileCheck --check-prefix=SPT64 %s
+// RUN: %clang -### -no-canonical-prefixes -target spirv64 -x clcpp -c %s 2>&1 | FileCheck --check-prefix=SPV64 %s
+// RUN: %clang -### -no-canonical-prefixes -target spirv64 -x c -S %s 2>&1 | FileCheck --check-prefix=SPT64 %s
+
+// SPT64: clang{{.*}} "-cc1" "-triple" "spirv64"
+// SPT64-SAME: "-o" [[BC:".*bc"]]
+// SPT64: {{".*llvm-spirv.*"}} [[BC]] "-spirv-text" "-o" {{".*s"}}
+
+// RUN: %clang -### -no-canonical-prefixes

[PATCH] D108696: [Coroutines] [Frontend] Lookup in std namespace first

2021-10-25 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

In D108696#3083081 , @Quuxplusone 
wrote:

> In D108696#3082866 , @ChuanqiXu 
> wrote:
>
>> @Quuxplusone gentle ping~
>
> I think this PR is mostly above my pay grade. :)

Sorry for disturbing. I would remind it.

> IIUC, there is a chicken-and-egg problem between D108696 
>  and D109433 
> ? If I understand the situation correctly 
> (which maybe I don't), I think you should add D108696 
>  as a "Parent Revision" of D109433 
> , and tag both of them with //both// 
> "libc++" //and// "clang" project tags, and then poke buildkite to re-run the 
> CI on both of them. I would hope that D109433 
> 's test results would still be green. And 
> then you'd land both D108696  and D109433 
>  in very quick succession. //But//, I'm not 
> going to be an approver on D108696  because 
> it's over my head. Originally you pinged @rjmccall @lxfind @junparser ; are 
> they still happy with D108696  and the 
> general direction we're taking on coroutines stuff in 14.x and 15.x?
>
> (AIUI, the intent is for libc++ 14.x to support both C++11 
> `` and C++20 ``, and then in libc++ 15.x 
> to support //only// C++20 ``.)

Yeah, this is a Parent Revision of D109433 . 
But I didn't tag this with 'libc++' since it didn't touch libcxx part. Do you 
mean it is necessary to tag it as 'libc++' even if it didn't touch libcxx?
(I would try to make D109433  green, of 
course)

This revision is approved originally but reverted due to the unwanted warning. 
I would ask them if they are happy with the current direction.

After all, thanks for looking into this : )




Comment at: clang/test/SemaCXX/coroutines-exp-namespace.cpp:2
+// This file is the same with coroutines.cpp except the coroutine components 
are defined in std::experimental namespace.
+// This intention of this test is to make sure the legacy imeplementation in 
std::experimental namespace could work.
+// TODO: Remove this test once we didn't support

Quuxplusone wrote:
> ldionne wrote:
> > 
> ...and not just "could work," but "works." :)
> ```
> // This file is the same as coroutines.cpp, except the components are defined 
> in namespace std::experimental.
> // The intent of this test is to make sure the std::experimental 
> implementation still works.
> // TODO: Remove this test once we drop support for .
> ```
> 
> Also, it occurs to me that you should probably be testing both `` 
> and `` in all the other tests, as well; e.g. 
> `coroutine_handle-address-return-type.cpp` should have a matching 
> `coroutine_handle-address-return-type-exp-namespace.cpp` and so on. 
> Otherwise, aren't you removing a lot of regression tests for 
> ``, despite that we still claim to support 
> `` in Clang 14.x?
> 
> In many cases, it should be possible to do something like
> ```
> // RUN: %clang_cc1 -std=c++14 -fcoroutines-ts -fsyntax-only -verify %s 
> -DINCLUDE_EXPERIMENTAL=1
> // RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s 
> -DINCLUDE_EXPERIMENTAL=0
> 
> #if INCLUDE_EXPERIMENTAL
> #include 
> namespace coro = std::experimental;
> #else
> #include 
> namespace coro = std;
> #endif
> 
> [...]
> ```
Thanks for reporting this. I would try to test both by duplicating the tests. 
The method to use macro may not be good due to it needs to mangled.


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

https://reviews.llvm.org/D108696

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


[PATCH] D108696: [Coroutines] [Frontend] Lookup in std namespace first

2021-10-25 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/test/SemaCXX/coroutines-exp-namespace.cpp:2
+// This file is the same with coroutines.cpp except the coroutine components 
are defined in std::experimental namespace.
+// This intention of this test is to make sure the legacy imeplementation in 
std::experimental namespace could work.
+// TODO: Remove this test once we didn't support

ChuanqiXu wrote:
> Quuxplusone wrote:
> > ldionne wrote:
> > > 
> > ...and not just "could work," but "works." :)
> > ```
> > // This file is the same as coroutines.cpp, except the components are 
> > defined in namespace std::experimental.
> > // The intent of this test is to make sure the std::experimental 
> > implementation still works.
> > // TODO: Remove this test once we drop support for .
> > ```
> > 
> > Also, it occurs to me that you should probably be testing both 
> > `` and `` in all the other tests, as 
> > well; e.g. `coroutine_handle-address-return-type.cpp` should have a 
> > matching `coroutine_handle-address-return-type-exp-namespace.cpp` and so 
> > on. Otherwise, aren't you removing a lot of regression tests for 
> > ``, despite that we still claim to support 
> > `` in Clang 14.x?
> > 
> > In many cases, it should be possible to do something like
> > ```
> > // RUN: %clang_cc1 -std=c++14 -fcoroutines-ts -fsyntax-only -verify %s 
> > -DINCLUDE_EXPERIMENTAL=1
> > // RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s 
> > -DINCLUDE_EXPERIMENTAL=0
> > 
> > #if INCLUDE_EXPERIMENTAL
> > #include 
> > namespace coro = std::experimental;
> > #else
> > #include 
> > namespace coro = std;
> > #endif
> > 
> > [...]
> > ```
> Thanks for reporting this. I would try to test both by duplicating the tests. 
> The method to use macro may not be good due to it needs to mangled.
(Ignore this) I just noticed that we could use the macro based method for Sema 
tests.


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

https://reviews.llvm.org/D108696

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


[PATCH] D112359: [NFC][RISCV] Unify depedency check and extension implication parsing logics

2021-10-25 Thread Yueh-Ting Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 381866.
eopXD added a comment.

Update clang-format.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112359

Files:
  clang/test/CodeGen/RISCV/riscv-metadata.c
  clang/test/CodeGen/RISCV/riscv32-ilp32-ilp32f-ilp32d-abi.c
  clang/test/CodeGen/RISCV/riscv32-ilp32d-abi.c
  clang/test/CodeGen/RISCV/riscv32-ilp32f-ilp32d-abi.c
  clang/test/CodeGen/RISCV/riscv64-lp64-lp64f-lp64d-abi.c
  clang/test/CodeGen/RISCV/riscv64-lp64d-abi.c
  clang/test/CodeGen/RISCV/riscv64-lp64f-lp64d-abi.c
  clang/test/CodeGen/riscv32-ilp32d-abi.cpp
  llvm/include/llvm/Support/RISCVISAInfo.h
  llvm/lib/Support/RISCVISAInfo.cpp

Index: llvm/lib/Support/RISCVISAInfo.cpp
===
--- llvm/lib/Support/RISCVISAInfo.cpp
+++ llvm/lib/Support/RISCVISAInfo.cpp
@@ -411,7 +411,6 @@
   assert(XLen == 32 || XLen == 64);
   std::unique_ptr ISAInfo(new RISCVISAInfo(XLen));
 
-  bool HasE = false;
   for (auto &Feature : Features) {
 StringRef ExtName = Feature;
 bool Experimental = false;
@@ -430,29 +429,19 @@
 if (ExtensionInfoIterator == ExtensionInfos.end())
   continue;
 
-if (Add) {
-  if (ExtName == "e") {
-if (XLen != 32)
-  return createStringError(
-  errc::invalid_argument,
-  "standard user-level extension 'e' requires 'rv32'");
-HasE = true;
-  }
-
+if (Add)
   ISAInfo->addExtension(ExtName, ExtensionInfoIterator->Version.Major,
 ExtensionInfoIterator->Version.Minor);
-} else
-  ISAInfo->Exts.erase(ExtName.str());
-  }
-  if (!HasE) {
-if (auto Version = findDefaultVersion("i"))
-  ISAInfo->addExtension("i", Version->Major, Version->Minor);
 else
-  llvm_unreachable("Default extension version for 'i' not found?");
+  ISAInfo->Exts.erase(ExtName.str());
   }
 
+  ISAInfo->updateImplication();
   ISAInfo->updateFLen();
 
+  if (Error Result = ISAInfo->checkDependency())
+return std::move(Result);
+
   return std::move(ISAInfo);
 }
 
@@ -478,7 +467,6 @@
   // The canonical order specified in ISA manual.
   // Ref: Table 22.1 in RISC-V User-Level ISA V2.2
   StringRef StdExts = AllStdExts;
-  bool HasF = false, HasD = false;
   char Baseline = Arch[4];
 
   // First letter should be 'e', 'i' or 'g'.
@@ -499,8 +487,6 @@
   case 'g':
 // g = imafd
 StdExts = StdExts.drop_front(4);
-HasF = true;
-HasD = true;
 break;
   }
 
@@ -581,34 +567,14 @@
 
 // The order is OK, then push it into features.
 // TODO: Use version number when setting target features
-switch (C) {
-default:
-  // Currently LLVM supports only "mafdcbv".
+// Currently LLVM supports only "mafdcbv".
+StringRef SupportedStandardExtension = "mafdcbv";
+if (SupportedStandardExtension.find(C) == StringRef::npos)
   return createStringError(errc::invalid_argument,
"unsupported standard user-level extension '%c'",
C);
-case 'm':
-  ISAInfo->addExtension("m", Major, Minor);
-  break;
-case 'a':
-  ISAInfo->addExtension("a", Major, Minor);
-  break;
-case 'f':
-  ISAInfo->addExtension("f", Major, Minor);
-  HasF = true;
-  break;
-case 'd':
-  ISAInfo->addExtension("d", Major, Minor);
-  HasD = true;
-  break;
-case 'c':
-  ISAInfo->addExtension("c", Major, Minor);
-  break;
-case 'v':
-  ISAInfo->addExtension("v", Major, Minor);
-  ISAInfo->addExtension("zvlsseg", Major, Minor);
-  break;
-}
+ISAInfo->addExtension(std::string(1, C), Major, Minor);
+
 // Consume full extension name and version, including any optional '_'
 // between this extension and the next
 ++I;
@@ -616,21 +582,6 @@
 if (*I == '_')
   ++I;
   }
-  // Dependency check.
-  // It's illegal to specify the 'd' (double-precision floating point)
-  // extension without also specifying the 'f' (single precision
-  // floating-point) extension.
-  // TODO: This has been removed in later specs, which specify that D implies F
-  if (HasD && !HasF)
-return createStringError(errc::invalid_argument,
- "d requires f extension to also be specified");
-
-  // Additional dependency checks.
-  // TODO: The 'q' extension requires rv64.
-  // TODO: It is illegal to specify 'e' extensions with 'f' and 'd'.
-
-  if (OtherExts.empty())
-return std::move(ISAInfo);
 
   // Handle other types of extensions other than the standard
   // general purpose and standard user-level extensions.
@@ -651,52 +602,53 @@
   std::array Prefix{"z", "x", "s", "sx"};
   auto I = Prefix.begin();
   auto E = Prefix.end();
+  if (Split.size() > 1 || Split[0] != "") {
+for (StringRef Ext : Split) {
+  if (Ext.empty())
+return createStringError(errc::invalid_argument,

[PATCH] D112401: [Clang] Mutate printf bulitin names under IEEE128 on PPC64

2021-10-25 Thread Qiu Chaofan via Phabricator via cfe-commits
qiucf updated this revision to Diff 381868.
qiucf added a reviewer: rjmccall.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112401

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/ppc64-f128-builtins.c


Index: clang/test/CodeGen/ppc64-f128-builtins.c
===
--- /dev/null
+++ clang/test/CodeGen/ppc64-f128-builtins.c
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -emit-llvm -o - %s \
+// RUN:   -mabi=ieeelongdouble | FileCheck --check-prefix=IEEE128 %s
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -emit-llvm -o - %s \
+// RUN:   | FileCheck --check-prefix=PPC128 %s
+
+long double x;
+char buf[20];
+
+// IEEE128-LABEL: define dso_local void @test_printf
+// IEEE128: call signext i32 (i8*, ...) @__printfieee128
+// PPC128-LABEL: define dso_local void @test_printf
+// PPC128: call signext i32 (i8*, ...) @printf
+void test_printf() {
+  __builtin_printf("%.Lf", x);
+}
+
+// IEEE128-LABEL: define dso_local void @test_vsnprintf
+// IEEE128: call signext i32 @__vsnprintfieee128
+// PPC128-LABEL: define dso_local void @test_vsnprintf
+// PPC128: call signext i32 @vsnprintf
+void test_vsnprintf(int n, ...) {
+  __builtin_va_list va;
+  __builtin_va_start(va, n);
+  __builtin_vsnprintf(buf, 20, "%.Lf", va);
+  __builtin_va_end(va);
+}
+
+// IEEE128-LABEL: define dso_local void @test_vsprintf
+// IEEE128: call signext i32 @__vsprintfieee128
+// PPC128-LABEL: define dso_local void @test_vsprintf
+// PPC128: call signext i32 @vsprintf
+void test_vsprintf(int n, ...) {
+  __builtin_va_list va;
+  __builtin_va_start(va, n);
+  __builtin_vsprintf(buf, "%.Lf", va);
+  __builtin_va_end(va);
+}
+
+// IEEE128-LABEL: define dso_local void @test_sprintf
+// IEEE128: call signext i32 (i8*, i8*, ...) @__sprintfieee128
+// PPC128-LABEL: define dso_local void @test_sprintf
+// PPC128: call signext i32 (i8*, i8*, ...) @sprintf
+void test_sprintf() {
+  __builtin_sprintf(buf, "%.Lf", x);
+}
+
+// IEEE128-LABEL: define dso_local void @test_snprintf
+// IEEE128: call signext i32 (i8*, i64, i8*, ...) @__snprintfieee128
+// PPC128-LABEL: define dso_local void @test_snprintf
+// PPC128: call signext i32 (i8*, i64, i8*, ...) @snprintf
+void test_snprintf() {
+  __builtin_snprintf(buf, 20, "%.Lf", x);
+}
Index: clang/lib/CodeGen/CGBuiltin.cpp
===
--- clang/lib/CodeGen/CGBuiltin.cpp
+++ clang/lib/CodeGen/CGBuiltin.cpp
@@ -96,13 +96,30 @@
   StringRef Name;
   GlobalDecl D(FD);
 
+  static SmallDenseMap F128Builtins{
+  {Builtin::BI__builtin_printf, "__printfieee128"},
+  {Builtin::BI__builtin_vsnprintf, "__vsnprintfieee128"},
+  {Builtin::BI__builtin_vsprintf, "__vsprintfieee128"},
+  {Builtin::BI__builtin_sprintf, "__sprintfieee128"},
+  {Builtin::BI__builtin_snprintf, "__snprintfieee128"},
+  {Builtin::BI__builtin_fprintf, "__fprintfieee128"},
+  };
+
   // If the builtin has been declared explicitly with an assembler label,
   // use the mangled name. This differs from the plain label on platforms
   // that prefix labels.
   if (FD->hasAttr())
 Name = getMangledName(D);
-  else
-Name = Context.BuiltinInfo.getName(BuiltinID) + 10;
+  else {
+// TODO: This mutation should also be applied to other targets other than
+// PPC, after backend supports IEEE 128-bit style libcalls.
+if (getTriple().isPPC64() &&
+&getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad() &&
+F128Builtins.find(BuiltinID) != F128Builtins.end())
+  Name = F128Builtins[BuiltinID];
+else
+  Name = Context.BuiltinInfo.getName(BuiltinID) + 10;
+  }
 
   llvm::FunctionType *Ty =
 cast(getTypes().ConvertType(FD->getType()));


Index: clang/test/CodeGen/ppc64-f128-builtins.c
===
--- /dev/null
+++ clang/test/CodeGen/ppc64-f128-builtins.c
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -emit-llvm -o - %s \
+// RUN:   -mabi=ieeelongdouble | FileCheck --check-prefix=IEEE128 %s
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -emit-llvm -o - %s \
+// RUN:   | FileCheck --check-prefix=PPC128 %s
+
+long double x;
+char buf[20];
+
+// IEEE128-LABEL: define dso_local void @test_printf
+// IEEE128: call signext i32 (i8*, ...) @__printfieee128
+// PPC128-LABEL: define dso_local void @test_printf
+// PPC128: call signext i32 (i8*, ...) @printf
+void test_printf() {
+  __builtin_printf("%.Lf", x);
+}
+
+// IEEE128-LABEL: define dso_local void @test_vsnprintf
+// IEEE128: call signext i32 @__vsnprintfieee128
+// PPC128-LABEL: define dso_local void @test_vsnprintf
+// PPC128: call signext i32 @vsnprintf
+void test_vsnprintf(int n, ...) {
+  __builtin_va_list va;
+  __builtin_va_start(va, n);
+  __builtin_vsnprintf(buf, 20, "%.Lf", va);
+  __builtin_va_end(va);
+}
+
+// IEEE128-LABE

[PATCH] D106102: [analyzer][solver] Introduce reasoning for not equal to operator

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

Thanks for the report @bjope and thanks for the action @manas and @steakhal !
Sorry guys, I should have run our CI safety net jobs for this patch. I tend to 
do that with all my solver related patches, I really don't know why I thought 
this was different.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D106102

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


[PATCH] D112413: [X86] Add -mskip-rax-setup support to align with GCC

2021-10-25 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei created this revision.
pengfei added reviewers: MaskRay, hjl.tools, erichkeane, LuoYuanke, 
craig.topper.
Herald added subscribers: dang, hiraditya.
pengfei requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

This fixes pr23258.
AMD64 ABI mandates caller to specify the number of used SSE registers
when passing variable arguments.
GCC also provides option -mskip-rax-setup to skip the setup of rax when
SSE is disabled. This helps to reduce the code size.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112413

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/x86_features.c
  llvm/lib/Target/X86/X86ISelLowering.cpp
  llvm/lib/Target/X86/pr23258.ll


Index: llvm/lib/Target/X86/pr23258.ll
===
--- /dev/null
+++ llvm/lib/Target/X86/pr23258.ll
@@ -0,0 +1,23 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu -mattr=+sse | FileCheck %s 
--check-prefix=HAS-RAX
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu -x86-skip-rax-setup | 
FileCheck %s --check-prefix=HAS-RAX
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu -mattr=+sse 
-x86-skip-rax-setup | FileCheck %s --check-prefix=HAS-RAX
+; RUN: llc < %s -mtriple=x86_64-unknown-linux-gnu -mattr=-sse 
-x86-skip-rax-setup | FileCheck %s --check-prefix=NO-RAX
+
+define dso_local void @foo() nounwind {
+; HAS-RAX-LABEL: foo:
+; HAS-RAX:   # %bb.0: # %entry
+; HAS-RAX-NEXT:movl $1, %edi
+; HAS-RAX-NEXT:xorl %eax, %eax
+; HAS-RAX-NEXT:jmp bar # TAILCALL
+;
+; NO-RAX-LABEL: foo:
+; NO-RAX:   # %bb.0: # %entry
+; NO-RAX-NEXT:movl $1, %edi
+; NO-RAX-NEXT:jmp bar # TAILCALL
+entry:
+  tail call void (i32, ...) @bar(i32 1)
+  ret void
+}
+
+declare dso_local void @bar(i32, ...)
Index: llvm/lib/Target/X86/X86ISelLowering.cpp
===
--- llvm/lib/Target/X86/X86ISelLowering.cpp
+++ llvm/lib/Target/X86/X86ISelLowering.cpp
@@ -93,6 +93,12 @@
  "stores respectively."),
 cl::Hidden);
 
+static cl::opt SkipRaxSetup(
+"x86-skip-rax-setup", cl::init(false),
+cl::desc("Skips setting up the RAX register when SSE is disabled and there 
"
+ "are no variable arguments passed in vector registers."),
+cl::Hidden);
+
 /// Call this when the user attempts to do something unsupported, like
 /// returning a double without SSE2 enabled on x86_64. This is not fatal, 
unlike
 /// report_fatal_error, so calling code should attempt to recover without
@@ -4414,7 +4420,8 @@
 }
   }
 
-  if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
+  if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail &&
+  (Subtarget.hasSSE1() || !SkipRaxSetup)) {
 // From AMD64 ABI document:
 // For calls that may call functions that use varargs or stdargs
 // (prototype-less calls or calls to functions containing ellipsis (...) in
Index: clang/test/Driver/x86_features.c
===
--- clang/test/Driver/x86_features.c
+++ clang/test/Driver/x86_features.c
@@ -5,3 +5,6 @@
 // Test that we don't produce an error with -mieee-fp.
 // RUN: %clang -### %s -mieee-fp -S 2>&1 | FileCheck --check-prefix=IEEE %s
 // IEEE-NOT: error: unknown argument
+
+// RUN: %clang -### %s -mskip-rax-setup -S 2>&1 | FileCheck --check-prefix=SRS 
%s
+// SRS: "-mllvm" "-x86-skip-rax-setup"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -2194,6 +2194,11 @@
 CmdArgs.push_back("-x86-asm-syntax=intel");
   }
 
+  if (Args.hasArg(options::OPT_mskip_rax_setup)) {
+CmdArgs.push_back("-mllvm");
+CmdArgs.push_back("-x86-skip-rax-setup");
+  }
+
   // Set flags to support MCU ABI.
   if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
 CmdArgs.push_back("-mfloat-abi");
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -3189,6 +3189,8 @@
 HelpText<"Disable function outlining (AArch64 only)">;
 def mno_ms_bitfields : Flag<["-"], "mno-ms-bitfields">, Group,
   HelpText<"Do not set the default structure layout to be compatible with the 
Microsoft compiler standard">;
+def mskip_rax_setup : Flag<["-"], "mskip-rax-setup">, Group, 
Flags<[NoXarchOption]>,
+  HelpText<"Skip setting up RAX register when passing variable arguments (x86 
only)">;
 def mstackrealign : Flag<["-"], "mstackrealign">, Group, 
Flags<[CC1Option]>,
   HelpText<"Force realign the stack at entry to every function">,
   MarshallingInfoFlag>;


Index: llvm/lib/Target/X86/

[PATCH] D112359: [RISCV] Unify depedency check and extension implication parsing logics

2021-10-25 Thread Yueh-Ting Chen via Phabricator via cfe-commits
eopXD updated this revision to Diff 381873.
eopXD edited the summary of this revision.
eopXD added a comment.

Since parsing logic is unified, code of RISCVAsmParser can be reduced.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112359

Files:
  clang/test/CodeGen/RISCV/riscv-metadata.c
  clang/test/CodeGen/RISCV/riscv32-ilp32-ilp32f-ilp32d-abi.c
  clang/test/CodeGen/RISCV/riscv32-ilp32d-abi.c
  clang/test/CodeGen/RISCV/riscv32-ilp32f-ilp32d-abi.c
  clang/test/CodeGen/RISCV/riscv64-lp64-lp64f-lp64d-abi.c
  clang/test/CodeGen/RISCV/riscv64-lp64d-abi.c
  clang/test/CodeGen/RISCV/riscv64-lp64f-lp64d-abi.c
  clang/test/CodeGen/riscv32-ilp32d-abi.cpp
  llvm/include/llvm/Support/RISCVISAInfo.h
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp

Index: llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
===
--- llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
+++ llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
@@ -2062,7 +2062,11 @@
 "unexpected token in '.attribute' directive"))
 return true;
 
-  if (Tag == RISCVAttrs::ARCH) {
+  if (IsIntegerValue)
+ getTargetStreamer().emitAttribute(Tag, IntegerValue);
+  else if (Tag != RISCVAttrs::ARCH)
+getTargetStreamer().emitTextAttribute(Tag, StringValue); 
+  else {
 StringRef Arch = StringValue;
 for (auto Feature : RISCVFeatureKV)
   if (llvm::RISCVISAInfo::isSupportedExtensionFeature(Feature.Key))
@@ -2070,7 +2074,7 @@
 
 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
 StringValue, /*EnableExperimentalExtension=*/true,
-/*ExperimentalExtensionVersionCheck=*/false);
+/*ExperimentalExtensionVersionCheck=*/true);
 if (!ParseResult) {
   std::string Buffer;
   raw_string_ostream OutputErrMsg(Buffer);
@@ -2093,35 +2097,9 @@
   setFeatureBits(RISCV::Feature64Bit, "64bit");
 else
   return Error(ValueExprLoc, "bad arch string " + Arch);
-  }
 
-  if (IsIntegerValue)
-getTargetStreamer().emitAttribute(Tag, IntegerValue);
-  else {
-if (Tag != RISCVAttrs::ARCH) {
-  getTargetStreamer().emitTextAttribute(Tag, StringValue);
-} else {
-  std::vector FeatureVector;
-  RISCVFeatures::toFeatureVector(FeatureVector, getSTI().getFeatureBits());
-
-  // Parse that by RISCVISAInfo->
-  unsigned XLen = getFeatureBits(RISCV::Feature64Bit) ? 64 : 32;
-  auto ParseResult = llvm::RISCVISAInfo::parseFeatures(XLen, FeatureVector);
-  if (!ParseResult) {
-std::string Buffer;
-raw_string_ostream OutputErrMsg(Buffer);
-handleAllErrors(ParseResult.takeError(),
-[&](llvm::StringError &ErrMsg) {
-  OutputErrMsg << ErrMsg.getMessage();
-});
-
-return Error(ValueExprLoc, OutputErrMsg.str());
-  }
-  auto &ISAInfo = *ParseResult;
-
-  // Then emit the arch string.
-  getTargetStreamer().emitTextAttribute(Tag, ISAInfo->toString());
-}
+// Then emit the arch string.
+getTargetStreamer().emitTextAttribute(Tag, ISAInfo->toString());
   }
 
   return false;
Index: llvm/lib/Support/RISCVISAInfo.cpp
===
--- llvm/lib/Support/RISCVISAInfo.cpp
+++ llvm/lib/Support/RISCVISAInfo.cpp
@@ -360,6 +360,11 @@
 
 if (ExperimentalExtensionVersionCheck &&
 (MajorStr.empty() && MinorStr.empty())) {
+  if (auto DefaultVersion = findDefaultVersion(Ext)) {
+Major = DefaultVersion->Major;
+Minor = DefaultVersion->Minor;
+return Error::success();
+  }
   std::string Error =
   "experimental extension requires explicit version number `" +
   Ext.str() + "`";
@@ -411,7 +416,6 @@
   assert(XLen == 32 || XLen == 64);
   std::unique_ptr ISAInfo(new RISCVISAInfo(XLen));
 
-  bool HasE = false;
   for (auto &Feature : Features) {
 StringRef ExtName = Feature;
 bool Experimental = false;
@@ -430,29 +434,19 @@
 if (ExtensionInfoIterator == ExtensionInfos.end())
   continue;
 
-if (Add) {
-  if (ExtName == "e") {
-if (XLen != 32)
-  return createStringError(
-  errc::invalid_argument,
-  "standard user-level extension 'e' requires 'rv32'");
-HasE = true;
-  }
-
+if (Add)
   ISAInfo->addExtension(ExtName, ExtensionInfoIterator->Version.Major,
 ExtensionInfoIterator->Version.Minor);
-} else
-  ISAInfo->Exts.erase(ExtName.str());
-  }
-  if (!HasE) {
-if (auto Version = findDefaultVersion("i"))
-  ISAInfo->addExtension("i", Version->Major, Version->Minor);
 else
-  llvm_unreachable("Default extension version for 'i' not found?");
+  ISAInfo->Exts.erase(ExtName.str());
   }
 
+  ISAInfo->updateImplication();
   I

[PATCH] D112406: [Driver][AArch64]Add driver support for neoverse-512tvb target

2021-10-25 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

This is a bit of a shame. I was hoping we wouldn't need the same hacks as GCC. 
The llvm cost modelling can work quite differently at times to GCC and I didn't 
think we were close enough to optimal code to need to worry about these kinds 
of differences. I guess having the option is useful for consistency.




Comment at: llvm/lib/Support/Host.cpp:216
 .Case("0xd49", "neoverse-n2")
+.Case("0xd4a", "neoverse-512tvb")
 .Default("generic");

This doesn't sound right - for a fake cpu to work with -mcpu=native.



Comment at: llvm/lib/Target/AArch64/AArch64Subtarget.cpp:158
+  case Neoverse512TVB:
+MaxInterleaveFactor = 4;
+break;

Should this have Loop Alignment too?

Is the interleave factor higher due to the 512bit vector bandwidth?



Comment at: llvm/lib/Target/ARM/ARM.td:1412
 
+def : ProcNoItin<"neoverse-512tvb", [ARMv84a,
+ FeatureHWDivThumb,

Are we sure gcc has a -mcpu=neoverse-512tvb option for Arm? Or is it AArch64 
only?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112406

___
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-25 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.

Sorry for blocking the review of this one for so long.




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:
> > > 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);
> > > ```
> > Yes, I see what you mean. I'm going to tough the part of C++ in the near 
> > future.
> > Yes, I see what you mean. I'm going to tough the part of C++ in the near 
> > future.
> *Yes, I see what you mean. I'm **not** going to tough the part of C++ in the 
> near future.
Okay, I see now.


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

https://reviews.llvm.org/D106681

___
cfe-commits mailing

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

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

Minor nits. Aside from that just land it.
Thanks for the fix.




Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1654
+  // 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)

If the return value of `getAnyInitializer()` is null, then the value of `VD` 
will be actually preserved.


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] D112415: [Driver] ignore -maccumulate_outgoing_args option

2021-10-25 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei created this revision.
pengfei added reviewers: efriedma, erichkeane, LuoYuanke.
Herald added a subscriber: dang.
pengfei requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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

Signed-off-by: Austin English 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112415

Files:
  clang/include/clang/Driver/Options.td
  clang/test/Driver/clang_f_opts.c


Index: clang/test/Driver/clang_f_opts.c
===
--- clang/test/Driver/clang_f_opts.c
+++ clang/test/Driver/clang_f_opts.c
@@ -304,6 +304,7 @@
 // RUN: -fno-implement-inlines -fimplement-inlines\
 // RUN: -fstack-check \
 // RUN: -fforce-addr  \
+// RUN: -maccumulate-outgoing-args\
 // RUN: -malign-functions=100 \
 // RUN: -malign-loops=100 \
 // RUN: -malign-jumps=100 \
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -3083,6 +3083,7 @@
 def miamcu : Flag<["-"], "miamcu">, Group, Flags<[NoXarchOption, 
CoreOption]>,
   HelpText<"Use Intel MCU ABI">;
 def mno_iamcu : Flag<["-"], "mno-iamcu">, Group, 
Flags<[NoXarchOption, CoreOption]>;
+def maccumulate_outgoing_args : Flag<["-"], "maccumulate-outgoing-args">, 
Group;
 def malign_functions_EQ : Joined<["-"], "malign-functions=">, 
Group;
 def malign_loops_EQ : Joined<["-"], "malign-loops=">, 
Group;
 def malign_jumps_EQ : Joined<["-"], "malign-jumps=">, 
Group;


Index: clang/test/Driver/clang_f_opts.c
===
--- clang/test/Driver/clang_f_opts.c
+++ clang/test/Driver/clang_f_opts.c
@@ -304,6 +304,7 @@
 // RUN: -fno-implement-inlines -fimplement-inlines\
 // RUN: -fstack-check \
 // RUN: -fforce-addr  \
+// RUN: -maccumulate-outgoing-args\
 // RUN: -malign-functions=100 \
 // RUN: -malign-loops=100 \
 // RUN: -malign-jumps=100 \
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -3083,6 +3083,7 @@
 def miamcu : Flag<["-"], "miamcu">, Group, Flags<[NoXarchOption, CoreOption]>,
   HelpText<"Use Intel MCU ABI">;
 def mno_iamcu : Flag<["-"], "mno-iamcu">, Group, Flags<[NoXarchOption, CoreOption]>;
+def maccumulate_outgoing_args : Flag<["-"], "maccumulate-outgoing-args">, Group;
 def malign_functions_EQ : Joined<["-"], "malign-functions=">, Group;
 def malign_loops_EQ : Joined<["-"], "malign-loops=">, Group;
 def malign_jumps_EQ : Joined<["-"], "malign-jumps=">, Group;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112408: [WIP][RISCV] Add the zve extension according to the v1.0-rc2 spec

2021-10-25 Thread Fraser Cormack via Phabricator via cfe-commits
frasercrmck added a comment.

Don't we need to teach ISel some tricks before we consider these extensions 
supported? E.g., we need to stop i64 vectors being legal under zve32x or zve32f.




Comment at: llvm/lib/Target/RISCV/RISCV.td:182
 
+def FeatureExtZve32x
+: SubtargetFeature<"experimental-zve32x", "HasStdExtZve32x", "true",

Do we need to define distinct `SubtargetFeature`s for each of these extensions 
or could they be broken down into a single `MaxEEW` feature (32 or 64) in 
conjunction with the pre-existing F/D features. This seems like it's more 
complicated than it needs to be.



Comment at: llvm/lib/Target/RISCV/RISCVSubtarget.h:141
+  // either v or zve* suppaort v instructions
+  bool hasStdExtV() const { return HasStdExtV || HasStdExtZve32x; }
+  bool hasStdExtZve32x() const { return HasStdExtZve32x; }

Is this correct? I thought we'd keep `hasStdExtV` as being the single-letter V 
extension, and Zve32x isn't that.



Comment at: llvm/test/CodeGen/RISCV/attributes.ll:8
 ; RUN: llc -mtriple=riscv32 -mattr=+c %s -o - | FileCheck --check-prefix=RV32C 
%s
-; RUN: llc -mtriple=riscv32 
-mattr=+experimental-v,+experimental-zvamo,+experimental-zvlsseg %s -o - | 
FileCheck --check-prefix=RV32V %s
+; RUN: llc -mtriple=riscv32 
-mattr=+f,+d,+experimental-v,+experimental-zvamo,+experimental-zvlsseg %s -o - 
| FileCheck --check-prefix=RV32V %s
 ; RUN: llc -mtriple=riscv32 -mattr=+experimental-zfh %s -o - | FileCheck 
--check-prefix=RV32ZFH %s

Why is this being changed in this patch?



Comment at: llvm/test/CodeGen/RISCV/rvv/fixed-vectors-bitcast.ll:158
 ; CHECK-NEXT:vmv.x.s a0, v8
+; CHECK-NEXT:lui a1, 1048560
+; CHECK-NEXT:or a0, a0, a1

What's going on here, do you know?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112408

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


[PATCH] D111642: [Analyzer][solver] Simplification: reorganize equalities with adjustment

2021-10-25 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

Awesome!
So clean, and I also like the tests.
Good job.




Comment at: clang/test/Analysis/solver-sym-simplification-adjustment.c:58
+  if (b != 1) {   // b == 1  --> c + 1 == 0 --> c == -1 contradiction
+clang_analyzer_eval(b == 0);  // expected-warning{{TRUE}}
+// Keep the symbols and the constraints! alive.

Please assert `clang_analyzer_eval(c == 0)` as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111642

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


[PATCH] D112296: [Analyzer][solver] Handle adjustments in constraint assignor remainder

2021-10-25 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

<3


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112296

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


[clang] e1fdec8 - [analyzer] Add std::string checker

2021-10-25 Thread Balazs Benics via cfe-commits
Author: Balazs Benics
Date: 2021-10-25T11:15:40+02:00
New Revision: e1fdec875ff13504057fa01227458c9afa08222f

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

LOG: [analyzer] Add std::string checker

This patch adds a checker checking `std::string` operations.
At first, it only checks the `std::string` single `const char *`
constructor for nullness.
If It might be `null`, it will constrain it to non-null and place a note
tag there.

Reviewed By: martong

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

Added: 
clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
clang/test/Analysis/std-string.cpp

Modified: 
clang/docs/analyzer/checkers.rst
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
clang/test/Analysis/Inputs/system-header-simulator-cxx.h
clang/test/Analysis/diagnostics/explicit-suppression.cpp

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index 267ff4437a64f..62eeb16d10dfa 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -313,6 +313,22 @@ cplusplus.SelfAssignment (C++)
 ""
 Checks C++ copy and move assignment operators for self assignment.
 
+.. _cplusplus-StringChecker:
+
+cplusplus.StringChecker (C++)
+"
+Checks std::string operations.
+
+.. code-block:: cpp
+
+ #include 
+
+ void f(const char *p) {
+   if (!p) {
+ std::string msg(p); // warn: p is NULL
+   }
+ }
+
 .. _deadcode-checkers:
 
 deadcode

diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index aac111982b235..bd21d7778f931 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -603,6 +603,10 @@ def SmartPtrModeling: Checker<"SmartPtrModeling">,
   ]>,
   Hidden;
 
+def StringChecker: Checker<"StringChecker">,
+  HelpText<"Checks C++ std::string bugs">,
+  Documentation;
+
 def MoveChecker: Checker<"Move">,
   HelpText<"Find use-after-move bugs in C++">,
   CheckerOptions<[

diff  --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index e7d424ae91504..3e85fadef0a2a 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -105,6 +105,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   StdLibraryFunctionsChecker.cpp
   STLAlgorithmModeling.cpp
   StreamChecker.cpp
+  StringChecker.cpp
   Taint.cpp
   TaintTesterChecker.cpp
   TestAfterDivZeroChecker.cpp

diff  --git a/clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
new file mode 100644
index 0..56b9cdb95c384
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
@@ -0,0 +1,101 @@
+//=== StringChecker.cpp ---*- C++ 
-*--//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements the modeling of the std::basic_string type.
+// This involves checking preconditions of the operations and applying the
+// effects of the operations, e.g. their post-conditions.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+class StringChecker : public Checker {
+  BugType BT_Null{this, "Dereference of null pointer", categories::LogicError};
+  mutable const FunctionDecl *StringConstCharPtrCtor = nullptr;
+  mutable CanQualType SizeTypeTy;
+  const CallDescription TwoParamStdStringCtor = {
+  {"std", "basic_string", "basic_string"}, 2, 2};
+
+  bool isCharToStringCtor(const CallEvent &Call, const ASTContext &ACtx) const;
+
+public:
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
+};
+
+bool StringChecker::isCharToStringCtor(const CallEvent &Call,
+   const ASTContext &ACtx) const {
+  if (!Call.isCalled(TwoParamStdStringCtor))
+return false;
+  const auto *FD = dyn_cast(Call.getDecl());
+  assert(FD);
+
+  // See if we already cached it.
+  if (StringConstCharPtrCt

[clang] caeef19 - [analyzer] Allow cmake options to be passed to satest container

2021-10-25 Thread Balazs Benics via cfe-commits
Author: Manas
Date: 2021-10-25T11:15:40+02:00
New Revision: caeef1995ab47387fa8da3e958afc5637b4e893d

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

LOG: [analyzer] Allow cmake options to be passed to satest container

This patch selects all cmake options and passes them to global cmake
command while building LLVM inside satest docker container.

Prior to this, the cmake command was hard-coded and this would consume
a huge amount of memory while building. There was no support to pass
extra cmake options for the build, except for changing the command
manually. This patch allows testers to pass all "-D*" cmake options to
the build.

Reviewed By: vsavchenko

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

Patch by: @manas (Manas Gupta)

Added: 


Modified: 
clang/utils/analyzer/entrypoint.py

Removed: 




diff  --git a/clang/utils/analyzer/entrypoint.py 
b/clang/utils/analyzer/entrypoint.py
index 9c84431da5482..b61f0d5192946 100644
--- a/clang/utils/analyzer/entrypoint.py
+++ b/clang/utils/analyzer/entrypoint.py
@@ -9,10 +9,11 @@
 
 def main():
 settings, rest = parse_arguments()
+cmake_opts = ['-D' + cmd for cmd in settings.D]
 if settings.wait:
 wait()
 if settings.build_llvm or settings.build_llvm_only:
-build_llvm()
+build_llvm(cmake_opts)
 if settings.build_llvm_only:
 return
 sys.exit(test(rest))
@@ -30,14 +31,15 @@ def parse_arguments() -> Tuple[argparse.Namespace, 
List[str]]:
 parser.add_argument('--wait', action='store_true')
 parser.add_argument('--build-llvm', action='store_true')
 parser.add_argument('--build-llvm-only', action='store_true')
+parser.add_argument('-D', action='append', default=[])
 return parser.parse_known_args()
 
 
-def build_llvm():
+def build_llvm(cmake_options):
 os.chdir('/build')
 try:
 if is_cmake_needed():
-cmake()
+cmake(cmake_options)
 ninja()
 except CalledProcessError:
 print("Build failed!")
@@ -55,8 +57,9 @@ def is_cmake_needed():
 "-DCLANG_ENABLE_STATIC_ANALYZER=ON"
 
 
-def cmake():
-check_call(CMAKE_COMMAND + ' /llvm-project/llvm', shell=True)
+def cmake(cmake_options):
+check_call(CMAKE_COMMAND + ' '.join(cmake_options) + ' /llvm-project/llvm',
+shell=True)
 
 
 def ninja():



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


[PATCH] D111247: [analyzer] Add std::string checker

2021-10-25 Thread Balázs Benics 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 rGe1fdec875ff1: [analyzer] Add std::string checker (authored 
by steakhal).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111247

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/StringChecker.cpp
  clang/test/Analysis/Inputs/system-header-simulator-cxx.h
  clang/test/Analysis/diagnostics/explicit-suppression.cpp
  clang/test/Analysis/std-string.cpp

Index: clang/test/Analysis/std-string.cpp
===
--- /dev/null
+++ clang/test/Analysis/std-string.cpp
@@ -0,0 +1,81 @@
+// RUN: %clang_analyze_cc1 -std=c++14 %s -verify  \
+// RUN:   -analyzer-checker=core,unix.Malloc,debug.ExprInspection \
+// RUN:   -analyzer-checker=cplusplus.StringChecker   \
+// RUN:   -analyzer-config eagerly-assume=false   \
+// RUN:   -analyzer-output=text
+
+#include "Inputs/system-header-simulator-cxx.h"
+
+void clang_analyzer_eval(bool);
+void clang_analyzer_warnIfReached();
+
+void free(void *ptr);
+
+void irrelevant_std_string_ctors(const char *p) {
+  std::string x1; // no-warning
+  std::string x2(2, 'x'); // no-warning
+  std::string x3(x1, /*pos=*/2);  // no-warning
+  std::string x4(x1, /*pos=*/2, /*count=*/2); // no-warning
+  std::string x5(p, /*count=*/(size_t)2); // no-warning
+  // skip std::string(const char*)
+  std::string x6(x1.begin(), x1.end()); // no-warning
+  std::string x7(x1);   // no-warning
+  std::string x8(std::move(x1));// no-warning
+  std::string x9({'a', 'b', '\0'}); // no-warning
+}
+
+void null_cstring_parameter(const char *p) {
+  clang_analyzer_eval(p == 0); // expected-warning {{UNKNOWN}} expected-note {{UNKNOWN}}
+  if (!p) {
+// expected-note@-1 2 {{Assuming 'p' is null}}
+// expected-note@-2 2 {{Taking true branch}}
+clang_analyzer_eval(p == 0); // expected-warning {{TRUE}} expected-note {{TRUE}}
+std::string x(p);
+// expected-warning@-1 {{The parameter must not be null}}
+// expected-note@-2{{The parameter must not be null}}
+clang_analyzer_warnIfReached(); // no-warning
+  }
+}
+
+void null_constant_parameter() {
+  std::string x((char *)0);
+  // expected-warning@-1 {{The parameter must not be null}}
+  // expected-note@-2{{The parameter must not be null}}
+}
+
+void ctor_notetag_on_constraining_symbol(const char *p) {
+  clang_analyzer_eval(p == 0); // expected-warning {{UNKNOWN}} expected-note {{UNKNOWN}}
+  std::string x(p);// expected-note {{Assuming the pointer is not null}}
+  clang_analyzer_eval(p == 0); // expected-warning {{FALSE}} expected-note {{FALSE}}
+
+  free((void *)p); // expected-note {{Memory is released}}
+  free((void *)p);
+  // expected-warning@-1 {{Attempt to free released memory}}
+  // expected-note@-2{{Attempt to free released memory}}
+}
+
+void ctor_no_notetag_symbol_already_constrained(const char *p) {
+  // expected-note@+2 + {{Assuming 'p' is non-null}}
+  // expected-note@+1 + {{Taking false branch}}
+  if (!p)
+return;
+
+  clang_analyzer_eval(p == 0); // expected-warning {{FALSE}} expected-note {{FALSE}}
+  std::string x(p);// no-note: 'p' is already constrained to be non-null.
+  clang_analyzer_eval(p == 0); // expected-warning {{FALSE}} expected-note {{FALSE}}
+
+  free((void *)p); // expected-note {{Memory is released}}
+  free((void *)p);
+  // expected-warning@-1 {{Attempt to free released memory}}
+  // expected-note@-2{{Attempt to free released memory}}
+}
+
+void ctor_no_notetag_if_not_interesting(const char *p1, const char *p2) {
+  std::string s1(p1); // expected-note {{Assuming the pointer is not null}}
+  std::string s2(p2); // no-note: s2 is not interesting
+
+  free((void *)p1); // expected-note {{Memory is released}}
+  free((void *)p1);
+  // expected-warning@-1 {{Attempt to free released memory}}
+  // expected-note@-2{{Attempt to free released memory}}
+}
Index: clang/test/Analysis/diagnostics/explicit-suppression.cpp
===
--- clang/test/Analysis/diagnostics/explicit-suppression.cpp
+++ clang/test/Analysis/diagnostics/explicit-suppression.cpp
@@ -19,6 +19,6 @@
 void testCopyNull(C *I, C *E) {
   std::copy(I, E, (C *)0);
 #ifndef SUPPRESSED
-  // expected-warning@../Inputs/system-header-simulator-cxx.h:709 {{Called C++ object pointer is null}}
+  // expected-warning@../Inputs/system-header-simulator-cxx.h:741 {{Called C++ object pointer is null}}
 #endif
 }
Index: clang/test/

[PATCH] D105447: [analyzer] Allow cmake options to be passed to satest container

2021-10-25 Thread Balázs Benics via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcaeef1995ab4: [analyzer] Allow cmake options to be passed to 
satest container (authored by manas, committed by steakhal).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D105447

Files:
  clang/utils/analyzer/entrypoint.py


Index: clang/utils/analyzer/entrypoint.py
===
--- clang/utils/analyzer/entrypoint.py
+++ clang/utils/analyzer/entrypoint.py
@@ -9,10 +9,11 @@
 
 def main():
 settings, rest = parse_arguments()
+cmake_opts = ['-D' + cmd for cmd in settings.D]
 if settings.wait:
 wait()
 if settings.build_llvm or settings.build_llvm_only:
-build_llvm()
+build_llvm(cmake_opts)
 if settings.build_llvm_only:
 return
 sys.exit(test(rest))
@@ -30,14 +31,15 @@
 parser.add_argument('--wait', action='store_true')
 parser.add_argument('--build-llvm', action='store_true')
 parser.add_argument('--build-llvm-only', action='store_true')
+parser.add_argument('-D', action='append', default=[])
 return parser.parse_known_args()
 
 
-def build_llvm():
+def build_llvm(cmake_options):
 os.chdir('/build')
 try:
 if is_cmake_needed():
-cmake()
+cmake(cmake_options)
 ninja()
 except CalledProcessError:
 print("Build failed!")
@@ -55,8 +57,9 @@
 "-DCLANG_ENABLE_STATIC_ANALYZER=ON"
 
 
-def cmake():
-check_call(CMAKE_COMMAND + ' /llvm-project/llvm', shell=True)
+def cmake(cmake_options):
+check_call(CMAKE_COMMAND + ' '.join(cmake_options) + ' /llvm-project/llvm',
+shell=True)
 
 
 def ninja():


Index: clang/utils/analyzer/entrypoint.py
===
--- clang/utils/analyzer/entrypoint.py
+++ clang/utils/analyzer/entrypoint.py
@@ -9,10 +9,11 @@
 
 def main():
 settings, rest = parse_arguments()
+cmake_opts = ['-D' + cmd for cmd in settings.D]
 if settings.wait:
 wait()
 if settings.build_llvm or settings.build_llvm_only:
-build_llvm()
+build_llvm(cmake_opts)
 if settings.build_llvm_only:
 return
 sys.exit(test(rest))
@@ -30,14 +31,15 @@
 parser.add_argument('--wait', action='store_true')
 parser.add_argument('--build-llvm', action='store_true')
 parser.add_argument('--build-llvm-only', action='store_true')
+parser.add_argument('-D', action='append', default=[])
 return parser.parse_known_args()
 
 
-def build_llvm():
+def build_llvm(cmake_options):
 os.chdir('/build')
 try:
 if is_cmake_needed():
-cmake()
+cmake(cmake_options)
 ninja()
 except CalledProcessError:
 print("Build failed!")
@@ -55,8 +57,9 @@
 "-DCLANG_ENABLE_STATIC_ANALYZER=ON"
 
 
-def cmake():
-check_call(CMAKE_COMMAND + ' /llvm-project/llvm', shell=True)
+def cmake(cmake_options):
+check_call(CMAKE_COMMAND + ' '.join(cmake_options) + ' /llvm-project/llvm',
+shell=True)
 
 
 def ninja():
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D109557: Adds a BlockIndent option to AlignAfterOpenBracket

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



Comment at: clang/docs/ReleaseNotes.rst:227
   correctly places the opening brace according to ``BraceWrapping.AfterEnum``.
+- Option ``AlignAfterOpenBracket: BlockIndent`` has been added. If set, it will
+  always break after an open bracket, if the parameters don't fit on a single

Add a new line before.



Comment at: clang/lib/Format/TokenAnnotator.cpp:4207-4212
+  if (Right.is(tok::r_paren) && Right.MatchingParen &&
+  !(Right.MatchingParen->Previous &&
+(Right.MatchingParen->Previous->is(tok::kw_for) ||
+ Right.MatchingParen->Previous->isIf(
+return Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent;
+

I'm not sure if this is sufficient. Before we returned always false. Shouldn't 
we use 2 ifs here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109557

___
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-25 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1757-1760
+  // FIXME: Nevertheless, we can't do the same for cases, like:
+  //   const char *str = "123"; // literal length is 4
+  //   char c = str[41];// offset is 41
+  // It should be properly handled before reaching this point.

Thanks for updating the patch! However, this `FIXME` makes me worried. Do you 
think you could pass the `Decl` itself to `getSValFromInitListExpr` in order to 
be able to check whether the type is a pointer or an array? 


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] D112420: [clang][ARM] PACBTI-M assembly support

2021-10-25 Thread Ties Stuij via Phabricator via cfe-commits
stuij created this revision.
Herald added subscribers: hiraditya, kristof.beyls.
stuij requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Introduce assembly support for Armv8.1-M PACBTI extension. This is an optional
extension in v8.1-M.

There are 10 new system registers and 5 new instructions, all predicated on the
feature.

The attribute for llvm-mc is called "pacbti". For armclang, an architecture
extension also called "pacbti" was created.

This patch is part of a series that adds support for the PACBTI-M extension of
the Armv8.1-M architecture, as detailed here:

https://community.arm.com/arm-community-blogs/b/architectures-and-processors-blog/posts/armv8-1-m-pointer-authentication-and-branch-target-identification-extension

The PACBTI-M specification can be found in the Armv8-M Architecture Reference
Manual:

https://developer.arm.com/documentation/ddi0553/latest

The following people contributed to this patch:

- Victor Campos
- Ties Stuij


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112420

Files:
  clang/test/Driver/armv8.1m.main.c
  llvm/include/llvm/Support/ARMTargetParser.def
  llvm/include/llvm/Support/ARMTargetParser.h
  llvm/lib/Target/ARM/ARM.td
  llvm/lib/Target/ARM/ARMInstrThumb2.td
  llvm/lib/Target/ARM/ARMPredicates.td
  llvm/lib/Target/ARM/ARMSubtarget.h
  llvm/lib/Target/ARM/ARMSystemRegister.td
  llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
  llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp
  llvm/test/MC/ARM/armv8.1m-pacbti-error.s
  llvm/test/MC/ARM/armv8.1m-pacbti.s
  llvm/test/MC/Disassembler/ARM/armv8.1m-pacbti.txt

Index: llvm/test/MC/Disassembler/ARM/armv8.1m-pacbti.txt
===
--- /dev/null
+++ llvm/test/MC/Disassembler/ARM/armv8.1m-pacbti.txt
@@ -0,0 +1,137 @@
+# RUN: llvm-mc -triple thumbv8.1m.main-arm-none-eabi -mattr=+pacbti -disassemble %s 2> /dev/null | FileCheck %s
+
+0x51,0xfb,0x02,0x0f
+0x5e,0xfb,0x0d,0xcf
+0xaf,0xf3,0x2d,0x80
+0x51,0xfb,0x12,0x0f
+0xaf,0xf3,0x0f,0x80
+0x61,0xfb,0x02,0xf0
+0x6e,0xfb,0x0d,0xfc
+0xaf,0xf3,0x1d,0x80
+0xaf,0xf3,0x0d,0x80
+0x80,0xf3,0x20,0x88
+0x80,0xf3,0x21,0x88
+0x80,0xf3,0x22,0x88
+0x80,0xf3,0x23,0x88
+0x80,0xf3,0x24,0x88
+0x80,0xf3,0x25,0x88
+0x80,0xf3,0x26,0x88
+0x80,0xf3,0x27,0x88
+0x80,0xf3,0xa0,0x88
+0x80,0xf3,0xa1,0x88
+0x80,0xf3,0xa2,0x88
+0x80,0xf3,0xa3,0x88
+0x80,0xf3,0xa4,0x88
+0x80,0xf3,0xa5,0x88
+0x80,0xf3,0xa6,0x88
+0x80,0xf3,0xa7,0x88
+0xef,0xf3,0x20,0x80
+0xef,0xf3,0x21,0x80
+0xef,0xf3,0x22,0x80
+0xef,0xf3,0x23,0x80
+0xef,0xf3,0x24,0x80
+0xef,0xf3,0x25,0x80
+0xef,0xf3,0x26,0x80
+0xef,0xf3,0x27,0x80
+0xef,0xf3,0xa0,0x80
+0xef,0xf3,0xa1,0x80
+0xef,0xf3,0xa2,0x80
+0xef,0xf3,0xa3,0x80
+0xef,0xf3,0xa4,0x80
+0xef,0xf3,0xa5,0x80
+0xef,0xf3,0xa6,0x80
+0xef,0xf3,0xa7,0x80
+
+# Test softfail encodings
+0xa7,0xf3,0x1d,0x80
+0xab,0xf3,0x1d,0x80
+0xad,0xf3,0x1d,0x80
+0xae,0xf3,0x1d,0x80
+0xaf,0xf3,0x1d,0x88
+0xaf,0xf3,0x1d,0xa0
+0xaf,0xf3,0x2d,0x80
+0xab,0xf3,0x2d,0x80
+0xad,0xf3,0x2d,0x80
+0xae,0xf3,0x2d,0x80
+0xaf,0xf3,0x2d,0x88
+0xaf,0xf3,0x2d,0xa0
+0xa7,0xf3,0x0f,0x80
+0xab,0xf3,0x0f,0x80
+0xad,0xf3,0x0f,0x80
+0xae,0xf3,0x0f,0x80
+0xaf,0xf3,0x0f,0x88
+0xaf,0xf3,0x0f,0xa0
+0xa7,0xf3,0x0d,0x80
+0xab,0xf3,0x0d,0x80
+0xad,0xf3,0x0d,0x80
+0xae,0xf3,0x0d,0x80
+0xaf,0xf3,0x0d,0x88
+0xaf,0xf3,0x0d,0xa0
+
+# CHECK: autg	r0, r1, r2
+# CHECK: autg r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: bxautr0, r1, r2
+# CHECK: bti
+# CHECK: pacg	r0, r1, r2
+# CHECK: pacg	r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pacbti   r12, lr, sp
+# CHECK: msr	pac_key_p_0, r0
+# CHECK: msr	pac_key_p_1, r0
+# CHECK: msr	pac_key_p_2, r0
+# CHECK: msr	pac_key_p_3, r0
+# CHECK: msr	pac_key_u_0, r0
+# CHECK: msr	pac_key_u_1, r0
+# CHECK: msr	pac_key_u_2, r0
+# CHECK: msr	pac_key_u_3, r0
+# CHECK: msr	pac_key_p_0_ns, r0
+# CHECK: msr	pac_key_p_1_ns, r0
+# CHECK: msr	pac_key_p_2_ns, r0
+# CHECK: msr	pac_key_p_3_ns, r0
+# CHECK: msr	pac_key_u_0_ns, r0
+# CHECK: msr	pac_key_u_1_ns, r0
+# CHECK: msr	pac_key_u_2_ns, r0
+# CHECK: msr	pac_key_u_3_ns, r0
+# CHECK: mrs	r0, pac_key_p_0
+# CHECK: mrs	r0, pac_key_p_1
+# CHECK: mrs	r0, pac_key_p_2
+# CHECK: mrs	r0, pac_key_p_3
+# CHECK: mrs	r0, pac_key_u_0
+# CHECK: mrs	r0, pac_key_u_1
+# CHECK: mrs	r0, pac_key_u_2
+# CHECK: mrs	r0, pac_key_u_3
+# CHECK: mrs	r0, pac_key_p_0_ns
+# CHECK: mrs	r0, pac_key_p_1_ns
+# CHECK: mrs	r0, pac_key_p_2_ns
+# CHECK: mrs	r0, pac_key_p_3_ns
+# CHECK: mrs	r0, pac_key_u_0_ns
+# CHECK: mrs	r0, pac_key_u_1_ns
+# CHECK: mrs	r0, pac_key_u_2_ns
+# CHECK: mrs	r0, pac_key_u_3_ns
+
+# Softfail encodings
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: pac  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# CHECK: aut  r12, lr, sp
+# 

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

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



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

crayroud wrote:
> HazardyKnusperkeks wrote:
> > Please remove again. :)
> I changed the documentation to have a space added or removed only before the 
> for loop colon. Indeed the space after the for is handled by 
> SpaceBeforeParens... and not SpaceBeforeRangeBasedForLoopColon. Why do you 
> think it is better to keep it as before ?
I must admit, I did not notice that the space is for the colon not the paren.

But nevertheless this is an unrelated change. You are very welcome to fix it, 
in its own commit.



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

crayroud wrote:
> HazardyKnusperkeks wrote:
> > Is this needed? Shouldn't the expand take care of that?
> Indeed the expand takes care of that and it would be nice not to have to 
> repeat it here.
> I had to add it for the test FormatTest.ConfigurationRoundTripTest, as it is 
> done for LLVMStyle.BraceWrapping.
> What do you think is best ?
If that's the case, than it may be so.


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] D110833: [clang-format] Refactor SpaceBeforeParens to add flags

2021-10-25 Thread Christian Rayroud via Phabricator via cfe-commits
crayroud added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:3170
+  // to add a space only before the first one
+  bool IsFirstLParen = true;
+  const FormatToken *Tok = Right.Previous;

I will simplify the following using Left.is(TT_FunctionDeclarationName)


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] D112421: [clang][ARM] PACBTI-M frontend support

2021-10-25 Thread Ties Stuij via Phabricator via cfe-commits
stuij created this revision.
Herald added subscribers: dexonsmith, hiraditya, kristof.beyls.
Herald added a reviewer: aaron.ballman.
stuij requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Handle branch protection option on the commandline as well as a function
attribute. One patch for both mechanisms, as they use the same underlying
parsing mechanism.

These are recorded in a set of LLVM IR module-level attributes like we do for
AArch64 PAC/BTI (see https://reviews.llvm.org/D85649):

- command-line options are "translated" to module-level LLVM IR attributes 
(metadata).

- functions have PAC/BTI specific attributes iff the 
__attribute__((target("branch-protection=...))) was used in the function 
declaration.

- command-line option -mbranch-protection to armclang targeting Arm,

following this grammar:

branch-protection ::= "-mbranch-protection=" 
protection ::=  "none" | "standard" | "bti" [ "+"  ]

  |  [ "+" "bti"]

pac-ret-clause ::= "pac-ret" [ "+"  ]
pac-ret-option ::= "leaf" ["+" "b-key"] | "b-key" ["+" "leaf"]

b-key is simply a placeholder to make it consistent with AArch64's
version. In Arm, however, it triggers a warning informing that b-key is
unsupported and a-key will be selected instead.

- Handle _attribute_((target(("branch-protection=..."))) for AArch32 with the

same grammer as the commandline options.

This patch is part of a series that adds support for the PACBTI-M extension of
the Armv8.1-M architecture, as detailed here:

https://community.arm.com/arm-community-blogs/b/architectures-and-processors-blog/posts/armv8-1-m-pointer-authentication-and-branch-target-identification-extension

The PACBTI-M specification can be found in the Armv8-M Architecture Reference
Manual:

https://developer.arm.com/documentation/ddi0553/latest

The following people contributed to this patch:

- Momchil Velikov
- Victor Campos
- Ties Stuij


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112421

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Basic/Targets/ARM.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/TargetInfo.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGen/arm-branch-protection-attr-1.c
  clang/test/CodeGen/arm-branch-protection-attr-2.c
  clang/test/CodeGen/arm_neon_intrinsics.c
  clang/test/Driver/arm-security-options.c
  clang/test/Frontend/arm-invalid-branch-protection.c
  clang/test/Sema/aarch64-branch-protection-attr-err.c
  clang/test/Sema/arm-branch-protection-attr-err.c
  clang/test/Sema/branch-protection-attr-err.c
  llvm/include/llvm/Support/AArch64TargetParser.h
  llvm/include/llvm/Support/TargetParser.h
  llvm/lib/Support/AArch64TargetParser.cpp
  llvm/lib/Support/TargetParser.cpp

Index: llvm/lib/Support/TargetParser.cpp
===
--- llvm/lib/Support/TargetParser.cpp
+++ llvm/lib/Support/TargetParser.cpp
@@ -333,3 +333,51 @@
 
 } // namespace RISCV
 } // namespace llvm
+
+// Parse a branch protection specification, which has the form
+//   standard | none | [bti,pac-ret[+b-key,+leaf]*]
+// Returns true on success, with individual elements of the specification
+// returned in `PBP`. Returns false in error, with `Err` containing
+// an erroneous part of the spec.
+bool ARM::parseBranchProtection(StringRef Spec, ParsedBranchProtection &PBP,
+StringRef &Err) {
+  PBP = {"none", "a_key", false};
+  if (Spec == "none")
+return true; // defaults are ok
+
+  if (Spec == "standard") {
+PBP.Scope = "non-leaf";
+PBP.BranchTargetEnforcement = true;
+return true;
+  }
+
+  SmallVector Opts;
+  Spec.split(Opts, "+");
+  for (int I = 0, E = Opts.size(); I != E; ++I) {
+StringRef Opt = Opts[I].trim();
+if (Opt == "bti") {
+  PBP.BranchTargetEnforcement = true;
+  continue;
+}
+if (Opt == "pac-ret") {
+  PBP.Scope = "non-leaf";
+  for (; I + 1 != E; ++I) {
+StringRef PACOpt = Opts[I + 1].trim();
+if (PACOpt == "leaf")
+  PBP.Scope = "all";
+else if (PACOpt == "b-key")
+  PBP.Key = "b_key";
+else
+  break;
+  }
+  continue;
+}
+if (Opt == "")
+  Err = "";
+else
+  Err = Opt;
+return false;
+  }
+
+  return true;
+}
Index: llvm/lib/Support/AArch64TargetParser.cpp
===
--- llvm/lib/Support/AArch64TargetParser.cpp
+++ llvm/lib/Support/AArch64TargetParser.cpp
@@ -238,52 +238,4 @@
   return C.ArchID;
   }
   return ArchKind::INVALID;
-}
-
-// Parse a branch protection specification, which has the form
-//   standard | none | [bti,pac-ret[+b-key,+leaf]*]
-// Returns true

[PATCH] D112422: [clang][ARM] emit PACBTI-M feature defines

2021-10-25 Thread Ties Stuij via Phabricator via cfe-commits
stuij created this revision.
Herald added a subscriber: kristof.beyls.
stuij requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

emit __ARM_FEATURE_BTI_DEFAULT and __ARM_FEATURE_PAC_DEFAULT defines when those
features have been enabled

This patch is part of a series that adds support for the PACBTI-M extension of
the Armv8.1-M architecture, as detailed here:

https://community.arm.com/arm-community-blogs/b/architectures-and-processors-blog/posts/armv8-1-m-pointer-authentication-and-branch-target-identification-extension

The PACBTI-M specification can be found in the Armv8-M Architecture Reference
Manual:

https://developer.arm.com/documentation/ddi0553/latest

The following people contributed to this patch:

- Victor Campos
- Ties Stuij


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112422

Files:
  clang/lib/Basic/Targets/ARM.cpp
  clang/test/Preprocessor/arm-target-features.c


Index: clang/test/Preprocessor/arm-target-features.c
===
--- clang/test/Preprocessor/arm-target-features.c
+++ clang/test/Preprocessor/arm-target-features.c
@@ -877,6 +877,25 @@
 // RUN: %clang -target arm-none-none-eabi -march=armv7-m -mfpu=softvfp -x c -E 
-dM %s -o - | FileCheck --check-prefix=CHECK-SOFTVFP %s
 // CHECK-SOFTVFP-NOT: #define __ARM_FP 0x
 
+// Test Armv8.1-M PACBTI
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -x c -E -dM %s 
-o - | FileCheck --check-prefixes=CHECK-NOBTI,CHECK-NOPAC %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main 
-mbranch-protection=bti -x c -E -dM %s -o - | FileCheck 
--check-prefixes=CHECK-BTI,CHECK-NOPAC %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main 
-mbranch-protection=pac-ret -x c -E -dM %s -o - | FileCheck 
--check-prefixes=CHECK-PAC,CHECK-NOBTI %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main 
-mbranch-protection=pac-ret+b-key -x c -E -dM %s -o - | FileCheck 
--check-prefixes=CHECK-PAC-BKEY,CHECK-NOBTI %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main 
-mbranch-protection=pac-ret+leaf -x c -E -dM %s -o - | FileCheck 
--check-prefixes=CHECK-PAC-LEAF,CHECK-NOBTI %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main 
-mbranch-protection=pac-ret+b-key+leaf -x c -E -dM %s -o - | FileCheck 
--check-prefixes=CHECK-PAC-BKEY-LEAF,CHECK-NOBTI %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main 
-mbranch-protection=bti+pac-ret -x c -E -dM %s -o - | FileCheck 
--check-prefixes=CHECK-PAC,CHECK-BTI %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main 
-mbranch-protection=bti+pac-ret+b-key -x c -E -dM %s -o - | FileCheck 
--check-prefixes=CHECK-PAC-BKEY,CHECK-BTI %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main 
-mbranch-protection=bti+pac-ret+leaf -x c -E -dM %s -o - | FileCheck 
--check-prefixes=CHECK-PAC-LEAF,CHECK-BTI %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main 
-mbranch-protection=bti+pac-ret+b-key+leaf -x c -E -dM %s -o - | FileCheck 
--check-prefixes=CHECK-PAC-BKEY-LEAF,CHECK-BTI %s
+// CHECK-NOBTI-NOT: #define __ARM_FEATURE_BTI_DEFAULT
+// CHECK-NOPAC-NOT: #define __ARM_FEATURE_PAC_DEFAULT
+// CHECK-BTI: #define __ARM_FEATURE_BTI_DEFAULT 1
+// CHECK-PAC: #define __ARM_FEATURE_PAC_DEFAULT 1
+// CHECK-PAC-BKEY: #define __ARM_FEATURE_PAC_DEFAULT 2
+// CHECK-PAC-LEAF: #define __ARM_FEATURE_PAC_DEFAULT 5
+// CHECK-PAC-BKEY-LEAF: #define __ARM_FEATURE_PAC_DEFAULT 6
+
 // == Check BFloat16 Extensions.
 // RUN: %clang -target arm-arm-none-eabi -march=armv8.6-a+bf16 -x c -E -dM %s 
-o - 2>&1 | FileCheck -check-prefix=CHECK-BFLOAT %s
 // CHECK-BFLOAT: #define __ARM_BF16_FORMAT_ALTERNATIVE 1
Index: clang/lib/Basic/Targets/ARM.cpp
===
--- clang/lib/Basic/Targets/ARM.cpp
+++ clang/lib/Basic/Targets/ARM.cpp
@@ -893,6 +893,16 @@
 Builder.defineMacro("__ARM_BF16_FORMAT_ALTERNATIVE", "1");
   }
 
+  if (Opts.BranchTargetEnforcement)
+Builder.defineMacro("__ARM_FEATURE_BTI_DEFAULT", "1");
+
+  if (Opts.hasSignReturnAddress()) {
+unsigned Value = Opts.isSignReturnAddressWithAKey() ? 1 : 2;
+if (Opts.isSignReturnAddressScopeAll())
+  Value |= 1 << 2;
+Builder.defineMacro("__ARM_FEATURE_PAC_DEFAULT", Twine(Value));
+  }
+
   switch (ArchKind) {
   default:
 break;


Index: clang/test/Preprocessor/arm-target-features.c
===
--- clang/test/Preprocessor/arm-target-features.c
+++ clang/test/Preprocessor/arm-target-features.c
@@ -877,6 +877,25 @@
 // RUN: %clang -target arm-none-none-eabi -march=armv7-m -mfpu=softvfp -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-SOFTVFP %s
 // CHECK-SOFTVFP-NOT: #define __ARM_FP 0x
 
+// Test Armv8.1-M PACBTI
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -x c -E -dM %s -o - | FileChec

[PATCH] D112430: [ARM][libunwind] add PACBTI-M support for libunwind

2021-10-25 Thread Ties Stuij via Phabricator via cfe-commits
stuij created this revision.
Herald added subscribers: libcxx-commits, kristof.beyls.
Herald added a project: libunwind.
Herald added a reviewer: libunwind.
stuij requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This patch implements the following:

- Emit PACBTI-M build attributes in libunwind asm files

- Authenticate LR in DWARF32 using PACBTI

Use Armv8.1-M.Main PACBTI extension to authenticate the return address
(stored in the LR register) before moving it to the PC (IP) register.

The AUTG instruction is used with the candidate return address, the CFA,
and the authentication code that is retrieved from the saved
pseudo-register RA_AUTH_CODE.

- Authenticate LR in EHABI using PACBTI

Authenticate the contents of the LR register using Armv8.1-M.Main PACBTI
extension.

A new frame unwinding instruction is introduced (0xb4). This
instruction pops out of the stack the return address authentication
code, which is then used in conjunction with the SP and the next-to-be
instruction pointer to perform authentication.

This authentication code is popped into a new register,
UNW_ARM_PSEUDO_PAC, which is a pseudo-register.

This patch is part of a series that adds support for the PACBTI-M extension of
the Armv8.1-M architecture, as detailed here:

https://community.arm.com/arm-community-blogs/b/architectures-and-processors-blog/posts/armv8-1-m-pointer-authentication-and-branch-target-identification-extension

The PACBTI-M specification can be found in the Armv8-M Architecture Reference
Manual:

https://developer.arm.com/documentation/ddi0553/latest

The following people contributed to this patch:

- Momchil Velikov
- Victor Campos
- Ties Stuij


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112430

Files:
  clang/lib/Headers/unwind.h
  libunwind/include/libunwind.h
  libunwind/include/unwind_arm_ehabi.h
  libunwind/src/DwarfInstructions.hpp
  libunwind/src/Registers.hpp
  libunwind/src/Unwind-EHABI.cpp
  libunwind/src/UnwindCursor.hpp
  libunwind/src/UnwindRegistersRestore.S
  libunwind/src/assembly.h

Index: libunwind/src/assembly.h
===
--- libunwind/src/assembly.h
+++ libunwind/src/assembly.h
@@ -81,7 +81,7 @@
 #define PPC64_OPD2
 #endif
 
-#if defined(__ARM_FEATURE_BTI_DEFAULT)
+#if defined(__aarch64__) && defined(__ARM_FEATURE_BTI_DEFAULT)
   .pushsection ".note.gnu.property", "a" SEPARATOR \
   .balign 8 SEPARATOR  \
   .long 4 SEPARATOR\
@@ -99,6 +99,17 @@
 #define AARCH64_BTI
 #endif
 
+#if !defined(__aarch64__)
+#ifdef __ARM_FEATURE_PAC_DEFAULT
+  .eabi_attribute Tag_PAC_extension, 2
+  .eabi_attribute Tag_PACRET_use, 1
+#endif
+#ifdef __ARM_FEATURE_BTI_DEFAULT
+  .eabi_attribute Tag_BTI_extension, 1
+  .eabi_attribute Tag_BTI_use, 1
+#endif
+#endif
+
 #define GLUE2(a, b) a ## b
 #define GLUE(a, b) GLUE2(a, b)
 #define SYMBOL_NAME(name) GLUE(__USER_LABEL_PREFIX__, name)
Index: libunwind/src/UnwindRegistersRestore.S
===
--- libunwind/src/UnwindRegistersRestore.S
+++ libunwind/src/UnwindRegistersRestore.S
@@ -660,7 +660,13 @@
   ldr sp, [lr, #52]
   ldr lr, [lr, #60]  @ restore pc into lr
 #endif
+#if defined(__ARM_FEATURE_BTI_DEFAULT) && !defined(__ARM_ARCH_ISA_ARM)
+  // 'bx' is not BTI setting when used with lr, therefore r12 is used instead
+  mov r12, lr
+  JMP(r12)
+#else
   JMP(lr)
+#endif
 
 @
 @ static void libunwind::Registers_arm::restoreVFPWithFLDMD(unw_fpreg_t* values)
Index: libunwind/src/UnwindCursor.hpp
===
--- libunwind/src/UnwindCursor.hpp
+++ libunwind/src/UnwindCursor.hpp
@@ -655,7 +655,9 @@
 #if defined(_LIBUNWIND_TARGET_X86_64)
   if (regNum >= UNW_X86_64_RAX && regNum <= UNW_X86_64_R15) return true;
 #elif defined(_LIBUNWIND_TARGET_ARM)
-  if (regNum >= UNW_ARM_R0 && regNum <= UNW_ARM_R15) return true;
+  if ((regNum >= UNW_ARM_R0 && regNum <= UNW_ARM_R15) ||
+  regNum == UNW_ARM_RA_AUTH_CODE)
+return true;
 #elif defined(_LIBUNWIND_TARGET_AARCH64)
   if (regNum >= UNW_AARCH64_X0 && regNum <= UNW_ARM64_X30) return true;
 #endif
Index: libunwind/src/Unwind-EHABI.cpp
===
--- libunwind/src/Unwind-EHABI.cpp
+++ libunwind/src/Unwind-EHABI.cpp
@@ -256,6 +256,7 @@
   size_t offset, size_t len) {
   bool wrotePC = false;
   bool finish = false;
+  bool hasReturnAddrAuthCode = false;
   while (offset < len && !finish) {
 uint8_t byte = getByte(data, offset++);
 if ((byte & 0x80) == 0) {
@@ -308,7 +309,7 @@
   if (offset >= len)
 return _URC_FAILURE;
   uint8_t registers = getByte(data, offset++);
-  if (registers & 0xf0 || !registers)
+  

[PATCH] D112431: [ARM][clang] Define feature test macro for the PACBTI-M extension

2021-10-25 Thread Ties Stuij via Phabricator via cfe-commits
stuij created this revision.
Herald added a subscriber: kristof.beyls.
stuij requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

If the extension string "+pacbti" was given in -march=... or -mcpu=... options 
the compiler shall define the following preprocessor macros:

  __ARM_FEATURE_PAUTH with value 1.
  __ARM_FEATURE_BTI with value 1.

This patch is part of a series that adds support for the PACBTI-M extension of
the Armv8.1-M architecture, as detailed here:

https://community.arm.com/arm-community-blogs/b/architectures-and-processors-blog/posts/armv8-1-m-pointer-authentication-and-branch-target-identification-extension

The PACBTI-M specification can be found in the Armv8-M Architecture Reference
Manual:

https://developer.arm.com/documentation/ddi0553/latest

The following people contributed to this patch:

- Momchil Velikov
- Ties Stuij


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112431

Files:
  clang/lib/Basic/Targets/ARM.cpp
  clang/lib/Basic/Targets/ARM.h
  clang/test/Preprocessor/arm-target-features.c


Index: clang/test/Preprocessor/arm-target-features.c
===
--- clang/test/Preprocessor/arm-target-features.c
+++ clang/test/Preprocessor/arm-target-features.c
@@ -896,6 +896,13 @@
 // CHECK-PAC-LEAF: #define __ARM_FEATURE_PAC_DEFAULT 5
 // CHECK-PAC-BKEY-LEAF: #define __ARM_FEATURE_PAC_DEFAULT 6
 
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -x c -E -dM %s 
-o - | FileCheck --check-prefixes=CHECK-NOBTI-EXT,CHECK-NOPAC-EXT %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv7-m+pacbti -x c -E -dM %s 
-o - | FileCheck --check-prefixes=CHECK-PACBTI-EXT %s
+// CHECK-NOBTI-EXT-NOT: #define __ARM_FEATURE_BTI 1
+// CHECK-NOPAC-EXT-NOT: #define __ARM_FEATURE_PAUTH 1
+// CHECK-PACBTI-EXT: #define __ARM_FEATURE_BTI 1
+// CHECK-PACBTI-EXT: #define __ARM_FEATURE_PAUTH 1
+
 // == Check BFloat16 Extensions.
 // RUN: %clang -target arm-arm-none-eabi -march=armv8.6-a+bf16 -x c -E -dM %s 
-o - 2>&1 | FileCheck -check-prefix=CHECK-BFLOAT %s
 // CHECK-BFLOAT: #define __ARM_BF16_FORMAT_ALTERNATIVE 1
Index: clang/lib/Basic/Targets/ARM.h
===
--- clang/lib/Basic/Targets/ARM.h
+++ clang/lib/Basic/Targets/ARM.h
@@ -78,6 +78,8 @@
   unsigned Unaligned : 1;
   unsigned DotProd : 1;
   unsigned HasMatMul : 1;
+  unsigned HasPAC : 1;
+  unsigned HasBTI : 1;
 
   enum {
 LDREX_B = (1 << 0), /// byte (8-bit)
Index: clang/lib/Basic/Targets/ARM.cpp
===
--- clang/lib/Basic/Targets/ARM.cpp
+++ clang/lib/Basic/Targets/ARM.cpp
@@ -465,6 +465,8 @@
   HWDiv = 0;
   DotProd = 0;
   HasMatMul = 0;
+  HasPAC = 0;
+  HasBTI = 0;
   HasFloat16 = true;
   ARMCDECoprocMask = 0;
   HasBFloat16 = false;
@@ -544,6 +546,9 @@
   ARMCDECoprocMask |= (1U << Coproc);
 } else if (Feature == "+bf16") {
   HasBFloat16 = true;
+} else if (Feature == "+pacbti") {
+  HasPAC = 1;
+  HasBTI = 1;
 }
   }
 
@@ -887,6 +892,11 @@
   if (HasMatMul)
 Builder.defineMacro("__ARM_FEATURE_MATMUL_INT8", "1");
 
+  if (HasPAC) {
+Builder.defineMacro("__ARM_FEATURE_PAUTH", "1");
+Builder.defineMacro("__ARM_FEATURE_BTI", "1");
+  }
+
   if (HasBFloat16) {
 Builder.defineMacro("__ARM_FEATURE_BF16", "1");
 Builder.defineMacro("__ARM_FEATURE_BF16_VECTOR_ARITHMETIC", "1");


Index: clang/test/Preprocessor/arm-target-features.c
===
--- clang/test/Preprocessor/arm-target-features.c
+++ clang/test/Preprocessor/arm-target-features.c
@@ -896,6 +896,13 @@
 // CHECK-PAC-LEAF: #define __ARM_FEATURE_PAC_DEFAULT 5
 // CHECK-PAC-BKEY-LEAF: #define __ARM_FEATURE_PAC_DEFAULT 6
 
+// RUN: %clang -target arm-arm-none-eabi -march=armv8.1-m.main -x c -E -dM %s -o - | FileCheck --check-prefixes=CHECK-NOBTI-EXT,CHECK-NOPAC-EXT %s
+// RUN: %clang -target arm-arm-none-eabi -march=armv7-m+pacbti -x c -E -dM %s -o - | FileCheck --check-prefixes=CHECK-PACBTI-EXT %s
+// CHECK-NOBTI-EXT-NOT: #define __ARM_FEATURE_BTI 1
+// CHECK-NOPAC-EXT-NOT: #define __ARM_FEATURE_PAUTH 1
+// CHECK-PACBTI-EXT: #define __ARM_FEATURE_BTI 1
+// CHECK-PACBTI-EXT: #define __ARM_FEATURE_PAUTH 1
+
 // == Check BFloat16 Extensions.
 // RUN: %clang -target arm-arm-none-eabi -march=armv8.6-a+bf16 -x c -E -dM %s -o - 2>&1 | FileCheck -check-prefix=CHECK-BFLOAT %s
 // CHECK-BFLOAT: #define __ARM_BF16_FORMAT_ALTERNATIVE 1
Index: clang/lib/Basic/Targets/ARM.h
===
--- clang/lib/Basic/Targets/ARM.h
+++ clang/lib/Basic/Targets/ARM.h
@@ -78,6 +78,8 @@
   unsigned Unaligned : 1;
   unsigned DotProd : 1;
   unsigned HasMatMul : 1;
+  unsigned HasPAC : 1;
+  unsigned HasBTI : 1;
 
   enum {
 LDREX_B = (1 << 0), /// byte (8-bit)
Index: cla

[PATCH] D112430: [ARM][libunwind] add PACBTI-M support for libunwind

2021-10-25 Thread Daniel Kiss via Phabricator via cfe-commits
danielkiss added inline comments.



Comment at: libunwind/src/Registers.hpp:2245-2246
 
+  if (regNum == UNW_ARM_RA_AUTH_CODE)
+return true;
+

Maybe we could gate this on __ARM_FEATURE_PAUTH because it won't work anyway 
without the feature enabled for libunwind.



Comment at: libunwind/src/Registers.hpp:2274-2275
 
+  if (regNum == UNW_ARM_RA_AUTH_CODE)
+return _pseudo_registers.__pac;
+

ditto, maybe better to run into a `_LIBUNWIND_ABORT` instead debugging a 
silently skipping the authentication.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112430

___
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-25 Thread Bradley Smith 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 rG0ce46a1d43c6: [AArch64][Driver][SVE] Allow 
-msve-vector-bits=+ syntax to mean no maximum… (authored by bsmith).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111790

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/AST/ASTContext.cpp
  clang/lib/Basic/Targets/AArch64.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGen/aarch64-sve-acle-__ARM_FEATURE_SVE_VECTOR_OPERATORS.c
  clang/test/CodeGen/aarch64-sve-acle-__ARM_FEATURE_SVE_VECTOR_OPERATORS.cpp
  clang/test/CodeGen/aarch64-sve-vector-bits-codegen.c
  clang/test/CodeGen/arm-sve-vector-bits-vscale-range.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-bitcast.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-call.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-cast.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-codegen.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-globals.c
  clang/test/CodeGen/attr-arm-sve-vector-bits-types.c
  clang/test/CodeGenCXX/aarch64-mangle-sve-fixed-vectors.cpp
  clang/test/CodeGenCXX/aarch64-sve-fixedtypeinfo.cpp
  clang/test/Driver/aarch64-sve-vector-bits.c
  clang/test/Preprocessor/aarch64-target-features.c
  clang/test/Sema/aarch64-sve-explicit-casts-fixed-size.c
  clang/test/Sema/aarch64-sve-lax-vector-conversions.c
  clang/test/Sema/attr-arm-sve-vector-bits.c
  clang/test/SemaCXX/aarch64-sve-explicit-casts-fixed-size.cpp
  clang/test/SemaCXX/aarch64-sve-lax-vector-conversions.cpp
  clang/test/SemaCXX/attr-arm-sve-vector-bits.cpp

Index: clang/test/SemaCXX/attr-arm-sve-vector-bits.cpp
===
--- clang/test/SemaCXX/attr-arm-sve-vector-bits.cpp
+++ clang/test/SemaCXX/attr-arm-sve-vector-bits.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +bf16 -ffreestanding -fsyntax-only -verify -std=c++11 -msve-vector-bits=512 -fallow-half-arguments-and-returns -Wconversion %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -target-feature +bf16 -ffreestanding -fsyntax-only -verify -std=c++11 -mvscale-min=4 -mvscale-max=4 -fallow-half-arguments-and-returns -Wconversion %s
 // expected-no-diagnostics
 
 #include 
Index: clang/test/SemaCXX/aarch64-sve-lax-vector-conversions.cpp
===
--- clang/test/SemaCXX/aarch64-sve-lax-vector-conversions.cpp
+++ clang/test/SemaCXX/aarch64-sve-lax-vector-conversions.cpp
@@ -1,6 +1,6 @@
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=512 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-none %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=512 -flax-vector-conversions=integer -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-integer %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=512 -flax-vector-conversions=all -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-all %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -mvscale-min=4 -mvscale-max=4 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-none %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -mvscale-min=4 -mvscale-max=4 -flax-vector-conversions=integer -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-integer %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -mvscale-min=4 -mvscale-max=4 -flax-vector-conversions=all -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify=lax-vector-all %s
 
 #include 
 
Index: clang/test/SemaCXX/aarch64-sve-explicit-casts-fixed-size.cpp
===
--- clang/test/SemaCXX/aarch64-sve-explicit-casts-fixed-size.cpp
+++ clang/test/SemaCXX/aarch64-sve-explicit-casts-fixed-size.cpp
@@ -1,8 +1,8 @@
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=128 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=256 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify %s
-// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -msve-vector-bits=512 -flax-vector-conversions=none -fallow-half-arguments-and-returns -ffreestanding -fsyntax-only -verify %s
-// RUN: %clang_

[clang] 0ce46a1 - [AArch64][Driver][SVE] Allow -msve-vector-bits=+ syntax to mean no maximum vscale

2021-10-25 Thread Bradley Smith via cfe-commits
Author: Bradley Smith
Date: 2021-10-25T11:10:52Z
New Revision: 0ce46a1d43c6c2e0df429a6a80848d4acc781eb6

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

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

This patch splits the existing SveVectorBits LangOpt into VScaleMin and
VScaleMax LangOpts such that we can represent such an option. The cc1
option has also been split into -mvscale-{min,max}= options so that the
cc1 arguments better reflect the vscale_range IR attribute.

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

Added: 


Modified: 
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Driver/Options.td
clang/lib/AST/ASTContext.cpp
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Sema/SemaType.cpp
clang/test/CodeGen/aarch64-sve-acle-__ARM_FEATURE_SVE_VECTOR_OPERATORS.c
clang/test/CodeGen/aarch64-sve-acle-__ARM_FEATURE_SVE_VECTOR_OPERATORS.cpp
clang/test/CodeGen/aarch64-sve-vector-bits-codegen.c
clang/test/CodeGen/arm-sve-vector-bits-vscale-range.c
clang/test/CodeGen/attr-arm-sve-vector-bits-bitcast.c
clang/test/CodeGen/attr-arm-sve-vector-bits-call.c
clang/test/CodeGen/attr-arm-sve-vector-bits-cast.c
clang/test/CodeGen/attr-arm-sve-vector-bits-codegen.c
clang/test/CodeGen/attr-arm-sve-vector-bits-globals.c
clang/test/CodeGen/attr-arm-sve-vector-bits-types.c
clang/test/CodeGenCXX/aarch64-mangle-sve-fixed-vectors.cpp
clang/test/CodeGenCXX/aarch64-sve-fixedtypeinfo.cpp
clang/test/Driver/aarch64-sve-vector-bits.c
clang/test/Preprocessor/aarch64-target-features.c
clang/test/Sema/aarch64-sve-explicit-casts-fixed-size.c
clang/test/Sema/aarch64-sve-lax-vector-conversions.c
clang/test/Sema/attr-arm-sve-vector-bits.c
clang/test/SemaCXX/aarch64-sve-explicit-casts-fixed-size.cpp
clang/test/SemaCXX/aarch64-sve-lax-vector-conversions.cpp
clang/test/SemaCXX/attr-arm-sve-vector-bits.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 912fd0ec18961..4651f4fff6aa0 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -425,7 +425,8 @@ LANGOPT(SpeculativeLoadHardening, 1, 0, "Speculative load 
hardening enabled")
 LANGOPT(RelativeCXXABIVTables, 1, 0,
 "Use an ABI-incompatible v-table layout that uses relative references")
 
-LANGOPT(ArmSveVectorBits, 32, 0, "SVE vector size in bits")
+LANGOPT(VScaleMin, 32, 0, "Minimum vscale value")
+LANGOPT(VScaleMax, 32, 0, "Maximum vscale value")
 
 ENUM_LANGOPT(ExtendIntArgs, ExtendArgsKind, 1, ExtendArgsKind::ExtendTo32,
  "Controls how scalar integer arguments are extended in calls "

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 25f3ddd97f12a..b4a2411fa5c5c 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3331,13 +3331,20 @@ foreach i = {8-15,18} in
   def fcall_saved_x#i : Flag<["-"], "fcall-saved-x"#i>, 
Group,
 HelpText<"Make the x"#i#" register call-saved (AArch64 only)">;
 
-def msve_vector_bits_EQ : Joined<["-"], "msve-vector-bits=">,
-  Group, Flags<[NoXarchOption,CC1Option]>,
+def msve_vector_bits_EQ : Joined<["-"], "msve-vector-bits=">, 
Group,
   HelpText<"Specify the size in bits of an SVE vector register. Defaults to 
the"
-   " vector length agnostic value of \"scalable\". (AArch64 only)">,
-  Values<"128,256,512,1024,2048,scalable">,
-  NormalizedValues<["128", "256", "512", "1024", "2048", "0"]>,
-  MarshallingInfoEnum, "0">;
+   " vector length agnostic value of \"scalable\". (AArch64 only)">;
+
+def mvscale_min_EQ : Joined<["-"], "mvscale-min=">,
+  Group, Flags<[NoXarchOption,CC1Option]>,
+  HelpText<"Specify the vscale minimum. Defaults to the"
+   " vector length agnostic value of \"0\". (AArch64 only)">,
+  MarshallingInfoInt>;
+def mvscale_max_EQ : Joined<["-"], "mvscale-max=">,
+  Group, Flags<[NoXarchOption,CC1Option]>,
+  HelpText<"Specify the vscale maximum. Defaults to the"
+   " vector length agnostic value of \"0\". (AArch64 only)">,
+  MarshallingInfoInt>;
 
 def msign_return_address_EQ : Joined<["-"], "msign-return-address=">,
   Flags<[CC1Option]>, Group, Values<"none,all,non-leaf">,

diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 84b09dcf16a0e..796a737b8c6dd 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -8768,8 +8768,8 @@ bool ASTContext::areCompatibleVectorTypes(QualType 
FirstVec,
 static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
   assert(Ty->isVLSTBui

[clang] ffa96f0 - [clang] Fix range for forward-declared enums

2021-10-25 Thread Kadir Cetinkaya via cfe-commits
Author: Kadir Cetinkaya
Date: 2021-10-25T13:16:14+02:00
New Revision: ffa96f022c3ff03888afca8fdda766fe556eb9c5

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

LOG: [clang] Fix range for forward-declared enums

This used to span just the `[[enum foo]] : bar;` in the absence of a
body. This patch expands the range to cover the base specifier, so that the
various consumers can detect the full range of the decl.

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

Added: 


Modified: 
clang/include/clang/AST/Decl.h
clang/lib/AST/Decl.cpp
clang/unittests/AST/DeclTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index b46499203b0bc..85a3a8ab69708 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -3701,6 +3701,10 @@ class EnumDecl : public TagDecl {
   bool IsFixed);
   static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
 
+  /// Overrides to provide correct range when there's an enum-base specifier
+  /// with forward declarations.
+  SourceRange getSourceRange() const override LLVM_READONLY;
+
   /// When created, the EnumDecl corresponds to a
   /// forward-declared enum. This method is used to mark the
   /// declaration as being defined; its enumerators have already been

diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 6a837430924f3..32dae5ccad3a9 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -4524,6 +4524,17 @@ unsigned EnumDecl::getODRHash() {
   return ODRHash;
 }
 
+SourceRange EnumDecl::getSourceRange() const {
+  auto Res = TagDecl::getSourceRange();
+  // Set end-point to enum-base, e.g. enum foo : ^bar
+  if (auto *TSI = getIntegerTypeSourceInfo()) {
+// TagDecl doesn't know about the enum base.
+if (!getBraceRange().getEnd().isValid())
+  Res.setEnd(TSI->getTypeLoc().getEndLoc());
+  }
+  return Res;
+}
+
 
//===--===//
 // RecordDecl Implementation
 
//===--===//

diff  --git a/clang/unittests/AST/DeclTest.cpp 
b/clang/unittests/AST/DeclTest.cpp
index 0964080c7a258..588ef859a181e 100644
--- a/clang/unittests/AST/DeclTest.cpp
+++ b/clang/unittests/AST/DeclTest.cpp
@@ -10,14 +10,17 @@
 //
 
//===--===//
 
+#include "clang/AST/Decl.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Mangle.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/Testing/Support/Annotations.h"
 #include "gtest/gtest.h"
 
 using namespace clang::ast_matchers;
@@ -138,3 +141,19 @@ TEST(Decl, MangleDependentSizedArray) {
   ASSERT_TRUE(0 == MangleA.compare("_ZTSA_i"));
   ASSERT_TRUE(0 == MangleB.compare("_ZTSAT0__T_"));
 }
+
+TEST(Decl, EnumDeclRange) {
+  llvm::Annotations Code(R"(
+typedef int Foo;
+[[enum Bar : Foo]];)");
+  auto AST = tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{});
+  ASTContext &Ctx = AST->getASTContext();
+  const auto &SM = Ctx.getSourceManager();
+
+  const auto *Bar =
+  selectFirst("Bar", match(enumDecl().bind("Bar"), Ctx));
+  auto BarRange =
+  Lexer::getAsCharRange(Bar->getSourceRange(), SM, Ctx.getLangOpts());
+  EXPECT_EQ(SM.getFileOffset(BarRange.getBegin()), Code.range().Begin);
+  EXPECT_EQ(SM.getFileOffset(BarRange.getEnd()), Code.range().End);
+}



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


[clang-tools-extra] 4e4511d - [clang] Traverse enum base specifier in RAV

2021-10-25 Thread Kadir Cetinkaya via cfe-commits
Author: Kadir Cetinkaya
Date: 2021-10-25T13:16:14+02:00
New Revision: 4e4511df8d33a6fc02d5e46c681855db495187cd

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

LOG: [clang] Traverse enum base specifier in RAV

Added: 


Modified: 
clang-tools-extra/clangd/unittests/SelectionTests.cpp
clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
clang-tools-extra/clangd/unittests/XRefsTests.cpp
clang/include/clang/AST/RecursiveASTVisitor.h
clang/unittests/AST/RecursiveASTVisitorTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 5a45e5bde8fae..1c3bc20958486 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -473,7 +473,19 @@ TEST(SelectionTest, CommonAncestor) {
 [[@property(retain, nonnull) <:[My^Object2]:> *x]]; // error-ok
 @end
   )cpp",
-   "ObjCPropertyDecl"}};
+   "ObjCPropertyDecl"},
+
+  {R"cpp(
+typedef int Foo;
+enum Bar : [[Fo^o]] {};
+  )cpp",
+   "TypedefTypeLoc"},
+  {R"cpp(
+typedef int Foo;
+enum Bar : [[Fo^o]];
+  )cpp",
+   "TypedefTypeLoc"},
+  };
 
   for (const Case &C : Cases) {
 trace::TestTracer Tracer;

diff  --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp 
b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
index 4653490f5b036..acada4180b0fe 100644
--- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -780,6 +780,16 @@ sizeof...($TemplateParameter[[Elements]]);
 $LocalVariable_decl[[d]]($LocalVariable[[b]]) ]() {}();
 }
   )cpp",
+  // Enum base specifier
+  R"cpp(
+using $Primitive_decl[[MyTypedef]] = int;
+enum $Enum_decl[[MyEnum]] : $Primitive[[MyTypedef]] {};
+  )cpp",
+  // Enum base specifier
+  R"cpp(
+typedef int $Primitive_decl[[MyTypedef]];
+enum $Enum_decl[[MyEnum]] : $Primitive[[MyTypedef]] {};
+  )cpp",
   };
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.

diff  --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 1f41dcd69913c..99a6b6e9d8bee 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -880,6 +880,19 @@ TEST(LocateSymbol, All) {
 };
   )cpp",
 
+  R"cpp(// Enum base
+typedef int $decl[[MyTypeDef]];
+enum Foo : My^TypeDef {};
+  )cpp",
+  R"cpp(// Enum base
+typedef int $decl[[MyTypeDef]];
+enum Foo : My^TypeDef;
+  )cpp",
+  R"cpp(// Enum base
+using $decl[[MyTypeDef]] = int;
+enum Foo : My^TypeDef {};
+  )cpp",
+
   R"objc(
 @protocol Dog;
 @protocol $decl[[Dog]]

diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 9b261e8540dac..dfc1bd35e51f9 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -1867,6 +1867,8 @@ DEF_TRAVERSE_DECL(EnumDecl, {
 TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
 
   TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
+  if (auto *TSI = D->getIntegerTypeSourceInfo())
+TRY_TO(TraverseTypeLoc(TSI->getTypeLoc()));
   // The enumerators are already traversed by
   // decls_begin()/decls_end().
 })

diff  --git a/clang/unittests/AST/RecursiveASTVisitorTest.cpp 
b/clang/unittests/AST/RecursiveASTVisitorTest.cpp
index aa8756527d315..f44a5eca18728 100644
--- a/clang/unittests/AST/RecursiveASTVisitorTest.cpp
+++ b/clang/unittests/AST/RecursiveASTVisitorTest.cpp
@@ -10,6 +10,8 @@
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/FunctionExtras.h"
@@ -53,7 +55,11 @@ enum class VisitEvent {
   StartTraverseFunction,
   EndTraverseFunction,
   StartTraverseAttr,
-  EndTraverseAttr
+  EndTraverseAttr,
+  StartTraverseEnum,
+  EndTraverseEnum,
+  StartTraverseTypedefType,
+  EndTraverseTypedefType,
 };
 
 class CollectInterestingEvents
@@ -75,6 +81,22 @@ class CollectInterestingEvents
 return Ret;
   }
 
+  bool TraverseEnumDecl(EnumDecl *D) {
+Events.push_back(VisitEvent::StartTraverseEnum);
+bool Ret = RecursiveASTVisitor::TraverseEnumDecl(D);
+Events.push_back(V

[clang-tools-extra] 9ab9caf - [clang] Visit enum base specifiers in libIndex

2021-10-25 Thread Kadir Cetinkaya via cfe-commits
Author: Kadir Cetinkaya
Date: 2021-10-25T13:16:14+02:00
New Revision: 9ab9caf214f47ea0ccf5cd3eb0aef2fcb88bd6e1

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

LOG: [clang] Visit enum base specifiers in libIndex

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

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/XRefsTests.cpp
clang/lib/Index/IndexDecl.cpp
clang/unittests/Index/IndexTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 99a6b6e9d8bee..802367645c859 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -1966,6 +1966,20 @@ TEST(FindReferences, WithinAST) {
   [[f^oo]](s);
 }
   )cpp",
+
+  // Enum base
+  R"cpp(
+typedef int $def[[MyTypeD^ef]];
+enum MyEnum : [[MyTy^peDef]] { };
+  )cpp",
+  R"cpp(
+typedef int $def[[MyType^Def]];
+enum MyEnum : [[MyTypeD^ef]];
+  )cpp",
+  R"cpp(
+using $def[[MyTypeD^ef]] = int;
+enum MyEnum : [[MyTy^peDef]] { };
+  )cpp",
   };
   for (const char *Test : Tests)
 checkFindRefs(Test);

diff  --git a/clang/lib/Index/IndexDecl.cpp b/clang/lib/Index/IndexDecl.cpp
index 00adb3644ff25..3139aedaf01d4 100644
--- a/clang/lib/Index/IndexDecl.cpp
+++ b/clang/lib/Index/IndexDecl.cpp
@@ -8,6 +8,7 @@
 
 #include "IndexingContext.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclVisitor.h"
 #include "clang/Index/IndexDataConsumer.h"
 
@@ -372,6 +373,15 @@ class IndexingDeclVisitor : public 
ConstDeclVisitor {
 return true;
   }
 
+  bool VisitEnumDecl(const EnumDecl *ED) {
+TRY_TO(VisitTagDecl(ED));
+// Indexing for enumdecl itself is handled inside TagDecl, we just want to
+// visit integer-base here, which is 
diff erent than other TagDecl bases.
+if (auto *TSI = ED->getIntegerTypeSourceInfo())
+  IndexCtx.indexTypeSourceInfo(TSI, ED, ED, /*isBase=*/true);
+return true;
+  }
+
   bool handleReferencedProtocols(const ObjCProtocolList &ProtList,
  const ObjCContainerDecl *ContD,
  SourceLocation SuperLoc) {

diff  --git a/clang/unittests/Index/IndexTests.cpp 
b/clang/unittests/Index/IndexTests.cpp
index 24230c68fa22f..88ad63b97b92a 100644
--- a/clang/unittests/Index/IndexTests.cpp
+++ b/clang/unittests/Index/IndexTests.cpp
@@ -377,6 +377,21 @@ TEST(IndexTest, RelationBaseOf) {
  Not(HasRole(SymbolRole::RelationBaseOf);
 }
 
+TEST(IndexTest, EnumBase) {
+  std::string Code = R"cpp(
+typedef int MyTypedef;
+enum Foo : MyTypedef;
+enum Foo : MyTypedef {};
+  )cpp";
+  auto Index = std::make_shared();
+  tooling::runToolOnCode(std::make_unique(Index), Code);
+  EXPECT_THAT(
+  Index->Symbols,
+  AllOf(Contains(AllOf(QName("MyTypedef"), HasRole(SymbolRole::Reference),
+   WrittenAt(Position(3, 16,
+Contains(AllOf(QName("MyTypedef"), HasRole(SymbolRole::Reference),
+   WrittenAt(Position(4, 16));
+}
 } // namespace
 } // namespace index
 } // namespace clang



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


[PATCH] D111259: [clang] Fix range for forward-declared enums

2021-10-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
kadircet marked 2 inline comments as done.
Closed by commit rGffa96f022c3f: [clang] Fix range for forward-declared enums 
(authored by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D111259?vs=377651&id=381931#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111259

Files:
  clang/include/clang/AST/Decl.h
  clang/lib/AST/Decl.cpp
  clang/unittests/AST/DeclTest.cpp


Index: clang/unittests/AST/DeclTest.cpp
===
--- clang/unittests/AST/DeclTest.cpp
+++ clang/unittests/AST/DeclTest.cpp
@@ -10,14 +10,17 @@
 //
 
//===--===//
 
+#include "clang/AST/Decl.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Mangle.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/Testing/Support/Annotations.h"
 #include "gtest/gtest.h"
 
 using namespace clang::ast_matchers;
@@ -138,3 +141,19 @@
   ASSERT_TRUE(0 == MangleA.compare("_ZTSA_i"));
   ASSERT_TRUE(0 == MangleB.compare("_ZTSAT0__T_"));
 }
+
+TEST(Decl, EnumDeclRange) {
+  llvm::Annotations Code(R"(
+typedef int Foo;
+[[enum Bar : Foo]];)");
+  auto AST = tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{});
+  ASTContext &Ctx = AST->getASTContext();
+  const auto &SM = Ctx.getSourceManager();
+
+  const auto *Bar =
+  selectFirst("Bar", match(enumDecl().bind("Bar"), Ctx));
+  auto BarRange =
+  Lexer::getAsCharRange(Bar->getSourceRange(), SM, Ctx.getLangOpts());
+  EXPECT_EQ(SM.getFileOffset(BarRange.getBegin()), Code.range().Begin);
+  EXPECT_EQ(SM.getFileOffset(BarRange.getEnd()), Code.range().End);
+}
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -4524,6 +4524,17 @@
   return ODRHash;
 }
 
+SourceRange EnumDecl::getSourceRange() const {
+  auto Res = TagDecl::getSourceRange();
+  // Set end-point to enum-base, e.g. enum foo : ^bar
+  if (auto *TSI = getIntegerTypeSourceInfo()) {
+// TagDecl doesn't know about the enum base.
+if (!getBraceRange().getEnd().isValid())
+  Res.setEnd(TSI->getTypeLoc().getEndLoc());
+  }
+  return Res;
+}
+
 
//===--===//
 // RecordDecl Implementation
 
//===--===//
Index: clang/include/clang/AST/Decl.h
===
--- clang/include/clang/AST/Decl.h
+++ clang/include/clang/AST/Decl.h
@@ -3701,6 +3701,10 @@
   bool IsFixed);
   static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
 
+  /// Overrides to provide correct range when there's an enum-base specifier
+  /// with forward declarations.
+  SourceRange getSourceRange() const override LLVM_READONLY;
+
   /// When created, the EnumDecl corresponds to a
   /// forward-declared enum. This method is used to mark the
   /// declaration as being defined; its enumerators have already been


Index: clang/unittests/AST/DeclTest.cpp
===
--- clang/unittests/AST/DeclTest.cpp
+++ clang/unittests/AST/DeclTest.cpp
@@ -10,14 +10,17 @@
 //
 //===--===//
 
+#include "clang/AST/Decl.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Mangle.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Lex/Lexer.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/Testing/Support/Annotations.h"
 #include "gtest/gtest.h"
 
 using namespace clang::ast_matchers;
@@ -138,3 +141,19 @@
   ASSERT_TRUE(0 == MangleA.compare("_ZTSA_i"));
   ASSERT_TRUE(0 == MangleB.compare("_ZTSAT0__T_"));
 }
+
+TEST(Decl, EnumDeclRange) {
+  llvm::Annotations Code(R"(
+typedef int Foo;
+[[enum Bar : Foo]];)");
+  auto AST = tooling::buildASTFromCodeWithArgs(Code.code(), /*Args=*/{});
+  ASTContext &Ctx = AST->getASTContext();
+  const auto &SM = Ctx.getSourceManager();
+
+  const auto *Bar =
+  selectFirst("Bar", match(enumDecl().bind("Bar"), Ctx));
+  auto BarRange =
+  Lexer::getAsCharRange(Bar->getSourceRange(), SM, Ctx.getLangOpts());
+  EXPECT_EQ(SM.getFileOffset(BarRange.getBegin()), Code.range().Begin);
+  EXPECT_EQ(SM.getFileOffset(BarRange.getEnd()), Code.range().End);
+}
Index: clang/lib/AST/Decl.cpp

[PATCH] D111260: [clang] Visit enum base specifiers in libIndex

2021-10-25 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9ab9caf214f4: [clang] Visit enum base specifiers in libIndex 
(authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111260

Files:
  clang-tools-extra/clangd/unittests/XRefsTests.cpp
  clang/lib/Index/IndexDecl.cpp
  clang/unittests/Index/IndexTests.cpp


Index: clang/unittests/Index/IndexTests.cpp
===
--- clang/unittests/Index/IndexTests.cpp
+++ clang/unittests/Index/IndexTests.cpp
@@ -377,6 +377,21 @@
  Not(HasRole(SymbolRole::RelationBaseOf);
 }
 
+TEST(IndexTest, EnumBase) {
+  std::string Code = R"cpp(
+typedef int MyTypedef;
+enum Foo : MyTypedef;
+enum Foo : MyTypedef {};
+  )cpp";
+  auto Index = std::make_shared();
+  tooling::runToolOnCode(std::make_unique(Index), Code);
+  EXPECT_THAT(
+  Index->Symbols,
+  AllOf(Contains(AllOf(QName("MyTypedef"), HasRole(SymbolRole::Reference),
+   WrittenAt(Position(3, 16,
+Contains(AllOf(QName("MyTypedef"), HasRole(SymbolRole::Reference),
+   WrittenAt(Position(4, 16));
+}
 } // namespace
 } // namespace index
 } // namespace clang
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -8,6 +8,7 @@
 
 #include "IndexingContext.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclVisitor.h"
 #include "clang/Index/IndexDataConsumer.h"
 
@@ -372,6 +373,15 @@
 return true;
   }
 
+  bool VisitEnumDecl(const EnumDecl *ED) {
+TRY_TO(VisitTagDecl(ED));
+// Indexing for enumdecl itself is handled inside TagDecl, we just want to
+// visit integer-base here, which is different than other TagDecl bases.
+if (auto *TSI = ED->getIntegerTypeSourceInfo())
+  IndexCtx.indexTypeSourceInfo(TSI, ED, ED, /*isBase=*/true);
+return true;
+  }
+
   bool handleReferencedProtocols(const ObjCProtocolList &ProtList,
  const ObjCContainerDecl *ContD,
  SourceLocation SuperLoc) {
Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -1966,6 +1966,20 @@
   [[f^oo]](s);
 }
   )cpp",
+
+  // Enum base
+  R"cpp(
+typedef int $def[[MyTypeD^ef]];
+enum MyEnum : [[MyTy^peDef]] { };
+  )cpp",
+  R"cpp(
+typedef int $def[[MyType^Def]];
+enum MyEnum : [[MyTypeD^ef]];
+  )cpp",
+  R"cpp(
+using $def[[MyTypeD^ef]] = int;
+enum MyEnum : [[MyTy^peDef]] { };
+  )cpp",
   };
   for (const char *Test : Tests)
 checkFindRefs(Test);


Index: clang/unittests/Index/IndexTests.cpp
===
--- clang/unittests/Index/IndexTests.cpp
+++ clang/unittests/Index/IndexTests.cpp
@@ -377,6 +377,21 @@
  Not(HasRole(SymbolRole::RelationBaseOf);
 }
 
+TEST(IndexTest, EnumBase) {
+  std::string Code = R"cpp(
+typedef int MyTypedef;
+enum Foo : MyTypedef;
+enum Foo : MyTypedef {};
+  )cpp";
+  auto Index = std::make_shared();
+  tooling::runToolOnCode(std::make_unique(Index), Code);
+  EXPECT_THAT(
+  Index->Symbols,
+  AllOf(Contains(AllOf(QName("MyTypedef"), HasRole(SymbolRole::Reference),
+   WrittenAt(Position(3, 16,
+Contains(AllOf(QName("MyTypedef"), HasRole(SymbolRole::Reference),
+   WrittenAt(Position(4, 16));
+}
 } // namespace
 } // namespace index
 } // namespace clang
Index: clang/lib/Index/IndexDecl.cpp
===
--- clang/lib/Index/IndexDecl.cpp
+++ clang/lib/Index/IndexDecl.cpp
@@ -8,6 +8,7 @@
 
 #include "IndexingContext.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/Decl.h"
 #include "clang/AST/DeclVisitor.h"
 #include "clang/Index/IndexDataConsumer.h"
 
@@ -372,6 +373,15 @@
 return true;
   }
 
+  bool VisitEnumDecl(const EnumDecl *ED) {
+TRY_TO(VisitTagDecl(ED));
+// Indexing for enumdecl itself is handled inside TagDecl, we just want to
+// visit integer-base here, which is different than other TagDecl bases.
+if (auto *TSI = ED->getIntegerTypeSourceInfo())
+  IndexCtx.indexTypeSourceInfo(TSI, ED, ED, /*isBase=*/true);
+return true;
+  }
+
   bool handleReferencedProtocols(const ObjCProtocolList &ProtList,
  const ObjCContainerDecl *ContD,
  SourceLocation SuperLoc) {
Index: clang-too

[PATCH] D111992: [MLIR][OpenMP] Added omp.atomic.read and omp.atomic.write

2021-10-25 Thread Shraiysh via Phabricator via cfe-commits
shraiysh updated this revision to Diff 381772.
shraiysh added a comment.

Rebase with main, updated syntax.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111992

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td
  mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
  mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
  mlir/test/Dialect/OpenMP/invalid.mlir
  mlir/test/Dialect/OpenMP/ops.mlir

Index: mlir/test/Dialect/OpenMP/ops.mlir
===
--- mlir/test/Dialect/OpenMP/ops.mlir
+++ mlir/test/Dialect/OpenMP/ops.mlir
@@ -454,3 +454,37 @@
 
   return
 }
+
+// CHECK-LABEL: omp_atomic_read
+// CHECK-SAME: (%[[ADDR:.*]]: memref)
+func @omp_atomic_read(%addr : memref) {
+  // CHECK: %{{.*}} = omp.atomic.read %[[ADDR]] : memref -> i32
+  %1 = omp.atomic.read %addr : memref -> i32
+  // CHECK: %{{.*}} = omp.atomic.read %[[ADDR]] memory_order(seq_cst) : memref -> i32
+  %2 = omp.atomic.read %addr memory_order(seq_cst) : memref -> i32
+  // CHECK: %{{.*}} = omp.atomic.read %[[ADDR]] memory_order(acquire) : memref -> i32
+  %5 = omp.atomic.read %addr memory_order(acquire) : memref -> i32
+  // CHECK: %{{.*}} = omp.atomic.read %[[ADDR]] memory_order(relaxed) : memref -> i32
+  %6 = omp.atomic.read %addr memory_order(relaxed) : memref -> i32
+  // CHECK: %{{.*}} = omp.atomic.read %[[ADDR]] hint(contended, nonspeculative) : memref -> i32
+  %7 = omp.atomic.read %addr hint(nonspeculative, contended) : memref -> i32
+  // CHECK: %{{.*}} = omp.atomic.read %[[ADDR]] memory_order(seq_cst) hint(contended, speculative) : memref -> i32
+  %8 = omp.atomic.read %addr hint(speculative, contended) memory_order(seq_cst) : memref -> i32
+  return
+}
+
+// CHECK-LABEL: omp_atomic_write
+// CHECK-SAME: (%[[ADDR:.*]]: memref, %[[VAL:.*]]: i32)
+func @omp_atomic_write(%addr : memref, %val : i32) {
+  // CHECK: omp.atomic.write %[[ADDR]], %[[VAL]] : memref, i32
+  omp.atomic.write %addr, %val : memref, i32
+  // CHECK: omp.atomic.write %[[ADDR]], %[[VAL]] memory_order(seq_cst) : memref, i32
+  omp.atomic.write %addr, %val memory_order(seq_cst) : memref, i32
+  // CHECK: omp.atomic.write %[[ADDR]], %[[VAL]] memory_order(release) : memref, i32
+  omp.atomic.write %addr, %val memory_order(release) : memref, i32
+  // CHECK: omp.atomic.write %[[ADDR]], %[[VAL]] memory_order(relaxed) : memref, i32
+  omp.atomic.write %addr, %val memory_order(relaxed) : memref, i32
+  // CHECK: omp.atomic.write %[[ADDR]], %[[VAL]] hint(uncontended, speculative) : memref, i32
+  omp.atomic.write %addr, %val hint(speculative, uncontended) : memref, i32
+  return
+}
Index: mlir/test/Dialect/OpenMP/invalid.mlir
===
--- mlir/test/Dialect/OpenMP/invalid.mlir
+++ mlir/test/Dialect/OpenMP/invalid.mlir
@@ -375,3 +375,99 @@
   }
   return
 }
+
+// -
+
+func @omp_atomic_read1(%addr : memref) {
+  // expected-error @below {{the hints omp_sync_hint_nonspeculative and omp_sync_hint_speculative cannot be combined.}}
+  %1 = omp.atomic.read %addr hint(speculative, nonspeculative) : memref -> i32
+  return
+}
+
+// -
+
+func @omp_atomic_read2(%addr : memref) {
+  // expected-error @below {{attribute 'memory_order' failed to satisfy constraint: MemoryOrderKind Clause}}
+  %1 = omp.atomic.read %addr memory_order(xyz) : memref -> i32
+  return
+}
+
+// -
+
+func @omp_atomic_read3(%addr : memref) {
+  // expected-error @below {{memory-order must not be acq_rel or release for atomic reads}}
+  %1 = omp.atomic.read %addr memory_order(acq_rel) : memref -> i32
+  return
+}
+
+// -
+
+func @omp_atomic_read4(%addr : memref) {
+  // expected-error @below {{memory-order must not be acq_rel or release for atomic reads}}
+  %1 = omp.atomic.read %addr memory_order(release) : memref -> i32
+  return
+}
+
+// -
+
+func @omp_atomic_read5(%addr : memref) {
+  // expected-error @below {{at most one memory_order clause can appear on the omp.atomic.read operation}}
+  %1 = omp.atomic.read %addr memory_order(acquire) memory_order(relaxed) : memref -> i32
+  return
+}
+
+// -
+
+func @omp_atomic_read6(%addr : memref) {
+  // expected-error @below {{at most one hint clause can appear on the omp.atomic.read operation}}
+  %1 = omp.atomic.read  %addr hint(speculative) hint(contended) : memref -> i32
+  return
+}
+
+// -
+
+func @omp_atomic_write1(%addr : memref, %val : i32) {
+  // expected-error @below {{the hints omp_sync_hint_uncontended and omp_sync_hint_contended cannot be combined}}
+  omp.atomic.write  %addr, %val hint(contended, uncontended) : memref, i32
+  return
+}
+
+// -
+
+func @omp_atomic_write2(%addr : memref, %val : i32) {
+  // expected-error @below {{memory-order must not be acq_rel or acquire for atomic writes}}
+  omp.atomic.write  %addr, %val memory_order(acq_rel) : memref, 

[PATCH] D111992: [MLIR][OpenMP] Added omp.atomic.read and omp.atomic.write

2021-10-25 Thread Peixin Qiao via Phabricator via cfe-commits
peixin added inline comments.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5993
   case OMPC_adjust_args:
+  case OMPC_memory_order:
 llvm_unreachable("Clause is not allowed in 'omp atomic'.");

The memory_order clause in clang side is not handled in this patch. Maybe 
leaving the error is better since users will know it is not supported yet in 
clang.



Comment at: mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td:513
+
+def AtomicReadOp : OpenMP_Op<"atomic.read"> {
+  let arguments = (ins OpenMP_PointerLikeType:$address,

How do you plan to handle synchronization between the threads if there is no 
region in atomic read op? Will there be one implicit `kmpc_flush` function call 
before `!$omp end atomic`? If yes, it is easier to find to location of emiting 
`kmpc_flush` if we have one region here. Please let me know if I am wrong. 



Comment at: mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp:1246
+StringRef memOrder = op.memory_order().getValue();
+if (memOrder.equals("acq_rel") || memOrder.equals("release"))
+  return op.emitError(

Please also check OpenMP 5.1 Spec. It seems that `acq_rel` is allowed if read 
clause is specified.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111992

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


[PATCH] D111992: [MLIR][OpenMP] Added omp.atomic.read and omp.atomic.write

2021-10-25 Thread Peixin Qiao via Phabricator via cfe-commits
peixin added inline comments.



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5993
   case OMPC_adjust_args:
+  case OMPC_memory_order:
 llvm_unreachable("Clause is not allowed in 'omp atomic'.");

peixin wrote:
> The memory_order clause in clang side is not handled in this patch. Maybe 
> leaving the error is better since users will know it is not supported yet in 
> clang.
> The memory_order clause in clang side is not handled in this patch. Maybe 
> leaving the error is better since users will know it is not supported yet in 
> clang.

Sorry. Please ignore this comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111992

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


[PATCH] D111992: [MLIR][OpenMP] Added omp.atomic.read and omp.atomic.write

2021-10-25 Thread Shraiysh via Phabricator via cfe-commits
shraiysh added a comment.

Thanks for the review @peixin.




Comment at: mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td:513
+
+def AtomicReadOp : OpenMP_Op<"atomic.read"> {
+  let arguments = (ins OpenMP_PointerLikeType:$address,

peixin wrote:
> How do you plan to handle synchronization between the threads if there is no 
> region in atomic read op? Will there be one implicit `kmpc_flush` function 
> call before `!$omp end atomic`? If yes, it is easier to find to location of 
> emiting `kmpc_flush` if we have one region here. Please let me know if I am 
> wrong. 
Yes - there will be a kmpc_flush call, but OpenMP Dialect does not have to 
worry about that. OpenMP IR Builder takes care of flushes in the function [[ 
https://llvm.org/doxygen/classllvm_1_1OpenMPIRBuilder.html#a388d5a62753f4e7ff4b72e54c1233fbc
 | createAtomicRead ]].



Comment at: mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp:1246
+StringRef memOrder = op.memory_order().getValue();
+if (memOrder.equals("acq_rel") || memOrder.equals("release"))
+  return op.emitError(

peixin wrote:
> Please also check OpenMP 5.1 Spec. It seems that `acq_rel` is allowed if read 
> clause is specified.
Thanks for this observation, I will update it with the 5.1 standard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111992

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


[PATCH] D111992: [MLIR][OpenMP] Added omp.atomic.read and omp.atomic.write

2021-10-25 Thread Shraiysh via Phabricator via cfe-commits
shraiysh added inline comments.



Comment at: mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp:1246
+StringRef memOrder = op.memory_order().getValue();
+if (memOrder.equals("acq_rel") || memOrder.equals("release"))
+  return op.emitError(

shraiysh wrote:
> peixin wrote:
> > Please also check OpenMP 5.1 Spec. It seems that `acq_rel` is allowed if 
> > read clause is specified.
> Thanks for this observation, I will update it with the 5.1 standard.
Just to be clear, the OpenMP 5.1 specification changes atomic by a considerable 
amount (especially it breaks capture into two sub-constructs (coming as a 
separate patch)) and AFAIK we are targeting OpenMP 5.0. So, do I still update 
it to the 5.1 standard (this will affect further implementation of atomic 
construct)? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111992

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


[PATCH] D110357: [Analyzer] Extend ConstraintAssignor to handle remainder op

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



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1618-1627
+const SymbolRef LHS = Sym->getLHS();
+const llvm::APSInt &Zero =
+Builder.getBasicValueFactory().getValue(0, Sym->getType());
+// a % b != 0 implies that a != 0.
+if (!Constraint.containsZero()) {
+  State = RCM.assumeSymNE(State, LHS, Zero, Zero);
+  if (!State)

Let me suggest possible changes.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1619-1620
+const SymbolRef LHS = Sym->getLHS();
+const llvm::APSInt &Zero =
+Builder.getBasicValueFactory().getValue(0, Sym->getType());
+// a % b != 0 implies that a != 0.

Howerver, put this line inside //if-body// below, since `Zero` isn't needed 
wherever else.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1618-1627
+const SymbolRef LHS = Sym->getLHS();
+const llvm::APSInt &Zero =
+Builder.getBasicValueFactory().getValue(0, Sym->getType());
+// a % b != 0 implies that a != 0.
+if (!Constraint.containsZero()) {
+  State = RCM.assumeSymNE(State, LHS, Zero, Zero);
+  if (!State)

martong wrote:
> ASDenysPetrov wrote:
> > How about using the family of `ProgramState::isNonNull` or 
> > `ProgramState::isNull` or `RangeConstraintManager::checkNull` functoins for 
> > this stuff?
> I've been checking this and turend out that `ProgramState::isNull` does not 
> modify the State (this is aligned with being a `const` member function). So, 
> these functions do not "assume" anything, they can be used only to query some 
> property of an SVal (or Symbol) from the State.
> 
> However, this comment and your other previous comment made me to do further 
> investigations towards exploiting the "assume" machinery better. The result 
> is a new child patch, where we can handle "adjustments" as well.
But I don't see you use the modified `State` in any way. Why it's important for 
you to change the `State`?




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110357

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


[PATCH] D112296: [Analyzer][solver] Handle adjustments in constraint assignor remainder

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



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1623
 if (!Constraint.containsZero()) {
-  State = RCM.assumeSymNE(State, LHS, Zero, Zero);
+  State = RCM.assumeSymRel(State, LHS, BO_NE, Zero);
   if (!State)

What I see, you're still trying to avoid using `State->assume`, which I 
recommend in a parent revision, but coming closer using its guts.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112296

___
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-25 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

In D106681#3083409 , @steakhal wrote:

> Sorry for blocking the review of this one for so long.

Thank you for the review!


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] D111985: [Clang] Add elementwise min/max builtins.

2021-10-25 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

ping :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111985

___
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-25 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1654
+  // 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)

steakhal wrote:
> If the return value of `getAnyInitializer()` is null, then the value of `VD` 
> will be actually preserved.
I'll add the comment before the load.


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] D112413: [X86] Add -mskip-rax-setup support to align with GCC

2021-10-25 Thread Joerg Sonnenberger via Phabricator via cfe-commits
joerg added inline comments.



Comment at: llvm/lib/Target/X86/X86ISelLowering.cpp:99
+cl::desc("Skips setting up the RAX register when SSE is disabled and there 
"
+ "are no variable arguments passed in vector registers."),
+cl::Hidden);

The description needs some further clarification. It should likely be "can be 
passed" otherwise it begs the question of when the conditional statement is 
false.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112413

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


[clang] 44e803e - [analyzer][NFCI] Move a block from `getBindingForElement` to separate functions

2021-10-25 Thread Denys Petrov via cfe-commits
Author: Denys Petrov
Date: 2021-10-25T15:14:10+03:00
New Revision: 44e803ef6d41770adf309960e37bcc6a75dbbe2c

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

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

Summary:
1. Improve readability by moving deeply nested block of code from 
RegionStoreManager::getBindingForElement to new separate functions:
- getConstantValFromConstArrayInitializer;
- getSValFromInitListExpr.
2. Handle the case when index is a symbolic value. Write specific test cases.
3. Add test cases when there is no initialization expression presented.
This patch implies to make next patches clearer and easier for review process.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp 
b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index 5e7352cc8756b..e0e6bca1e7cc3 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -437,6 +437,10 @@ class RegionStoreManager : public StoreManager {
 
   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 @@ 
RegionStoreManager::findLazyBinding(RegionBindingsConstRef B,
   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 = ptr[4];  // UB
+  //   int x5 = ptr[-1]; // UB
+  const llvm::APSInt &OffsetInt = OffsetVal->getValue();
+  const auto Offset = static_cast(OffsetInt.getExtValue());
+  // Use `getZExtValue` because array extent can not be negative.
+  const uint64_t Extent = CAT->getSize().getZExtValue();
+  // Check for `OffsetInt < 0` but NOT for `Offset < 0`, because `OffsetInt`
+  // CAN be negative, but `Offset` can NOT, because `Offset` is an uint64_t.
+  if (OffsetInt < 0 || Offset >= Extent)
+return UndefinedVal();
+  // From here `Offset` is in the bounds.
+
+  // Handle InitListExpr.
+  if (const auto *ILE = dyn_cast(Init))
+return getSValFromInitListExpr(ILE, Offset, R->getElementType());
+
+  // FIXME: Handle StringLiteral.
+
+  // FIXME: Handle CompoundLiteralExpr.
+
+  return None;
+}
+
+Optional
+RegionStoreManager::getSValFromInitListExpr(const InitListExpr *ILE,
+uint64_t Offset, QualType ElemT) {
+  assert(ILE && "InitListExpr should not be null");
+
+  // C

[clang] 3b1165b - [analyzer] Retrieve incomplete array extent from its redeclaration.

2021-10-25 Thread Denys Petrov via cfe-commits
Author: Denys Petrov
Date: 2021-10-25T15:14:10+03:00
New Revision: 3b1165ba3d15de83699be3ff4be3b6adf4d6e977

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

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

Summary: Fix a case when the extent can not be retrieved correctly from 
incomplete array declaration. Use redeclaration to get the array extent.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp 
b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
index e0e6bca1e7cc..5565e9cfd08c 100644
--- a/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RegionStore.cpp
@@ -1641,8 +1641,18 @@ Optional 
RegionStoreManager::getConstantValFromConstArrayInitializer(
   (!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`. If the return value of the function is null than `VD` won't be
+  // replaced.
+  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;
 

diff  --git a/clang/test/Analysis/initialization.c 
b/clang/test/Analysis/initialization.c
index 7981465394ea..9015113f8640 100644
--- a/clang/test/Analysis/initialization.c
+++ b/clang/test/Analysis/initialization.c
@@ -103,3 +103,42 @@ 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}}
 }
+
+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}}
+}



___
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-25 Thread Denys Petrov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG44e803ef6d41: [analyzer][NFCI] Move a block from 
`getBindingForElement` to separate functions (authored by ASDenysPetrov).

Repository:
  rG LLVM Github Monorepo

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 = ptr[4];  // UB
+  //   int x5 = ptr[-1]; // UB

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

2021-10-25 Thread Denys Petrov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3b1165ba3d15: [analyzer] Retrieve incomplete array extent 
from its redeclaration. (authored by ASDenysPetrov).

Changed prior to commit:
  https://reviews.llvm.org/D111542?vs=381252&id=381944#toc

Repository:
  rG LLVM Github Monorepo

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,18 @@
   (!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`. If the return value of the function is null than `VD` won't be
+  // replaced.
+  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}

[PATCH] D111654: [analyzer] Retrieve a value from list initialization of multi-dimensional array declaration.

2021-10-25 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

This is an important step towards better handling of global initializer 
expressions.
I'm looking forward to it. Although, I have concerns to address.




Comment at: clang/lib/AST/Type.cpp:141-143
+/// Return an array with extents of the declared array type.
+///
+/// E.g. for `const int x[1][2][3];` returns {1,2,3}.

These comments should be in the header file instead.



Comment at: clang/lib/AST/Type.cpp:149
+Extents.push_back(CAT->getSize().getZExtValue());
+  } while ((CAT = dyn_cast(CAT->getElementType(;
+  return Extents;

I suspect this not gonna look through typedefs.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1643-1654
+  const VarRegion *VR = dyn_cast(R->getSuperRegion());
+  SmallVector SValOffsets;
+  SValOffsets.push_back(R->getIndex());
+  if (const ElementRegion *ER = dyn_cast(R->getSuperRegion())) {
+const ElementRegion *LastER = nullptr;
+do {
+  SValOffsets.push_back(ER->getIndex());

I dislike this part of code. It has side effects all over the place.
Please use immediately called lambdas to describe your intentions in a more 
//pure// manner.

Besides that, when I see `ElementRegions`, I'm always scared. They sometimes 
represent reinterpret casts.
Since you have dealt with so many casts and region store stuff in the past, I'm 
assuming you have thought about this here.
Although, I'm still scared slightly, and I'd like to have evidence of this 
thought process. Likely some assertions or at least some comments? Could you 
@ASDenysPetrov elaborate on this?



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1728
+  // Reverse `SValOffsets` to make it consistent with `Extents`.
+  for (SVal &V : llvm::reverse(SValOffsets)) {
+if (auto CI = V.getAs()) {

I would rather take it by value. They are designed so.
A mutable reference is always a bad sign anyway.
BTW for a brief moment I thought `reverse()` returns a temporary, but it 
doesn't, so we don't dangle at least.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1734
+  // be negative, but `I` can NOT (because it's an uint64_t).
+  if (Offset < 0 || I >= *(ExtentIt++))
+return UndefinedVal();

Please use the `isNegative()`. And don't have sideffects in conditions. advance 
the iterator at the end of the `if`.
I also think you can eliminate the `I` variable.
That way the `getExtValue()` would be guarded by the negativity check. I know 
that your code would behave the same, but I would find that phrasing slightly 
easier to follow.
This way you could even spare the 2 comment lines.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1738
+  *(OffsetIt++) = I;
+} else
+  // Symbolic index presented. Return Unknown value.

This is probably a rare case when a `continue` is preferred instead of the 
`else` statement.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1777
 
-  // C++20 [dcl.init.string] 9.4.2.1:
-  //   An array of ordinary character type [...] can be initialized by [...]
-  //   an appropriately-typed string-literal enclosed in braces.
-  // Example:
-  //   const char arr[] = { "abc" };
-  if (ILE->isStringLiteralInit())
-if (const auto *SL = dyn_cast(ILE->getInit(0)))
-  return getSValFromStringLiteral(SL, Offset, ElemT);
-
-  // C++20 [expr.add] 9.4.17.5 (excerpt):
-  //   i-th array element is value-initialized for each k < i ≤ n,
-  //   where k is an expression-list size and n is an array extent.
-  if (Offset >= ILE->getNumInits())
-return svalBuilder.makeZeroVal(ElemT);
-
-  // Return a constant value, if it is presented.
-  // FIXME: Support other SVals.
-  const Expr *E = ILE->getInit(Offset);
-  return svalBuilder.getConstantVal(E);
+  for (auto Offset : ConcreteOffsets) {
+// C++20 [dcl.init.string] 9.4.2.1:

Just spell out `uint64_t` here. We don't win much by using `auto`.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1795-1800
+if (const auto *IL = dyn_cast(E))
+  ILE = IL;
+else
+  // Return a constant value, if it is presented.
+  // FIXME: Support other SVals.
+  return svalBuilder.getConstantVal(E);

Please, restructure this. Probably negating the condition and returning on that 
path would do the job.



Comment at: clang/test/Analysis/initialization.cpp:17-23
-int const arr[2][2] = {};
-void arr2init() {
-  int i = 1;
-  // FIXME: Should recognize that it is 0.
-  clang_analyzer_eval(arr[i][0]); // expected-warning{{UNKNOWN}}
-}
-

Sorry If I was misunderstood in the previous patches.
I think, for this instance, the key is that `arr` is `const`, so this TU is 
supposed to provide this linker symbol, thus any other definitions would 

[PATCH] D110065: [AArch64] Add support for the 'R' architecture profile.

2021-10-25 Thread John Brawn via Phabricator via cfe-commits
john.brawn accepted this revision.
john.brawn added a comment.
This revision is now accepted and ready to land.

I have one small comment, but otherwise LGTM.




Comment at: llvm/lib/Target/AArch64/MCTargetDesc/AArch64InstPrinter.cpp:1558
+
+  if (Reg && !isValidSysReg(Reg, Read, STI))
+Reg = AArch64SysReg::lookupSysRegByName(Reg->AltName);

It would be good to have a comment here explaining what's going on.


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

https://reviews.llvm.org/D110065

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


[PATCH] D111985: [Clang] Add elementwise min/max builtins.

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



Comment at: clang/include/clang/Sema/Sema.h:12715-12716
 
+  ExprResult SemaBuiltinElementwiseMath(CallExpr *TheCall,
+ExprResult CallResult);
+

Why oh why did we start slapping `Sema` as a prefix on a bunch 
of functions implemented in a class named `Sema`?



Comment at: clang/lib/Sema/SemaChecking.cpp:1981
 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
-
   case Builtin::BI__builtin_matrix_column_major_load:

Spurious whitespace change?



Comment at: clang/lib/Sema/SemaChecking.cpp:16659-16660
+// false.
+static bool checkMathBuiltinElementType(SourceLocation Loc, QualType Ty,
+Sema &S) {
+  if (!Ty->getAs() && !ConstantMatrixType::isValidElementType(Ty)) 
{

`Sema` typically comes first, so this is just to match local style.



Comment at: clang/lib/Sema/SemaChecking.cpp:16661
+Sema &S) {
+  if (!Ty->getAs() && !ConstantMatrixType::isValidElementType(Ty)) 
{
+S.Diag(Loc, diag::err_elementwise_math_invalid_arg_type) << Ty;

I'm a bit surprised we'd need `!Ty->getAs()` as I would have 
expected `!ConstantMatrixType::isValidElementType(Ty)` to cover all the type 
checking of `Ty`. Can you explain why the extra check is needed here?



Comment at: clang/lib/Sema/SemaChecking.cpp:16669
+ExprResult Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall,
+ExprResult CallResult) {
+  if (checkArgCount(*this, TheCall, 2))

Do we actually need this parameter?



Comment at: clang/lib/Sema/SemaChecking.cpp:16673-16678
+  Expr *A = TheCall->getArg(0);
+  Expr *B = TheCall->getArg(1);
+  QualType TyA = A->getType();
+  QualType TyB = B->getType();
+
+  if (TyA != TyB)

Should these arguments undergo usual conversions (array to pointer decay, 
integer promotions, etc)?



Comment at: clang/test/Sema/builtins-elementwise-math.c:20-21
+
+  i = __builtin_elementwise_max();
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 
0}}
+

Also:
```
i = __builtin_elementwise_max(i, i, i); // too many arguments
```



Comment at: clang/test/Sema/builtins-elementwise-math.c:42
+  // expected-error@-1 {{argument types do not match, 'float4' (vector of 4 
'float' values) != 'int3' (vector of 3 'int' values)}}
+}

Additional tests I would like to see:
```
int i;
short s;

__builtin_elementwise_min(i, s); // ok (integer promotions)?

enum e { one, two };
__builtin_elementwise_min(one, two); // ok (using enums)?

enum f { three };
__builtin_elementwise_min(one, three); // ok (different enums)?

_ExtInt(32) ext;
__builtin_elementwise_min(ext, ext); // ok (using bit-precise integers)?

const int ci;
__builtin_elementwise_min(i, ci); // ok (qualifiers don't match)?
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111985

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


[PATCH] D112101: [AST] Fix the EndLoc calculation for ObjCObjectPointer

2021-10-25 Thread Luke Petre via Phabricator via cfe-commits
lpetre created this revision.
lpetre updated this revision to Diff 381958.
lpetre added a comment.
lpetre updated this revision to Diff 381960.
lpetre retitled this revision from "Fix the EndLoc calculation for 
ObjCObjectPointer" to "[AST] Fix the EndLoc calculation for ObjCObjectPointer".
lpetre edited the summary of this revision.
lpetre added a reviewer: rsmith.
lpetre added a project: clang.
lpetre published this revision for review.
Herald added a subscriber: cfe-commits.

Updating diff with full commit range

My initial arc diff only picked up the final commit, now running for all commits


lpetre added a comment.

Trying again to include both commits


There is an issue where the AST code does not compute the correct SourceRange 
for a ObjCObjectPointer.

>From Richard Smith (ie @zygoloid) in discord:

> I think the problem is that we set an invalid location for the * (because 
> there isn't one): 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaType.cpp#L1121
> And then we use the default getLocalSourceRangeImpl for a PointerLikeTypeLoc 
> that just assumes the * location is the type's end location: 
> https://github.com/llvm/llvm-project/blob/main/clang/include/clang/AST/TypeLoc.h#L1293
> Possibly we should be special-casing that here: 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/TypeLoc.cpp#L228

My change:

- introduces a AST dump test to show the issue in the first commit
- special cases ObjCObjectPointerType in the second commit to correctly compute 
the end location


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112101

Files:
  clang/lib/AST/TypeLoc.cpp
  clang/test/AST/ast-dump-decl.mm


Index: clang/test/AST/ast-dump-decl.mm
===
--- clang/test/AST/ast-dump-decl.mm
+++ clang/test/AST/ast-dump-decl.mm
@@ -55,4 +55,11 @@
 // CHECK-NEXT:   CXXThisExpr {{.*}}  'Test *' this
   }
   void yada();
+  // CHECK:  CXXMethodDecl {{.*}}  col:8 used 
yada 'void ()'
 };
+
+@protocol P
+@end;
+
+using TestAlias = id;
+// CHECK:  TypeAliasDecl {{.+}} <{{.+}}:[[@LINE-1]]:1, col:23> col:7 
TestAlias 'id'
Index: clang/lib/AST/TypeLoc.cpp
===
--- clang/lib/AST/TypeLoc.cpp
+++ clang/lib/AST/TypeLoc.cpp
@@ -257,6 +257,7 @@
   if (!Last)
 Last = Cur;
   break;
+case ObjCObjectPointer:
 case Qualified:
 case Elaborated:
   break;


Index: clang/test/AST/ast-dump-decl.mm
===
--- clang/test/AST/ast-dump-decl.mm
+++ clang/test/AST/ast-dump-decl.mm
@@ -55,4 +55,11 @@
 // CHECK-NEXT:   CXXThisExpr {{.*}}  'Test *' this
   }
   void yada();
+  // CHECK:  CXXMethodDecl {{.*}}  col:8 used yada 'void ()'
 };
+
+@protocol P
+@end;
+
+using TestAlias = id;
+// CHECK:  TypeAliasDecl {{.+}} <{{.+}}:[[@LINE-1]]:1, col:23> col:7 TestAlias 'id'
Index: clang/lib/AST/TypeLoc.cpp
===
--- clang/lib/AST/TypeLoc.cpp
+++ clang/lib/AST/TypeLoc.cpp
@@ -257,6 +257,7 @@
   if (!Last)
 Last = Cur;
   break;
+case ObjCObjectPointer:
 case Qualified:
 case Elaborated:
   break;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 333c36b - [clang][unittests] Fix shared lib builds

2021-10-25 Thread Kadir Cetinkaya via cfe-commits
Author: Kadir Cetinkaya
Date: 2021-10-25T15:09:45+02:00
New Revision: 333c36bec09a954b59ceb01e21f1525f17530ec0

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

LOG: [clang][unittests] Fix shared lib builds

Added: 


Modified: 
clang/unittests/AST/CMakeLists.txt

Removed: 




diff  --git a/clang/unittests/AST/CMakeLists.txt 
b/clang/unittests/AST/CMakeLists.txt
index e33c74d7ce72..ab718d192024 100644
--- a/clang/unittests/AST/CMakeLists.txt
+++ b/clang/unittests/AST/CMakeLists.txt
@@ -39,6 +39,7 @@ clang_target_link_libraries(ASTTests
   clangASTMatchers
   clangBasic
   clangFrontend
+  clangLex
   clangSerialization
   clangTesting
   clangTooling



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


[PATCH] D112447: [clangd] IncludeCleaner: Support macros

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

Collect the macro definition locations for all the macros used in the main
file.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112447

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  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,16 @@
   "struct ^X { enum ^Language { ^CXX = 42, Python = 9000}; };",
   "int Lang = X::CXX;",
   },
+  // Macros
+  {
+  "#define ^CONSTANT 42",
+  "int Foo = CONSTANT;",
+  },
+  {
+  "#define ^FOO x",
+  "#define BAR FOO",
+  },
+  // Misc
   {
   // When a type is resolved via a using declaration, the
   // UsingShadowDecl is not referenced in the AST.
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -33,11 +33,13 @@
 using ReferencedLocations = llvm::DenseSet;
 /// Finds locations of all symbols used in the main file.
 ///
-/// Uses RecursiveASTVisitor to go through main file AST and computes all the
-/// locations used symbols are coming from. Returned locations may be macro
-/// expansions, and are not resolved to their spelling/expansion location. 
These
-/// locations are later used to determine which headers should be marked as
-/// "used" and "directly used".
+/// - For non-macros uses RecursiveASTVisitor to go through main file AST and
+///   computes all the locations used symbols are coming from. Returned
+///   locations may be macro expansions, and are not resolved to their spelling
+///   or expansion location. These locations are later used to determine which
+///   headers should /   be marked as "used" and "directly used".
+/// - For macros iteratates over \p AST tokens and collects locations of the
+///   used macro definition.
 ///
 /// We use this to compute unused headers, so we:
 ///
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -7,9 +7,11 @@
 
//===--===//
 
 #include "IncludeCleaner.h"
+#include "SourceCode.h"
 #include "support/Logger.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Tooling/Syntax/Tokens.h"
 
 namespace clang {
 namespace clangd {
@@ -133,13 +135,28 @@
   }
 };
 
+// Gets the tokens from the main file, iterates through them and adds 
definition
+// locations for the found macros.
+void findReferencedMacros(ParsedAST &AST, ReferencedLocations &Result) {
+  auto Tokens =
+  AST.getTokens().spelledTokens(AST.getSourceManager().getMainFileID());
+  for (const syntax::Token &Tok : Tokens) {
+auto Macro = locateMacroAt(Tok, AST.getPreprocessor());
+if (!Macro)
+  continue;
+auto Loc = Macro->Info->getDefinitionLoc();
+if (Loc.isValid())
+  Result.insert(Loc);
+  }
+}
+
 } // namespace
 
 ReferencedLocations findReferencedLocations(ParsedAST &AST) {
   ReferencedLocations Result;
   ReferencedLocationCrawler Crawler(Result);
   Crawler.TraverseAST(AST.getASTContext());
-  // FIXME(kirillbobyrev): Handle macros.
+  findReferencedMacros(AST, Result);
   return Result;
 }
 


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,16 @@
   "struct ^X { enum ^Language { ^CXX = 42, Python = 9000}; };",
   "int Lang = X::CXX;",
   },
+  // Macros
+  {
+  "#define ^CONSTANT 42",
+  "int Foo = CONSTANT;",
+  },
+  {
+  "#define ^FOO x",
+  "#define BAR FOO",
+  },
+  // Misc
   {
   // When a type is resolved via a using declaration, the
   // UsingShadowDecl is not referenced in the AST.
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -33,11 +33,13 @@
 using ReferencedLocations = llvm::DenseS

[PATCH] D109557: Adds a BlockIndent option to AlignAfterOpenBracket

2021-10-25 Thread Cameron Mulhern via Phabricator via cfe-commits
csmulhern updated this revision to Diff 381974.
csmulhern marked 2 inline comments as done.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109557

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/ContinuationIndenter.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
@@ -18539,6 +18539,8 @@
   FormatStyle::BAS_DontAlign);
   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
   FormatStyle::BAS_AlwaysBreak);
+  CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
+  FormatStyle::BAS_BlockIndent);
   // For backward compatibility:
   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
   FormatStyle::BAS_DontAlign);
@@ -22397,6 +22399,192 @@
   EXPECT_EQ(Code, format(Code, Style));
 }
 
+TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
+  auto Style = getLLVMStyle();
+
+  StringRef Short = "functionCall(paramA, paramB, paramC);\n"
+"void functionDecl(int a, int b, int c);";
+
+  StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
+ "paramF, paramG, paramH, paramI);\n"
+ "void functionDecl(int argumentA, int argumentB, int "
+ "argumentC, int argumentD, int argumentE);";
+
+  verifyFormat(Short, Style);
+
+  StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
+  "paramF, paramG, paramH,\n"
+  " paramI);\n"
+  "void functionDecl(int argumentA, int argumentB, int "
+  "argumentC, int argumentD,\n"
+  "  int argumentE);";
+
+  verifyFormat(NoBreak, Medium, Style);
+  verifyFormat(NoBreak,
+   "functionCall(\n"
+   "paramA,\n"
+   "paramB,\n"
+   "paramC,\n"
+   "paramD,\n"
+   "paramE,\n"
+   "paramF,\n"
+   "paramG,\n"
+   "paramH,\n"
+   "paramI\n"
+   ");\n"
+   "void functionDecl(\n"
+   "int argumentA,\n"
+   "int argumentB,\n"
+   "int argumentC,\n"
+   "int argumentD,\n"
+   "int argumentE\n"
+   ");",
+   Style);
+
+  verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
+   "  nestedLongFunctionCall(argument1, "
+   "argument2, argument3,\n"
+   " argument4, "
+   "argument5));",
+   Style);
+
+  Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
+  Style.AllowAllArgumentsOnNextLine = false;
+  Style.AllowAllConstructorInitializersOnNextLine = false;
+  Style.AllowAllParametersOfDeclarationOnNextLine = false;
+
+  verifyFormat(Short, Style);
+  verifyFormat(
+  "functionCall(\n"
+  "paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
+  "paramI\n"
+  ");\n"
+  "void functionDecl(\n"
+  "int argumentA, int argumentB, int argumentC, int argumentD, int "
+  "argumentE\n"
+  ");",
+  Medium, Style);
+
+  Style.BinPackArguments = false;
+  Style.BinPackParameters = false;
+
+  verifyFormat(Short, Style);
+
+  verifyFormat("functionCall(\n"
+   "paramA,\n"
+   "paramB,\n"
+   "paramC,\n"
+   "paramD,\n"
+   "paramE,\n"
+   "paramF,\n"
+   "paramG,\n"
+   "paramH,\n"
+   "paramI\n"
+   ");\n"
+   "void functionDecl(\n"
+   "int argumentA,\n"
+   "int argumentB,\n"
+   "int argumentC,\n"
+   "int argumentD,\n"
+   "int argumentE\n"
+   ");",
+   Medium, Style);
+
+  verifyFormat("outerFunctionCall(\n"
+   "nestedFunctionCall(argument1),\n"
+   "nestedLongFunctionCall(\n"
+   "argument1,\n"
+   "argument2,\n"
+   "argument3,\n"
+   "argument4,\n"
+   "argument5\n"
+   ")\n"
+   ");",
+   Style);
+
+  verifyFormat("int a = (int)b;", Style);
+  verifyFormat("int a = (int)b;",
+

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

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



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1757-1760
+  // FIXME: Nevertheless, we can't do the same for cases, like:
+  //   const char *str = "123"; // literal length is 4
+  //   char c = str[41];// offset is 41
+  // It should be properly handled before reaching this point.

martong wrote:
> Thanks for updating the patch! However, this `FIXME` makes me worried. Do you 
> think you could pass the `Decl` itself to `getSValFromInitListExpr` in order 
> to be able to check whether the type is a pointer or an array? 
This worried me as well. Currently I can't find a way to get the `Decl` for 
`SL`.



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] D111654: [analyzer] Retrieve a value from list initialization of multi-dimensional array declaration.

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



Comment at: clang/include/clang/AST/Type.h:2953
   const llvm::APInt &getSize() const { return Size; }
+  SmallVector getAllExtents() const;
   const Expr *getSizeExpr() const {

Could this be a free function (not a member function)? That way we could put it 
as an implementation detail of `RegionStore.cpp` and we could spare the timely 
review from the AST code owners.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:444-446
+  getSValFromInitListExpr(const InitListExpr *ILE,
+  const SmallVector &ConcreteOffsets,
+  QualType ElemT);

Could you please add docs to this function? Especially to `ConcreteOffsets` 
param.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1641-1654
+  // Treat an n-dimensional array. Get offsets from the expression,
+  // like `arr[4][2][1];`, `SValOffsets` should be {1, 2, 4};
+  const VarRegion *VR = dyn_cast(R->getSuperRegion());
+  SmallVector SValOffsets;
+  SValOffsets.push_back(R->getIndex());
+  if (const ElementRegion *ER = dyn_cast(R->getSuperRegion())) {
+const ElementRegion *LastER = nullptr;

I think this could be implemented in it's own separate function, couldn't it?



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1656
+
+  // TODO: Add a test case for this check.
+  if (!VR)

Please address this TODO.



Comment at: clang/lib/StaticAnalyzer/Core/RegionStore.cpp:1706-1743
+  // Check offsets 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:

Perhaps this hunk could be in an individual implementation function?



Comment at: clang/test/Analysis/initialization.c:76
   int x = 2, y = -2;
-  // FIXME: Should be UNDEFINED.
-  clang_analyzer_eval(glob_arr2[x][y] == 5); // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(glob_arr2[x][y] == 5); // expected-warning{{UNDEFINED}}
   x = 3;

Very good!


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

https://reviews.llvm.org/D111654

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


[PATCH] D112390: [AIX][ZOS] Disable tests due to lack of Objective-C support

2021-10-25 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan updated this revision to Diff 381979.
Jake-Egan added a comment.

Fixed objc_direct.ll


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112390

Files:
  clang/test/Modules/ModuleDebugInfo.cpp
  clang/test/Modules/ModuleDebugInfo.m
  clang/test/Modules/clang_module_file_info.m
  clang/test/Modules/debug-info-moduleimport-in-module.m
  clang/test/Modules/module-debuginfo-prefix.m
  llvm/test/DebugInfo/X86/objc_direct.ll


Index: llvm/test/DebugInfo/X86/objc_direct.ll
===
--- llvm/test/DebugInfo/X86/objc_direct.ll
+++ llvm/test/DebugInfo/X86/objc_direct.ll
@@ -1,3 +1,4 @@
+; UNSUPPORTED: -zos, -aix
 ; RUN: llc < %s -filetype=obj -o %t
 ; RUN: llvm-dwarfdump -v %t | FileCheck %s
 
Index: clang/test/Modules/module-debuginfo-prefix.m
===
--- clang/test/Modules/module-debuginfo-prefix.m
+++ clang/test/Modules/module-debuginfo-prefix.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // REQUIRES: asserts
 
 // Modules:
Index: clang/test/Modules/debug-info-moduleimport-in-module.m
===
--- clang/test/Modules/debug-info-moduleimport-in-module.m
+++ clang/test/Modules/debug-info-moduleimport-in-module.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that an @import inside a module is not represented in the debug info.
 
 // REQUIRES: asserts
Index: clang/test/Modules/clang_module_file_info.m
===
--- clang/test/Modules/clang_module_file_info.m
+++ clang/test/Modules/clang_module_file_info.m
@@ -1,4 +1,4 @@
-
+// UNSUPPORTED: -zos, -aix
 @import DependsOnModule;
 
 // RUN: rm -rf %t %t-obj
Index: clang/test/Modules/ModuleDebugInfo.m
===
--- clang/test/Modules/ModuleDebugInfo.m
+++ clang/test/Modules/ModuleDebugInfo.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that debug info is emitted for an Objective-C module and
 // a precompiled header.
 
Index: clang/test/Modules/ModuleDebugInfo.cpp
===
--- clang/test/Modules/ModuleDebugInfo.cpp
+++ clang/test/Modules/ModuleDebugInfo.cpp
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that (the same) debug info is emitted for an Objective-C++
 // module and a C++ precompiled header.
 


Index: llvm/test/DebugInfo/X86/objc_direct.ll
===
--- llvm/test/DebugInfo/X86/objc_direct.ll
+++ llvm/test/DebugInfo/X86/objc_direct.ll
@@ -1,3 +1,4 @@
+; UNSUPPORTED: -zos, -aix
 ; RUN: llc < %s -filetype=obj -o %t
 ; RUN: llvm-dwarfdump -v %t | FileCheck %s
 
Index: clang/test/Modules/module-debuginfo-prefix.m
===
--- clang/test/Modules/module-debuginfo-prefix.m
+++ clang/test/Modules/module-debuginfo-prefix.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // REQUIRES: asserts
 
 // Modules:
Index: clang/test/Modules/debug-info-moduleimport-in-module.m
===
--- clang/test/Modules/debug-info-moduleimport-in-module.m
+++ clang/test/Modules/debug-info-moduleimport-in-module.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that an @import inside a module is not represented in the debug info.
 
 // REQUIRES: asserts
Index: clang/test/Modules/clang_module_file_info.m
===
--- clang/test/Modules/clang_module_file_info.m
+++ clang/test/Modules/clang_module_file_info.m
@@ -1,4 +1,4 @@
-
+// UNSUPPORTED: -zos, -aix
 @import DependsOnModule;
 
 // RUN: rm -rf %t %t-obj
Index: clang/test/Modules/ModuleDebugInfo.m
===
--- clang/test/Modules/ModuleDebugInfo.m
+++ clang/test/Modules/ModuleDebugInfo.m
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that debug info is emitted for an Objective-C module and
 // a precompiled header.
 
Index: clang/test/Modules/ModuleDebugInfo.cpp
===
--- clang/test/Modules/ModuleDebugInfo.cpp
+++ clang/test/Modules/ModuleDebugInfo.cpp
@@ -1,3 +1,4 @@
+// UNSUPPORTED: -zos, -aix
 // Test that (the same) debug info is emitted for an Objective-C++
 // module and a C++ precompiled header.
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D112296: [Analyzer][solver] Handle adjustments in constraint assignor remainder

2021-10-25 Thread Gabor Marton via Phabricator via cfe-commits
martong marked an inline comment as done.
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1623
 if (!Constraint.containsZero()) {
-  State = RCM.assumeSymNE(State, LHS, Zero, Zero);
+  State = RCM.assumeSymRel(State, LHS, BO_NE, Zero);
   if (!State)

ASDenysPetrov wrote:
> What I see, you're still trying to avoid using `State->assume`, which I 
> recommend in a parent revision, but coming closer using its guts.
So, it would look like this:
```
State = State->assume(Builder.makeSymbolVal(LHS).castAs(), 
true);
```
The main  reason why we cannot use `State->assume` is that it boils down to 
`RangedConstraintManager::assumeSym` that has a specific logic for the 
`boolean` assumption. I.e. the operator is being negated in a case:
```
if (BinaryOperator::isComparisonOp(op) && op != BO_Cmp) {
  if (!Assumption)
op = BinaryOperator::negateComparisonOp(op);

  return assumeSymRel(State, SIE->getLHS(), op, SIE->getRHS());
}
```
You can try it for yourself, and see that the test case added in this patch 
will not pass if we were to use `State->assume`. Essentially, we have to evade 
the special "bool" logic, and the closest we can get is using `assumeSymRel`.

Besides that, by using `State->assume` we would have a superfluous conversion 
chain `Symbol->SVal->Symbol` until we reach `assumeSymRel`. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112296

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


[PATCH] D112235: [HIP][OpenMP] Fix assertion in deferred diag due to incomplete class definition

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



Comment at: clang/test/OpenMP/deferred-diags.cpp:40
+// Test deleting object with incomplete class definition does not causing
+// assertion.
+namespace TestDeleteIncompleteClassDefinition {

rjmccall wrote:
> "Test that deleting an incomplete class type doesn't cause an assertion."
will do when committing


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

https://reviews.llvm.org/D112235

___
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-25 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:38
   bool VisitTagType(TagType *TT) {
+// For enumerations we will require only the definition if it's present and
+// the underlying type is not specified.

I don't understand this special case.
It seems you're trying to avoid requiring too many redecls of a referenced 
type. Why is this important, and different from e.g. Class?



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:93
 
+  // Require redeclarations only for definitions and only when the underlying
+  // type is specified.

This says what, rather than why.

Rather maybe:
``` 
Enums may be usefully forward-declared as *complete* types by specifying an 
underlying type.
In this case, the definition should see the declaration so they can be checked 
for compatibility.
```



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:96
+  bool VisitEnumDecl(EnumDecl *D) {
+if (D != D->getDefinition() || !D->getIntegerTypeSourceInfo())
+  return false;

D->isThisDeclarationADefinition() is more idiomatic for the first part



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:98
+  return false;
+for (const auto *Redecl : D->redecls())
+  Result.insert(Redecl->getLocation());

rather add(D) here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112209

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


[PATCH] D112453: [Sema] When dereferencing a pointer of dependent type, infer the result type.

2021-10-25 Thread Clement Courbet via Phabricator via cfe-commits
courbet created this revision.
courbet added reviewers: rsmith, aaron.ballman.
courbet requested review of this revision.
Herald added a project: clang.

Example:

  template  auto f(T* t) {
return *t;
  }

Before that change, the `UnaryOperator` for `*t` has type ``.
After the change, its type is a `T` lvalue.

I've added simple tests to verify that giving knowledge of the type to clang
does not yields false positives in contexts where c++ does not allow it to use
that knowledge.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D112453

Files:
  clang/lib/Sema/SemaOverload.cpp
  clang/test/SemaTemplate/dependent-type-identity.cpp


Index: clang/test/SemaTemplate/dependent-type-identity.cpp
===
--- clang/test/SemaTemplate/dependent-type-identity.cpp
+++ clang/test/SemaTemplate/dependent-type-identity.cpp
@@ -69,6 +69,16 @@
   void f8(typename N::X2::template apply *);
   void f8(typename N::X2::template apply *);
   void f8(typename ::Nalias::X2::template apply *); // 
expected-error{{redeclar}}
+
+  // (17.4.2): If an expression e is type-dependent (17.6.2.2), decltype(e)
+  // denotes a unique dependent type. Two such decltype-specifiers refer to the
+  // same type only if their expressions are equivalent (17.5.6.1)
+  T* a;
+  T* b;
+  using V = decltype(*a);
+  void f9(decltype(*a)); // expected-note{{previous}}
+  void f9(decltype(*b));
+  void f9(V); // expected-error{{redeclar}}
 };
 
 namespace PR6851 {
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -13323,10 +13323,22 @@
   ArrayRef ArgsArray(Args, NumArgs);
 
   if (Input->isTypeDependent()) {
-if (Fns.empty())
-  return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
-   VK_PRValue, OK_Ordinary, OpLoc, false,
+if (Fns.empty()) {
+  QualType ResultTy = Context.DependentTy;
+  ExprValueKind ResultKind = VK_PRValue;
+  if (getLangOpts().CPlusPlus && (Opc == UO_Deref) &&
+  Input->getType()->isPointerType()) {
+// In c++, a deref of a `T*` always has type `T&` (16.6.8). There is no
+// way for other overloads to be selected since overloads of 
`operator*`
+// always have class or enum parameters.
+ResultTy = cast(Input->getType().getCanonicalType())
+   ->getPointeeType();
+ResultKind = VK_LValue;
+  }
+  return UnaryOperator::Create(Context, Input, Opc, ResultTy, ResultKind,
+   OK_Ordinary, OpLoc, false,
CurFPFeatureOverrides());
+}
 
 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
 ExprResult Fn = CreateUnresolvedLookupExpr(


Index: clang/test/SemaTemplate/dependent-type-identity.cpp
===
--- clang/test/SemaTemplate/dependent-type-identity.cpp
+++ clang/test/SemaTemplate/dependent-type-identity.cpp
@@ -69,6 +69,16 @@
   void f8(typename N::X2::template apply *);
   void f8(typename N::X2::template apply *);
   void f8(typename ::Nalias::X2::template apply *); // expected-error{{redeclar}}
+
+  // (17.4.2): If an expression e is type-dependent (17.6.2.2), decltype(e)
+  // denotes a unique dependent type. Two such decltype-specifiers refer to the
+  // same type only if their expressions are equivalent (17.5.6.1)
+  T* a;
+  T* b;
+  using V = decltype(*a);
+  void f9(decltype(*a)); // expected-note{{previous}}
+  void f9(decltype(*b));
+  void f9(V); // expected-error{{redeclar}}
 };
 
 namespace PR6851 {
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -13323,10 +13323,22 @@
   ArrayRef ArgsArray(Args, NumArgs);
 
   if (Input->isTypeDependent()) {
-if (Fns.empty())
-  return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy,
-   VK_PRValue, OK_Ordinary, OpLoc, false,
+if (Fns.empty()) {
+  QualType ResultTy = Context.DependentTy;
+  ExprValueKind ResultKind = VK_PRValue;
+  if (getLangOpts().CPlusPlus && (Opc == UO_Deref) &&
+  Input->getType()->isPointerType()) {
+// In c++, a deref of a `T*` always has type `T&` (16.6.8). There is no
+// way for other overloads to be selected since overloads of `operator*`
+// always have class or enum parameters.
+ResultTy = cast(Input->getType().getCanonicalType())
+   ->getPointeeType();
+ResultKind = VK_LValue;
+  }
+  return UnaryOperator::Create(Context, Input, Opc, ResultTy, ResultKind,
+   OK_Ordinary, OpLoc, false,
CurFPFeatureOverr

[PATCH] D110357: [Analyzer] Extend ConstraintAssignor to handle remainder op

2021-10-25 Thread Gabor Marton via Phabricator via cfe-commits
martong marked 6 inline comments as done.
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1619-1620
+const SymbolRef LHS = Sym->getLHS();
+const llvm::APSInt &Zero =
+Builder.getBasicValueFactory().getValue(0, Sym->getType());
+// a % b != 0 implies that a != 0.

ASDenysPetrov wrote:
> Howerver, put this line inside //if-body// below, since `Zero` isn't needed 
> wherever else.
Thanks, that is correct. I am going to address this in the child patch.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1618-1627
+const SymbolRef LHS = Sym->getLHS();
+const llvm::APSInt &Zero =
+Builder.getBasicValueFactory().getValue(0, Sym->getType());
+// a % b != 0 implies that a != 0.
+if (!Constraint.containsZero()) {
+  State = RCM.assumeSymNE(State, LHS, Zero, Zero);
+  if (!State)

ASDenysPetrov wrote:
> martong wrote:
> > ASDenysPetrov wrote:
> > > How about using the family of `ProgramState::isNonNull` or 
> > > `ProgramState::isNull` or `RangeConstraintManager::checkNull` functoins 
> > > for this stuff?
> > I've been checking this and turend out that `ProgramState::isNull` does not 
> > modify the State (this is aligned with being a `const` member function). 
> > So, these functions do not "assume" anything, they can be used only to 
> > query some property of an SVal (or Symbol) from the State.
> > 
> > However, this comment and your other previous comment made me to do further 
> > investigations towards exploiting the "assume" machinery better. The result 
> > is a new child patch, where we can handle "adjustments" as well.
> But I don't see you use the modified `State` in any way. Why it's important 
> for you to change the `State`?
> 
> 
> But I don't see you use the modified `State` in any way. 

Actually, we do use it. The `State` we overwrite here is the member of the 
class `ConstraintAssignor`, it is not a local variable.

> Why it's important for you to change the `State`?

It is important, because we'd like to assign new information to the existing 
things we know (i.e. to the State). So, once we see a modulo then we can defer 
some extra constraints and that is done via the `ConstraintAssignor`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110357

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


  1   2   >