[PATCH] D157201: [Clang] Support qualified name as member designator in offsetof

2023-08-10 Thread Yichi Lee via Phabricator via cfe-commits
yichi170 added inline comments.



Comment at: clang/test/SemaCXX/offsetof.cpp:106
+int x3[__builtin_offsetof(struct X2, X2::static_a) == 0 ? 1 : -1]; // 
expected-error{{no member named 'static_a'}}
+int x4[__builtin_offsetof(struct X2, X2::X2) == 0 ? 1 : -1]; // 
expected-error{{no member named 'X2'}}
+

hubert.reinterpretcast wrote:
> aaron.ballman wrote:
> > yichi170 wrote:
> > > aaron.ballman wrote:
> > > > There's one more test I'd like to see:
> > > > ```
> > > > struct S {
> > > >   int Foo;
> > > > };
> > > > 
> > > > template 
> > > > void func() {
> > > >   static_assert(__builtin_offsetof(Ty, Ty::Foo) == 0, "");
> > > > }
> > > > 
> > > > void inst() {
> > > >   func();
> > > > }
> > > > ```
> > > It would get the compile error in the current patch, but I think it 
> > > should be compiled without any error, right?
> > Correct, that should be accepted: https://godbolt.org/z/1f6a9Yaxa
> Should expect this to pass too:
> ```
> template 
> struct Z {
>   static_assert(!__builtin_offsetof(T, template Q::x));
> };
> 
> struct A {
>   template  using Q = T;
>   int x;
> };
> 
> Z za;
> ```
Wow. Does it mean we cannot simply parse the identifier, `::`, `.` and brackets 
in `__builtin_offsetof`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157201

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


[PATCH] D156858: Add Documentation for Execution Results Handling in Clang-REPL

2023-08-10 Thread Krishna Narayanan via Phabricator via cfe-commits
Krishna-13-cyber updated this revision to Diff 549034.
Krishna-13-cyber added a comment.

- Address the comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156858

Files:
  clang/docs/ClangRepl.rst
  clang/docs/autoprint.png
  clang/docs/prettyprint.png
  clang/docs/valuesynth.png

Index: clang/docs/ClangRepl.rst
===
--- clang/docs/ClangRepl.rst
+++ clang/docs/ClangRepl.rst
@@ -215,6 +215,319 @@
 automatic language interoperability. It also helps static languages such as C/C++ become
 apt for data science.
 
+Execution Results Handling in Clang-Repl
+
+
+Execution Results Handling features discussed below help extend the Clang-REPL 
+functionality by creating an interface between the execution results of a 
+program and the compiled program.
+
+1. **Capture Execution Results**: This feature helps capture the execution results 
+of a program and bring them back to the compiled program.
+
+2. **Dump Captured Execution Results**: This feature helps create a temporary dump 
+for Value Printing/Automatic Printf, that is, to display the value and type of 
+the captured data. 
+
+
+1. Capture Execution Results
+
+
+In many cases, it is useful to bring back the program execution result to the 
+compiled program. This result can be stored in an object of type **Value**.
+
+How Execution Results are captured (Value Synthesis):
+-
+
+The synthesizer chooses which expression to synthesize, and then it replaces 
+the original expression with the synthesized expression. Depending on the 
+expression type, it may choose to save an object (``LastValue``) of type 'value'
+while allocating memory to it (``SetValueWithAlloc()``), or not (
+``SetValueNoAlloc()``).
+
+.. image:: valuesynth.png
+   :align: center
+   :alt: valuesynth design
+
+Where is the captured result stored?
+
+
+``LastValue`` holds the last result of the value printing. It is a class member 
+because it can be accessed even after subsequent inputs. 
+
+**Note:** If no value printing happens, then it is in an invalid state. 
+
+Improving Efficiency and User Experience
+
+
+The Value object is essentially used to create a mapping between an expression 
+'type' and the 'memory' to be allocated. Built-in types (bool, char, int, 
+float, double, etc.) are simpler, since their memory allocation size is known. 
+In case of objects, a pointer can be saved, since the size of the object is 
+not known.
+
+For further improvement, the underlying Clang Type is also identified. For 
+example, ``X(char, Char_S)``, where ``Char_S`` is the Clang type. Clang types are 
+very efficient, which is important since these will be used in hotspots (high 
+utilization areas of the program). The ``Value.h`` header file has a very low 
+token count and was developed with strict constraints in mind, since it can 
+affect the performance of the interpreter.
+
+This also enables the user to receive the computed 'type' back in their code 
+and then transform the type into something else (e.g., transform a double into 
+a float). Normally, the compiler can handle these conversions transparently, 
+but in interpreter mode, the compiler cannot see all the 'from' and 'to' types,
+so it cannot implicitly do the conversions. So this logic enables providing 
+these conversions on request. 
+
+On-request conversions can help improve the user experience, by allowing 
+conversion to a desired 'to' type, when the 'from' type is unknown or unclear
+
+Significance of this Feature
+
+
+The 'Value' object enables wrapping a memory region that comes from the 
+JIT, and bringing it back to the compiled code (and vice versa). 
+This is a very useful functionality when:
+
+- connecting an interpreter to the compiled code, or
+- connecting an interpreter in another language.
+
+For example, the CPPYY code makes use of this feature to enable running 
+C++ within Python. It enables transporting values/information between C++ 
+and Python.
+
+In a nutshell, this feature enables a new way of developing code, paving the 
+way for language interoperability and easier interactive programming.
+
+Implementation Details
+==
+
+Interpreter as a REPL vs. as a Library
+--
+
+1 - If we're using the interpreter in interactive (REPL) mode, it will dump 
+the value (i.e., value printing).
+
+.. code-block:: console
+
+  if (LastValue.isValid()) {
+if (!V) {
+  LastValue.dump();
+  LastValue.clear();
+} else
+  *V = std::move(LastValue);
+  }
+
+
+2 - If we're using the interpreter as a library, then it will pass the value 
+to the user.
+
+Incremental AST Consumer
+-

[PATCH] D157485: [X86][RFC] Support new feature AVX10

2023-08-10 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: clang/lib/Basic/Targets/X86.h:99
+  bool HasAVX10_1 = false;
+  bool HasAVX10_512BIT = false;
   bool HasAVX512CD = false;

goldstein.w.n wrote:
> Maybe should be HasAVX10_1_512? As brought up the rfc, there might be an 
> avx10.2-512
> 
> Likewise elsewhere, or is this to match GCC?
No. `HasAVX10_512BIT` is a single feature which can be combined with 
`HasAVX10_1`, `HasAVX10_2` etc.
AFAIK, GCC chooses the similar idea here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157485

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


[PATCH] D157201: [Clang] Support qualified name as member designator in offsetof

2023-08-10 Thread Yichi Lee via Phabricator via cfe-commits
yichi170 added a comment.

Is there any code handling the nested qualifier that I can reference? I tried 
to modify the `OffsetOfNode`, which allows me to handle the basic template case 
but still failed on the nested case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157201

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


[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-10 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Thanks for the updates, more comments inline. Also:

> The remarks printed miss carets.

Why and can you share an example?

> The parseOptimizationRemark, addDiagnosticArgs and printDiagnosticOptions 
> functions created are identical to the ones used in Clang.

In which case we should seriously consider moving this code somewhere where it 
can be shared. If outside the scope of this change, please document in code 
that there's scope for re-use.




Comment at: flang/include/flang/Frontend/CodeGenOptions.h:72-118
+  enum class RemarkKind {
+RK_Missing,// Remark argument not present on the command line.
+RK_Enabled,// Remark enabled via '-Rgroup'.
+RK_EnabledEverything,  // Remark enabled via '-Reverything'.
+RK_Disabled,   // Remark disabled via '-Rno-group'.
+RK_DisabledEverything, // Remark disabled via '-Rno-everything'.
+RK_WithPattern,// Remark pattern specified via '-Rgroup=regexp'.

From what I can see, this has been borrowed almost verbatim from Clang: 
https://github.com/llvm/llvm-project/blob/3a100ea901ed79d6a06a5f018be2b4d3bbca51e8/clang/include/clang/Basic/CodeGenOptions.h#L331-L376.

This is fine (and common throughout the driver), but please document more. In 
particular:
* Highlight that ATM this code is identical that what Clang contains (and add a 
`TODO` to perhaps share with Clang at some point),
* Highlight that the list of options in Flang and Clang is _identical - it is 
really good that the interfaces in Clang and Flang are consistent. That's a 
good reason to re-use the logic from Clang.





Comment at: flang/lib/Frontend/CompilerInvocation.cpp:156-158
+/// Parse a remark command line argument. It may be missing, disabled/enabled 
by
+/// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
+/// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.

Could you give an example (and write a test ) for `-Rgroup=regexp`. Also, 
@kiranchandramohan , is this form actually needed? I am thinking that it's a 
complexity that could be avoided. It  could definitely simplify this patch.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:786
   parseShowColorsArgs(args, /*defaultDiagColor=*/false);
+  res.getDiagnosticOpts().ShowColors = res.getFrontendOpts().showColors;
 

victorkingi wrote:
> Apparently without forwarding the color option to the CompilerInvocation, 
> flang doesn't print remark errors with color. Hence the need for this.
> Also, a question, why do we have 2 instances of DiagnosticsEngine, one in 
> CompilerInvocation and the other passed as an argument?
> Apparently without forwarding the color option to the CompilerInvocation, 
> flang doesn't print remark errors with color. Hence the need for this.

It is already "forwarded" here: 
https://github.com/llvm/llvm-project/blob/3a100ea901ed79d6a06a5f018be2b4d3bbca51e8/flang/lib/Frontend/CompilerInvocation.cpp#L117-L122.
 Could you explain why you need this change _here_?

> Also, a question, why do we have 2 instances of DiagnosticsEngine, one in 
> CompilerInvocation and the other passed as an argument?

[[ 
https://github.com/llvm/llvm-project/blob/3a100ea901ed79d6a06a5f018be2b4d3bbca51e8/flang/tools/flang-driver/fc1_main.cpp#L37-L40
 | One  ]] is for the driver itself, to generate diagnostics related to "driver 
errors" (e.g. option parsing errors). The [[ 
https://github.com/llvm/llvm-project/blob/3a100ea901ed79d6a06a5f018be2b4d3bbca51e8/flang/include/flang/Frontend/CompilerInstance.h#L64-L65
 | other ]] belongs to `CompilerInstance` rather than `CompilerInvocation` and 
is used to report compilation errors (e.g. semantic or parsing errors). 



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:1070
   }
 
+  addDiagnosticArgs(args, clang::driver::options::OPT_R_Group,

Is this specifically for parsing remarks options? Please add a comment



Comment at: flang/lib/Frontend/FrontendActions.cpp:927
 
+class StandaloneBackendConsumer : public llvm::DiagnosticHandler {
+

Why `StandaloneBackendConsumer`? Isn't this specifically for remarks? Also, 
could you document this class a bit?



Comment at: flang/lib/Frontend/TextDiagnosticPrinter.cpp:37
+// Print any diagnostic option information to a raw_ostream.
+static void printDiagnosticOptions(llvm::raw_ostream &os,
+   clang::DiagnosticsEngine::Level level,

Why is this method needed and can it be tested?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[PATCH] D152436: [clang][analyzer] Move checker alpha.unix.StdCLibraryFunctions out of alpha.

2023-08-10 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

About the questions:

- How many issues does it raise? Would we flood the user?

I did not experience that the checker produces many warnings. Any warning from 
this checker is connected to a function call of a standard API, and the number 
of such calls is usually not high. Typically one 
problem which the checker reports can occur often in a specific program, for 
example the `fileno` case (fileno returns -1 at failure, often this failure is 
not handled and value -1 is used as a file number). 
This should not be a case of hundreds of warnings.

- How "interesting" those issues are? Do they have *actual* value for the user? 
(Not only niece edge-cases, that is fancy to know about, but actual users would 
genuinely commit such mistakes)

If the coder cares about all edge-cases of API calls, these are real and 
important issues. More often most of the results are just cases of ignored 
errors that are very rare, the programmer probably intentionally did not handle 
these because it is not worth for a such rare situation. From security point of 
view these cases can be used to find places where it is possible to make an API 
call (which normally "never" fails) intentionally fail and produce unexpected 
behavior of the program. So for an average application many results are not 
very important, for stability and security critical code the results can be 
more important.

- How long those bug-paths are in practice? I'd argue, the longer they are, 
usually the less actionable they are for the user. Less actionable reports are 
also less valuable, or even harmful.

The bug path can be long, often only the very last part is important, but 
sometimes not.

- In general, how understandable these reports are? Do we have all the 
interesting "notes" or "events" on the path?

These should be not more difficult to understand than a division by zero, only 
with a function call instead of division.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152436

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


[PATCH] D140828: [C++] Implement "Deducing this" (P0847R7)

2023-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:7280
+  "a %select{function|lambda}0 with an explicit object parameter cannot "
+  "%select{be const|be mutable|have reference qualifiers|be volatile}1">;
+def err_invalid_explicit_object_type_in_lambda: Error<

cor3ntin wrote:
> aaron.ballman wrote:
> > cor3ntin wrote:
> > > aaron.ballman wrote:
> > > > I think you're missing `restrict` here as well. Perhaps this is a case 
> > > > where it's better to diagnose the qualifiers generically and rely on 
> > > > the diagnostic's source range? e.g., `cannot have qualifiers` instead 
> > > > of the current %1 selection. This also works around weird with things 
> > > > like `void func() const &;` where it has multiple qualifiers.
> > > Forming a source range to the qualifiers may be challenging though.
> > > 
> > > In what case would `restrict` come into play?
> > > 
> > > ```
> > > struct test {
> > > void f() restrict;
> > > };
> > > ```
> > > does not seem valid, I'm assuming  it is in some language mode?
> > Ah, it's spelled `__restrict` in C++ mode, but we also support other 
> > qualifiers like `_Nonnull` as well. I left some examples in other comments 
> > that should demonstrate this.
> Maybe we need a way to compute the range of all qualifiers. I'll look into 
> that - I'm not sure the information exists atm.
> SourceLocation objects are ordered, right?
Correct, source locations are ordered; you can use 
`SourceManager::isBeforeInTranslationUnit()` to compare orderings within the 
same TU.



Comment at: clang/lib/Parse/ParseTentative.cpp:1563
+  case tok::kw_this: {
+if (getLangOpts().CPlusPlus) {
+  RevertingTentativeParsingAction PA(*this);

cor3ntin wrote:
> aaron.ballman wrote:
> > Should this be checking for CPlusPlus23 instead?
> Nope, again we don't want to produce terrible error messages!
Thanks for confirming; I thought that was the case. I think it's fine because 
it won't impact any valid code (I was momentarily worried this would change 
parsing behavior in older language modes, but it won't).



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:14924
 
-  // Builds the "this" pointer.
-  ThisBuilder This;
+  // Builds the function object parameter
+  std::optional This;





Comment at: clang/lib/Sema/SemaDeclCXX.cpp:15299
 
-  // Builds the "this" pointer.
-  ThisBuilder This;
+  // Builds the function object parameter
+  std::optional This;

There is so much code duplication in here... it'd be nice to 
unify the copy and move assign functionality as much as we can.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:15436-15437
   if (!Invalid) {
 // Add a "return *this;"
-ExprResult ThisObj =
-CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
+// Add a "return *this;"
+Expr *ThisExpr = (ExplicitObject ? (ExprBuilder &)*ExplicitObject

It's important to know what's happening here, but not so important you need to 
repeat it. ;-)



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:18171
 
+bool Sema::CheckOverridingExplicitObjectMembers(CXXMethodDecl *New,
+const CXXMethodDecl *Old) {

This function name feels off to me; would it make more sense as 
`DiagnoseExplicitObjectOverride()` or something along those lines? It's not 
really doing a general check, just checking one specific property.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:18174
+  // CWG2553
+  // A virtual function shall not be an explicit object member function
+  if (!New->isExplicitObjectMemberFunction())





Comment at: clang/lib/Sema/SemaDeclCXX.cpp:8419-8420
 ExprResult LHS;
-if (isa(FD)) {
+if (auto *MD = dyn_cast(FD);
+MD && MD->isImplicitObjectMemberFunction()) {
   // LHS is '*this'.

cor3ntin wrote:
> aaron.ballman wrote:
> > I'm seeing this pattern enough that I wonder if it makes sense to add a 
> > member function to `FunctionDecl` just to do this dance for us? It'd be a 
> > bit weird because `FunctionDecl` is never a member function, but we have 
> > some helper functionality already related to member functions in the class 
> > (`isOutOfLine()` and `getInstantiatedFromMemberFunction()` come to mind).
> It might be weird because a FunctionDecl might be neither explicit, not 
> implicit, nor static... knowing it's not explicit is only useful in the 
> places we look at it in this PR basically.
> Or we'd need some `enum { NonMember, Static, Implicit, Explicit }` to cover 
> our bases, but I'm not sure it would be worth it.
Okay, let's hold off on changes for now then.



Comment at: clang/lib/Sema/SemaExceptionSpec.cpp:899
+const PartialDiagnostic &DiagID, const PartialDiagnostic &NoteID,
+

[PATCH] D157201: [Clang] Support qualified name as member designator in offsetof

2023-08-10 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/test/SemaCXX/offsetof.cpp:106
+int x3[__builtin_offsetof(struct X2, X2::static_a) == 0 ? 1 : -1]; // 
expected-error{{no member named 'static_a'}}
+int x4[__builtin_offsetof(struct X2, X2::X2) == 0 ? 1 : -1]; // 
expected-error{{no member named 'X2'}}
+

yichi170 wrote:
> hubert.reinterpretcast wrote:
> > aaron.ballman wrote:
> > > yichi170 wrote:
> > > > aaron.ballman wrote:
> > > > > There's one more test I'd like to see:
> > > > > ```
> > > > > struct S {
> > > > >   int Foo;
> > > > > };
> > > > > 
> > > > > template 
> > > > > void func() {
> > > > >   static_assert(__builtin_offsetof(Ty, Ty::Foo) == 0, "");
> > > > > }
> > > > > 
> > > > > void inst() {
> > > > >   func();
> > > > > }
> > > > > ```
> > > > It would get the compile error in the current patch, but I think it 
> > > > should be compiled without any error, right?
> > > Correct, that should be accepted: https://godbolt.org/z/1f6a9Yaxa
> > Should expect this to pass too:
> > ```
> > template 
> > struct Z {
> >   static_assert(!__builtin_offsetof(T, template Q::x));
> > };
> > 
> > struct A {
> >   template  using Q = T;
> >   int x;
> > };
> > 
> > Z za;
> > ```
> Wow. Does it mean we cannot simply parse the identifier, `::`, `.` and 
> brackets in `__builtin_offsetof`?
GCC seems to support that. 

We probably want to call `ParseOptionalCXXScopeSpecifier` and store the 
`NestedNameSpecifierLoc` we'd get from it (and then parse the (sequence of) 
identifier(s) corresponding to the member) as we do now.

The documentation of 
https://gcc.gnu.org/onlinedocs/gcc-13.2.0/gcc/Offsetof.html#index-_005f_005fbuiltin_005foffsetof
 
seems inaccurate,

it seems to be

`"__builtin_offsetof" "(" typename ","  nested-name-specifier 
offsetof_member_designator ")"`


Note that you will have to take care of transforming the nested name in 
TreeTransform and handle type dependencies. Let me know if you have further 
questions,
it's more involved than what you signed for. Sorry for not spotting that 
earlier (Thanks @hubert.reinterpretcast !)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157201

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


[PATCH] D157201: [Clang] Support qualified name as member designator in offsetof

2023-08-10 Thread Yichi Lee via Phabricator via cfe-commits
yichi170 added inline comments.



Comment at: clang/test/SemaCXX/offsetof.cpp:106
+int x3[__builtin_offsetof(struct X2, X2::static_a) == 0 ? 1 : -1]; // 
expected-error{{no member named 'static_a'}}
+int x4[__builtin_offsetof(struct X2, X2::X2) == 0 ? 1 : -1]; // 
expected-error{{no member named 'X2'}}
+

cor3ntin wrote:
> yichi170 wrote:
> > hubert.reinterpretcast wrote:
> > > aaron.ballman wrote:
> > > > yichi170 wrote:
> > > > > aaron.ballman wrote:
> > > > > > There's one more test I'd like to see:
> > > > > > ```
> > > > > > struct S {
> > > > > >   int Foo;
> > > > > > };
> > > > > > 
> > > > > > template 
> > > > > > void func() {
> > > > > >   static_assert(__builtin_offsetof(Ty, Ty::Foo) == 0, "");
> > > > > > }
> > > > > > 
> > > > > > void inst() {
> > > > > >   func();
> > > > > > }
> > > > > > ```
> > > > > It would get the compile error in the current patch, but I think it 
> > > > > should be compiled without any error, right?
> > > > Correct, that should be accepted: https://godbolt.org/z/1f6a9Yaxa
> > > Should expect this to pass too:
> > > ```
> > > template 
> > > struct Z {
> > >   static_assert(!__builtin_offsetof(T, template Q::x));
> > > };
> > > 
> > > struct A {
> > >   template  using Q = T;
> > >   int x;
> > > };
> > > 
> > > Z za;
> > > ```
> > Wow. Does it mean we cannot simply parse the identifier, `::`, `.` and 
> > brackets in `__builtin_offsetof`?
> GCC seems to support that. 
> 
> We probably want to call `ParseOptionalCXXScopeSpecifier` and store the 
> `NestedNameSpecifierLoc` we'd get from it (and then parse the (sequence of) 
> identifier(s) corresponding to the member) as we do now.
> 
> The documentation of 
> https://gcc.gnu.org/onlinedocs/gcc-13.2.0/gcc/Offsetof.html#index-_005f_005fbuiltin_005foffsetof
>  
> seems inaccurate,
> 
> it seems to be
> 
> `"__builtin_offsetof" "(" typename ","  nested-name-specifier 
> offsetof_member_designator ")"`
> 
> 
> Note that you will have to take care of transforming the nested name in 
> TreeTransform and handle type dependencies. Let me know if you have further 
> questions,
> it's more involved than what you signed for. Sorry for not spotting that 
> earlier (Thanks @hubert.reinterpretcast !)
Thank you for all the help! I'll take a look at it!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157201

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


[PATCH] D157566: [SEH] fix assertion when -fasy-exceptions is used.

2023-08-10 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei accepted this revision.
pengfei added a comment.
This revision is now accepted and ready to land.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157566

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


[PATCH] D140828: [C++] Implement "Deducing this" (P0847R7)

2023-08-10 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin marked 9 inline comments as done.
cor3ntin added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:7280
+  "a %select{function|lambda}0 with an explicit object parameter cannot "
+  "%select{be const|be mutable|have reference qualifiers|be volatile}1">;
+def err_invalid_explicit_object_type_in_lambda: Error<

aaron.ballman wrote:
> cor3ntin wrote:
> > aaron.ballman wrote:
> > > cor3ntin wrote:
> > > > aaron.ballman wrote:
> > > > > I think you're missing `restrict` here as well. Perhaps this is a 
> > > > > case where it's better to diagnose the qualifiers generically and 
> > > > > rely on the diagnostic's source range? e.g., `cannot have qualifiers` 
> > > > > instead of the current %1 selection. This also works around weird 
> > > > > with things like `void func() const &;` where it has multiple 
> > > > > qualifiers.
> > > > Forming a source range to the qualifiers may be challenging though.
> > > > 
> > > > In what case would `restrict` come into play?
> > > > 
> > > > ```
> > > > struct test {
> > > > void f() restrict;
> > > > };
> > > > ```
> > > > does not seem valid, I'm assuming  it is in some language mode?
> > > Ah, it's spelled `__restrict` in C++ mode, but we also support other 
> > > qualifiers like `_Nonnull` as well. I left some examples in other 
> > > comments that should demonstrate this.
> > Maybe we need a way to compute the range of all qualifiers. I'll look into 
> > that - I'm not sure the information exists atm.
> > SourceLocation objects are ordered, right?
> Correct, source locations are ordered; you can use 
> `SourceManager::isBeforeInTranslationUnit()` to compare orderings within the 
> same TU.
Thanks! I ended up using a different approach though


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140828

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


[PATCH] D141757: [clangd] allow extracting to variable for lambda expressions

2023-08-10 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

I promise I haven't forgotten about this. It's just been a challenge finding a 
large enough chunk of time to page in all the relevant context and think 
through the issues. Maybe this weekend...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141757

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


[PATCH] D157610: [include-cleaner][clangd][clang-tidy] Ignore resource dir during include-cleaner analysis.

2023-08-10 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clang-tidy/misc/IncludeCleanerCheck.cpp:122
   llvm::DenseSet SeenSymbols;
+  std::string ResourceDir = HS->getHeaderSearchOpts().ResourceDir;
   // FIXME: Find a way to have less code duplication between include-cleaner

let's use `HS->getModuleMap().getBuiltinDir()` then we can get away with just 
comparing that pointer to `H.physical()->getLastRef().getDir()` (same applies 
to all the other places as well)



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:309
   continue;
+auto Dir = llvm::StringRef{MFI.Resolved}.rsplit('/').first;
+if (Dir == AST.getPreprocessor()

let's move this into `mayConsiderUnused`, we also convert this include into a 
FileEntry in there, so we can directly compare the directory agian.



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:579-580
+  auto TU = TestTU::withCode(R"cpp(
+#include "resources/amintrin.h"
+#include "resources/imintrin.h"
+void baz() {

can you rather include these as ``



Comment at: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp:587-588
+  TU.ExtraArgs.push_back(testPath("resources"));
+  TU.AdditionalFiles["resources/amintrin.h"] = "";
+   TU.AdditionalFiles["resources/imintrin.h"] = guard(R"cpp(
+#include "emintrin.h"

we should put these under `resources/include/.h`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157610

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


[PATCH] D153536: [Clang] Implement P2169 A nice placeholder with no name

2023-08-10 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

In D153536#4576683 , @aaron.ballman 
wrote:

> In D153536#4571435 , @vitalybuka 
> wrote:
>
>>> Thanks! We might need someone from clangd to help here. The logs do not 
>>> have any information explaining what's failing with the test, and looking 
>>> at the test code, I struggle to see how these changes would impact that 
>>> test. We've had some significant issues with flaky clangd tests 
>>> (https://github.com/clangd/clangd/issues/1712), so it's possible this is 
>>> happenstance.
>>
>> I tried to debug that, and it looks like false Asan report. Maybe a bug in 
>> FakeStack::GC related code.
>
> Thank you for looking into it! I came to the same general conclusion; and it 
> seems the impacted bot has gone back to green in the meantime: 
> https://lab.llvm.org/buildbot/#/builders/168/builds/15031 so hopefully we're 
> in good shape.

Yes. Fixed by D157552 . It's amusing to see 
this unrelated patch exposing ~10 years old bug, which was never reported 
before.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153536

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


[PATCH] D157114: [clang][ASTImporter] Improve StructuralEquivalence algorithm on repeated friends

2023-08-10 Thread Ding Fei via Phabricator via cfe-commits
danix800 updated this revision to Diff 549059.
danix800 added a comment.

`CXXRecordDecl::friend_iterator` is actually a reversed iterator. Deduplication 
with
different iterator direction produces different result. ASTImporter uses 
forward iterator
so structural equivalence checking should be in consistent with that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157114

Files:
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/ASTStructuralEquivalence.cpp
  clang/unittests/AST/ASTImporterTest.cpp
  clang/unittests/AST/StructuralEquivalenceTest.cpp

Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -833,7 +833,18 @@
   auto t = makeNamedDecls("struct foo { friend class X; };",
   "struct foo { friend class X; friend class X; };",
   Lang_CXX11);
-  EXPECT_FALSE(testStructuralMatch(t));
+  EXPECT_TRUE(testStructuralMatch(t));
+}
+
+TEST_F(StructuralEquivalenceRecordTest,
+   SameFriendMultipleTimesForwardIteratorDirection) {
+  // Deduplication with forward iterator produces the same 'foo', but reverse
+  // iterator doesn't.
+  auto t = makeNamedDecls(
+  "struct foo { friend class X; friend class Y;};",
+  "struct foo { friend class X; friend class Y; friend class X; };",
+  Lang_CXX11);
+  EXPECT_TRUE(testStructuralMatch(t));
 }
 
 TEST_F(StructuralEquivalenceRecordTest, SameFriendsDifferentOrder) {
Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -10,6 +10,7 @@
 //
 //===--===//
 
+#include "clang/AST/ASTStructuralEquivalence.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
 #include "llvm/ADT/StringMap.h"
@@ -4385,6 +4386,44 @@
   EXPECT_EQ(ToFriend2, ToImportedFriend2);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase, ImportRepeatedFriendDeclIntoEmptyDC) {
+  Decl *From, *To;
+  std::tie(From, To) = getImportedDecl(R"(
+  template 
+  class A {
+  public:
+template  friend A &f();
+template  friend A &f();
+  };
+  )",
+   Lang_CXX17, "", Lang_CXX17, "A");
+
+  auto *FromFriend1 = FirstDeclMatcher().match(From, friendDecl());
+  auto *FromFriend2 = LastDeclMatcher().match(From, friendDecl());
+  auto *ToFriend1 = FirstDeclMatcher().match(To, friendDecl());
+  auto *ToFriend2 = LastDeclMatcher().match(To, friendDecl());
+
+  // Two different FriendDecls in From context.
+  EXPECT_TRUE(FromFriend1 != FromFriend2);
+  // Only one is imported into empty DC.
+  EXPECT_TRUE(ToFriend1 == ToFriend2);
+
+  // 'A' is imported into empty DC, keeping structure equivalence.
+  llvm::DenseSet> NonEquivalentDecls01;
+  llvm::DenseSet> NonEquivalentDecls10;
+  StructuralEquivalenceContext Ctx01(
+  From->getASTContext(), To->getASTContext(), NonEquivalentDecls01,
+  StructuralEquivalenceKind::Default, false, false);
+  StructuralEquivalenceContext Ctx10(
+  To->getASTContext(), From->getASTContext(), NonEquivalentDecls10,
+  StructuralEquivalenceKind::Default, false, false);
+
+  bool Eq01 = Ctx01.IsEquivalent(From, To);
+  bool Eq10 = Ctx10.IsEquivalent(To, From);
+  EXPECT_EQ(Eq01, Eq10);
+  EXPECT_TRUE(Eq01);
+}
+
 TEST_P(ASTImporterOptionSpecificTestBase, FriendFunInClassTemplate) {
   auto *Code = R"(
   template 
Index: clang/lib/AST/ASTStructuralEquivalence.cpp
===
--- clang/lib/AST/ASTStructuralEquivalence.cpp
+++ clang/lib/AST/ASTStructuralEquivalence.cpp
@@ -1464,6 +1464,165 @@
   return IsStructurallyEquivalent(GetName(D1), GetName(D2));
 }
 
+static bool
+IsCXXRecordBaseStructurallyEquivalent(StructuralEquivalenceContext &Context,
+  RecordDecl *D1, RecordDecl *D2) {
+  auto *D1CXX = cast(D1);
+  auto *D2CXX = cast(D2);
+
+  if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
+if (Context.Complain) {
+  Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic(
+   diag::err_odr_tag_type_inconsistent))
+  << Context.ToCtx.getTypeDeclType(D2);
+  Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
+  << D2CXX->getNumBases();
+  Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
+  << D1CXX->getNumBases();
+}
+return false;
+  }
+
+  for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
+  BaseEnd1 = D1CXX->bases_end(),
+  Base2 

[PATCH] D155858: Add a concept AST node.

2023-08-10 Thread Jens Massberg via Phabricator via cfe-commits
massberg updated this revision to Diff 549066.
massberg marked an inline comment as done.
massberg added a comment.
Herald added a reviewer: jdoerfert.
Herald added subscribers: jplehr, sstefan1.

Only call `AddConceptReference` if there is a concept reference.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155858

Files:
  clang/include/clang/AST/ASTConcept.h
  clang/include/clang/AST/DeclTemplate.h
  clang/include/clang/AST/ExprConcepts.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/TypeLoc.h
  clang/include/clang/Serialization/ASTRecordReader.h
  clang/include/clang/Serialization/ASTRecordWriter.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/AST/ExprConcepts.cpp
  clang/lib/AST/TypeLoc.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaType.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTReaderStmt.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/lib/Serialization/ASTWriterStmt.cpp
  clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp

Index: clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp
===
--- clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp
+++ clang/unittests/Tooling/RecursiveASTVisitorTests/Concept.cpp
@@ -29,12 +29,22 @@
 ++ConceptRequirementsTraversed;
 return ExpectedLocationVisitor::TraverseConceptRequirement(R);
   }
+  bool TraverseConceptReference(const ConceptReference *CR) {
+++ConceptReferencesTraversed;
+return ExpectedLocationVisitor::TraverseConceptReference(CR);
+  }
+  bool VisitConceptReference(const ConceptReference *CR) {
+++ConceptReferencesVisited;
+return true;
+  }
 
   bool shouldVisitImplicitCode() { return ShouldVisitImplicitCode; }
 
   int ConceptSpecializationExprsVisited = 0;
   int TypeConstraintsTraversed = 0;
   int ConceptRequirementsTraversed = 0;
+  int ConceptReferencesTraversed = 0;
+  int ConceptReferencesVisited = 0;
   bool ShouldVisitImplicitCode = false;
 };
 
@@ -50,6 +60,8 @@
   EXPECT_EQ(1, Visitor.ConceptSpecializationExprsVisited);
   // Also check we traversed the TypeConstraint that produced the expr.
   EXPECT_EQ(1, Visitor.TypeConstraintsTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesVisited);
 
   Visitor = {}; // Don't visit implicit code now.
   EXPECT_TRUE(Visitor.runOver("template  concept Fooable = true;\n"
@@ -59,6 +71,8 @@
   // generated immediately declared expression.
   EXPECT_EQ(0, Visitor.ConceptSpecializationExprsVisited);
   EXPECT_EQ(1, Visitor.TypeConstraintsTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesVisited);
 
   Visitor = {};
   EXPECT_TRUE(Visitor.runOver("template  concept A = true;\n"
@@ -70,6 +84,8 @@
   "};",
   ConceptVisitor::Lang_CXX2a));
   EXPECT_EQ(3, Visitor.ConceptRequirementsTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesTraversed);
+  EXPECT_EQ(1, Visitor.ConceptReferencesVisited);
 }
 
 struct VisitDeclOnlyOnce : ExpectedLocationVisitor {
@@ -86,6 +102,10 @@
 ++AutoTypeLocVisited;
 return true;
   }
+  bool VisitConceptReference(const ConceptReference *) {
+++ConceptReferencesVisited;
+return true;
+  }
 
   bool TraverseVarDecl(VarDecl *V) {
 // The base traversal visits only the `TypeLoc`.
@@ -99,6 +119,7 @@
   int ConceptDeclsVisited = 0;
   int AutoTypeVisited = 0;
   int AutoTypeLocVisited = 0;
+  int ConceptReferencesVisited = 0;
 };
 
 TEST(RecursiveASTVisitor, ConceptDeclInAutoType) {
@@ -111,6 +132,7 @@
   EXPECT_EQ(1, Visitor.AutoTypeVisited);
   EXPECT_EQ(1, Visitor.AutoTypeLocVisited);
   EXPECT_EQ(1, Visitor.ConceptDeclsVisited);
+  EXPECT_EQ(1, Visitor.ConceptReferencesVisited);
 }
 
 } // end anonymous namespace
Index: clang/lib/Serialization/ASTWriterStmt.cpp
===
--- clang/lib/Serialization/ASTWriterStmt.cpp
+++ clang/lib/Serialization/ASTWriterStmt.cpp
@@ -11,15 +11,16 @@
 ///
 //===--===//
 
-#include "clang/AST/ExprOpenMP.h"
-#include "clang/Serialization/ASTRecordWriter.h"
-#include "clang/Sema/DeclSpec.h"
+#include "clang/AST/ASTConcept.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/ExprOpenMP.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Lex/Token.h"
+#include "clang/Sema/DeclSpec.h"
+#include "clang/Serialization/ASTRecordWriter.h"
 #include "

[PATCH] D140828: [C++] Implement "Deducing this" (P0847R7)

2023-08-10 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:18171
 
+bool Sema::CheckOverridingExplicitObjectMembers(CXXMethodDecl *New,
+const CXXMethodDecl *Old) {

aaron.ballman wrote:
> This function name feels off to me; would it make more sense as 
> `DiagnoseExplicitObjectOverride()` or something along those lines? It's not 
> really doing a general check, just checking one specific property.
I don't disagree but it is consistent with other function in the vicinity

CheckOverridingFunctionAttributes
CheckOverridingFunctionReturnType
CheckPureMethod





Comment at: clang/lib/Sema/SemaExpr.cpp:20550-20554
+static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
+Sema &SemaRef, ValueDecl *D, Expr *E) {
+  DeclRefExpr *ID = dyn_cast(E);
+  if (!ID || ID->isTypeDependent())
+return;

aaron.ballman wrote:
> 
ID is used later in the function



Comment at: clang/lib/Sema/SemaExprCXX.cpp:4330-4331
+ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn);
+if (Res.isInvalid())
+  return ExprError();
 

aaron.ballman wrote:
> Do you have test coverage for this change or is it an NFC change?
Before this patch `FixOverloadedFunctionReference` would never fail, now it 
can, in some places. I think it is covered by tests but I'll double check. The 
change here is mechanical, the important changes are in 
`FixOverloadedFunctionReference`



Comment at: clang/lib/Sema/SemaLambda.cpp:393-394
+  CXXRecordDecl *RD = Method->getParent();
+  if (Method->isDependentContext())
+return;
+  if (RD->getLambdaCaptureDefault() == LambdaCaptureDefault::LCD_None &&

aaron.ballman wrote:
> Do we care that the method is a dependent context? I thought we'd be checking 
> if the method itself is dependent?
How would you do that through its type?



Comment at: clang/lib/Sema/SemaOverload.cpp:1299-1300
+
+// We do not allow overloading based off of '__restrict'.
+Q.removeRestrict();
+

aaron.ballman wrote:
> Just restrict? So `_Nonnull` is fine?
Good question. This was pre-existing code though. I'll think about it more


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140828

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


[PATCH] D157632: [Profile] Allow online merging with debug info correlation.

2023-08-10 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu created this revision.
zequanwu added reviewers: ellis, MaskRay, davidxl.
Herald added subscribers: Enna1, ormris.
Herald added a project: All.
zequanwu requested review of this revision.
Herald added projects: clang, Sanitizers.
Herald added subscribers: Sanitizers, cfe-commits.

When using debug info correlation, value profiling needs to be switched off.
So, we are only merging counter sections. In that case the existance of data
section is just used to provide an extra check in case of corrupted profile.

This patch performs counter merging by iterating the counter section by counter
size and add them together.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157632

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  compiler-rt/lib/profile/InstrProfilingMerge.c
  compiler-rt/test/profile/Darwin/instrprof-debug-info-correlate.c
  compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c

Index: compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
===
--- compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
+++ compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
@@ -24,3 +24,19 @@
 // RUN: llvm-profdata merge -o %t.cov.normal.profdata %t.cov.profraw
 
 // RUN: diff <(llvm-profdata show %t.cov.normal.profdata) <(llvm-profdata show %t.cov.profdata)
+
+// Test debug info correlate with online merging.
+
+// RUN: rm -rf %t.profdir && mkdir %t.profdir
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm --disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp %S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t %t.profdir/
+
+// RUN: diff <(llvm-profdata show %t.normal.profdata) <(llvm-profdata show %t.profdata)
+
+// RUN: rm -rf %t.profdir && mkdir %t.profdir
+// RUN: %clang_pgogen -o %t.cov -g -mllvm --debug-info-correlate -mllvm -pgo-function-entry-coverage -mllvm --disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp %S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.cov.proflite %run %t.cov
+// RUN: llvm-profdata merge -o %t.cov.profdata --debug-info=%t.cov %t.profdir/
+
+// RUN: diff <(llvm-profdata show %t.cov.normal.profdata) <(llvm-profdata show %t.cov.profdata)
Index: compiler-rt/test/profile/Darwin/instrprof-debug-info-correlate.c
===
--- compiler-rt/test/profile/Darwin/instrprof-debug-info-correlate.c
+++ compiler-rt/test/profile/Darwin/instrprof-debug-info-correlate.c
@@ -18,3 +18,19 @@
 // RUN: llvm-profdata merge -o %t.cov.normal.profdata %t.cov.profraw
 
 // RUN: diff %t.cov.normal.profdata %t.cov.profdata
+
+// Test debug info correlate with online merging.
+
+// RUN: rm -rf %t.profdir && mkdir %t.profdir
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm --disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp %S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t.dSYM %t.profdir/
+
+// RUN: diff %t.normal.profdata %t.profdata
+
+// RUN: rm -rf %t.profdir && mkdir %t.profdir
+// RUN: %clang_pgogen -o %t.cov -g -mllvm --debug-info-correlate -mllvm -pgo-function-entry-coverage -mllvm --disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp %S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.cov.proflite %run %t.cov
+// RUN: llvm-profdata merge -o %t.cov.profdata --debug-info=%t.cov.dSYM %t.profdir/
+
+// RUN: diff %t.cov.normal.profdata %t.cov.profdata
Index: compiler-rt/lib/profile/InstrProfilingMerge.c
===
--- compiler-rt/lib/profile/InstrProfilingMerge.c
+++ compiler-rt/lib/profile/InstrProfilingMerge.c
@@ -1,3 +1,4 @@
+#include "/tmp/debug.h"
 /*===- InstrProfilingMerge.c - Profile in-process Merging  ---===*\
 |*
 |* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
@@ -11,6 +12,7 @@
 
 #include "InstrProfiling.h"
 #include "InstrProfilingInternal.h"
+#include "InstrProfilingPort.h"
 #include "InstrProfilingUtil.h"
 
 #define INSTR_PROF_VALUE_PROF_DATA
@@ -102,17 +104,10 @@
 COMPILER_RT_VISIBILITY
 int __llvm_profile_merge_from_buffer(const char *ProfileData,
  uint64_t ProfileSize) {
-  if (__llvm_profile_get_version() & VARIANT_MASK_DBG_CORRELATE) {
-PROF_ERR(
-"%s\n",
-"Debug info correlation does not support profile merging at runtime. "
-"Instead, merge raw profiles using the llvm-profdata tool.");
-return 1;
-  }
-
   __llvm_profile_data *SrcDataStart, *SrcDataEnd, *SrcData, *DstData;
   __llvm_profile_header *Hea

[PATCH] D157632: [Profile] Allow online merging with debug info correlation.

2023-08-10 Thread Zequan Wu via Phabricator via cfe-commits
zequanwu updated this revision to Diff 549077.
zequanwu added a comment.

Remove debug includes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157632

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  compiler-rt/lib/profile/InstrProfilingMerge.c
  compiler-rt/test/profile/Darwin/instrprof-debug-info-correlate.c
  compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c

Index: compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
===
--- compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
+++ compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c
@@ -24,3 +24,19 @@
 // RUN: llvm-profdata merge -o %t.cov.normal.profdata %t.cov.profraw
 
 // RUN: diff <(llvm-profdata show %t.cov.normal.profdata) <(llvm-profdata show %t.cov.profdata)
+
+// Test debug info correlate with online merging.
+
+// RUN: rm -rf %t.profdir && mkdir %t.profdir
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm --disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp %S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t %t.profdir/
+
+// RUN: diff <(llvm-profdata show %t.normal.profdata) <(llvm-profdata show %t.profdata)
+
+// RUN: rm -rf %t.profdir && mkdir %t.profdir
+// RUN: %clang_pgogen -o %t.cov -g -mllvm --debug-info-correlate -mllvm -pgo-function-entry-coverage -mllvm --disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp %S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.cov.proflite %run %t.cov
+// RUN: llvm-profdata merge -o %t.cov.profdata --debug-info=%t.cov %t.profdir/
+
+// RUN: diff <(llvm-profdata show %t.cov.normal.profdata) <(llvm-profdata show %t.cov.profdata)
Index: compiler-rt/test/profile/Darwin/instrprof-debug-info-correlate.c
===
--- compiler-rt/test/profile/Darwin/instrprof-debug-info-correlate.c
+++ compiler-rt/test/profile/Darwin/instrprof-debug-info-correlate.c
@@ -18,3 +18,19 @@
 // RUN: llvm-profdata merge -o %t.cov.normal.profdata %t.cov.profraw
 
 // RUN: diff %t.cov.normal.profdata %t.cov.profdata
+
+// Test debug info correlate with online merging.
+
+// RUN: rm -rf %t.profdir && mkdir %t.profdir
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm --disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp %S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t.dSYM %t.profdir/
+
+// RUN: diff %t.normal.profdata %t.profdata
+
+// RUN: rm -rf %t.profdir && mkdir %t.profdir
+// RUN: %clang_pgogen -o %t.cov -g -mllvm --debug-info-correlate -mllvm -pgo-function-entry-coverage -mllvm --disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp %S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.cov.proflite %run %t.cov
+// RUN: llvm-profdata merge -o %t.cov.profdata --debug-info=%t.cov.dSYM %t.profdir/
+
+// RUN: diff %t.cov.normal.profdata %t.cov.profdata
Index: compiler-rt/lib/profile/InstrProfilingMerge.c
===
--- compiler-rt/lib/profile/InstrProfilingMerge.c
+++ compiler-rt/lib/profile/InstrProfilingMerge.c
@@ -102,17 +102,10 @@
 COMPILER_RT_VISIBILITY
 int __llvm_profile_merge_from_buffer(const char *ProfileData,
  uint64_t ProfileSize) {
-  if (__llvm_profile_get_version() & VARIANT_MASK_DBG_CORRELATE) {
-PROF_ERR(
-"%s\n",
-"Debug info correlation does not support profile merging at runtime. "
-"Instead, merge raw profiles using the llvm-profdata tool.");
-return 1;
-  }
-
   __llvm_profile_data *SrcDataStart, *SrcDataEnd, *SrcData, *DstData;
   __llvm_profile_header *Header = (__llvm_profile_header *)ProfileData;
-  char *SrcCountersStart;
+  char *SrcCountersStart, *DstCounter;
+  const char *SrcCountersEnd, *SrcCounter;
   const char *SrcNameStart;
   const char *SrcValueProfDataStart, *SrcValueProfData;
   uintptr_t CountersDelta = Header->CountersDelta;
@@ -122,14 +115,36 @@
   Header->BinaryIdsSize);
   SrcDataEnd = SrcDataStart + Header->DataSize;
   SrcCountersStart = (char *)SrcDataEnd;
-  SrcNameStart = SrcCountersStart +
- Header->CountersSize * __llvm_profile_counter_entry_size();
+  SrcCountersEnd = SrcCountersStart +
+ Header->CountersSize * __llvm_profile_counter_entry_size(); 
+  SrcNameStart = SrcCountersEnd;
   SrcValueProfDataStart =
   SrcNameStart + Header->NamesSize +
   __llvm_profile_get_num_padding_bytes(Header->NamesSize);
   i

[PATCH] D140828: [C++] Implement "Deducing this" (P0847R7)

2023-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:18171
 
+bool Sema::CheckOverridingExplicitObjectMembers(CXXMethodDecl *New,
+const CXXMethodDecl *Old) {

cor3ntin wrote:
> aaron.ballman wrote:
> > This function name feels off to me; would it make more sense as 
> > `DiagnoseExplicitObjectOverride()` or something along those lines? It's not 
> > really doing a general check, just checking one specific property.
> I don't disagree but it is consistent with other function in the vicinity
> 
> CheckOverridingFunctionAttributes
> CheckOverridingFunctionReturnType
> CheckPureMethod
> 
> 
Okay, then how about `CheckExplicitObjectOverride`?



Comment at: clang/lib/Sema/SemaLambda.cpp:393-394
+  CXXRecordDecl *RD = Method->getParent();
+  if (Method->isDependentContext())
+return;
+  if (RD->getLambdaCaptureDefault() == LambdaCaptureDefault::LCD_None &&

cor3ntin wrote:
> aaron.ballman wrote:
> > Do we care that the method is a dependent context? I thought we'd be 
> > checking if the method itself is dependent?
> How would you do that through its type?
`Method->getType()->isDependentType()` should suffice, no?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140828

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


[clang] 5aa06b1 - [libclang] Expose arguments of clang::annotate

2023-08-10 Thread Aaron Ballman via cfe-commits

Author: fridtjof
Date: 2023-08-10T12:40:23-04:00
New Revision: 5aa06b18940c9b96cbf1c31da6aee3fbb92183ed

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

LOG: [libclang] Expose arguments of clang::annotate

This enables easy consumption of arbitrary data added
to this annotation in addition to the annotation category,
which was already exposed.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/CursorVisitor.h
clang/unittests/libclang/LibclangTest.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e8533f071e0754..8fa0c14b9ed0c3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -245,6 +245,8 @@ clang-format
 libclang
 
 
+- Exposed arguments of ``clang::annotate``.
+
 Static Analyzer
 ---
 

diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 1bdc0bf742a8ce..ca9467eb1ac23e 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -23,6 +23,7 @@
 #include "CursorVisitor.h"
 #include "clang-c/FatalErrorHandler.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/AttrVisitor.h"
 #include "clang/AST/DeclObjCCommon.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
@@ -575,6 +576,13 @@ bool CursorVisitor::VisitChildren(CXCursor Cursor) {
   A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
   }
 
+  if (clang_isAttribute(Cursor.kind)) {
+if (const Attr *A = getCursorAttr(Cursor))
+  return Visit(A);
+
+return false;
+  }
+
   // If pointing inside a macro definition, check if the token is an identifier
   // that was ever defined as a macro. In such a case, create a "pseudo" macro
   // expansion cursor for that token.
@@ -2089,7 +2097,8 @@ class MemberRefVisit : public VisitorJob {
 (SourceLocation::UIntTy)(uintptr_t)data[1]);
   }
 };
-class EnqueueVisitor : public ConstStmtVisitor {
+class EnqueueVisitor : public ConstStmtVisitor,
+   public ConstAttrVisitor {
   friend class OMPClauseEnqueue;
   VisitorWorkList &WL;
   CXCursor Parent;
@@ -2231,6 +2240,9 @@ class EnqueueVisitor : public 
ConstStmtVisitor {
   void VisitOMPTargetTeamsDistributeSimdDirective(
   const OMPTargetTeamsDistributeSimdDirective *D);
 
+  // Attributes
+  void VisitAnnotateAttr(const AnnotateAttr *A);
+
 private:
   void AddDeclarationNameInfo(const Stmt *S);
   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
@@ -2242,6 +2254,7 @@ class EnqueueVisitor : public 
ConstStmtVisitor {
   void AddTypeLoc(TypeSourceInfo *TI);
   void EnqueueChildren(const Stmt *S);
   void EnqueueChildren(const OMPClause *S);
+  void EnqueueChildren(const AnnotateAttr *A);
 };
 } // namespace
 
@@ -2736,6 +2749,20 @@ void EnqueueVisitor::EnqueueChildren(const OMPClause *S) 
{
   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
   std::reverse(I, E);
 }
+
+void EnqueueVisitor::EnqueueChildren(const AnnotateAttr *A) {
+  unsigned size = WL.size();
+  for (const Expr *Arg : A->args()) {
+VisitStmt(Arg);
+  }
+  if (size == WL.size())
+return;
+  // Now reverse the entries we just added.  This will match the DFS
+  // ordering performed by the worklist.
+  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
+  std::reverse(I, E);
+}
+
 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
   WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
 }
@@ -3008,7 +3035,7 @@ void EnqueueVisitor::VisitOpaqueValueExpr(const 
OpaqueValueExpr *E) {
   // If the opaque value has a source expression, just transparently
   // visit that.  This is useful for (e.g.) pseudo-object expressions.
   if (Expr *SourceExpr = E->getSourceExpr())
-return Visit(SourceExpr);
+return ConstStmtVisitor::Visit(SourceExpr);
 }
 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
   AddStmt(E->getBody());
@@ -3028,7 +3055,7 @@ void EnqueueVisitor::VisitCXXParenListInitExpr(const 
CXXParenListInitExpr *E) {
 }
 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
   // Treat the expression like its syntactic form.
-  Visit(E->getSyntacticForm());
+  ConstStmtVisitor::Visit(E->getSyntacticForm());
 }
 
 void EnqueueVisitor::VisitOMPExecutableDirective(
@@ -3338,9 +3365,28 @@ void 
EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
   VisitOMPLoopDirective(D);
 }
 
+void EnqueueVisitor::VisitAnnotateAttr(const AnnotateAttr *A) {
+  EnqueueChildren(A);
+}
+
 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
   EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest))
-  

[PATCH] D151373: [libclang] Expose arguments of clang::annotate

2023-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5aa06b18940c: [libclang] Expose arguments of clang::annotate 
(authored by fridtjof, committed by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151373

Files:
  clang/docs/ReleaseNotes.rst
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/CursorVisitor.h
  clang/unittests/libclang/LibclangTest.cpp

Index: clang/unittests/libclang/LibclangTest.cpp
===
--- clang/unittests/libclang/LibclangTest.cpp
+++ clang/unittests/libclang/LibclangTest.cpp
@@ -1246,6 +1246,50 @@
   EXPECT_EQ(fromCXString(clang_getCursorSpelling(*staticAssertCsr)), "");
 }
 
+TEST_F(LibclangParseTest, ExposesAnnotateArgs) {
+  const char testSource[] = R"cpp(
+[[clang::annotate("category", 42)]]
+void func() {}
+)cpp";
+  std::string fileName = "main.cpp";
+  WriteFile(fileName, testSource);
+
+  const char *Args[] = {"-xc++"};
+  ClangTU = clang_parseTranslationUnit(Index, fileName.c_str(), Args, 1,
+   nullptr, 0, TUFlags);
+
+  int attrCount = 0;
+
+  Traverse(
+  [&attrCount](CXCursor cursor, CXCursor parent) -> CXChildVisitResult {
+if (cursor.kind == CXCursor_AnnotateAttr) {
+  int childCount = 0;
+  clang_visitChildren(
+  cursor,
+  [](CXCursor child, CXCursor,
+ CXClientData data) -> CXChildVisitResult {
+int *pcount = static_cast(data);
+
+// we only expect one argument here, so bail otherwise
+EXPECT_EQ(*pcount, 0);
+
+auto *result = clang_Cursor_Evaluate(child);
+EXPECT_NE(result, nullptr);
+EXPECT_EQ(clang_EvalResult_getAsInt(result), 42);
+++*pcount;
+
+return CXChildVisit_Recurse;
+  },
+  &childCount);
+  attrCount++;
+  return CXChildVisit_Continue;
+}
+return CXChildVisit_Recurse;
+  });
+
+  EXPECT_EQ(attrCount, 1);
+}
+
 class LibclangRewriteTest : public LibclangParseTest {
 public:
   CXRewriter Rew = nullptr;
Index: clang/tools/libclang/CursorVisitor.h
===
--- clang/tools/libclang/CursorVisitor.h
+++ clang/tools/libclang/CursorVisitor.h
@@ -276,7 +276,9 @@
   bool IsInRegionOfInterest(CXCursor C);
   bool RunVisitorWorkList(VisitorWorkList &WL);
   void EnqueueWorkList(VisitorWorkList &WL, const Stmt *S);
+  void EnqueueWorkList(VisitorWorkList &WL, const Attr *A);
   LLVM_ATTRIBUTE_NOINLINE bool Visit(const Stmt *S);
+  LLVM_ATTRIBUTE_NOINLINE bool Visit(const Attr *A);
 
 private:
   std::optional handleDeclForVisitation(const Decl *D);
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -23,6 +23,7 @@
 #include "CursorVisitor.h"
 #include "clang-c/FatalErrorHandler.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/AttrVisitor.h"
 #include "clang/AST/DeclObjCCommon.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
@@ -575,6 +576,13 @@
   A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
   }
 
+  if (clang_isAttribute(Cursor.kind)) {
+if (const Attr *A = getCursorAttr(Cursor))
+  return Visit(A);
+
+return false;
+  }
+
   // If pointing inside a macro definition, check if the token is an identifier
   // that was ever defined as a macro. In such a case, create a "pseudo" macro
   // expansion cursor for that token.
@@ -2089,7 +2097,8 @@
 (SourceLocation::UIntTy)(uintptr_t)data[1]);
   }
 };
-class EnqueueVisitor : public ConstStmtVisitor {
+class EnqueueVisitor : public ConstStmtVisitor,
+   public ConstAttrVisitor {
   friend class OMPClauseEnqueue;
   VisitorWorkList &WL;
   CXCursor Parent;
@@ -2231,6 +2240,9 @@
   void VisitOMPTargetTeamsDistributeSimdDirective(
   const OMPTargetTeamsDistributeSimdDirective *D);
 
+  // Attributes
+  void VisitAnnotateAttr(const AnnotateAttr *A);
+
 private:
   void AddDeclarationNameInfo(const Stmt *S);
   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
@@ -2242,6 +2254,7 @@
   void AddTypeLoc(TypeSourceInfo *TI);
   void EnqueueChildren(const Stmt *S);
   void EnqueueChildren(const OMPClause *S);
+  void EnqueueChildren(const AnnotateAttr *A);
 };
 } // namespace
 
@@ -2736,6 +2749,20 @@
   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
   std::reverse(I, E);
 }
+
+void EnqueueVisitor::EnqueueChildren(const AnnotateAttr *A) {
+  unsigned size = WL.size();
+  for (const Expr *Arg : A->args()) {
+VisitStmt(Arg);
+  }
+  if (size == WL.size())
+return;
+  // Now reverse the entries we just added.  This will match the DFS
+ 

[clang] 0d459b7 - [Driver][DXC] Treat stdin as HLSL

2023-08-10 Thread Justin Bogner via cfe-commits

Author: Justin Bogner
Date: 2023-08-10T09:52:31-07:00
New Revision: 0d459b71dc280eede85f443921240df4f7a5c6ff

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

LOG: [Driver][DXC] Treat stdin as HLSL

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

Added: 
clang/test/Driver/dxc_stdin.hlsl

Modified: 
clang/lib/Driver/Driver.cpp

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 60f5eed8e2d729..150040cc9dd2e4 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -2648,6 +2648,8 @@ void Driver::BuildInputs(const ToolChain &TC, 
DerivedArgList &Args,
 if (memcmp(Value, "-", 2) == 0) {
   if (IsFlangMode()) {
 Ty = types::TY_Fortran;
+  } else if (IsDXCMode()) {
+Ty = types::TY_HLSL;
   } else {
 // If running with -E, treat as a C input (this changes the
 // builtin macros, for example). This may be overridden by -ObjC

diff  --git a/clang/test/Driver/dxc_stdin.hlsl 
b/clang/test/Driver/dxc_stdin.hlsl
new file mode 100644
index 00..98055b446b7b79
--- /dev/null
+++ b/clang/test/Driver/dxc_stdin.hlsl
@@ -0,0 +1,3 @@
+// RUN: %clang_dxc -Tlib_6_7 - -### 2>&1 | FileCheck %s
+// CHECK: "-cc1"
+// CHECK-SAME: "-x" "hlsl" "-"



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


[PATCH] D157562: [Driver][DXC] Treat stdin as HLSL

2023-08-10 Thread Justin Bogner 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 rG0d459b71dc28: [Driver][DXC] Treat stdin as HLSL (authored by 
bogner).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157562

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/dxc_stdin.hlsl


Index: clang/test/Driver/dxc_stdin.hlsl
===
--- /dev/null
+++ clang/test/Driver/dxc_stdin.hlsl
@@ -0,0 +1,3 @@
+// RUN: %clang_dxc -Tlib_6_7 - -### 2>&1 | FileCheck %s
+// CHECK: "-cc1"
+// CHECK-SAME: "-x" "hlsl" "-"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2648,6 +2648,8 @@
 if (memcmp(Value, "-", 2) == 0) {
   if (IsFlangMode()) {
 Ty = types::TY_Fortran;
+  } else if (IsDXCMode()) {
+Ty = types::TY_HLSL;
   } else {
 // If running with -E, treat as a C input (this changes the
 // builtin macros, for example). This may be overridden by -ObjC


Index: clang/test/Driver/dxc_stdin.hlsl
===
--- /dev/null
+++ clang/test/Driver/dxc_stdin.hlsl
@@ -0,0 +1,3 @@
+// RUN: %clang_dxc -Tlib_6_7 - -### 2>&1 | FileCheck %s
+// CHECK: "-cc1"
+// CHECK-SAME: "-x" "hlsl" "-"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2648,6 +2648,8 @@
 if (memcmp(Value, "-", 2) == 0) {
   if (IsFlangMode()) {
 Ty = types::TY_Fortran;
+  } else if (IsDXCMode()) {
+Ty = types::TY_HLSL;
   } else {
 // If running with -E, treat as a C input (this changes the
 // builtin macros, for example). This may be overridden by -ObjC
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157566: [SEH] fix assertion when -fasy-exceptions is used.

2023-08-10 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

lgtm


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157566

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


[PATCH] D157619: [clang][Interp] Reject calling virtual constexpr functions in pre-c++20

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157619

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


[PATCH] D156320: [Flang][Driver] Add support for Rpass and related options

2023-08-10 Thread Kiran Chandramohan via Phabricator via cfe-commits
kiranchandramohan added inline comments.



Comment at: flang/lib/Frontend/CompilerInvocation.cpp:156-158
+/// Parse a remark command line argument. It may be missing, disabled/enabled 
by
+/// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
+/// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.

awarzynski wrote:
> Could you give an example (and write a test ) for `-Rgroup=regexp`. Also, 
> @kiranchandramohan , is this form actually needed? I am thinking that it's a 
> complexity that could be avoided. It  could definitely simplify this patch.
`Rpass=regex` is used, particularly `Rpass=.`. So this is required, but can be 
deferred to a separate patch to simplify this one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156320

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


[PATCH] D153536: [Clang] Implement P2169 A nice placeholder with no name

2023-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D153536#4577187 , @vitalybuka 
wrote:

> In D153536#4576683 , @aaron.ballman 
> wrote:
>
>> In D153536#4571435 , @vitalybuka 
>> wrote:
>>
 Thanks! We might need someone from clangd to help here. The logs do not 
 have any information explaining what's failing with the test, and looking 
 at the test code, I struggle to see how these changes would impact that 
 test. We've had some significant issues with flaky clangd tests 
 (https://github.com/clangd/clangd/issues/1712), so it's possible this is 
 happenstance.
>>>
>>> I tried to debug that, and it looks like false Asan report. Maybe a bug in 
>>> FakeStack::GC related code.
>>
>> Thank you for looking into it! I came to the same general conclusion; and it 
>> seems the impacted bot has gone back to green in the meantime: 
>> https://lab.llvm.org/buildbot/#/builders/168/builds/15031 so hopefully we're 
>> in good shape.
>
> Yes. Fixed by D157552 . It's amusing to see 
> this unrelated patch exposing ~10 years old bug, which was never reported 
> before.

Oh wow! Great fix, thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153536

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


[PATCH] D157566: [SEH] fix assertion when -fasy-exceptions is used.

2023-08-10 Thread Aaron Smith via Phabricator via cfe-commits
asmith accepted this revision.
asmith added inline comments.



Comment at: clang/test/CodeGen/windows-seh-async-exceptions.cpp:21
+{
+devif_Warning("");
+return 0;

nit; spacing


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157566

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


[PATCH] D156312: [analyzer] Upstream BitwiseShiftChecker

2023-08-10 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy marked 21 inline comments as done.
donat.nagy added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:29-30
+
+using namespace clang;
+using namespace ento;
+

steakhal wrote:
> This is used quite often and hinders the readability by indenting the args a 
> lot. Making the spelling shorter, would somewhat mitigate this.
Good idea!



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:57-59
+  // Secondary mutable state, used only for note tag creation:
+  enum { NonNegLeft = 1, NonNegRight = 2 };
+  unsigned NonNegFlags = 0;

donat.nagy wrote:
> steakhal wrote:
> > How about using the same enum type for these two? It would signify that 
> > these are used together.
> > Also, by only looking at the possible values, it's not apparent that these 
> > are bitflag values. A suffix might help the reader.
> Using the enum type is a good idea, however I'd probably put the `Flag` 
> suffix into the name of the type:
> ```
> enum SignednessFlags : unsigned { NonNegLeft = 1, NonNegRight = 2 };
> SignednessFlags NonNegOperands = 0;
> ```
I rename the member `NonNegFlags` to `NonNegOperands` but its type remains a 
plain `unsigned` because otherwise using the or-assign operator like 
`NonNegOperands |= NonNegLeft` produces the error
> Assigning to 'enum SignednessFlags' from incompatible type 'unsigned int' 
> (clang typecheck_convert_incompatible)
(note that both operands were from the same enum type).



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:218
+   Side == OperandSide::Left ? "Left" : 
"Right",
+   isLeftShift() ? "left" : "right")
+ .str();

steakhal wrote:
> The `isLeftShift() ? "left" : "right"` expression appears 4 times in total.
> I'd also recommend to not distinguish the capitalized "left" and "right" 
> strings, and just post-process the messages to ensure that the first 
> character is capitalized inside the `createBugReport()`.
> 
> Also note that you can reuse the same placeholder, so you would only need to 
> pass the `side()` only once.
> ```lang=C++
> static void capitalizeBeginning(std::string &Str) {
>   if (Str.empty())
> return;
>   Str[0] = llvm::toUpper(Str[0]);
> }
> 
> StringRef side() const {
>   return isLeftShift() ? "left" : "right";
> }
> ```
I introduced a method for `isLeftShift() ? "left" : "right"` (which is indeed 
repeated several times), but I didn't define `capitalizeBeginning` because that 
would've been used only once.

Your remark that [with the capitalization function] "you can reuse the same 
placeholder, so you would only need to pass the side() only once" seems to be 
incorrect, because `Side == OperandSide::Left ? "Left" : "Right"` (which 
operand are we talking about?) and `isLeftShift() ? "left" : "right"` (what 
kind of shift operator are we talking about?) are two independent values.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156312

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


[PATCH] D156312: [analyzer] Upstream BitwiseShiftChecker

2023-08-10 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy updated this revision to Diff 549091.
donat.nagy marked 2 inline comments as done.
donat.nagy added a comment.

Uploading a new version based on the reviews.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156312

Files:
  clang/docs/analyzer/checkers.rst
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/test/Analysis/analyzer-config.c
  clang/test/Analysis/analyzer-enabled-checkers.c
  clang/test/Analysis/bitwise-ops-nocrash.c
  clang/test/Analysis/bitwise-ops.c
  clang/test/Analysis/bitwise-shift-common.c
  clang/test/Analysis/bitwise-shift-pedantic.c
  clang/test/Analysis/bitwise-shift-sanity-checks.c
  clang/test/Analysis/bitwise-shift-state-update.c
  clang/test/Analysis/casts.c
  clang/test/Analysis/diagnostics/track_subexpressions.cpp
  clang/test/Analysis/left-shift-cxx2a.cpp
  clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
  clang/test/Analysis/symbol-simplification-nonloc-loc.cpp

Index: clang/test/Analysis/symbol-simplification-nonloc-loc.cpp
===
--- clang/test/Analysis/symbol-simplification-nonloc-loc.cpp
+++ clang/test/Analysis/symbol-simplification-nonloc-loc.cpp
@@ -14,7 +14,7 @@
   if (p) {
 // no-crash
   }
-  if (p == (int *)0x404) {
+  if (p == (int *)0x1b) {
 // no-crash
   }
 }
@@ -29,7 +29,7 @@
   if (p) {
 // no-crash
   }
-  if (p == (int *)0x404) {
+  if (p == (int *)0x1b) {
 // no-crash
   }
 }
@@ -43,8 +43,6 @@
   nonloc_OP_loc(p, BINOP(-)); // no-crash
 
   // Bitwise operators:
-  // expected-warning@+2 {{The result of the left shift is undefined due to shifting by '1028', which is greater or equal to the width of type 'int' [core.UndefinedBinaryOperatorResult]}}
-  // expected-warning@+2 {{The result of the right shift is undefined due to shifting by '1028', which is greater or equal to the width of type 'int' [core.UndefinedBinaryOperatorResult]}}
   nonloc_OP_loc(p, BINOP(<<)); // no-crash
   nonloc_OP_loc(p, BINOP(>>)); // no-crash
   nonloc_OP_loc(p, BINOP(&));
Index: clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
===
--- clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
+++ clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c
@@ -24,6 +24,7 @@
 // CHECK-NEXT: apiModeling.TrustReturnsNonnull
 // CHECK-NEXT: apiModeling.llvm.CastValue
 // CHECK-NEXT: apiModeling.llvm.ReturnValue
+// CHECK-NEXT: core.BitwiseShift
 // CHECK-NEXT: core.DivideZero
 // CHECK-NEXT: core.DynamicTypePropagation
 // CHECK-NEXT: core.NonnilStringConstants
Index: clang/test/Analysis/left-shift-cxx2a.cpp
===
--- clang/test/Analysis/left-shift-cxx2a.cpp
+++ clang/test/Analysis/left-shift-cxx2a.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx17 -std=c++17 %s
-// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx2a -std=c++2a %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-disable-checker core.BitwiseShift -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx17 -std=c++17 %s
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection -analyzer-disable-checker core.BitwiseShift -triple x86_64-apple-darwin13 -Wno-shift-count-overflow -verify=expected,cxx2a -std=c++2a %s
 
 int testNegativeShift(int a) {
   if (a == -5) {
Index: clang/test/Analysis/diagnostics/track_subexpressions.cpp
===
--- clang/test/Analysis/diagnostics/track_subexpressions.cpp
+++ clang/test/Analysis/diagnostics/track_subexpressions.cpp
@@ -12,10 +12,10 @@
 
 void shift_by_undefined_value() {
   uint8_t shift_amount = get_uint8_max(); // expected-note{{'shift_amount' initialized to 255}}
-// expected-note@-1{{Calling 'get_uint8_max'}}
-// expected-note@-2{{Returning from 'get_uint8_max'}}
-  (void)(TCP_MAXWIN << shift_amount); // expected-warning{{The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'int'}}
-  // expected-note@-1{{The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'int'}}
+  // expected-note@-1{{Calling 'get_uint8_max'}}
+  // expected-note@-2{{Returning from 'get_uint8_max'}}
+  (void)(TCP_MAXWIN << shift_amount); // expected-warning{{Left shift by '255' overfl

[PATCH] D157554: [NFC][Clang] Fix static analyzer concern about null pointer dereference

2023-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D157554#4576720 , @eandrews wrote:

> In D157554#4576478 , @aaron.ballman 
> wrote:
>
>> This feels a bit more like a functional change than a non-functional change 
>> because it seems like we should be able to test this case (whereas, if we 
>> think `TC` can never be null in reality, we could add an `assert` for it and 
>> not add test coverage). That said, I'm not certain how to induce a failure 
>> here. Adding @erichkeane in case he has ideas.
>
> Yea I agree. I see that this is inside 
> `ReturnTypeRequirement.isTypeConstraint()` so maybe `Param` should always 
> have a type constraint? I'm just naively guessing here though

As I read the code, I think an assert is sufficient -- if the param is a type 
constraint, I believe we expect a non-null type constraint and a null one is a 
sign of a bug.


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

https://reviews.llvm.org/D157554

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


[PATCH] D157559: [clang][modules] Respect "-fmodule-name=" when serializing included files into a PCH

2023-08-10 Thread Jan Svoboda via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGbbdb0c7e4496: [clang][modules] Respect 
"-fmodule-name=" when serializing included files into… (authored by 
jansvoboda11).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157559

Files:
  clang/lib/Lex/ModuleMap.cpp
  clang/test/Modules/pch-with-module-name-import-twice.c


Index: clang/test/Modules/pch-with-module-name-import-twice.c
===
--- /dev/null
+++ clang/test/Modules/pch-with-module-name-import-twice.c
@@ -0,0 +1,19 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// This test checks that headers that are part of a module named by
+// -fmodule-name= don't get included again if previously included from a PCH.
+
+//--- include/module.modulemap
+module Mod { header "Mod.h" }
+//--- include/Mod.h
+struct Symbol {};
+//--- pch.h
+#import "Mod.h"
+//--- tu.c
+#import "Mod.h" // expected-no-diagnostics
+
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache 
-fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -emit-pch -x c-header %t/pch.h -o %t/pch.pch
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache 
-fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -fsyntax-only %t/tu.c -include-pch %t/pch.pch -verify
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1268,8 +1268,7 @@
   HeaderList.push_back(KH);
   Mod->Headers[headerRoleToKind(Role)].push_back(Header);
 
-  bool isCompilingModuleHeader =
-  LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
+  bool isCompilingModuleHeader = Mod->isForBuilding(LangOpts);
   if (!Imported || isCompilingModuleHeader) {
 // When we import HeaderFileInfo, the external source is expected to
 // set the isModuleHeader flag itself.


Index: clang/test/Modules/pch-with-module-name-import-twice.c
===
--- /dev/null
+++ clang/test/Modules/pch-with-module-name-import-twice.c
@@ -0,0 +1,19 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// This test checks that headers that are part of a module named by
+// -fmodule-name= don't get included again if previously included from a PCH.
+
+//--- include/module.modulemap
+module Mod { header "Mod.h" }
+//--- include/Mod.h
+struct Symbol {};
+//--- pch.h
+#import "Mod.h"
+//--- tu.c
+#import "Mod.h" // expected-no-diagnostics
+
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache -fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -emit-pch -x c-header %t/pch.h -o %t/pch.pch
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache -fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -fsyntax-only %t/tu.c -include-pch %t/pch.pch -verify
Index: clang/lib/Lex/ModuleMap.cpp
===
--- clang/lib/Lex/ModuleMap.cpp
+++ clang/lib/Lex/ModuleMap.cpp
@@ -1268,8 +1268,7 @@
   HeaderList.push_back(KH);
   Mod->Headers[headerRoleToKind(Role)].push_back(Header);
 
-  bool isCompilingModuleHeader =
-  LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
+  bool isCompilingModuleHeader = Mod->isForBuilding(LangOpts);
   if (!Imported || isCompilingModuleHeader) {
 // When we import HeaderFileInfo, the external source is expected to
 // set the isModuleHeader flag itself.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bbdb0c7 - [clang][modules] Respect "-fmodule-name=" when serializing included files into a PCH

2023-08-10 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2023-08-10T10:11:43-07:00
New Revision: bbdb0c7e4496b145a5e9354f951eec272695049d

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

LOG: [clang][modules] Respect "-fmodule-name=" when serializing included files 
into a PCH

Clang writes the set of textually included files into AST files, so that 
importers know to avoid including those files again and instead deserialize 
their contents from the AST on-demand.

Logic for determining the set of included files files only considers headers 
that are either non-modular or that are modular but with 
`HeaderFileInfo::isCompilingModuleHeader` set. Logic for computing that bit is 
different than the one that determines whether to include a header textually 
with the "-fmodule-name=Mod" option. That can lead to header from module "Mod" 
being included textually in a PCH, but be omitted in the serialized set of 
included files. This can then allow such header to be textually included from 
importer of the PCH, wreaking havoc.

This patch fixes that by aligning the logic for computing 
`HeaderFileInfo::isCompilingModuleHeader` with the logic for deciding whether 
to include modular header textually.

As far as I can tell, this bug has been in Clang for forever. It got 
accidentally "fixed" by D114095 (that changed the logic for determining the set 
of included files) and got broken again in D155131 (which is essentially a 
revert of the former).

rdar://113520515

Reviewed By: benlangmuir

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

Added: 
clang/test/Modules/pch-with-module-name-import-twice.c

Modified: 
clang/lib/Lex/ModuleMap.cpp

Removed: 




diff  --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 5a1b0a918caab1..f8b767e1b5eb80 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -1268,8 +1268,7 @@ void ModuleMap::addHeader(Module *Mod, Module::Header 
Header,
   HeaderList.push_back(KH);
   Mod->Headers[headerRoleToKind(Role)].push_back(Header);
 
-  bool isCompilingModuleHeader =
-  LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
+  bool isCompilingModuleHeader = Mod->isForBuilding(LangOpts);
   if (!Imported || isCompilingModuleHeader) {
 // When we import HeaderFileInfo, the external source is expected to
 // set the isModuleHeader flag itself.

diff  --git a/clang/test/Modules/pch-with-module-name-import-twice.c 
b/clang/test/Modules/pch-with-module-name-import-twice.c
new file mode 100644
index 00..67932a4ba46aa6
--- /dev/null
+++ b/clang/test/Modules/pch-with-module-name-import-twice.c
@@ -0,0 +1,19 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// This test checks that headers that are part of a module named by
+// -fmodule-name= don't get included again if previously included from a PCH.
+
+//--- include/module.modulemap
+module Mod { header "Mod.h" }
+//--- include/Mod.h
+struct Symbol {};
+//--- pch.h
+#import "Mod.h"
+//--- tu.c
+#import "Mod.h" // expected-no-diagnostics
+
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache 
-fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -emit-pch -x c-header %t/pch.h -o %t/pch.pch
+// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/cache 
-fimplicit-module-maps -fmodule-name=Mod -I %t/include \
+// RUN:   -fsyntax-only %t/tu.c -include-pch %t/pch.pch -verify



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


[PATCH] D157554: [NFC][Clang] Fix static analyzer concern about null pointer dereference

2023-08-10 Thread Elizabeth Andrews via Phabricator via cfe-commits
eandrews added a comment.

In D157554#4577504 , @aaron.ballman 
wrote:

> In D157554#4576720 , @eandrews 
> wrote:
>
>> In D157554#4576478 , 
>> @aaron.ballman wrote:
>>
>>> This feels a bit more like a functional change than a non-functional change 
>>> because it seems like we should be able to test this case (whereas, if we 
>>> think `TC` can never be null in reality, we could add an `assert` for it 
>>> and not add test coverage). That said, I'm not certain how to induce a 
>>> failure here. Adding @erichkeane in case he has ideas.
>>
>> Yea I agree. I see that this is inside 
>> `ReturnTypeRequirement.isTypeConstraint()` so maybe `Param` should always 
>> have a type constraint? I'm just naively guessing here though
>
> As I read the code, I think an assert is sufficient -- if the param is a type 
> constraint, I believe we expect a non-null type constraint and a null one is 
> a sign of a bug.

Alright. I'll make the change then. Thanks!


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

https://reviews.llvm.org/D157554

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


[PATCH] D157572: [clang] Add `[[clang::library_extension]]` attribute

2023-08-10 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:5690-5691
+def warn_unknown_ext : Warning<"Unknown extension kind: %0">;
+def warn_cxx11_ext : Warning<"%0 is a C++11 extension">,
+InGroup;
+def warn_cxx14_ext : Warning<"%0 is a C++14 extension">,

We shouldn't need this one, since Clang (almost) doesn't distinguish between 
C++03 and C++11. To my knowledge, C++03 doesn't even support attributes, so 
this would be a moot addition.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:8227-8229
+  if (llvm::none_of(std::array{"C++11", "C++14", "C++17", "C++20", "C++23",
+   "C++26", "GNU"},
+[&](const char *K) { return K == Kind; })) {





Comment at: clang/test/SemaCXX/attr-library-extension.cpp:9-13
+#ifdef GNUAttr
+#define EXTENSION(name) __attribute__((library_extension(name)))
+#else
+#define EXTENSION(name) [[clang::library_extension(name)]]
+#endif

I don't think we need to test for both of these: using 
`[[clang::library_extension]]` directly should suffice.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157572

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


[PATCH] D155850: [Clang][CodeGen][RFC] Add codegen support for C++ Parallel Algorithm Offload

2023-08-10 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx updated this revision to Diff 549097.
AlexVlx added a comment.

Add support for handling certain cases of unambiguously accelerator unsupported 
ASM i.e. cases where constraints are clearly mismatched. When that happens, we 
instead emit an `ASM__stdpar_unsupported` stub which takes as its single 
argument the `constexpr` string value of the ASM block. Later, in the 
AcceleratorCodeSelection pass, if such a stub is reachable from an accelerator 
callable, we error out and print the offending ASM alongside the location.


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

https://reviews.llvm.org/D155850

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenStdPar/unannotated-functions-get-emitted.cpp
  clang/test/CodeGenStdPar/unsupported-ASM.cpp
  clang/test/CodeGenStdPar/unsupported-builtins.cpp

Index: clang/test/CodeGenStdPar/unsupported-builtins.cpp
===
--- /dev/null
+++ clang/test/CodeGenStdPar/unsupported-builtins.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   --stdpar -x hip -emit-llvm -fcuda-is-device -o - %s | FileCheck %s
+
+#define __global__ __attribute__((global))
+
+__global__ void foo() { return __builtin_ia32_pause(); }
+
+// CHECK: declare void @__builtin_ia32_pause__stdpar_unsupported()
Index: clang/test/CodeGenStdPar/unsupported-ASM.cpp
===
--- /dev/null
+++ clang/test/CodeGenStdPar/unsupported-ASM.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   --stdpar -x hip -emit-llvm -fcuda-is-device -o - %s | FileCheck %s
+
+#define __global__ __attribute__((global))
+
+__global__ void foo(int i) {
+asm ("addl %2, %1; seto %b0" : "=q" (i), "+g" (i) : "r" (i));
+}
+
+// CHECK: declare void @ASM__stdpar_unsupported([{{.*}}])
Index: clang/test/CodeGenStdPar/unannotated-functions-get-emitted.cpp
===
--- /dev/null
+++ clang/test/CodeGenStdPar/unannotated-functions-get-emitted.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -x hip -emit-llvm -fcuda-is-device \
+// RUN:   -o - %s | FileCheck --check-prefix=NO-STDPAR-DEV %s
+
+// RUN: %clang_cc1 --stdpar -emit-llvm -fcuda-is-device \
+// RUN:   -o - %s | FileCheck --check-prefix=STDPAR-DEV %s
+
+#define __device__ __attribute__((device))
+
+// NO-STDPAR-DEV-NOT: define {{.*}} void @_Z3fooPff({{.*}})
+// STDPAR-DEV: define {{.*}} void @_Z3fooPff({{.*}})
+void foo(float *a, float b) {
+  *a = b;
+}
+
+// NO-STDPAR-DEV: define {{.*}} void @_Z3barPff({{.*}})
+// STDPAR-DEV: define {{.*}} void @_Z3barPff({{.*}})
+__device__ void bar(float *a, float b) {
+  *a = b;
+}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -3558,7 +3558,10 @@
   !Global->hasAttr() &&
   !Global->hasAttr() &&
   !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
-  !Global->getType()->isCUDADeviceBuiltinTextureType())
+  !Global->getType()->isCUDADeviceBuiltinTextureType() &&
+  !(LangOpts.HIPStdPar &&
+isa(Global) &&
+!Global->hasAttr()))
 return;
 } else {
   // We need to emit host-side 'shadows' for all global
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2594,10 +2594,15 @@
   std::string MissingFeature;
   llvm::StringMap CallerFeatureMap;
   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
+  // When compiling in StdPar mode we have to be conservative in rejecting
+  // target specific features in the FE, and defer the possible error to the
+  // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
+  // referenced by an accelerator executable function, we emit an error.
+  bool IsStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice
   if (BuiltinID) {
 StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
 if (!Builtin::evaluateRequiredTargetFeatures(
-FeatureList, CallerFeatureMap)) {
+FeatureList, CallerFeatureMap) && !IsStdPar) {
   CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
   << TargetDecl->getDeclName()
   << FeatureList;
@@ -2630,7 +2635,7 @@
 return false;
   }
   return true;
-}))
+}) && !IsStdPar)
   CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
   << FD->getDeclName() << TargetDecl->getDeclName() << Mis

[PATCH] D157332: [clang] Make init for empty no_unique_address fields a no-op write

2023-08-10 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo updated this revision to Diff 549099.
mstorsjo added a comment.

Plumb the info from EmitInitializerForField through AggValueSlot and 
ReturnValueSlot to EmitCall.

The fields/variables could use better names.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157332

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGCall.h
  clang/lib/CodeGen/CGClass.cpp
  clang/lib/CodeGen/CGExprAgg.cpp
  clang/lib/CodeGen/CGValue.h
  clang/test/CodeGenCXX/ctor-empty-nounique.cpp

Index: clang/test/CodeGenCXX/ctor-empty-nounique.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/ctor-empty-nounique.cpp
@@ -0,0 +1,43 @@
+// RUN: %clang_cc1 -triple x86_64-windows-gnu -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-windows-gnu -emit-llvm -o - %s | FileCheck %s
+
+// An empty struct is handled as a struct with a dummy i8, on all targets.
+// Most targets treat an empty struct return value as essentially void - but
+// some don't. (Currently, at least x86_64-windows-* and powerpc64le-* don't
+// treat it as void.)
+//
+// When intializing a struct with such a no_unique_address member, make sure we
+// don't write the dummy i8 into the struct where there's no space allocated for
+// it.
+//
+// This can only be tested with targets that don't treat empty struct returns as
+// void.
+
+struct S {};
+S f();
+struct Z {
+  int x;
+  [[no_unique_address]] S y;
+  Z();
+};
+Z::Z() : x(111), y(f()) {}
+
+// CHECK: define {{.*}} @_ZN1ZC2Ev
+// CHECK: %call = call i8 @_Z1fv()
+// CHECK-NEXT: ret void
+
+struct S2 {
+  S2();
+};
+struct Z2 {
+  int x;
+  [[no_unique_address]] S2 y;
+  Z2();
+};
+Z2::Z2() : x(111) {}
+
+// CHECK: define {{.*}} @_ZN2Z2C2Ev(ptr {{.*}} %this)
+// CHECK: %this.addr = alloca ptr
+// CHECK: store ptr %this, ptr %this.addr
+// CHECK: %this1 = load ptr, ptr %this.addr
+// CHECK: call void @_ZN2S2C1Ev(ptr {{.*}} %this1)
Index: clang/lib/CodeGen/CGValue.h
===
--- clang/lib/CodeGen/CGValue.h
+++ clang/lib/CodeGen/CGValue.h
@@ -559,13 +559,16 @@
   /// them.
   bool SanitizerCheckedFlag : 1;
 
+  bool IsDummy : 1;
+
+public:
   AggValueSlot(Address Addr, Qualifiers Quals, bool DestructedFlag,
bool ObjCGCFlag, bool ZeroedFlag, bool AliasedFlag,
-   bool OverlapFlag, bool SanitizerCheckedFlag)
+   bool OverlapFlag, bool SanitizerCheckedFlag, bool IsDummy)
   : Addr(Addr), Quals(Quals), DestructedFlag(DestructedFlag),
 ObjCGCFlag(ObjCGCFlag), ZeroedFlag(ZeroedFlag),
 AliasedFlag(AliasedFlag), OverlapFlag(OverlapFlag),
-SanitizerCheckedFlag(SanitizerCheckedFlag) {}
+SanitizerCheckedFlag(SanitizerCheckedFlag), IsDummy(IsDummy) {}
 
 public:
   enum IsAliased_t { IsNotAliased, IsAliased };
@@ -574,6 +577,7 @@
   enum Overlap_t { DoesNotOverlap, MayOverlap };
   enum NeedsGCBarriers_t { DoesNotNeedGCBarriers, NeedsGCBarriers };
   enum IsSanitizerChecked_t { IsNotSanitizerChecked, IsSanitizerChecked };
+  enum IsDummy_t { IsNotADummySlot, IsADummySlot };
 
   /// ignored - Returns an aggregate value slot indicating that the
   /// aggregate value is being ignored.
@@ -592,27 +596,26 @@
   ///   for calling destructors on this object
   /// \param needsGC - true if the slot is potentially located
   ///   somewhere that ObjC GC calls should be emitted for
-  static AggValueSlot forAddr(Address addr,
-  Qualifiers quals,
-  IsDestructed_t isDestructed,
-  NeedsGCBarriers_t needsGC,
-  IsAliased_t isAliased,
-  Overlap_t mayOverlap,
-  IsZeroed_t isZeroed = IsNotZeroed,
-   IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) {
+  static AggValueSlot
+  forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed,
+  NeedsGCBarriers_t needsGC, IsAliased_t isAliased,
+  Overlap_t mayOverlap, IsZeroed_t isZeroed = IsNotZeroed,
+  IsSanitizerChecked_t isChecked = IsNotSanitizerChecked,
+  IsDummy_t isDummy = IsNotADummySlot) {
 if (addr.isValid())
   addr.setKnownNonNull();
 return AggValueSlot(addr, quals, isDestructed, needsGC, isZeroed, isAliased,
-mayOverlap, isChecked);
+mayOverlap, isChecked, isDummy);
   }
 
   static AggValueSlot
   forLValue(const LValue &LV, CodeGenFunction &CGF, IsDestructed_t isDestructed,
 NeedsGCBarriers_t needsGC, IsAliased_t isAliased,
 Overlap_t mayOverlap, IsZeroed_t isZeroed = IsNotZeroed,
-IsSanitizerChecked_t isChecked = IsNotSanitizerChecked) {
+IsSanitizerChecked_t isChecked = IsNotSanitizerChecked,
+IsDummy_t isDummy = IsN

[PATCH] D155850: [Clang][CodeGen][RFC] Add codegen support for C++ Parallel Algorithm Offload

2023-08-10 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx updated this revision to Diff 549101.
AlexVlx added a comment.

Fix typo.


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

https://reviews.llvm.org/D155850

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenStdPar/unannotated-functions-get-emitted.cpp
  clang/test/CodeGenStdPar/unsupported-ASM.cpp
  clang/test/CodeGenStdPar/unsupported-builtins.cpp

Index: clang/test/CodeGenStdPar/unsupported-builtins.cpp
===
--- /dev/null
+++ clang/test/CodeGenStdPar/unsupported-builtins.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   --stdpar -x hip -emit-llvm -fcuda-is-device -o - %s | FileCheck %s
+
+#define __global__ __attribute__((global))
+
+__global__ void foo() { return __builtin_ia32_pause(); }
+
+// CHECK: declare void @__builtin_ia32_pause__stdpar_unsupported()
Index: clang/test/CodeGenStdPar/unsupported-ASM.cpp
===
--- /dev/null
+++ clang/test/CodeGenStdPar/unsupported-ASM.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   --stdpar -x hip -emit-llvm -fcuda-is-device -o - %s | FileCheck %s
+
+#define __global__ __attribute__((global))
+
+__global__ void foo(int i) {
+asm ("addl %2, %1; seto %b0" : "=q" (i), "+g" (i) : "r" (i));
+}
+
+// CHECK: declare void @ASM__stdpar_unsupported([{{.*}}])
Index: clang/test/CodeGenStdPar/unannotated-functions-get-emitted.cpp
===
--- /dev/null
+++ clang/test/CodeGenStdPar/unannotated-functions-get-emitted.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -x hip -emit-llvm -fcuda-is-device \
+// RUN:   -o - %s | FileCheck --check-prefix=NO-STDPAR-DEV %s
+
+// RUN: %clang_cc1 --stdpar -emit-llvm -fcuda-is-device \
+// RUN:   -o - %s | FileCheck --check-prefix=STDPAR-DEV %s
+
+#define __device__ __attribute__((device))
+
+// NO-STDPAR-DEV-NOT: define {{.*}} void @_Z3fooPff({{.*}})
+// STDPAR-DEV: define {{.*}} void @_Z3fooPff({{.*}})
+void foo(float *a, float b) {
+  *a = b;
+}
+
+// NO-STDPAR-DEV: define {{.*}} void @_Z3barPff({{.*}})
+// STDPAR-DEV: define {{.*}} void @_Z3barPff({{.*}})
+__device__ void bar(float *a, float b) {
+  *a = b;
+}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -3558,7 +3558,10 @@
   !Global->hasAttr() &&
   !Global->hasAttr() &&
   !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
-  !Global->getType()->isCUDADeviceBuiltinTextureType())
+  !Global->getType()->isCUDADeviceBuiltinTextureType() &&
+  !(LangOpts.HIPStdPar &&
+isa(Global) &&
+!Global->hasAttr()))
 return;
 } else {
   // We need to emit host-side 'shadows' for all global
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2594,10 +2594,15 @@
   std::string MissingFeature;
   llvm::StringMap CallerFeatureMap;
   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
+  // When compiling in StdPar mode we have to be conservative in rejecting
+  // target specific features in the FE, and defer the possible error to the
+  // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
+  // referenced by an accelerator executable function, we emit an error.
+  bool IsStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice
   if (BuiltinID) {
 StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
 if (!Builtin::evaluateRequiredTargetFeatures(
-FeatureList, CallerFeatureMap)) {
+FeatureList, CallerFeatureMap) && !IsStdPar) {
   CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
   << TargetDecl->getDeclName()
   << FeatureList;
@@ -2630,7 +2635,7 @@
 return false;
   }
   return true;
-}))
+}) && !IsStdPar)
   CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
   << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
   } else if (!FD->isMultiVersion() && FD->hasAttr()) {
@@ -2639,7 +2644,8 @@
 
 for (const auto &F : CalleeFeatureMap) {
   if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
-   !CallerFeatureMap.find(F.getKey())->getValue()))
+   !CallerFeatureMap.find(F.getKey())->getValue()) &&
+  !IsStdPar)
 CGM.getDiags().Report(Loc, diag::err_function_needs_featu

[PATCH] D156749: [modules] Fix error about the same module being defined in different .pcm files when using VFS overlays.

2023-08-10 Thread Volodymyr Sapsai 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 rG97dfaf4cd278: [modules] Fix error about the same module 
being defined in different .pcm files… (authored by vsapsai).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156749

Files:
  clang/lib/Lex/HeaderSearch.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/VFS/module-map-path.m

Index: clang/test/VFS/module-map-path.m
===
--- /dev/null
+++ clang/test/VFS/module-map-path.m
@@ -0,0 +1,110 @@
+// Test the module map path is consistent between clang invocations when using VFS overlays.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// Pre-populate the module cache with the modules that don't use VFS overlays.
+// RUN: %clang_cc1 -fsyntax-only -F%t/Frameworks -I%t/include %t/prepopulate_module_cache.m \
+// RUN: -fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache
+
+// Execute a compilation with VFS overlay. .pcm file path looks like /ModuleName-.pcm.
+//  corresponds to the compilation settings like language options.
+//  corresponds to the module map path. So if any of those change, we should use a different module.
+// But for VFS overlay we make an exception that it's not a part of  to reduce the number of built .pcm files.
+// Test that paths in overlays don't leak into  and don't cause using 2 .pcm files for the same module.
+// DEFINE: %{command} = %clang_cc1 -fsyntax-only -verify -F%t/Frameworks -I%t/include %t/test.m \
+// DEFINE:-fmodules -fimplicit-module-maps -fmodules-cache-path=%t/modules.cache
+// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e "s@USE_EXTERNAL_NAMES_OPTION@@g" %t/overlay.yaml.template > %t/external-names-default.yaml
+// RUN: %{command} -ivfsoverlay %t/external-names-default.yaml
+
+// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e "s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': true,@g" %t/overlay.yaml.template > %t/external-names-true.yaml
+// RUN: %{command} -ivfsoverlay %t/external-names-true.yaml
+
+// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e "s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': false,@g" %t/overlay.yaml.template > %t/external-names-false.yaml
+// RUN: %{command} -ivfsoverlay %t/external-names-false.yaml
+
+//--- prepopulate_module_cache.m
+#import 
+
+//--- test.m
+// At first import multi-path modules directly, so clang decides which .pcm file they should belong to.
+#import 
+#import 
+
+// Then import a module from the module cache and all its transitive dependencies.
+// Make sure the .pcm files loaded directly are the same as 'Redirecting' is referencing.
+#import 
+// expected-no-diagnostics
+
+
+//--- Frameworks/MultiPath.framework/Headers/MultiPath.h
+void multiPathFramework(void);
+
+//--- Frameworks/MultiPath.framework/Modules/module.modulemap
+framework module MultiPath {
+header "MultiPath.h"
+export *
+}
+
+
+//--- include/MultiPathHeader.h
+void multiPathHeader(void);
+
+//--- include/module.modulemap
+module MultiPathHeader {
+header "MultiPathHeader.h"
+export *
+}
+
+
+//--- Frameworks/Redirecting.framework/Headers/Redirecting.h
+#import 
+#import 
+
+//--- Frameworks/Redirecting.framework/Modules/module.modulemap
+framework module Redirecting {
+header "Redirecting.h"
+export *
+}
+
+
+//--- BuildTemporaries/MultiPath.h
+void multiPathFramework(void);
+//--- BuildTemporaries/module.modulemap
+framework module MultiPath {
+header "MultiPath.h"
+export *
+}
+//--- BuildTemporaries/header.h
+void multiPathHeader(void);
+//--- BuildTemporaries/include.modulemap
+module MultiPathHeader {
+header "MultiPathHeader.h"
+export *
+}
+
+//--- overlay.yaml.template
+{
+  'version': 0,
+  USE_EXTERNAL_NAMES_OPTION
+  'roots': [
+{ 'name': 'TMP_DIR/Frameworks/MultiPath.framework/Headers', 'type': 'directory',
+  'contents': [
+{ 'name': 'MultiPath.h', 'type': 'file',
+  'external-contents': 'TMP_DIR/BuildTemporaries/MultiPath.h'}
+]},
+{ 'name': 'TMP_DIR/Frameworks/MultiPath.framework/Modules', 'type': 'directory',
+  'contents': [
+{ 'name': 'module.modulemap', 'type': 'file',
+  'external-contents': 'TMP_DIR/BuildTemporaries/module.modulemap'}
+]},
+{ 'name': 'TMP_DIR/include', 'type': 'directory',
+  'contents': [
+{ 'name': 'MultiPathHeader.h', 'type': 'file',
+  'external-contents': 'TMP_DIR/BuildTemporaries/header.h'},
+{ 'name': 'module.modulemap', 'type': 'file',
+  'external-contents': 'TMP_DIR/BuildTemporaries/include.modulemap'}
+]}
+  ]
+}
+
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -1327,7 +13

[clang] 97dfaf4 - [modules] Fix error about the same module being defined in different .pcm files when using VFS overlays.

2023-08-10 Thread Volodymyr Sapsai via cfe-commits

Author: Volodymyr Sapsai
Date: 2023-08-10T10:47:51-07:00
New Revision: 97dfaf4cd27814bdf9aa9d2eafc21fdb4f76c56d

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

LOG: [modules] Fix error about the same module being defined in different .pcm 
files when using VFS overlays.

Fix errors like
> module 'MultiPath' is defined in both 
> 'path/to/modules.cache/3JR48BPRU7BCG/MultiPath-1352QHUF8RNMU.pcm' and 
> 'path/to/modules.cache/3JR48BPRU7BCG/MultiPath-20HNSLLIUDDV1.pcm'

To avoid building extra identical modules `-ivfsoverlay` option is not a
part of the hash like "/3JR48BPRU7BCG/". And it is build system's
responsibility to provide `-ivfsoverlay` options that don't cause
observable differences.  We also need to make sure the hash like
"-1352QHUF8RNMU" is not affected by `-ivfsoverlay`. As this hash is
defined by the module map path, use the path prior to any VFS
remappings.

rdar://111921464

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

Added: 
clang/test/VFS/module-map-path.m

Modified: 
clang/lib/Lex/HeaderSearch.cpp
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index f42d51d65dcdf3..80e1bad72ce9b7 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -177,7 +177,7 @@ std::string HeaderSearch::getCachedModuleFileName(Module 
*Module) {
   // *.modulemap file. In this case, just return an empty string.
   if (!ModuleMap)
 return {};
-  return getCachedModuleFileName(Module->Name, ModuleMap->getName());
+  return getCachedModuleFileName(Module->Name, 
ModuleMap->getNameAsRequested());
 }
 
 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,

diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 8b0015f1ee9f6c..289c0383cd4b0e 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1327,7 +1327,8 @@ void ASTWriter::WriteControlBlock(Preprocessor &PP, 
ASTContext &Context,
 
 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
 AddPath(WritingModule->PresumedModuleMapFile.empty()
-? Map.getModuleMapFileForUniquing(WritingModule)->getName()
+? Map.getModuleMapFileForUniquing(WritingModule)
+  ->getNameAsRequested()
 : StringRef(WritingModule->PresumedModuleMapFile),
 Record);
 

diff  --git a/clang/test/VFS/module-map-path.m 
b/clang/test/VFS/module-map-path.m
new file mode 100644
index 00..0f3c0a7aa499eb
--- /dev/null
+++ b/clang/test/VFS/module-map-path.m
@@ -0,0 +1,110 @@
+// Test the module map path is consistent between clang invocations when using 
VFS overlays.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// Pre-populate the module cache with the modules that don't use VFS overlays.
+// RUN: %clang_cc1 -fsyntax-only -F%t/Frameworks -I%t/include 
%t/prepopulate_module_cache.m \
+// RUN: -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules.cache
+
+// Execute a compilation with VFS overlay. .pcm file path looks like 
/ModuleName-.pcm.
+//  corresponds to the compilation settings like language options.
+//  corresponds to the module map path. So if any of those change, we 
should use a 
diff erent module.
+// But for VFS overlay we make an exception that it's not a part of  to 
reduce the number of built .pcm files.
+// Test that paths in overlays don't leak into  and don't cause using 2 
.pcm files for the same module.
+// DEFINE: %{command} = %clang_cc1 -fsyntax-only -verify -F%t/Frameworks 
-I%t/include %t/test.m \
+// DEFINE:-fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules.cache
+// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@@g" %t/overlay.yaml.template > 
%t/external-names-default.yaml
+// RUN: %{command} -ivfsoverlay %t/external-names-default.yaml
+
+// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': true,@g" 
%t/overlay.yaml.template > %t/external-names-true.yaml
+// RUN: %{command} -ivfsoverlay %t/external-names-true.yaml
+
+// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': false,@g" 
%t/overlay.yaml.template > %t/external-names-false.yaml
+// RUN: %{command} -ivfsoverlay %t/external-names-false.yaml
+
+//--- prepopulate_module_cache.m
+#import 
+
+//--- test.m
+// At first import multi-path modules directly, so clang decides which .pcm 
file they should belong to.
+#import 
+#import 
+
+// Then import a module from the module cache and all its transitive 
dependencies.
+// Make sure the .pcm files loaded directly are the same as 'Redire

[PATCH] D157334: [clang] Define _MSC_EXTENSIONS on -gnu if -fms-extensions is set

2023-08-10 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D157334#4574197 , @aidengrossman 
wrote:

> It's interesting that GCC doesn't set the `_MSC_EXTENSIONS` macro with 
> `-fms-extensions`. It should if it wants to match the behavior of MSVC.

FWIW, I filed https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110977 to see what 
the GCC devs think and hopefully we can proactively avoid diverging for too 
long here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157334

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


[PATCH] D155850: [Clang][CodeGen][RFC] Add codegen support for C++ Parallel Algorithm Offload

2023-08-10 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: clang/lib/CodeGen/CGStmt.cpp:2422
+static void EmitStdParUnsupportedAsm(CodeGenFunction *CGF, const AsmStmt &S) {
+  constexpr auto Name = "ASM__stdpar_unsupported";
+

maybe prefix with `__` to avoid potential name collision with users' code


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

https://reviews.llvm.org/D155850

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


[PATCH] D154838: [analyzer] Add check for null pointer passed to %p of printf family

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

Looks pretty good.




Comment at: clang/docs/analyzer/checkers.rst:704
+optin.portabilityMinor.UnixAPI
+"
+Finds non-severe implementation-defined behavior in UNIX/Posix functions.

This line should be just as long, as the line above.



Comment at: clang/docs/analyzer/checkers.rst:705
+"
+Finds non-severe implementation-defined behavior in UNIX/Posix functions.
+

Our docs aren't great, but we should have a brief description what the checker 
detects, basically here it would be "Find null pointers being passed to 
printf-like functions. Usually, passing null pointers to such functions is 
implementation defined, thus non-portable. Printf-like functions are: x, y, z."
Illustrate one example for diagnosing a case. Also illustrate one case similar 
to the bad one, that is fixed (basically ensure that the pointer is not null 
there).
And that's it.



Comment at: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td:45-50
+// The PortabilityMinor package is for checkers that find non-severe 
portability
+// issues (see also the Portability package). Such checks may be unwanted for
+// developers who want to ignore minor portability issues, hence they are put 
in
+// a separate package.
+def PortabilityMinorOptIn : Package<"portabilityMinor">, ParentPackage;
+

I don't think we should create a separate package. A separate checker should be 
enough in `alpha.unix`, or `alpha.optin`, or just `optin`.



Comment at: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td:1671
+
+def UnixAPIPortabilityMinorChecker : Checker<"UnixAPI">,
+  HelpText<"Finds non-severe implementation-defined behavior in UNIX/Posix 
functions">,

Usually, the user-facing checker name which is the `<"...">` part there, 
matches the name of the checker's class name. It helps for maintenance.
I would strongly suggest keeping this naming convention.



Comment at: clang/include/clang/StaticAnalyzer/Checkers/Checkers.td:1673
+  HelpText<"Finds non-severe implementation-defined behavior in UNIX/Posix 
functions">,
+  Documentation;
+

Docs are not really optional these days, but we can come back later once the 
checker is ironed out.



Comment at: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp:88
 
+class UnixAPIPortabilityMinorChecker
+: public Checker> {

Usually, we put separate checkers into their own file.



Comment at: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp:89
+class UnixAPIPortabilityMinorChecker
+: public Checker> {
+public:

Prefer using the `check::PreCall` callback over the `PreStmt`.



Comment at: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp:94
+private:
+  mutable std::unique_ptr BT_printfPointerConversionSpecifierNULL;
+

Nowdays, if I'm not mistaken, we just inline initialize these eagerly.
That way you could also avoid marking it mutable.



Comment at: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp:102
+  void
+  ReportPrintfPointerConversionSpecifierNULL(clang::ento::CheckerContext &C,
+ ProgramStateRef nullState,

Feel free to just call it `reportBug`.
Also, in the cpp file, usually we use the namespaces `clang,llvm,ento` already. 
You don't need to fully-qualify these names.



Comment at: clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp:593-594
+
+  if (FName == "printf")
+CheckPrintfPointerConversionSpecifierNULL(C, CE, 1);
+

For matching names, we usually use `CallDescriptions` to do it for us.
If think you could use them while also checking if the Call is a 
`CallEvent::isGlobalCFunction()`. I suspect, you only wanna check those.
I think you should define a `CallDescriptionMap`, because you will also need 
your specific `data_arg_index`...
Look for uses of such maps and you will get inspired.



Comment at: clang/test/Analysis/unix-fns.c:81-92
+#ifndef NULL
+#define NULL ((void*) 0)
+#endif
+
+struct FILE_t;
+typedef struct FILE_t FILE;
+

I'd highly recommend not touching this file to avoid the bulk change in the 
expected plist output. Please just introduce a new test file.



Comment at: clang/test/Analysis/unix-fns.c:280-289
+// Test pointer constraint.
+void printf_pointer_conversion_specifier_null_pointer_constraint(char *format, 
void *pointer1) {
+  void *pointer2 = NULL;
+  printf(format, pointer2); // expected-warning{{The result of passing a null 
pointer to the pointer conversion specifier of the printf family of functions 
is implementation defined}}
+  if (pointer1 != NULL) {
+printf(format, pointer1); // no-warning
+return;

I would appreciate a 

[PATCH] D157606: [C2x] Support -std=c23 and -std=gnu23

2023-08-10 Thread Aaron Ballman 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 rG13629b140801: [C2x] Support -std=c23 and -std=gnu23 
(authored by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157606

Files:
  clang-tools-extra/clangd/index/StdLib.cpp
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/LangStandards.def
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Headers/limits.h
  clang/lib/Headers/stdalign.h
  clang/lib/Headers/stdarg.h
  clang/lib/Headers/stdatomic.h
  clang/lib/Headers/stddef.h
  clang/lib/Headers/stdint.h
  clang/test/C/C11/n1330.c
  clang/test/C/drs/dr0xx.c
  clang/test/C/drs/dr2xx.c
  clang/test/C/drs/dr3xx.c
  clang/test/C/drs/dr411.c
  clang/test/Driver/unknown-std.c
  clang/test/Headers/limits.cpp
  clang/test/Headers/stdint.c
  clang/test/Lexer/unicode.c
  clang/test/Lexer/utf8-char-literal.cpp
  clang/test/Preprocessor/c2x.c
  clang/test/Preprocessor/ucn-allowed-chars.c
  clang/test/Sema/atomic-expr.c

Index: clang/test/Sema/atomic-expr.c
===
--- clang/test/Sema/atomic-expr.c
+++ clang/test/Sema/atomic-expr.c
@@ -152,23 +152,23 @@
   _Atomic(const int *) acip5 = cicp;
   _Atomic(const void *) acvip3 = cicp;
 
-#if __STDC_VERSION__ >= 202000L
+#if __STDC_VERSION__ >= 202311L
   // the left operand has an atomic ... version of the nullptr_t type and the
   // right operand is a null pointer constant or its type is nullptr_t
   typedef typeof(nullptr) nullptr_t;
   nullptr_t n;
   _Atomic nullptr_t cn2 = n;
   _Atomic nullptr_t cn3 = nullptr;
-#endif // __STDC_VERSION__ >= 202000L
+#endif // __STDC_VERSION__ >= 202311L
 
   // the left operand is an atomic ... pointer, and the right operand is a null
   // pointer constant or its type is nullptr_t;
   _Atomic(int *) aip2 = 0;
-#if __STDC_VERSION__ >= 202000L
+#if __STDC_VERSION__ >= 202311L
   _Atomic(int *) ip2 = n;
   _Atomic(int *) ip3 = nullptr;
   _Atomic(const int *) ip4 = nullptr;
-#endif // __STDC_VERSION__ >= 202000L
+#endif // __STDC_VERSION__ >= 202311L
 }
 
 // Ensure that the assignment constraints also work at file scope.
@@ -185,14 +185,14 @@
 const void *cvp = 0;
 _Atomic(const int *) acip2 = cvp; // expected-error {{initializer element is not a compile-time constant}}
 
-#if __STDC_VERSION__ >= 202000L
+#if __STDC_VERSION__ >= 202311L
   // the left operand has an atomic ... version of the nullptr_t type and the
   // right operand is a null pointer constant or its type is nullptr_t
   typedef typeof(nullptr) nullptr_t;
   nullptr_t n;
   _Atomic nullptr_t cn2 = n; // expected-error {{initializer element is not a compile-time constant}}
   _Atomic(int *) aip2 = nullptr;
-#endif // __STDC_VERSION__ >= 202000L
+#endif // __STDC_VERSION__ >= 202311L
 
 // FIXME: &ai is an address constant, so this should be accepted as an
 // initializer, but the bit-cast inserted due to the pointer conversion is
Index: clang/test/Preprocessor/ucn-allowed-chars.c
===
--- clang/test/Preprocessor/ucn-allowed-chars.c
+++ clang/test/Preprocessor/ucn-allowed-chars.c
@@ -53,8 +53,8 @@
 
 # endif
 #else
-# if __STDC_VERSION__ >= 201800L
-// C2X
+# if __STDC_VERSION__ >= 202311L
+// C23
 // expected-warning@8 {{using this character in an identifier is incompatible with C99}}
 // expected-error@10 {{character  not allowed in an identifier}}
 // expected-error@12 {{character  not allowed in an identifier}}
Index: clang/test/Preprocessor/c2x.c
===
--- clang/test/Preprocessor/c2x.c
+++ clang/test/Preprocessor/c2x.c
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c2x %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c23 %s
 // expected-no-diagnostics
 
-// FIXME: Test the correct value once C23 ships.
-_Static_assert(__STDC_VERSION__ > 201710L, "Incorrect __STDC_VERSION__");
+_Static_assert(__STDC_VERSION__ == 202311L, "Incorrect __STDC_VERSION__");
Index: clang/test/Lexer/utf8-char-literal.cpp
===
--- clang/test/Lexer/utf8-char-literal.cpp
+++ clang/test/Lexer/utf8-char-literal.cpp
@@ -16,7 +16,7 @@
 char d = u8'\u1234'; // expected-error {{character too large for enclosing character literal type}}
 char e = u8'ሴ'; // expected-error {{character too large for enclosing character literal type}}
 char f = u8'ab'; // expected-error {{Unicode character literals may not contain multiple characters}}
-#elif __STDC_VERSION__ >= 202000L
+#elif __STDC_VERSION__ >= 202311L
 char a = u8'ñ';  // expected-error {{character too large for enclosing character literal type}}
 char b = u8'\x80';   // ok
 char c = u8'\u'; // ok
@@ -49,8 +49,8 @@
 #  endif
 #endif
 
-/// In C2x, u8 char literals are always

[PATCH] D157572: [clang] Add `[[clang::library_extension]]` attribute

2023-08-10 Thread Nikolas Klauser via Phabricator via cfe-commits
philnik added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:5690-5691
+def warn_unknown_ext : Warning<"Unknown extension kind: %0">;
+def warn_cxx11_ext : Warning<"%0 is a C++11 extension">,
+InGroup;
+def warn_cxx14_ext : Warning<"%0 is a C++14 extension">,

cjdb wrote:
> We shouldn't need this one, since Clang (almost) doesn't distinguish between 
> C++03 and C++11. To my knowledge, C++03 doesn't even support attributes, so 
> this would be a moot addition.
It does enough to regularly cause headaches (no `>>`, `constexpr`, `alignas`, 
buggy `enum class`). C++03 has supported GNU attributes forever, and since LLVM 
17 also supports C++11 attributes. Also note that this isn't a new warning.



Comment at: clang/test/SemaCXX/attr-library-extension.cpp:9-13
+#ifdef GNUAttr
+#define EXTENSION(name) __attribute__((library_extension(name)))
+#else
+#define EXTENSION(name) [[clang::library_extension(name)]]
+#endif

cjdb wrote:
> I don't think we need to test for both of these: using 
> `[[clang::library_extension]]` directly should suffice.
I've been asked to test both before, and IMO it's a good idea, since there are 
attributes which only have one of the spellings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157572

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


[PATCH] D157445: [CodeGen][UBSan] Add support for handling attributed functions in getUBSanFunctionTypeHash.

2023-08-10 Thread Yeoul Na via Phabricator via cfe-commits
rapidsna requested changes to this revision.
rapidsna added a comment.
This revision now requires changes to proceed.

We should add a test to exercise when `Ty` is wrapped by other sugar types. 
Could you try with `typedef`?




Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:573-575
+  if (isa(Ty))
+Ty = Ty.getDesugaredType(getContext());
+





Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:578
   // noexcept function through a non-noexcept pointer.
   if (!isa(Ty))
 Ty = getContext().getFunctionTypeWithExceptionSpec(Ty, EST_None);

Checking `isa` still doesn't handle cases where `Ty` is wrapped in other 
sugar types (not just `AttributedType`).

Instead of adding `if (isa(Ty))` above, I would use
`Ty->isFunctionNoProtoType()` here.

`isFunctionNoProtoType` is a helper function that uses 
`getAs()`. `getAs` removes any existing sugar until it 
reaches `T` or a non-sugar type.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157445

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


[PATCH] D157149: [Option] Add "Visibility" field and clone the OptTable APIs to use it

2023-08-10 Thread Justin Bogner via Phabricator via cfe-commits
bogner updated this revision to Diff 549111.
bogner added a comment.

Resolve conflicts


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157149

Files:
  clang-tools-extra/clangd/CompileCommands.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  lld/MachO/DriverUtils.cpp
  lld/MinGW/Driver.cpp
  lld/wasm/Driver.cpp
  llvm/include/llvm/Option/OptParser.td
  llvm/include/llvm/Option/OptTable.h
  llvm/include/llvm/Option/Option.h
  llvm/lib/ExecutionEngine/JITLink/COFFDirectiveParser.cpp
  llvm/lib/Option/OptTable.cpp
  llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp
  llvm/lib/ToolDrivers/llvm-lib/LibDriver.cpp
  llvm/tools/dsymutil/dsymutil.cpp
  llvm/tools/llvm-cvtres/llvm-cvtres.cpp
  llvm/tools/llvm-cxxfilt/llvm-cxxfilt.cpp
  llvm/tools/llvm-debuginfod/llvm-debuginfod.cpp
  llvm/tools/llvm-dwarfutil/llvm-dwarfutil.cpp
  llvm/tools/llvm-dwp/llvm-dwp.cpp
  llvm/tools/llvm-lipo/llvm-lipo.cpp
  llvm/tools/llvm-mt/llvm-mt.cpp
  llvm/tools/llvm-objcopy/ObjcopyOptions.cpp
  llvm/tools/llvm-rc/llvm-rc.cpp
  llvm/tools/llvm-strings/llvm-strings.cpp
  llvm/tools/llvm-symbolizer/llvm-symbolizer.cpp
  llvm/tools/llvm-tli-checker/llvm-tli-checker.cpp
  llvm/unittests/Option/OptionMarshallingTest.cpp
  llvm/unittests/Option/OptionParsingTest.cpp
  llvm/unittests/Option/Opts.td
  llvm/utils/TableGen/OptParserEmitter.cpp

Index: llvm/utils/TableGen/OptParserEmitter.cpp
===
--- llvm/utils/TableGen/OptParserEmitter.cpp
+++ llvm/utils/TableGen/OptParserEmitter.cpp
@@ -302,7 +302,7 @@
   OS << "INVALID";
 
 // The other option arguments (unused for groups).
-OS << ", INVALID, nullptr, 0, 0";
+OS << ", INVALID, nullptr, 0, 0, 0";
 
 // The option help text.
 if (!isa(R.getValueInit("HelpText"))) {
@@ -340,8 +340,10 @@
 // The containing option group (if any).
 OS << ", ";
 const ListInit *GroupFlags = nullptr;
+const ListInit *GroupVis = nullptr;
 if (const DefInit *DI = dyn_cast(R.getValueInit("Group"))) {
   GroupFlags = DI->getDef()->getValueAsListInit("Flags");
+  GroupVis = DI->getDef()->getValueAsListInit("Vis");
   OS << getOptionName(*DI->getDef());
 } else
   OS << "INVALID";
@@ -382,6 +384,21 @@
 if (NumFlags == 0)
   OS << '0';
 
+// The option visibility flags.
+OS << ", ";
+int NumVisFlags = 0;
+LI = R.getValueAsListInit("Vis");
+for (Init *I : *LI)
+  OS << (NumVisFlags++ ? " | " : "")
+ << cast(I)->getDef()->getName();
+if (GroupVis) {
+  for (Init *I : *GroupVis)
+OS << (NumVisFlags++ ? " | " : "")
+   << cast(I)->getDef()->getName();
+}
+if (NumVisFlags == 0)
+  OS << '0';
+
 // The option parameter field.
 OS << ", " << R.getValueAsInt("NumArgs");
 
Index: llvm/unittests/Option/Opts.td
===
--- llvm/unittests/Option/Opts.td
+++ llvm/unittests/Option/Opts.td
@@ -4,6 +4,8 @@
 def OptFlag2 : OptionFlag;
 def OptFlag3 : OptionFlag;
 
+def SubtoolVis : OptionVisibility;
+
 def A : Flag<["-"], "A">, HelpText<"The A option">, Flags<[OptFlag1]>;
 def AB : Flag<["-"], "AB">;
 def B : Joined<["-"], "B">, HelpText<"The B option">, MetaVarName<"B">, Flags<[OptFlag2]>;
@@ -35,6 +37,8 @@
 def Cramb : Joined<["/"], "cramb:">, HelpText<"The cramb option">, MetaVarName<"CRAMB">, Flags<[OptFlag1]>;
 def Doopf1 : Flag<["-"], "doopf1">, HelpText<"The doopf1 option">, Flags<[OptFlag1]>;
 def Doopf2 : Flag<["-"], "doopf2">, HelpText<"The doopf2 option">, Flags<[OptFlag2]>;
+def Xyzzy1 : Flag<["-"], "xyzzy1">, HelpText<"The xyzzy1 option">, Vis<[SubtoolVis]>;
+def Xyzzy2 : Flag<["-"], "xyzzy2">, HelpText<"The xyzzy2 option">, Vis<[Default]>;
 def Ermgh : Joined<["--"], "ermgh">, HelpText<"The ermgh option">, MetaVarName<"ERMGH">, Flags<[OptFlag1]>;
 def Fjormp : Flag<["--"], "fjormp">, HelpText<"The fjormp option">, Flags<[OptFlag1]>;
 
@@ -43,6 +47,9 @@
 def Blurmpq : Flag<["--"], "blurmp">;
 def Blurmpq_eq : Flag<["--"], "blurmp=">;
 
+def Q : Flag<["-"], "Q">, Vis<[SubtoolVis]>;
+def R : Flag<["-"], "R">, Vis<[Default, SubtoolVis]>;
+
 class XOpts : KeyPathAndMacro<"X->", base> {}
 
 def marshalled_flag_d : Flag<["-"], "marshalled-flag-d">,
Index: llvm/unittests/Option/OptionParsingTest.cpp
===
--- llvm/unittests/Option/OptionParsingTest.cpp
+++ llvm/unittests/Option/OptionParsingTest.cpp
@@ -44,6 +44,10 @@
   OptFlag3 = (1 << 6)
 };
 
+enum OptionVisibility {
+  SubtoolVis = (1 << 2),
+};
+
 static constexpr OptTable::Info InfoTable[] = {
 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
 #include "Opts.inc"
@@ -163,6 +167,43 @@
   EXPECT_EQ("bar", AL.getLastArgValue(OPT_C));
 }
 
+TYPED_TEST(OptTableTest, ParseWithVisibility) {
+  TypeParam T;
+  unsigned MAI, MAC;
+
+  const char *STArgs[] = {"-A

[clang-tools-extra] 13629b1 - [C2x] Support -std=c23 and -std=gnu23

2023-08-10 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-08-10T13:57:40-04:00
New Revision: 13629b140801870feff855ca168edf6b34dbef8d

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

LOG: [C2x] Support -std=c23 and -std=gnu23

C2x was finalized at the June 2023 WG14 meeting. The DIS is out for
balloting and the comment period for that closes later this year/early
next year. While that does leave an opportunity for more changes to the
standard during the DIS ballot resolution process, only editorial
changes are anticipated and as a result, the C committee considers C2x
to be final. The committee took a straw poll on what we'd prefer the
informal name of the standard be, and we decided it should be called
C23 regardless of what year ISO publishes it.

However, because the final publication is not out, this patch does not
add the language standard alias for the -std=iso9899: spelling of
the standard mode; that will be added once ISO finally publishes the
document and the year chosen will match the publication date.

This also changes the value of __STDC_VERSION__ from the placeholder
value 202000L to the final value 202311L.

Subsequent patches will start renaming things from c2x to c23, cleaning
up documentation, etc.

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

Added: 


Modified: 
clang-tools-extra/clangd/index/StdLib.cpp
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/LangStandards.def
clang/lib/Frontend/InitPreprocessor.cpp
clang/lib/Headers/limits.h
clang/lib/Headers/stdalign.h
clang/lib/Headers/stdarg.h
clang/lib/Headers/stdatomic.h
clang/lib/Headers/stddef.h
clang/lib/Headers/stdint.h
clang/test/C/C11/n1330.c
clang/test/C/drs/dr0xx.c
clang/test/C/drs/dr2xx.c
clang/test/C/drs/dr3xx.c
clang/test/C/drs/dr411.c
clang/test/Driver/unknown-std.c
clang/test/Headers/limits.cpp
clang/test/Headers/stdint.c
clang/test/Lexer/unicode.c
clang/test/Lexer/utf8-char-literal.cpp
clang/test/Preprocessor/c2x.c
clang/test/Preprocessor/ucn-allowed-chars.c
clang/test/Sema/atomic-expr.c

Removed: 




diff  --git a/clang-tools-extra/clangd/index/StdLib.cpp 
b/clang-tools-extra/clangd/index/StdLib.cpp
index d9aa46d6b75b15..f12b246255c9f1 100644
--- a/clang-tools-extra/clangd/index/StdLib.cpp
+++ b/clang-tools-extra/clangd/index/StdLib.cpp
@@ -60,7 +60,7 @@ LangStandard::Kind standardFromOpts(const LangOptions &LO) {
 return LangStandard::lang_cxx98;
   }
   if (LO.C2x)
-return LangStandard::lang_c2x;
+return LangStandard::lang_c23;
   // C17 has no new features, so treat {C11,C17} as C17.
   if (LO.C11)
 return LangStandard::lang_c17;

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8fa0c14b9ed0c3..8d15845625b888 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -98,6 +98,10 @@ C Language Changes
 
 C2x Feature Support
 ^^^
+- Clang now accepts ``-std=c23`` and ``-std=gnu23`` as language standard modes,
+  and the ``__STDC_VERSION__`` macro now expands to ``202311L`` instead of its
+  previous placeholder value. Clang continues to accept ``-std=c2x`` and
+  ``-std=gnu2x`` as aliases for C23 and GNU C23, respectively.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/include/clang/Basic/LangStandards.def 
b/clang/include/clang/Basic/LangStandards.def
index 5c28bdd28ef257..90e279ffb790c8 100644
--- a/clang/include/clang/Basic/LangStandards.def
+++ b/clang/include/clang/Basic/LangStandards.def
@@ -87,13 +87,17 @@ LANGSTANDARD(gnu17, "gnu17",
  LineComment | C99 | C11 | C17 | Digraphs | GNUMode | HexFloat)
 LANGSTANDARD_ALIAS(gnu17, "gnu18")
 
-// C2x modes
-LANGSTANDARD(c2x, "c2x",
- C, "Working Draft for ISO C2x",
+// C23 modes
+LANGSTANDARD(c23, "c23",
+ C, "Working Draft for ISO C23",
  LineComment | C99 | C11 | C17 | C2x | Digraphs | HexFloat)
-LANGSTANDARD(gnu2x, "gnu2x",
- C, "Working Draft for ISO C2x with GNU extensions",
+LANGSTANDARD_ALIAS_DEPR(c23, "c2x")
+LANGSTANDARD(gnu23, "gnu23",
+ C, "Working Draft for ISO C23 with GNU extensions",
  LineComment | C99 | C11 | C17 | C2x | Digraphs | GNUMode | 
HexFloat)
+LANGSTANDARD_ALIAS_DEPR(gnu23, "gnu2x")
+// FIXME: Add the alias for iso9899:202* once we know the year ISO publishes
+// the document (expected to be 2024).
 
 // C++ modes
 LANGSTANDARD(cxx98, "c++98",

diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 6df18a1d6e8880..0f5077712dd04a 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -438,9 +438,8 @@ static

[PATCH] D155833: [Clang][Sema][RFC] Add Sema support for C++ Parallel Algorithm Offload

2023-08-10 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx updated this revision to Diff 549113.
AlexVlx removed a reviewer: jdoerfert.
AlexVlx added a comment.

Remove noise / unintended file. Add support for dealing with unsupported ASM.


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

https://reviews.llvm.org/D155833

Files:
  clang/lib/Sema/SemaCUDA.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  clang/test/SemaStdPar/Inputs/stdpar_lib.hpp
  clang/test/SemaStdPar/device-can-call-host.cpp

Index: clang/test/SemaStdPar/device-can-call-host.cpp
===
--- /dev/null
+++ clang/test/SemaStdPar/device-can-call-host.cpp
@@ -0,0 +1,91 @@
+// RUN: %clang %s --stdpar --stdpar-path=%S/Inputs \
+// RUN:   --stdpar-thrust-path=%S/Inputs --stdpar-prim-path=%S/Inputs \
+// RUN:   --offload-device-only -emit-llvm -o /dev/null -Xclang -verify
+
+// Note: These would happen implicitly, within the implementation of the
+//   accelerator specific algorithm library, and not from user code.
+
+// Calls from the accelerator side to implicitly host (i.e. unannotated)
+// functions are fine.
+
+// expected-no-diagnostics
+
+extern "C" void host_fn() {}
+
+struct Dummy {};
+
+struct S {
+  S() {}
+  ~S() { host_fn(); }
+
+  int x;
+};
+
+struct T {
+  __device__ void hd() { host_fn(); }
+
+  __device__ void hd3();
+
+  void h() {}
+
+  void operator+();
+  void operator-(const T&) {}
+
+  operator Dummy() { return Dummy(); }
+};
+
+__device__ void T::hd3() { host_fn(); }
+
+template  __device__ void hd2() { host_fn(); }
+
+__global__ void kernel() { hd2(); }
+
+__device__ void hd() { host_fn(); }
+
+template  __device__ void hd3() { host_fn(); }
+__device__ void device_fn() { hd3(); }
+
+__device__ void local_var() {
+  S s;
+}
+
+__device__ void explicit_destructor(S *s) {
+  s->~S();
+}
+
+__device__ void hd_member_fn() {
+  T t;
+
+  t.hd();
+}
+
+__device__ void h_member_fn() {
+  T t;
+  t.h();
+}
+
+__device__ void unaryOp() {
+  T t;
+  (void) +t;
+}
+
+__device__ void binaryOp() {
+  T t;
+  (void) (t - t);
+}
+
+__device__ void implicitConversion() {
+  T t;
+  Dummy d = t;
+}
+
+template 
+struct TmplStruct {
+  template  __device__ void fn() {}
+};
+
+template <>
+template <>
+__device__ void TmplStruct::fn() { host_fn(); }
+
+__device__ void double_specialization() { TmplStruct().fn(); }
Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -271,7 +271,8 @@
   OutputName = Names[i]->getName();
 
 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
-if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
+if (!Context.getTargetInfo().validateOutputConstraint(Info) &&
+!(LangOpts.HIPStdPar && LangOpts.CUDAIsDevice)) {
   targetDiag(Literal->getBeginLoc(),
  diag::err_asm_invalid_output_constraint)
   << Info.getConstraintStr();
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -19106,7 +19106,7 @@
   // Diagnose ODR-use of host global variables in device functions.
   // Reference of device global variables in host functions is allowed
   // through shadow variables therefore it is not diagnosed.
-  if (SemaRef.LangOpts.CUDAIsDevice) {
+  if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
 SemaRef.targetDiag(Var->getLocation(),
Index: clang/lib/Sema/SemaCUDA.cpp
===
--- clang/lib/Sema/SemaCUDA.cpp
+++ clang/lib/Sema/SemaCUDA.cpp
@@ -231,6 +231,15 @@
   (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
 return CFP_Native;
 
+  // StdPar mode is special, in that assessing whether a device side call to a
+  // host target is deferred to a subsequent pass, and cannot unambiguously be
+  // adjudicated in the AST, hence we optimistically allow them to pass here.
+  if (getLangOpts().HIPStdPar &&
+  (CallerTarget == CFT_Global || CallerTarget == CFT_Device ||
+   CallerTarget == CFT_HostDevice) &&
+  CalleeTarget == CFT_Host)
+return CFP_HostDevice;
+
   // (d) HostDevice behavior depends on compilation mode.
   if (CallerTarget == CFT_HostDevice) {
 // It's OK to call a compilation-mode matching function from an HD one.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157637: [ASTImporter][NFC] Fix typo in testcase

2023-08-10 Thread Ding Fei via Phabricator via cfe-commits
danix800 created this revision.
danix800 added a reviewer: balazske.
Herald added a subscriber: martong.
Herald added a reviewer: a.sidorin.
Herald added a project: All.
danix800 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fix typo in testcase.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157637

Files:
  clang/unittests/AST/StructuralEquivalenceTest.cpp


Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -992,8 +992,8 @@
 
 TEST_F(StructuralEquivalenceRecordContextTest, NamespaceInlineTopLevel) {
   auto Decls =
-  makeNamedDecls("inline namespace A { class X; } }",
- "inline namespace B { class X; } }", Lang_CXX17, "X");
+  makeNamedDecls("inline namespace A { class X; }",
+ "inline namespace B { class X; }", Lang_CXX17, "X");
   EXPECT_TRUE(testStructuralMatch(Decls));
 }
 


Index: clang/unittests/AST/StructuralEquivalenceTest.cpp
===
--- clang/unittests/AST/StructuralEquivalenceTest.cpp
+++ clang/unittests/AST/StructuralEquivalenceTest.cpp
@@ -992,8 +992,8 @@
 
 TEST_F(StructuralEquivalenceRecordContextTest, NamespaceInlineTopLevel) {
   auto Decls =
-  makeNamedDecls("inline namespace A { class X; } }",
- "inline namespace B { class X; } }", Lang_CXX17, "X");
+  makeNamedDecls("inline namespace A { class X; }",
+ "inline namespace B { class X; }", Lang_CXX17, "X");
   EXPECT_TRUE(testStructuralMatch(Decls));
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155833: [Clang][Sema][RFC] Add Sema support for C++ Parallel Algorithm Offload

2023-08-10 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx updated this revision to Diff 549117.
AlexVlx added a comment.

Fix typo.


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

https://reviews.llvm.org/D155833

Files:
  clang/lib/Sema/SemaCUDA.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaStmtAsm.cpp
  clang/test/SemaStdPar/Inputs/stdpar_lib.hpp
  clang/test/SemaStdPar/device-can-call-host.cpp

Index: clang/test/SemaStdPar/device-can-call-host.cpp
===
--- /dev/null
+++ clang/test/SemaStdPar/device-can-call-host.cpp
@@ -0,0 +1,91 @@
+// RUN: %clang %s --stdpar --stdpar-path=%S/Inputs \
+// RUN:   --stdpar-thrust-path=%S/Inputs --stdpar-prim-path=%S/Inputs \
+// RUN:   --offload-device-only -emit-llvm -o /dev/null -Xclang -verify
+
+// Note: These would happen implicitly, within the implementation of the
+//   accelerator specific algorithm library, and not from user code.
+
+// Calls from the accelerator side to implicitly host (i.e. unannotated)
+// functions are fine.
+
+// expected-no-diagnostics
+
+extern "C" void host_fn() {}
+
+struct Dummy {};
+
+struct S {
+  S() {}
+  ~S() { host_fn(); }
+
+  int x;
+};
+
+struct T {
+  __device__ void hd() { host_fn(); }
+
+  __device__ void hd3();
+
+  void h() {}
+
+  void operator+();
+  void operator-(const T&) {}
+
+  operator Dummy() { return Dummy(); }
+};
+
+__device__ void T::hd3() { host_fn(); }
+
+template  __device__ void hd2() { host_fn(); }
+
+__global__ void kernel() { hd2(); }
+
+__device__ void hd() { host_fn(); }
+
+template  __device__ void hd3() { host_fn(); }
+__device__ void device_fn() { hd3(); }
+
+__device__ void local_var() {
+  S s;
+}
+
+__device__ void explicit_destructor(S *s) {
+  s->~S();
+}
+
+__device__ void hd_member_fn() {
+  T t;
+
+  t.hd();
+}
+
+__device__ void h_member_fn() {
+  T t;
+  t.h();
+}
+
+__device__ void unaryOp() {
+  T t;
+  (void) +t;
+}
+
+__device__ void binaryOp() {
+  T t;
+  (void) (t - t);
+}
+
+__device__ void implicitConversion() {
+  T t;
+  Dummy d = t;
+}
+
+template 
+struct TmplStruct {
+  template  __device__ void fn() {}
+};
+
+template <>
+template <>
+__device__ void TmplStruct::fn() { host_fn(); }
+
+__device__ void double_specialization() { TmplStruct().fn(); }
Index: clang/lib/Sema/SemaStmtAsm.cpp
===
--- clang/lib/Sema/SemaStmtAsm.cpp
+++ clang/lib/Sema/SemaStmtAsm.cpp
@@ -271,7 +271,8 @@
   OutputName = Names[i]->getName();
 
 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
-if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
+if (!Context.getTargetInfo().validateOutputConstraint(Info) &&
+!(LangOpts.HIPStdPar && LangOpts.CUDAIsDevice)) {
   targetDiag(Literal->getBeginLoc(),
  diag::err_asm_invalid_output_constraint)
   << Info.getConstraintStr();
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -19106,7 +19106,7 @@
   // Diagnose ODR-use of host global variables in device functions.
   // Reference of device global variables in host functions is allowed
   // through shadow variables therefore it is not diagnosed.
-  if (SemaRef.LangOpts.CUDAIsDevice) {
+  if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
 SemaRef.targetDiag(Var->getLocation(),
Index: clang/lib/Sema/SemaCUDA.cpp
===
--- clang/lib/Sema/SemaCUDA.cpp
+++ clang/lib/Sema/SemaCUDA.cpp
@@ -231,6 +231,15 @@
   (CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
 return CFP_Native;
 
+  // StdPar mode is special, in that assessing whether a device side call to a
+  // host target is deferred to a subsequent pass, and cannot unambiguously be
+  // adjudicated in the AST, hence we optimistically allow them to pass here.
+  if (getLangOpts().HIPStdPar &&
+  (CallerTarget == CFT_Global || CallerTarget == CFT_Device ||
+   CallerTarget == CFT_HostDevice) &&
+  CalleeTarget == CFT_Host)
+return CFP_HostDevice;
+
   // (d) HostDevice behavior depends on compilation mode.
   if (CallerTarget == CFT_HostDevice) {
 // It's OK to call a compilation-mode matching function from an HD one.
@@ -877,7 +886,7 @@
   if (!ShouldCheck || !Capture.isReferenceCapture())
 return;
   auto DiagKind = SemaDiagnosticBuilder::K_Deferred;
-  if (Capture.isVariableCapture()) {
+  if (Capture.isVariableCapture() && !getLangOpts().HIPStdPar) {
 SemaDiagnosticBuilder(DiagKind, Capture.getLocation(),
   diag::err_capture_bad_target, Callee, *this)
 << Capture.getVariable();
___
cfe-commits mailing lis

[PATCH] D157334: [clang] Define _MSC_EXTENSIONS on -gnu if -fms-extensions is set

2023-08-10 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In D157334#4573902 , @aaron.ballman 
wrote:

> I'm curious to hear what others think about this (especially @rnk and @hans).

Seems reasonable to me.

(Looks like the define was originally added here: 
https://github.com/llvm/llvm-project/commit/4992ca4b17d82743c304f4c1b2da020f237d6b18)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157334

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


[clang] 315d1d0 - [C23] Update user-facing docs for C23

2023-08-10 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-08-10T14:19:41-04:00
New Revision: 315d1d094f7fe3f2a28fb3658f576bea0c33c094

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

LOG: [C23] Update user-facing docs for C23

This changes some public references of C2x to be C23, corrects standard
citations to use the final paragraph numbers, and adds some information
about differences between C17 and C23 modes.

Added: 


Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/MatrixTypes.rst
clang/docs/ReleaseNotes.rst
clang/docs/UsersManual.rst

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index be80751b40668a..56c277983a7403 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -612,7 +612,7 @@ to perform additional operations on certain scalar and 
vector types.
 
 Let ``T`` be one of the following types:
 
-* an integer type (as in C2x 6.2.5p19), but excluding enumerated types and 
_Bool
+* an integer type (as in C23 6.2.5p22), but excluding enumerated types and 
``bool``
 * the standard floating types float or double
 * a half-precision floating point type, if one is supported on the target
 * a vector type.
@@ -1462,8 +1462,8 @@ Conditional ``explicit``   
__cpp_conditional_explicit   C++20
 ``static operator()``  __cpp_static_call_operator   C++23  
   C++03
 --  
- -
 Designated initializers (N494)  C99
   C89
-Array & element qualification (N2607)   C2x
   C89
-Attributes (N2335)  C2x
   C89
+Array & element qualification (N2607)   C23
   C89
+Attributes (N2335)  C23
   C89
 ==  
= =
 
 Type Trait Primitives
@@ -3669,7 +3669,7 @@ A predefined typedef for the target-specific ``va_list`` 
type.
 
 A builtin function for the target-specific ``va_start`` function-like macro.
 The ``parameter-name`` argument is the name of the parameter preceding the
-ellipsis (``...``) in the function signature. Alternatively, in C2x mode or
+ellipsis (``...``) in the function signature. Alternatively, in C23 mode or
 later, it may be the integer literal ``0`` if there is no parameter preceding
 the ellipsis. This function initializes the given ``__builtin_va_list`` object.
 It is undefined behavior to call this function on an already initialized

diff  --git a/clang/docs/MatrixTypes.rst b/clang/docs/MatrixTypes.rst
index 2efebbfad93819..e32e13b73aba61 100644
--- a/clang/docs/MatrixTypes.rst
+++ b/clang/docs/MatrixTypes.rst
@@ -33,7 +33,7 @@ program is ill-formed.
 Currently, the element type of a matrix is only permitted to be one of the
 following types:
 
-* an integer type (as in C2x 6.2.5p19), but excluding enumerated types and 
``_Bool``
+* an integer type (as in C23 6.2.5p22), but excluding enumerated types and 
``bool``
 * the standard floating types ``float`` or ``double``
 * a half-precision floating point type, if one is supported on the target
 
@@ -68,7 +68,7 @@ rows and columns are the same and the value's elements can be 
converted to the
 element type of the result type. The result is a matrix where each element is
 the converted corresponding element.
 
-A value of any real type (as in C2x 6.2.5p17) can be converted to a matrix type
+A value of any real type (as in C23 6.2.5p14) can be converted to a matrix type
 if it can be converted to the element type of the matrix. The result is a
 matrix where all elements are the converted original value.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8d15845625b888..c438db074a19b7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -96,7 +96,7 @@ C Language Changes
   constant expressions.  This change is more consistent with the behavior of
   GCC.
 
-C2x Feature Support
+C23 Feature Support
 ^^^
 - Clang now accepts ``-std=c23`` and ``-std=gnu23`` as language standard modes,
   and the ``__STDC_VERSION__`` macro now expands to ``202311L`` instead of its

diff  --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index a774fd91aa277f..558e205d69c2a3 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -3172,7 +3172,7 @@ Differences between various standard modes
 
 clang supports the -std option, which changes what language mode clang uses.
 The supported modes for C are c89, gnu89

[PATCH] D156312: [analyzer] Upstream BitwiseShiftChecker

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

Great progress.
Now, moving to the docs.
Have you checked that the docs compile without errors and look as you would 
expect? Please post how it looks.

Please make a note about this new checker in the clang's release docs, as we 
usually announce new checkers and major changes there.




Comment at: clang/docs/analyzer/checkers.rst:58-64
+ int basic_examples(int a, int b) {
+   if (b < 0) {
+ return a >> b; // warn: right argument is negative
+   } else if (b >= 32) {
+ return a << b; // warn: right argument >= capacity
+   }
+ }

else after return



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:272
+  if (const auto ConcreteRight = Right.getAs()) {
+const std::int64_t RHS = ConcreteRight->getValue().getExtValue();
+assert(RHS > MaximalAllowedShift);

`getExtValue()`, I believe, asserts that it "fits", thus the concrete int is at 
most 64 bits wide. Does it work for `_BigInt`s? (or whatever we have like that 
:D)



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:299-303
+  if (Side == OperandSide::Left) {
+NonNegOperands |= NonNegLeft;
+  } else {
+NonNegOperands |= NonNegRight;
+  }

When I see something like this I always think of using a ternary.
Have you also considered?



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:335-339
+auto R =
+std::make_unique(BT, ShortMsg, Msg, ErrNode);
+bugreporter::trackExpressionValue(ErrNode, Op->getLHS(), *R);
+bugreporter::trackExpressionValue(ErrNode, Op->getRHS(), *R);
+return R;

AHA! Now I got you. You also call this `R`.
Just use `R` at the callsite as well. Job done.



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:355-357
+if (!BTPtr)
+  BTPtr = std::make_unique(this, "Bitwise shift",
+"Suspicious operation");

How about eagerly inline initializing this field? And avoiding `mutable` as 
well.



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:367-369
+
+  const AnalyzerOptions &Opts = Mgr.getAnalyzerOptions();
+





Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:53
+class BitwiseShiftValidator {
+  // Primary mutable state:
+  CheckerContext &Ctx;

donat.nagy wrote:
> steakhal wrote:
> > Where does this comment corresponds to?
> The two data members (`Ctx` and `State`) that are directly below the comment.
> 
> I tried to split the list of data members into three groups (primary mutable 
> state, secondary mutable state, `const`  members), but now I reconsider this 
> I feel that these header comments are actually superfluous.
> 
> I'll return to a variant of the earlier layout where I put 
> `NonNegFlags`/`UpperBound` to the end and comment that they are only used for 
> note tag creation; but don't emphasize the (immediately visible) `const`ness 
> / non-`const`-ness of other members with comments.
One way to emphasize this is by choosing names like `FoldedState`, or anything 
else that has something to do with "motion" or "change".
Given that if we have `ProgramStateRefs` in helper classes they usually remain 
still. Think of BugReportVisitors for example. Consequently,it's important to 
raise awareness when it's not like that. A different name would achieve this.



Comment at: clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp:57-59
+  // Secondary mutable state, used only for note tag creation:
+  enum { NonNegLeft = 1, NonNegRight = 2 };
+  unsigned NonNegFlags = 0;

donat.nagy wrote:
> donat.nagy wrote:
> > steakhal wrote:
> > > How about using the same enum type for these two? It would signify that 
> > > these are used together.
> > > Also, by only looking at the possible values, it's not apparent that 
> > > these are bitflag values. A suffix might help the reader.
> > Using the enum type is a good idea, however I'd probably put the `Flag` 
> > suffix into the name of the type:
> > ```
> > enum SignednessFlags : unsigned { NonNegLeft = 1, NonNegRight = 2 };
> > SignednessFlags NonNegOperands = 0;
> > ```
> I rename the member `NonNegFlags` to `NonNegOperands` but its type remains a 
> plain `unsigned` because otherwise using the or-assign operator like 
> `NonNegOperands |= NonNegLeft` produces the error
> > Assigning to 'enum SignednessFlags' from incompatible type 'unsigned int' 
> > (clang typecheck_convert_incompatible)
> (note that both operands were from the same enum type).
Okay, indeed one would need to define the `operator|(SignednessStatus, 
SignednessStatus)` and `operato&|(SignednessStatus, SignednessStatus)` as well.
It probably doesn't worth it. Such a pity that we can't have nice things in C++.



[PATCH] D155610: [Clang][Sema] Fix display of characters on static assertion failure

2023-08-10 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

In D155610#4575579 , @cor3ntin wrote:

> @hubert.reinterpretcast It does not, Unicode characters are only escaped in 
> Diagnostics.cpp, and I think this is what we want.
> Currently, llvm assume UTF-8 terminal, except on Windows where we convert to 
> UTF-16 and use the wide windows APIs (`raw_fd_ostream::write_impl`).

I am skeptical of the extent to which that assumption is exercised in a 
problematic manner today. The characters being emitted (aside from the [U+0020, 
U+007E] fixed message text itself) generally come from the text of the source 
file, which is generally written using characters that the user can display 
(even if they are not "basic Latin" characters).


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

https://reviews.llvm.org/D155610

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


[PATCH] D157151: [Driver] Refactor to use llvm Option's new Visibility flags

2023-08-10 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Hey @bogner , I've only skimmed through so far and it's looking great! That 
Include/Exclude API was not fun to use. What you are proposing here takes 
Options.td to a much a better place - this is a much needed and long overdue 
refactor.

There's quite a bit of churn here, so I will need a few days to scan. In the 
meantime, could you update flang/docs/FlangDriver.md? And in general, please 
note that this updates (primarily) `clangDriver` logic, which is used by both 
by Clang and Flang. In particular, Options.td is shared. I think that it's 
worth highlighting that this change benefits both sub-projects.

> introduced in llvm Option

Could you add a link?




Comment at: clang/include/clang/Driver/Options.h:25-37
-  CoreOption = (1 << 8),
-  CLOption = (1 << 9),
-  CC1Option = (1 << 10),
-  CC1AsOption = (1 << 11),
-  NoDriverOption = (1 << 12),
-  LinkOption = (1 << 13),
-  FlangOption = (1 << 14),

What happens to `CoreOption`s? Same for `NoDriverOption`s?



Comment at: clang/include/clang/Driver/Options.td:193
 def m_x86_Features_Group : OptionGroup<"">,
-   Group, Flags<[CoreOption]>, DocName<"X86">;
+   Group, Vis<[Default, CLOption, DXCOption]>,
+   DocName<"X86">;

What's `Default` in `Vis<[Default, CLOption, DXCOption]>,`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157151

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


[clang] 91b10f6 - Revert "[modules] Fix error about the same module being defined in different .pcm files when using VFS overlays."

2023-08-10 Thread Volodymyr Sapsai via cfe-commits

Author: Volodymyr Sapsai
Date: 2023-08-10T11:27:08-07:00
New Revision: 91b10f69740ec91ca80ec45323d9807c39252334

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

LOG: Revert "[modules] Fix error about the same module being defined in 
different .pcm files when using VFS overlays."

This reverts commit 97dfaf4cd27814bdf9aa9d2eafc21fdb4f76c56d.

llvm-clang-x86_64-sie-win buildbot is failing with the added test.

Added: 


Modified: 
clang/lib/Lex/HeaderSearch.cpp
clang/lib/Serialization/ASTWriter.cpp

Removed: 
clang/test/VFS/module-map-path.m



diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index 80e1bad72ce9b7..f42d51d65dcdf3 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -177,7 +177,7 @@ std::string HeaderSearch::getCachedModuleFileName(Module 
*Module) {
   // *.modulemap file. In this case, just return an empty string.
   if (!ModuleMap)
 return {};
-  return getCachedModuleFileName(Module->Name, 
ModuleMap->getNameAsRequested());
+  return getCachedModuleFileName(Module->Name, ModuleMap->getName());
 }
 
 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,

diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 289c0383cd4b0e..8b0015f1ee9f6c 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1327,8 +1327,7 @@ void ASTWriter::WriteControlBlock(Preprocessor &PP, 
ASTContext &Context,
 
 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
 AddPath(WritingModule->PresumedModuleMapFile.empty()
-? Map.getModuleMapFileForUniquing(WritingModule)
-  ->getNameAsRequested()
+? Map.getModuleMapFileForUniquing(WritingModule)->getName()
 : StringRef(WritingModule->PresumedModuleMapFile),
 Record);
 

diff  --git a/clang/test/VFS/module-map-path.m 
b/clang/test/VFS/module-map-path.m
deleted file mode 100644
index 0f3c0a7aa499eb..00
--- a/clang/test/VFS/module-map-path.m
+++ /dev/null
@@ -1,110 +0,0 @@
-// Test the module map path is consistent between clang invocations when using 
VFS overlays.
-
-// RUN: rm -rf %t
-// RUN: split-file %s %t
-
-// Pre-populate the module cache with the modules that don't use VFS overlays.
-// RUN: %clang_cc1 -fsyntax-only -F%t/Frameworks -I%t/include 
%t/prepopulate_module_cache.m \
-// RUN: -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules.cache
-
-// Execute a compilation with VFS overlay. .pcm file path looks like 
/ModuleName-.pcm.
-//  corresponds to the compilation settings like language options.
-//  corresponds to the module map path. So if any of those change, we 
should use a 
diff erent module.
-// But for VFS overlay we make an exception that it's not a part of  to 
reduce the number of built .pcm files.
-// Test that paths in overlays don't leak into  and don't cause using 2 
.pcm files for the same module.
-// DEFINE: %{command} = %clang_cc1 -fsyntax-only -verify -F%t/Frameworks 
-I%t/include %t/test.m \
-// DEFINE:-fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules.cache
-// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@@g" %t/overlay.yaml.template > 
%t/external-names-default.yaml
-// RUN: %{command} -ivfsoverlay %t/external-names-default.yaml
-
-// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': true,@g" 
%t/overlay.yaml.template > %t/external-names-true.yaml
-// RUN: %{command} -ivfsoverlay %t/external-names-true.yaml
-
-// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': false,@g" 
%t/overlay.yaml.template > %t/external-names-false.yaml
-// RUN: %{command} -ivfsoverlay %t/external-names-false.yaml
-
-//--- prepopulate_module_cache.m
-#import 
-
-//--- test.m
-// At first import multi-path modules directly, so clang decides which .pcm 
file they should belong to.
-#import 
-#import 
-
-// Then import a module from the module cache and all its transitive 
dependencies.
-// Make sure the .pcm files loaded directly are the same as 'Redirecting' is 
referencing.
-#import 
-// expected-no-diagnostics
-
-
-//--- Frameworks/MultiPath.framework/Headers/MultiPath.h
-void multiPathFramework(void);
-
-//--- Frameworks/MultiPath.framework/Modules/module.modulemap
-framework module MultiPath {
-header "MultiPath.h"
-export *
-}
-
-
-//--- include/MultiPathHeader.h
-void multiPathHeader(void);
-
-//--- include/module.modulemap
-module MultiPathHeader {
-header "MultiPathHeader.h"
-export *
-}
-
-
-//--- Frameworks/Redirecting.framework/Headers/Redirecting.h
-#import

[PATCH] D141918: WIP: [Clang] Emit 'unwindabort' when applicable.

2023-08-10 Thread James Y Knight via Phabricator via cfe-commits
jyknight added a comment.

In D141918#4566838 , @smeenai wrote:

> $ clang -std=c++20 -O2 -c crash.cpp
> cannot use musttail with unwindabort

Thanks for the report. We were missing a check of `CI.isUnwindAbort()` in 
CoroSplit.cpp's `shouldBeMustTail()` function -- fixed for next version of the 
series. (It's not a regression in tail-callability for coroutines, since that 
`call unwindabort` would've previously been an `invoke`, which also cannot be 
musttail'd.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141918

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


[PATCH] D156032: Implement CWG2137 (list-initialization from objects of the same type)

2023-08-10 Thread Mital Ashok via Phabricator via cfe-commits
MitalAshok updated this revision to Diff 549145.
MitalAshok added a comment.
Herald added a project: libc++.
Herald added a subscriber: libcxx-commits.
Herald added a reviewer: libc++.

Fix broken libc++ pair constructor test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156032

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaInit.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/CXX/drs/dr14xx.cpp
  clang/test/CXX/drs/dr21xx.cpp
  clang/test/CXX/drs/dr23xx.cpp
  clang/www/cxx_dr_status.html
  libcxx/test/std/utilities/utility/pairs/pairs.pair/ctor.pair_U_V_move.pass.cpp

Index: libcxx/test/std/utilities/utility/pairs/pairs.pair/ctor.pair_U_V_move.pass.cpp
===
--- libcxx/test/std/utilities/utility/pairs/pairs.pair/ctor.pair_U_V_move.pass.cpp
+++ libcxx/test/std/utilities/utility/pairs/pairs.pair/ctor.pair_U_V_move.pass.cpp
@@ -121,7 +121,30 @@
 test_pair_rv();
 test_pair_rv();
 
-test_pair_rv();
+/* For ExplicitTypes::CopyOnly, two of the viable candidates for initializing from a non-const xvalue are:
+ *   pair(const pair&);  // (defaulted copy constructor)
+ *   template explicit pair(const pair&&); [U1 = ExplicitTypes::CopyOnly, U2 = int]
+ * This results in diverging behavior for test_convertible which uses copy-list-initialization
+ * Prior to CWG2137, this would have selected the first (non-explicit) ctor as explicit ctors would not be considered
+ * Afterwards, it should select the second since it is a better match, and then failed because it is explicit
+ *
+ * This may change with future defect reports, and some compilers only have partial support for CWG2137,
+ * so use std::is_convertible directly to avoid a copy-list-initialization
+ */
+//test_pair_rv();
+static_assert(std::is_constructible,
+std::pair&&>::value,
+  "");
+static_assert(std::is_convertible&&,
+  std::pair>::value,
+  "");
+static_assert(std::is_constructible,
+std::pair&&>::value,
+  "");
+static_assert(std::is_convertible&&,
+  std::pair>::value,
+  "");
+
 test_pair_rv();
 test_pair_rv();
 
Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -12629,7 +12629,7 @@
 https://cplusplus.github.io/CWG/issues/2137.html";>2137
 CD4
 List-initialization from object of same type
-Unknown
+Clang 18
   
   
 https://cplusplus.github.io/CWG/issues/2138.html";>2138
Index: clang/test/CXX/drs/dr23xx.cpp
===
--- clang/test/CXX/drs/dr23xx.cpp
+++ clang/test/CXX/drs/dr23xx.cpp
@@ -5,6 +5,16 @@
 // RUN: %clang_cc1 -std=c++20 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
 // RUN: %clang_cc1 -std=c++23 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
 
+namespace std {
+  __extension__ typedef __SIZE_TYPE__ size_t;
+
+  template struct initializer_list {
+const E *p; size_t n;
+initializer_list(const E *p, size_t n);
+initializer_list();
+  };
+}
+
 #if __cplusplus >= 201103L
 namespace dr2303 { // dr2303: 12
 template 
@@ -37,6 +47,67 @@
 } //namespace dr2303
 #endif
 
+namespace dr2311 {
+#if __cplusplus >= 201707L
+template
+void test() {
+  // Ensure none of these expressions try to call a move constructor
+  T a = T{T(0)};
+  T b{T(0)};
+  auto c{T(0)};
+  T d = {T(0)};
+  auto e = {T(0)};
+#if __cplusplus >= 202302L
+  auto f = auto{T(0)};
+#endif
+  void(*fn)(T);
+  fn({T(0)});
+}
+
+struct NonMovable {
+  NonMovable(int);
+  NonMovable(NonMovable&&) = delete;
+};
+struct NonMovableNonApplicableIList {
+  NonMovableNonApplicableIList(int);
+  NonMovableNonApplicableIList(NonMovableNonApplicableIList&&) = delete;
+  NonMovableNonApplicableIList(std::initializer_list);
+};
+struct ExplicitMovable {
+  ExplicitMovable(int);
+  explicit ExplicitMovable(ExplicitMovable&&);
+};
+struct ExplicitNonMovable {
+  ExplicitNonMovable(int);
+  explicit ExplicitNonMovable(ExplicitNonMovable&&) = delete;
+};
+struct ExplicitNonMovableNonApplicableIList {
+  ExplicitNonMovableNonApplicableIList(int);
+  explicit ExplicitNonMovableNonApplicableIList(ExplicitNonMovableNonApplicableIList&&) = delete;
+  ExplicitNonMovableNonApplicableIList(std::initializer_list);
+};
+struct CopyOnly {
+  CopyOnly(int);
+  CopyOnly(const CopyOnly&);
+  CopyOnly(CopyOnly&&) = delete;
+};
+struct ExplicitCopyOnly {
+  ExplicitCopyOnly(int);
+

[PATCH] D143967: [DebugInfo][BPF] Add 'btf:type_tag' annotation in DWARF

2023-08-10 Thread Eduard Zingerman via Phabricator via cfe-commits
eddyz87 added a comment.

Hi @dblaikie,

Could you please take a look at my response 
?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143967

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


[PATCH] D156032: Implement CWG2137 (list-initialization from objects of the same type)

2023-08-10 Thread Mital Ashok via Phabricator via cfe-commits
MitalAshok marked 2 inline comments as done and an inline comment as not done.
MitalAshok added a comment.

It seems there were two places which relied on `T x = { xvalue_of_type_T }` 
being a copy-initialization: The test at 
https://reviews.llvm.org/D156032#inline-1509544 and that one pair constructor 
test.

GCC seems to allow it but I don't think that's standard. I also have a pretty 
short patch to implement this behaviour if we decide that it needs to be 
supported (maybe this is a standard defect?)




Comment at: clang/test/CXX/drs/dr23xx.cpp:9
+namespace std {
+  __extension__ typedef __SIZE_TYPE__ size_t;
+

cor3ntin wrote:
> 
Wouldn't work in c++98 mode this file is being run in. I've copied this from 
other tests in this directory. I guess I can put a `#if __cplusplus >= 201103L` 
instead?



Comment at: clang/test/CXX/drs/dr23xx.cpp:50
 
+namespace dr2311 {
+#if __cplusplus >= 201707L

cor3ntin wrote:
> the dr status html page is generated automatically by leaving a magic comment 
> here - and then running `clang/www/make_cxx_dr_status`
CWG2311 is still open, but clang did support list-initialization elision before 
this patch. The committee still needs to decide how exactly this elision is 
going to work, which might be different from how this patch implements it, so 
hesitant to mark this as done.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156032

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


[clang-tools-extra] 7f29f14 - [clang-tidy] Ignore unevaluated context in cppcoreguidelines-pro-type-vararg

2023-08-10 Thread Piotr Zegar via cfe-commits

Author: Piotr Zegar
Date: 2023-08-10T19:51:09Z
New Revision: 7f29f14d025702a04ca3e5cdd31de40c392e2799

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

LOG: [clang-tidy] Ignore unevaluated context in 
cppcoreguidelines-pro-type-vararg

Ignore decltype, sizeof, alignof in this check.

Fixes: #30542

Reviewed By: ccotter

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
index ac1f40cfe18ae6..3923df312791db 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "ProTypeVarargCheck.h"
+#include "../utils/Matchers.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
@@ -133,7 +134,9 @@ void ProTypeVarargCheck::registerMatchers(MatchFinder 
*Finder) {
 
   Finder->addMatcher(
   callExpr(callee(functionDecl(isVariadic(),
-   unless(hasAnyName(AllowedVariadics)
+   unless(hasAnyName(AllowedVariadics,
+   unless(hasAncestor(expr(matchers::hasUnevaluatedContext(,
+   unless(hasAncestor(typeLoc(
   .bind("callvararg"),
   this);
 

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index c4b09bae18ec37..7f3ae301081231 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -176,6 +176,10 @@ Changes in existing checks
   ` check to
   ignore delegate constructors.
 
+- Improved :doc:`cppcoreguidelines-pro-type-vararg
+  ` check to ignore
+  false-positives in unevaluated context (e.g., ``decltype``, ``sizeof``, ...).
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
index 823b0eaaad382e..e74b00694630bf 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
@@ -7,7 +7,8 @@ This check flags all calls to c-style vararg functions and all 
use of
 ``va_arg``.
 
 To allow for SFINAE use of vararg functions, a call is not flagged if a literal
-0 is passed as the only vararg argument.
+0 is passed as the only vararg argument or function is used in unevaluated
+context.
 
 Passing to varargs assumes the correct type will be read. This is fragile
 because it cannot generally be enforced to be safe in the language and so 
relies

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
index e5bf98f02d8b39..6792c7920dd112 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
@@ -66,3 +66,16 @@ void no_false_positive_desugar_va_list(char *in) {
   char *tmp1 = in;
   void *tmp2 = in;
 }
+
+namespace PR30542 {
+  struct X;
+  template 
+  char IsNullConstant(X*);
+  template 
+  char (&IsNullConstant(...))[2];
+
+  static_assert(sizeof(IsNullConstant(0)) == 1, "");
+  static_assert(sizeof(IsNullConstant(17)) == 2, "");
+
+  using Type = decltype(IsNullConstant(17));
+}



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


[clang-tools-extra] 894140b - [clang-tidy] Ignore delegate constructors in cppcoreguidelines-pro-type-member-init

2023-08-10 Thread Piotr Zegar via cfe-commits

Author: Piotr Zegar
Date: 2023-08-10T19:51:09Z
New Revision: 894140b4fdde10b6bff7fc99104b2292ade3c91c

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

LOG: [clang-tidy] Ignore delegate constructors in 
cppcoreguidelines-pro-type-member-init

Ignore dependend delegate constructors.

Fixes: #37250

Reviewed By: ccotter

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
index 07b88d5c49e80a..ff5a750a8dac45 100644
--- a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
@@ -281,8 +281,14 @@ ProTypeMemberInitCheck::ProTypeMemberInitCheck(StringRef 
Name,
 
 void ProTypeMemberInitCheck::registerMatchers(MatchFinder *Finder) {
   auto IsUserProvidedNonDelegatingConstructor =
-  allOf(isUserProvided(),
-unless(anyOf(isInstantiated(), isDelegatingConstructor(;
+  allOf(isUserProvided(), unless(isInstantiated()),
+unless(isDelegatingConstructor()),
+ofClass(cxxRecordDecl().bind("parent")),
+unless(hasAnyConstructorInitializer(cxxCtorInitializer(
+isWritten(), unless(isMemberInitializer()),
+hasTypeLoc(loc(
+qualType(hasDeclaration(equalsBoundNode("parent");
+
   auto IsNonTrivialDefaultConstructor = allOf(
   isDefaultConstructor(), unless(isUserProvided()),
   hasParent(cxxRecordDecl(unless(isTriviallyDefaultConstructible();

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 7f3ae301081231..703d8b0edd8cc9 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -176,6 +176,10 @@ Changes in existing checks
   ` check to
   ignore delegate constructors.
 
+- Improved :doc:`cppcoreguidelines-pro-type-member-init
+  ` check to ignore
+  dependent delegate constructors.
+
 - Improved :doc:`cppcoreguidelines-pro-type-vararg
   ` check to ignore
   false-positives in unevaluated context (e.g., ``decltype``, ``sizeof``, ...).

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
index 2e2097bae361a7..8d6992afef08a9 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
@@ -372,8 +372,7 @@ template 
 class PositiveSelfInitialization : NegativeAggregateType
 {
   PositiveSelfInitialization() : PositiveSelfInitialization() {}
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize 
these bases: NegativeAggregateType
-  // CHECK-FIXES: PositiveSelfInitialization() : NegativeAggregateType(), 
PositiveSelfInitialization() {}
+  // This will be detected by -Wdelegating-ctor-cycles and there is no proper 
way to fix this
 };
 
 class PositiveIndirectMember {
@@ -579,3 +578,42 @@ struct S3 {
 int C = 0;
   };
 };
+
+// Ignore issues from delegate constructors
+namespace PR37250 {
+  template 
+  struct A {
+A() : A(42) {}
+explicit A(int value) : value_(value) {}
+int value_;
+  };
+
+  struct B {
+B() : B(42) {}
+explicit B(int value) : value_(value) {}
+int value_;
+  };
+
+  template 
+  struct C {
+C() : C(T()) {}
+explicit C(T value) : value_(value) {}
+T value_;
+  };
+
+  struct V {
+unsigned size() const;
+  };
+
+  struct S {
+unsigned size_;
+
+S(unsigned size) : size_{size} {}
+
+template
+S(const U& u) : S(u.size()) {}
+  };
+
+  const V v;
+  const S s{v};
+}



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


[PATCH] D157367: [clang-tidy] Ignore delegate constructors in cppcoreguidelines-pro-type-member-init

2023-08-10 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG894140b4fdde: [clang-tidy] Ignore delegate constructors in 
cppcoreguidelines-pro-type-member… (authored by PiotrZSL).

Changed prior to commit:
  https://reviews.llvm.org/D157367?vs=548085&id=549148#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157367

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
@@ -372,8 +372,7 @@
 class PositiveSelfInitialization : NegativeAggregateType
 {
   PositiveSelfInitialization() : PositiveSelfInitialization() {}
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize 
these bases: NegativeAggregateType
-  // CHECK-FIXES: PositiveSelfInitialization() : NegativeAggregateType(), 
PositiveSelfInitialization() {}
+  // This will be detected by -Wdelegating-ctor-cycles and there is no proper 
way to fix this
 };
 
 class PositiveIndirectMember {
@@ -579,3 +578,42 @@
 int C = 0;
   };
 };
+
+// Ignore issues from delegate constructors
+namespace PR37250 {
+  template 
+  struct A {
+A() : A(42) {}
+explicit A(int value) : value_(value) {}
+int value_;
+  };
+
+  struct B {
+B() : B(42) {}
+explicit B(int value) : value_(value) {}
+int value_;
+  };
+
+  template 
+  struct C {
+C() : C(T()) {}
+explicit C(T value) : value_(value) {}
+T value_;
+  };
+
+  struct V {
+unsigned size() const;
+  };
+
+  struct S {
+unsigned size_;
+
+S(unsigned size) : size_{size} {}
+
+template
+S(const U& u) : S(u.size()) {}
+  };
+
+  const V v;
+  const S s{v};
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -176,6 +176,10 @@
   ` check to
   ignore delegate constructors.
 
+- Improved :doc:`cppcoreguidelines-pro-type-member-init
+  ` check to ignore
+  dependent delegate constructors.
+
 - Improved :doc:`cppcoreguidelines-pro-type-vararg
   ` check to ignore
   false-positives in unevaluated context (e.g., ``decltype``, ``sizeof``, ...).
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp
@@ -281,8 +281,14 @@
 
 void ProTypeMemberInitCheck::registerMatchers(MatchFinder *Finder) {
   auto IsUserProvidedNonDelegatingConstructor =
-  allOf(isUserProvided(),
-unless(anyOf(isInstantiated(), isDelegatingConstructor(;
+  allOf(isUserProvided(), unless(isInstantiated()),
+unless(isDelegatingConstructor()),
+ofClass(cxxRecordDecl().bind("parent")),
+unless(hasAnyConstructorInitializer(cxxCtorInitializer(
+isWritten(), unless(isMemberInitializer()),
+hasTypeLoc(loc(
+qualType(hasDeclaration(equalsBoundNode("parent");
+
   auto IsNonTrivialDefaultConstructor = allOf(
   isDefaultConstructor(), unless(isUserProvided()),
   hasParent(cxxRecordDecl(unless(isTriviallyDefaultConstructible();


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-member-init.cpp
@@ -372,8 +372,7 @@
 class PositiveSelfInitialization : NegativeAggregateType
 {
   PositiveSelfInitialization() : PositiveSelfInitialization() {}
-  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these bases: NegativeAggregateType
-  // CHECK-FIXES: PositiveSelfInitialization() : NegativeAggregateType(), PositiveSelfInitialization() {}
+  // This will be detected by -Wdelegating-ctor-cycles and there is no proper way to fix this
 };
 
 class PositiveIndirectMember {
@@ -579,3 +578,42 @@
 int C = 0;
   };
 };
+
+// Ignore issues from delegate constructors
+namespace PR37250 {
+  template 
+  struct A {
+A() : A(42) {}
+explicit A(int value) : value_(value) {}
+int value_;
+  };
+
+  struct B {
+B() : B(42) {}
+explicit B(int value) : val

[PATCH] D157376: [clang-tidy] Ignore unevaluated context in cppcoreguidelines-pro-type-vararg

2023-08-10 Thread Piotr Zegar via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7f29f14d0257: [clang-tidy] Ignore unevaluated context in 
cppcoreguidelines-pro-type-vararg (authored by PiotrZSL).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157376

Files:
  clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
@@ -66,3 +66,16 @@
   char *tmp1 = in;
   void *tmp2 = in;
 }
+
+namespace PR30542 {
+  struct X;
+  template 
+  char IsNullConstant(X*);
+  template 
+  char (&IsNullConstant(...))[2];
+
+  static_assert(sizeof(IsNullConstant(0)) == 1, "");
+  static_assert(sizeof(IsNullConstant(17)) == 2, "");
+
+  using Type = decltype(IsNullConstant(17));
+}
Index: 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
===
--- 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
+++ 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
@@ -7,7 +7,8 @@
 ``va_arg``.
 
 To allow for SFINAE use of vararg functions, a call is not flagged if a literal
-0 is passed as the only vararg argument.
+0 is passed as the only vararg argument or function is used in unevaluated
+context.
 
 Passing to varargs assumes the correct type will be read. This is fragile
 because it cannot generally be enforced to be safe in the language and so 
relies
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -176,6 +176,10 @@
   ` check to
   ignore delegate constructors.
 
+- Improved :doc:`cppcoreguidelines-pro-type-vararg
+  ` check to ignore
+  false-positives in unevaluated context (e.g., ``decltype``, ``sizeof``, ...).
+
 - Improved :doc:`llvm-namespace-comment
   ` check to provide fixes for
   ``inline`` namespaces in the same format as :program:`clang-format`.
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "ProTypeVarargCheck.h"
+#include "../utils/Matchers.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
@@ -133,7 +134,9 @@
 
   Finder->addMatcher(
   callExpr(callee(functionDecl(isVariadic(),
-   unless(hasAnyName(AllowedVariadics)
+   unless(hasAnyName(AllowedVariadics,
+   unless(hasAncestor(expr(matchers::hasUnevaluatedContext(,
+   unless(hasAncestor(typeLoc(
   .bind("callvararg"),
   this);
 


Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/pro-type-vararg.cpp
@@ -66,3 +66,16 @@
   char *tmp1 = in;
   void *tmp2 = in;
 }
+
+namespace PR30542 {
+  struct X;
+  template 
+  char IsNullConstant(X*);
+  template 
+  char (&IsNullConstant(...))[2];
+
+  static_assert(sizeof(IsNullConstant(0)) == 1, "");
+  static_assert(sizeof(IsNullConstant(17)) == 2, "");
+
+  using Type = decltype(IsNullConstant(17));
+}
Index: clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
===
--- clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
+++ clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-type-vararg.rst
@@ -7,7 +7,8 @@
 ``va_arg``.
 
 To allow for SFINAE use of vararg functions, a call is not flagged if a literal
-0 is passed as the only vararg argument.
+0 is passed as the only vararg argument or function is used in unevaluated
+context.
 
 Passing to varargs assumes the correct type will be read. This is fragile
 because it cannot generally be enforced to be safe in the languag

[PATCH] D156474: [-Wunsafe-buffer-usage][NFC] Slightly refactor and optimize the code

2023-08-10 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156474

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


[PATCH] D157649: [clang-tidy] Fix crash when diagnostic is emit with invalid location

2023-08-10 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL created this revision.
PiotrZSL added reviewers: njames93, aaron.ballman, carlosgalvezp.
Herald added a subscriber: xazax.hun.
Herald added a project: All.
PiotrZSL requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Fix crash when diagnostic is emit with invalid location,
but with attached valid ranges. Diagnostic can contain
invalid location, but SourceManager attached to it still
can be valid, use it in such case or fallback to known
SourceManager.

Fixes: #64602


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157649

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/diagnostic.cpp


Index: clang-tools-extra/test/clang-tidy/infrastructure/diagnostic.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/diagnostic.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/diagnostic.cpp
@@ -25,6 +25,7 @@
 // RUN: not clang-tidy -checks='-*,modernize-use-override' 
%T/diagnostics/input.cpp -- -DCOMPILATION_ERROR 2>&1 | FileCheck 
-check-prefix=CHECK6 -implicit-check-not='{{warning:|error:}}' %s
 // RUN: clang-tidy 
-checks='-*,modernize-use-override,clang-diagnostic-macro-redefined' %s -- 
-DMACRO_FROM_COMMAND_LINE -std=c++20 | FileCheck -check-prefix=CHECK4 
-implicit-check-not='{{warning:|error:}}' %s
 // RUN: clang-tidy 
-checks='-*,modernize-use-override,clang-diagnostic-macro-redefined,clang-diagnostic-literal-conversion'
 %s -- -DMACRO_FROM_COMMAND_LINE -std=c++20 -Wno-macro-redefined | FileCheck 
--check-prefix=CHECK7 -implicit-check-not='{{warning:|error:}}' %s
+// RUN: not clang-tidy -checks='-*,modernize-use-override' %s -- -std=c++20 
-DPR64602 | FileCheck -check-prefix=CHECK8 
-implicit-check-not='{{warning:|error:}}' %s
 
 // CHECK1: error: no input files [clang-diagnostic-error]
 // CHECK1: error: no such file or directory: '{{.*}}nonexistent.cpp' 
[clang-diagnostic-error]
@@ -54,3 +55,18 @@
   // CHECK6: :[[@LINE-1]]:3: error: cannot take the address of an rvalue of 
type 'int' [clang-diagnostic-error]
 }
 #endif
+
+#ifdef PR64602 // Should not crash
+template 
+struct S
+{
+auto foo(auto);
+};
+
+template <>
+auto S<>::foo(auto)
+{
+return 1;
+}
+// CHECK8: error: template parameter list matching the non-templated nested 
type 'S<>' should be empty ('template<>') [clang-diagnostic-error]
+#endif
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -436,9 +436,10 @@
 Errors.back());
 SmallString<100> Message;
 Info.FormatDiagnostic(Message);
-FullSourceLoc Loc;
-if (Info.getLocation().isValid() && Info.hasSourceManager())
-  Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
+FullSourceLoc Loc(Info.getLocation(),
+  Info.hasSourceManager()
+  ? Info.getSourceManager()
+  : Context.DiagEngine->getSourceManager());
 Converter.emitDiagnostic(Loc, DiagLevel, Message, Info.getRanges(),
  Info.getFixItHints());
   }


Index: clang-tools-extra/test/clang-tidy/infrastructure/diagnostic.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/diagnostic.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/diagnostic.cpp
@@ -25,6 +25,7 @@
 // RUN: not clang-tidy -checks='-*,modernize-use-override' %T/diagnostics/input.cpp -- -DCOMPILATION_ERROR 2>&1 | FileCheck -check-prefix=CHECK6 -implicit-check-not='{{warning:|error:}}' %s
 // RUN: clang-tidy -checks='-*,modernize-use-override,clang-diagnostic-macro-redefined' %s -- -DMACRO_FROM_COMMAND_LINE -std=c++20 | FileCheck -check-prefix=CHECK4 -implicit-check-not='{{warning:|error:}}' %s
 // RUN: clang-tidy -checks='-*,modernize-use-override,clang-diagnostic-macro-redefined,clang-diagnostic-literal-conversion' %s -- -DMACRO_FROM_COMMAND_LINE -std=c++20 -Wno-macro-redefined | FileCheck --check-prefix=CHECK7 -implicit-check-not='{{warning:|error:}}' %s
+// RUN: not clang-tidy -checks='-*,modernize-use-override' %s -- -std=c++20 -DPR64602 | FileCheck -check-prefix=CHECK8 -implicit-check-not='{{warning:|error:}}' %s
 
 // CHECK1: error: no input files [clang-diagnostic-error]
 // CHECK1: error: no such file or directory: '{{.*}}nonexistent.cpp' [clang-diagnostic-error]
@@ -54,3 +55,18 @@
   // CHECK6: :[[@LINE-1]]:3: error: cannot take the address of an rvalue of type 'int' [clang-diagnostic-error]
 }
 #endif
+
+#ifdef PR64602 // Should not crash
+template 
+struct S
+{
+auto foo(auto);
+};
+
+template <>
+auto S<>::foo(auto)
+{
+return 1;
+}
+// CHECK8: error: template parameter list ma

[PATCH] D155383: [clang][AST] TextNodeDumper learned to output exception specifications

2023-08-10 Thread Timo Stripf via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7fc6fa97edb6: [clang][AST] TextNodeDumper learned to output 
exception specifications (authored by strimo378).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155383

Files:
  clang/lib/AST/TextNodeDumper.cpp
  clang/test/AST/ast-dump-functionprototype.cpp


Index: clang/test/AST/ast-dump-functionprototype.cpp
===
--- /dev/null
+++ clang/test/AST/ast-dump-functionprototype.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++17 
-Wno-dynamic-exception-spec -ast-dump %s | FileCheck -strict-whitespace %s
+
+struct A {};
+struct B {};
+
+typedef void (type1)() noexcept(10 > 5);
+
+// CHECK:  TypedefDecl {{.*}} type1 'void () noexcept(10 > 5)':'void () 
noexcept(10 > 5)'
+// CHECK-NEXT: `-ParenType {{.*}}
+// CHECK-NEXT:   `-FunctionProtoType {{.*}} 'void () noexcept(10 > 5)' 
exceptionspec_noexcept_true cdecl
+// CHECK-NEXT: |-NoexceptExpr: ConstantExpr {{.*}} 'bool'
+// CHECK-NEXT: | `-value: Int 1
+// CHECK-NEXT: `-BuiltinType {{.*}} 'void'
+
+typedef void (type2)() throw(A, B);
+
+// CHECK:  TypedefDecl {{.*}} type2 'void () throw(A, B)':'void () 
throw(A, B)'
+// CHECK-NEXT: `-ParenType {{.*}}
+// CHECK-NEXT:   `-FunctionProtoType {{.*}} 'void () throw(A, B)' 
exceptionspec_dynamic cdecl
+// CHECK-NEXT: |-Exceptions: 'A':'A', 'B':'B'
+// CHECK-NEXT: `-BuiltinType {{.*}} 'void'
+
Index: clang/lib/AST/TextNodeDumper.cpp
===
--- clang/lib/AST/TextNodeDumper.cpp
+++ clang/lib/AST/TextNodeDumper.cpp
@@ -1541,7 +1541,64 @@
 OS << " &&";
 break;
   }
-  // FIXME: Exception specification.
+
+  switch (EPI.ExceptionSpec.Type) {
+  case EST_None:
+break;
+  case EST_DynamicNone:
+OS << " exceptionspec_dynamic_none";
+break;
+  case EST_Dynamic:
+OS << " exceptionspec_dynamic";
+break;
+  case EST_MSAny:
+OS << " exceptionspec_ms_any";
+break;
+  case EST_NoThrow:
+OS << " exceptionspec_nothrow";
+break;
+  case EST_BasicNoexcept:
+OS << " exceptionspec_basic_noexcept";
+break;
+  case EST_DependentNoexcept:
+OS << " exceptionspec_dependent_noexcept";
+break;
+  case EST_NoexceptFalse:
+OS << " exceptionspec_noexcept_false";
+break;
+  case EST_NoexceptTrue:
+OS << " exceptionspec_noexcept_true";
+break;
+  case EST_Unevaluated:
+OS << " exceptionspec_unevaluated";
+break;
+  case EST_Uninstantiated:
+OS << " exceptionspec_uninstantiated";
+break;
+  case EST_Unparsed:
+OS << " exceptionspec_unparsed";
+break;
+  }
+  if (!EPI.ExceptionSpec.Exceptions.empty()) {
+AddChild([=] {
+  OS << "Exceptions:";
+  for (unsigned I = 0, N = EPI.ExceptionSpec.Exceptions.size(); I != N;
+   ++I) {
+if (I)
+  OS << ",";
+dumpType(EPI.ExceptionSpec.Exceptions[I]);
+  }
+});
+  }
+  if (EPI.ExceptionSpec.NoexceptExpr) {
+AddChild([=] {
+  OS << "NoexceptExpr: ";
+  Visit(EPI.ExceptionSpec.NoexceptExpr);
+});
+  }
+  dumpDeclRef(EPI.ExceptionSpec.SourceDecl, "ExceptionSourceDecl");
+  dumpDeclRef(EPI.ExceptionSpec.SourceTemplate, "ExceptionSourceTemplate");
+
   // FIXME: Consumed parameters.
   VisitFunctionType(T);
 }


Index: clang/test/AST/ast-dump-functionprototype.cpp
===
--- /dev/null
+++ clang/test/AST/ast-dump-functionprototype.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++17 -Wno-dynamic-exception-spec -ast-dump %s | FileCheck -strict-whitespace %s
+
+struct A {};
+struct B {};
+
+typedef void (type1)() noexcept(10 > 5);
+
+// CHECK:  TypedefDecl {{.*}} type1 'void () noexcept(10 > 5)':'void () noexcept(10 > 5)'
+// CHECK-NEXT: `-ParenType {{.*}}
+// CHECK-NEXT:   `-FunctionProtoType {{.*}} 'void () noexcept(10 > 5)' exceptionspec_noexcept_true cdecl
+// CHECK-NEXT: |-NoexceptExpr: ConstantExpr {{.*}} 'bool'
+// CHECK-NEXT: | `-value: Int 1
+// CHECK-NEXT: `-BuiltinType {{.*}} 'void'
+
+typedef void (type2)() throw(A, B);
+
+// CHECK:  TypedefDecl {{.*}} type2 'void () throw(A, B)':'void () throw(A, B)'
+// CHECK-NEXT: `-ParenType {{.*}}
+// CHECK-NEXT:   `-FunctionProtoType {{.*}} 'void () throw(A, B)' exceptionspec_dynamic cdecl
+// CHECK-NEXT: |-Exceptions: 'A':'A', 'B':'B'
+// CHECK-NEXT: `-BuiltinType {{.*}} 'void'
+
Index: clang/lib/AST/TextNodeDumper.cpp
===
--- clang/lib/AST/TextNodeDumper.cpp
+++ clang/lib/AST/TextNodeDumper.cpp
@@ -1541,7 +1541,64 @@
 OS << " &&";
 break;
   }
-  // FIXME: Exception specification.
+
+  switch (EPI.ExceptionSpec.Type) {
+  case EST_None:
+break;
+  case EST_Dynamic

[clang] 7fc6fa9 - [clang][AST] TextNodeDumper learned to output exception specifications

2023-08-10 Thread Timo Stripf via cfe-commits

Author: Timo Stripf
Date: 2023-08-10T20:42:34Z
New Revision: 7fc6fa97edb6aedf0e25a124dee925dc6d00c69d

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

LOG: [clang][AST] TextNodeDumper learned to output exception specifications

Extended TextNodeDumper::VisitFunctionProtoType to output exception 
specifications

Reviewed By: aaron.ballman

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

Added: 
clang/test/AST/ast-dump-functionprototype.cpp

Modified: 
clang/lib/AST/TextNodeDumper.cpp

Removed: 




diff  --git a/clang/lib/AST/TextNodeDumper.cpp 
b/clang/lib/AST/TextNodeDumper.cpp
index a174faa6635efe..d6c72d6207df22 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -1541,7 +1541,64 @@ void TextNodeDumper::VisitFunctionProtoType(const 
FunctionProtoType *T) {
 OS << " &&";
 break;
   }
-  // FIXME: Exception specification.
+
+  switch (EPI.ExceptionSpec.Type) {
+  case EST_None:
+break;
+  case EST_DynamicNone:
+OS << " exceptionspec_dynamic_none";
+break;
+  case EST_Dynamic:
+OS << " exceptionspec_dynamic";
+break;
+  case EST_MSAny:
+OS << " exceptionspec_ms_any";
+break;
+  case EST_NoThrow:
+OS << " exceptionspec_nothrow";
+break;
+  case EST_BasicNoexcept:
+OS << " exceptionspec_basic_noexcept";
+break;
+  case EST_DependentNoexcept:
+OS << " exceptionspec_dependent_noexcept";
+break;
+  case EST_NoexceptFalse:
+OS << " exceptionspec_noexcept_false";
+break;
+  case EST_NoexceptTrue:
+OS << " exceptionspec_noexcept_true";
+break;
+  case EST_Unevaluated:
+OS << " exceptionspec_unevaluated";
+break;
+  case EST_Uninstantiated:
+OS << " exceptionspec_uninstantiated";
+break;
+  case EST_Unparsed:
+OS << " exceptionspec_unparsed";
+break;
+  }
+  if (!EPI.ExceptionSpec.Exceptions.empty()) {
+AddChild([=] {
+  OS << "Exceptions:";
+  for (unsigned I = 0, N = EPI.ExceptionSpec.Exceptions.size(); I != N;
+   ++I) {
+if (I)
+  OS << ",";
+dumpType(EPI.ExceptionSpec.Exceptions[I]);
+  }
+});
+  }
+  if (EPI.ExceptionSpec.NoexceptExpr) {
+AddChild([=] {
+  OS << "NoexceptExpr: ";
+  Visit(EPI.ExceptionSpec.NoexceptExpr);
+});
+  }
+  dumpDeclRef(EPI.ExceptionSpec.SourceDecl, "ExceptionSourceDecl");
+  dumpDeclRef(EPI.ExceptionSpec.SourceTemplate, "ExceptionSourceTemplate");
+
   // FIXME: Consumed parameters.
   VisitFunctionType(T);
 }

diff  --git a/clang/test/AST/ast-dump-functionprototype.cpp 
b/clang/test/AST/ast-dump-functionprototype.cpp
new file mode 100644
index 00..4ba57bd5ace0ed
--- /dev/null
+++ b/clang/test/AST/ast-dump-functionprototype.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -std=c++17 
-Wno-dynamic-exception-spec -ast-dump %s | FileCheck -strict-whitespace %s
+
+struct A {};
+struct B {};
+
+typedef void (type1)() noexcept(10 > 5);
+
+// CHECK:  TypedefDecl {{.*}} type1 'void () noexcept(10 > 5)':'void () 
noexcept(10 > 5)'
+// CHECK-NEXT: `-ParenType {{.*}}
+// CHECK-NEXT:   `-FunctionProtoType {{.*}} 'void () noexcept(10 > 5)' 
exceptionspec_noexcept_true cdecl
+// CHECK-NEXT: |-NoexceptExpr: ConstantExpr {{.*}} 'bool'
+// CHECK-NEXT: | `-value: Int 1
+// CHECK-NEXT: `-BuiltinType {{.*}} 'void'
+
+typedef void (type2)() throw(A, B);
+
+// CHECK:  TypedefDecl {{.*}} type2 'void () throw(A, B)':'void () 
throw(A, B)'
+// CHECK-NEXT: `-ParenType {{.*}}
+// CHECK-NEXT:   `-FunctionProtoType {{.*}} 'void () throw(A, B)' 
exceptionspec_dynamic cdecl
+// CHECK-NEXT: |-Exceptions: 'A':'A', 'B':'B'
+// CHECK-NEXT: `-BuiltinType {{.*}} 'void'
+



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


[PATCH] D155850: [Clang][CodeGen][RFC] Add codegen support for C++ Parallel Algorithm Offload

2023-08-10 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx updated this revision to Diff 549159.
AlexVlx added a comment.

Switch to `__ASM` prefix.


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

https://reviews.llvm.org/D155850

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenStdPar/unannotated-functions-get-emitted.cpp
  clang/test/CodeGenStdPar/unsupported-ASM.cpp
  clang/test/CodeGenStdPar/unsupported-builtins.cpp

Index: clang/test/CodeGenStdPar/unsupported-builtins.cpp
===
--- /dev/null
+++ clang/test/CodeGenStdPar/unsupported-builtins.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   --stdpar -x hip -emit-llvm -fcuda-is-device -o - %s | FileCheck %s
+
+#define __global__ __attribute__((global))
+
+__global__ void foo() { return __builtin_ia32_pause(); }
+
+// CHECK: declare void @__builtin_ia32_pause__stdpar_unsupported()
Index: clang/test/CodeGenStdPar/unsupported-ASM.cpp
===
--- /dev/null
+++ clang/test/CodeGenStdPar/unsupported-ASM.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   --stdpar -x hip -emit-llvm -fcuda-is-device -o - %s | FileCheck %s
+
+#define __global__ __attribute__((global))
+
+__global__ void foo(int i) {
+asm ("addl %2, %1; seto %b0" : "=q" (i), "+g" (i) : "r" (i));
+}
+
+// CHECK: declare void @__ASM__stdpar_unsupported([{{.*}}])
Index: clang/test/CodeGenStdPar/unannotated-functions-get-emitted.cpp
===
--- /dev/null
+++ clang/test/CodeGenStdPar/unannotated-functions-get-emitted.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -x hip -emit-llvm -fcuda-is-device \
+// RUN:   -o - %s | FileCheck --check-prefix=NO-STDPAR-DEV %s
+
+// RUN: %clang_cc1 --stdpar -emit-llvm -fcuda-is-device \
+// RUN:   -o - %s | FileCheck --check-prefix=STDPAR-DEV %s
+
+#define __device__ __attribute__((device))
+
+// NO-STDPAR-DEV-NOT: define {{.*}} void @_Z3fooPff({{.*}})
+// STDPAR-DEV: define {{.*}} void @_Z3fooPff({{.*}})
+void foo(float *a, float b) {
+  *a = b;
+}
+
+// NO-STDPAR-DEV: define {{.*}} void @_Z3barPff({{.*}})
+// STDPAR-DEV: define {{.*}} void @_Z3barPff({{.*}})
+__device__ void bar(float *a, float b) {
+  *a = b;
+}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -3558,7 +3558,10 @@
   !Global->hasAttr() &&
   !Global->hasAttr() &&
   !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
-  !Global->getType()->isCUDADeviceBuiltinTextureType())
+  !Global->getType()->isCUDADeviceBuiltinTextureType() &&
+  !(LangOpts.HIPStdPar &&
+isa(Global) &&
+!Global->hasAttr()))
 return;
 } else {
   // We need to emit host-side 'shadows' for all global
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2594,10 +2594,15 @@
   std::string MissingFeature;
   llvm::StringMap CallerFeatureMap;
   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
+  // When compiling in StdPar mode we have to be conservative in rejecting
+  // target specific features in the FE, and defer the possible error to the
+  // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
+  // referenced by an accelerator executable function, we emit an error.
+  bool IsStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice
   if (BuiltinID) {
 StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
 if (!Builtin::evaluateRequiredTargetFeatures(
-FeatureList, CallerFeatureMap)) {
+FeatureList, CallerFeatureMap) && !IsStdPar) {
   CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
   << TargetDecl->getDeclName()
   << FeatureList;
@@ -2630,7 +2635,7 @@
 return false;
   }
   return true;
-}))
+}) && !IsStdPar)
   CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
   << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
   } else if (!FD->isMultiVersion() && FD->hasAttr()) {
@@ -2639,7 +2644,8 @@
 
 for (const auto &F : CalleeFeatureMap) {
   if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
-   !CallerFeatureMap.find(F.getKey())->getValue()))
+   !CallerFeatureMap.find(F.getKey())->getValue()) &&
+  !IsStdPar)
 CGM.getDiags().Report(Loc, diag::err_fu

[PATCH] D157651: [RISCV] Rewrite CheckInvalidVLENandLMUL to avoid floating point.

2023-08-10 Thread Craig Topper via Phabricator via cfe-commits
craig.topper created this revision.
craig.topper added reviewers: 4vtomat, kito-cheng, reames, asb.
Herald added subscribers: jobnoorman, VincentWu, vkmr, luismarques, 
sameer.abuasal, s.egerton, Jim, benna, psnobl, rogfer01, shiva0217, simoncook, 
arichardson.
Herald added a project: All.
craig.topper requested review of this revision.
Herald added subscribers: cfe-commits, wangpc, eopXD.
Herald added a project: clang.

This avoids needing an FP value to represent LMUL.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157651

Files:
  clang/lib/Sema/SemaChecking.cpp


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -4473,14 +4473,22 @@
   assert((EGW == 128 || EGW == 256) && "EGW can only be 128 or 256 bits");
 
   // LMUL * VLEN >= EGW
-  uint64_t ElemSize = Type->isRVVType(32, false) ? 32 : 64;
-  uint64_t ElemCount = Type->isRVVType(1) ? 1 :
+  unsigned ElemSize = Type->isRVVType(32, false) ? 32 : 64;
+  unsigned ElemCount = Type->isRVVType(1) ? 1 :
Type->isRVVType(2) ? 2 :
Type->isRVVType(4) ? 4 :
Type->isRVVType(8) ? 8 :
16;
-  float Lmul = (float)(ElemSize * ElemCount) / llvm::RISCV::RVVBitsPerBlock;
-  uint64_t MinRequiredVLEN = std::max(EGW / Lmul, (float)ElemSize);
+
+  unsigned EGS = EGW / ElemSize;
+  // If EGS is more than our minimum number of elements we're done.
+  if (EGS <= ElemCount)
+return false;
+
+  // We need vscale to be at least this value.
+  unsigned VScaleFactor = EGS / ElemCount;
+  // Vscale is VLEN/RVVBitsPerBlock.
+  unsigned MinRequiredVLEN = VScaleFactor * llvm::RISCV::RVVBitsPerBlock;
   std::string RequiredExt = "zvl" + std::to_string(MinRequiredVLEN) + "b";
   if (!TI.hasFeature(RequiredExt))
 return S.Diag(TheCall->getBeginLoc(),


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -4473,14 +4473,22 @@
   assert((EGW == 128 || EGW == 256) && "EGW can only be 128 or 256 bits");
 
   // LMUL * VLEN >= EGW
-  uint64_t ElemSize = Type->isRVVType(32, false) ? 32 : 64;
-  uint64_t ElemCount = Type->isRVVType(1) ? 1 :
+  unsigned ElemSize = Type->isRVVType(32, false) ? 32 : 64;
+  unsigned ElemCount = Type->isRVVType(1) ? 1 :
Type->isRVVType(2) ? 2 :
Type->isRVVType(4) ? 4 :
Type->isRVVType(8) ? 8 :
16;
-  float Lmul = (float)(ElemSize * ElemCount) / llvm::RISCV::RVVBitsPerBlock;
-  uint64_t MinRequiredVLEN = std::max(EGW / Lmul, (float)ElemSize);
+
+  unsigned EGS = EGW / ElemSize;
+  // If EGS is more than our minimum number of elements we're done.
+  if (EGS <= ElemCount)
+return false;
+
+  // We need vscale to be at least this value.
+  unsigned VScaleFactor = EGS / ElemCount;
+  // Vscale is VLEN/RVVBitsPerBlock.
+  unsigned MinRequiredVLEN = VScaleFactor * llvm::RISCV::RVVBitsPerBlock;
   std::string RequiredExt = "zvl" + std::to_string(MinRequiredVLEN) + "b";
   if (!TI.hasFeature(RequiredExt))
 return S.Diag(TheCall->getBeginLoc(),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157520: [Driver] Replace a link to openradar with a comment. NFC

2023-08-10 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 549165.
ahatanak added a comment.

Mention that the linker bug has been fixed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157520

Files:
  clang/lib/Driver/ToolChains/Clang.cpp


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5578,8 +5578,11 @@
   }
 
   // Enable -mconstructor-aliases except on darwin, where we have to work 
around
-  // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
-  // code, where aliases aren't supported.
+  // a linker bug where aliasing symbols are not moved to the new locations 
when
+  // the aliased symbol is moved, and CUDA device code, where aliases aren't
+  // supported.
+  // FIXME: Enable this on Darwin after extensive testing. The linker bug
+  // mentioned above has been fixed.
   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
 CmdArgs.push_back("-mconstructor-aliases");
 


Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -5578,8 +5578,11 @@
   }
 
   // Enable -mconstructor-aliases except on darwin, where we have to work around
-  // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
-  // code, where aliases aren't supported.
+  // a linker bug where aliasing symbols are not moved to the new locations when
+  // the aliased symbol is moved, and CUDA device code, where aliases aren't
+  // supported.
+  // FIXME: Enable this on Darwin after extensive testing. The linker bug
+  // mentioned above has been fixed.
   if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
 CmdArgs.push_back("-mconstructor-aliases");
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157520: [Driver] Replace a link to openradar with a comment. NFC

2023-08-10 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added a comment.

It looks like the linker bug has been fixed, but we probably need extensive 
testing before enabling it on Darwin.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157520

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


[PATCH] D157566: [SEH] fix assertion when -fasy-exceptions is used.

2023-08-10 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 updated this revision to Diff 549174.
jyu2 added a comment.

Thanks all for the review!  This is fix space problem.


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

https://reviews.llvm.org/D157566

Files:
  clang/lib/CodeGen/CGCleanup.cpp
  clang/test/CodeGen/windows-seh-async-exceptions.cpp


Index: clang/test/CodeGen/windows-seh-async-exceptions.cpp
===
--- /dev/null
+++ clang/test/CodeGen/windows-seh-async-exceptions.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple x86_64-windows -fasync-exceptions -x c++ \
+// RUN:  -emit-llvm %s -o -| FileCheck %s
+
+extern "C" int printf(const char*,...);
+class PrintfArg
+{
+public:
+  PrintfArg();
+  PrintfArg(const char* s);
+
+  // compiler crash fixed if this destructor removed
+  ~PrintfArg() {int x; printf("ddd\n");  }
+};
+
+void devif_Warning(const char* fmt, PrintfArg arg1 = PrintfArg());
+// CHECK-NOT: invoke void @llvm.seh.scope.begin()
+// CHECK-NOT: invoke void @llvm.seh.scope.end()
+unsigned myfunc(unsigned index)
+{
+  devif_Warning("");
+  return 0;
+}
Index: clang/lib/CodeGen/CGCleanup.cpp
===
--- clang/lib/CodeGen/CGCleanup.cpp
+++ clang/lib/CodeGen/CGCleanup.cpp
@@ -207,8 +207,13 @@
 Scope->setLifetimeMarker();
 
   // With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup
+  // If exceptions are disabled/ignored and SEH is not in use, then there is no
+  // invoke destination. SEH "works" even if exceptions are off. In practice,
+  // this means that C++ destructors and other EH cleanups don't run, which is
+  // consistent with MSVC's behavior, except in the presence of -EHa.
+  // Check getInvokeDest() to generate llvm.seh.scope.begin() as needed.
   if (CGF->getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&
-  CGF->getTarget().getCXXABI().isMicrosoft())
+  CGF->getTarget().getCXXABI().isMicrosoft() && CGF->getInvokeDest())
 CGF->EmitSehCppScopeBegin();
 
   return Scope->getCleanupBuffer();


Index: clang/test/CodeGen/windows-seh-async-exceptions.cpp
===
--- /dev/null
+++ clang/test/CodeGen/windows-seh-async-exceptions.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple x86_64-windows -fasync-exceptions -x c++ \
+// RUN:  -emit-llvm %s -o -| FileCheck %s
+
+extern "C" int printf(const char*,...);
+class PrintfArg
+{
+public:
+  PrintfArg();
+  PrintfArg(const char* s);
+
+  // compiler crash fixed if this destructor removed
+  ~PrintfArg() {int x; printf("ddd\n");  }
+};
+
+void devif_Warning(const char* fmt, PrintfArg arg1 = PrintfArg());
+// CHECK-NOT: invoke void @llvm.seh.scope.begin()
+// CHECK-NOT: invoke void @llvm.seh.scope.end()
+unsigned myfunc(unsigned index)
+{
+  devif_Warning("");
+  return 0;
+}
Index: clang/lib/CodeGen/CGCleanup.cpp
===
--- clang/lib/CodeGen/CGCleanup.cpp
+++ clang/lib/CodeGen/CGCleanup.cpp
@@ -207,8 +207,13 @@
 Scope->setLifetimeMarker();
 
   // With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup
+  // If exceptions are disabled/ignored and SEH is not in use, then there is no
+  // invoke destination. SEH "works" even if exceptions are off. In practice,
+  // this means that C++ destructors and other EH cleanups don't run, which is
+  // consistent with MSVC's behavior, except in the presence of -EHa.
+  // Check getInvokeDest() to generate llvm.seh.scope.begin() as needed.
   if (CGF->getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&
-  CGF->getTarget().getCXXABI().isMicrosoft())
+  CGF->getTarget().getCXXABI().isMicrosoft() && CGF->getInvokeDest())
 CGF->EmitSehCppScopeBegin();
 
   return Scope->getCleanupBuffer();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D156054: [Clang][Sema] DR722 (nullptr and varargs) and missing -Wvarargs diagnostics

2023-08-10 Thread Mital Ashok via Phabricator via cfe-commits
MitalAshok updated this revision to Diff 549176.
MitalAshok added a comment.

Address feedback; Reuse DefaultArgumentPromotion instead of duplicating its 
functionality when building VaArgExpr

There is the added bonus for it working with dependent types somewhat 
(`template __builtin_va_arg(ap, T[2]);` will warn in the template 
instead of waiting for it to be instantiated).
I can add the check for dependent types back if this is unwanted.

I don't think there are any edge cases where this will give a false warning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156054

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/FormatString.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CXX/drs/dr7xx.cpp
  clang/test/CodeGen/xcore-abi.c
  clang/test/Sema/format-pointer.c
  clang/test/Sema/format-strings-pedantic.c
  clang/test/SemaCXX/format-strings-0x-nopedantic.cpp
  clang/test/SemaCXX/varargs.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -4373,7 +4373,7 @@
 https://cplusplus.github.io/CWG/issues/722.html";>722
 CD2
 Can nullptr be passed to an ellipsis?
-Unknown
+Clang 18
   
   
 https://cplusplus.github.io/CWG/issues/726.html";>726
Index: clang/test/SemaCXX/varargs.cpp
===
--- clang/test/SemaCXX/varargs.cpp
+++ clang/test/SemaCXX/varargs.cpp
@@ -55,6 +55,16 @@
   (void)__builtin_va_arg(ap, unsigned int);
 
   (void)__builtin_va_arg(ap, bool); // expected-warning {{second argument to 'va_arg' is of promotable type 'bool'; this va_arg has undefined behavior because arguments will be promoted to 'int'}}
+
+  (void)__builtin_va_arg(ap, float); // expected-warning {{second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'}}
+  (void)__builtin_va_arg(ap, __fp16); // expected-warning {{second argument to 'va_arg' is of promotable type '__fp16'; this va_arg has undefined behavior because arguments will be promoted to 'double'}}
+
+#if __cplusplus >= 201103L
+  (void)__builtin_va_arg(ap, decltype(nullptr)); // expected-warning {{second argument to 'va_arg' is of promotable type 'decltype(nullptr)' (aka 'std::nullptr_t'); this va_arg has undefined behavior because arguments will be promoted to 'void *'}}
+#endif
+
+  (void)__builtin_va_arg(ap, int[3]); // expected-warning {{second argument to 'va_arg' is of promotable type 'int[3]'; this va_arg has undefined behavior because arguments will be promoted to 'int *'}}
+  (void)__builtin_va_arg(ap, const int[3]); // expected-warning {{second argument to 'va_arg' is of promotable type 'const int[3]'; this va_arg has undefined behavior because arguments will be promoted to 'const int *'}}
 }
 
 #if __cplusplus >= 201103L
Index: clang/test/SemaCXX/format-strings-0x-nopedantic.cpp
===
--- clang/test/SemaCXX/format-strings-0x-nopedantic.cpp
+++ clang/test/SemaCXX/format-strings-0x-nopedantic.cpp
@@ -5,6 +5,7 @@
 extern int printf(const char *restrict, ...);
 }
 
-void f(char *c) {
+void f(char *c, int *q) {
   printf("%p", c);
+  printf("%p", q);
 }
Index: clang/test/Sema/format-strings-pedantic.c
===
--- clang/test/Sema/format-strings-pedantic.c
+++ clang/test/Sema/format-strings-pedantic.c
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -Wno-format -Wformat-pedantic %s
 // RUN: %clang_cc1 -xobjective-c -fblocks -fsyntax-only -verify -Wno-format -Wformat-pedantic %s
 // RUN: %clang_cc1 -xc++ -fsyntax-only -verify -Wno-format -Wformat-pedantic %s
+// RUN: %clang_cc1 -std=c2x -fsyntax-only -verify -Wno-format -Wformat-pedantic %s
 
 __attribute__((format(printf, 1, 2)))
 int printf(const char *restrict, ...);
@@ -14,7 +15,7 @@
   printf("%p", (id)0); // expected-warning {{format specifies type 'void *' but the argument has type 'id'}}
 #endif
 
-#ifdef __cplusplus
-  printf("%p", nullptr); // expected-warning {{format specifies type 'void *' but the argument has type 'std::nullptr_t'}}
+#if !__is_identifier(nullptr)
+  printf("%p", nullptr);
 #endif
 }
Index: clang/test/Sema/format-pointer.c
===
--- /dev/null
+++ clang/test/Sema/format-pointer.c
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -xc -Wformat %s -verify
+// RUN: %clang_cc1 -xc -Wformat -std=c2x %s -verify
+// RUN: %clang_cc1 -xc++ -Wformat %s -verify
+// RUN: %clang_cc1 -xobjective-c -Wformat -fblocks %s -verify
+// RUN: %clang_cc1 -xobjective-c++ -Wformat -fblocks %s -verify
+// RUN: %clang_cc1 -xc -std=c2x -Wformat %s -pedantic -verify=expected,pedantic
+// RUN: %clang_cc1 -xc++ -Wformat %s -pedantic -verify=ex

[PATCH] D156054: [Clang][Sema] DR722 (nullptr and varargs) and missing -Wvarargs diagnostics

2023-08-10 Thread Mital Ashok via Phabricator via cfe-commits
MitalAshok updated this revision to Diff 549177.
MitalAshok added a comment.

clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D156054

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/FormatString.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CXX/drs/dr7xx.cpp
  clang/test/CodeGen/xcore-abi.c
  clang/test/Sema/format-pointer.c
  clang/test/Sema/format-strings-pedantic.c
  clang/test/SemaCXX/format-strings-0x-nopedantic.cpp
  clang/test/SemaCXX/varargs.cpp
  clang/www/cxx_dr_status.html

Index: clang/www/cxx_dr_status.html
===
--- clang/www/cxx_dr_status.html
+++ clang/www/cxx_dr_status.html
@@ -4373,7 +4373,7 @@
 https://cplusplus.github.io/CWG/issues/722.html";>722
 CD2
 Can nullptr be passed to an ellipsis?
-Unknown
+Clang 18
   
   
 https://cplusplus.github.io/CWG/issues/726.html";>726
Index: clang/test/SemaCXX/varargs.cpp
===
--- clang/test/SemaCXX/varargs.cpp
+++ clang/test/SemaCXX/varargs.cpp
@@ -55,6 +55,16 @@
   (void)__builtin_va_arg(ap, unsigned int);
 
   (void)__builtin_va_arg(ap, bool); // expected-warning {{second argument to 'va_arg' is of promotable type 'bool'; this va_arg has undefined behavior because arguments will be promoted to 'int'}}
+
+  (void)__builtin_va_arg(ap, float); // expected-warning {{second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'}}
+  (void)__builtin_va_arg(ap, __fp16); // expected-warning {{second argument to 'va_arg' is of promotable type '__fp16'; this va_arg has undefined behavior because arguments will be promoted to 'double'}}
+
+#if __cplusplus >= 201103L
+  (void)__builtin_va_arg(ap, decltype(nullptr)); // expected-warning {{second argument to 'va_arg' is of promotable type 'decltype(nullptr)' (aka 'std::nullptr_t'); this va_arg has undefined behavior because arguments will be promoted to 'void *'}}
+#endif
+
+  (void)__builtin_va_arg(ap, int[3]); // expected-warning {{second argument to 'va_arg' is of promotable type 'int[3]'; this va_arg has undefined behavior because arguments will be promoted to 'int *'}}
+  (void)__builtin_va_arg(ap, const int[3]); // expected-warning {{second argument to 'va_arg' is of promotable type 'const int[3]'; this va_arg has undefined behavior because arguments will be promoted to 'const int *'}}
 }
 
 #if __cplusplus >= 201103L
Index: clang/test/SemaCXX/format-strings-0x-nopedantic.cpp
===
--- clang/test/SemaCXX/format-strings-0x-nopedantic.cpp
+++ clang/test/SemaCXX/format-strings-0x-nopedantic.cpp
@@ -5,6 +5,7 @@
 extern int printf(const char *restrict, ...);
 }
 
-void f(char *c) {
+void f(char *c, int *q) {
   printf("%p", c);
+  printf("%p", q);
 }
Index: clang/test/Sema/format-strings-pedantic.c
===
--- clang/test/Sema/format-strings-pedantic.c
+++ clang/test/Sema/format-strings-pedantic.c
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -Wno-format -Wformat-pedantic %s
 // RUN: %clang_cc1 -xobjective-c -fblocks -fsyntax-only -verify -Wno-format -Wformat-pedantic %s
 // RUN: %clang_cc1 -xc++ -fsyntax-only -verify -Wno-format -Wformat-pedantic %s
+// RUN: %clang_cc1 -std=c2x -fsyntax-only -verify -Wno-format -Wformat-pedantic %s
 
 __attribute__((format(printf, 1, 2)))
 int printf(const char *restrict, ...);
@@ -14,7 +15,7 @@
   printf("%p", (id)0); // expected-warning {{format specifies type 'void *' but the argument has type 'id'}}
 #endif
 
-#ifdef __cplusplus
-  printf("%p", nullptr); // expected-warning {{format specifies type 'void *' but the argument has type 'std::nullptr_t'}}
+#if !__is_identifier(nullptr)
+  printf("%p", nullptr);
 #endif
 }
Index: clang/test/Sema/format-pointer.c
===
--- /dev/null
+++ clang/test/Sema/format-pointer.c
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -xc -Wformat %s -verify
+// RUN: %clang_cc1 -xc -Wformat -std=c2x %s -verify
+// RUN: %clang_cc1 -xc++ -Wformat %s -verify
+// RUN: %clang_cc1 -xobjective-c -Wformat -fblocks %s -verify
+// RUN: %clang_cc1 -xobjective-c++ -Wformat -fblocks %s -verify
+// RUN: %clang_cc1 -xc -std=c2x -Wformat %s -pedantic -verify=expected,pedantic
+// RUN: %clang_cc1 -xc++ -Wformat %s -pedantic -verify=expected,pedantic
+// RUN: %clang_cc1 -xobjective-c -Wformat -fblocks -pedantic %s -verify=expected,pedantic
+
+__attribute__((__format__(__printf__, 1, 2)))
+int printf(const char *, ...);
+__attribute__((__format__(__scanf__, 1, 2)))
+int scanf(const char *, ...);
+
+void f(void *vp, const void *cvp, char *cp, signed char *scp, int *ip) {
+  int arr[2];
+
+  printf("%p", cp);
+  printf("%p", cvp);
+  printf("%p", vp);
+  printf(

[PATCH] D157040: [OpenMP][IR] Set correct alignment for internal variables

2023-08-10 Thread Hao Jin via Phabricator via cfe-commits
erjin added a comment.

Ping. :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157040

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


[PATCH] D157452: [RFC][Clang][Codegen] `std::type_info` needs special care with explicit address spaces

2023-08-10 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:5237-5238
+
+  if (VTy->isPointerTy() &&
+  VTy->getPointerAddressSpace() != IRTy->getPointerAddressSpace()) 
{
+// In the case of targets that use a non-default address space for

you can also just unconditionally call CreateAddrSpaceCast and let it no-op if 
the types match


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157452

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


[clang] b070be8 - Reland "[modules] Fix error about the same module being defined in different .pcm files when using VFS overlays."

2023-08-10 Thread Volodymyr Sapsai via cfe-commits

Author: Volodymyr Sapsai
Date: 2023-08-10T14:52:49-07:00
New Revision: b070be82bb8fb4414a8a6eb4fbfc77921d89fa4b

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

LOG: Reland "[modules] Fix error about the same module being defined in 
different .pcm files when using VFS overlays."

Fixing Windows buildbot by using the same separators for `-F` and `-I`
paths both in VFS overlay and on command line.

Fix errors like
> module 'MultiPath' is defined in both 
> 'path/to/modules.cache/3JR48BPRU7BCG/MultiPath-1352QHUF8RNMU.pcm' and 
> 'path/to/modules.cache/3JR48BPRU7BCG/MultiPath-20HNSLLIUDDV1.pcm'

To avoid building extra identical modules `-ivfsoverlay` option is not a
part of the hash like "/3JR48BPRU7BCG/". And it is build system's
responsibility to provide `-ivfsoverlay` options that don't cause
observable differences.  We also need to make sure the hash like
"-1352QHUF8RNMU" is not affected by `-ivfsoverlay`. As this hash is
defined by the module map path, use the path prior to any VFS
remappings.

rdar://111921464

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

Added: 
clang/test/VFS/module-map-path.m

Modified: 
clang/lib/Lex/HeaderSearch.cpp
clang/lib/Serialization/ASTWriter.cpp

Removed: 




diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index f42d51d65dcdf3..80e1bad72ce9b7 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -177,7 +177,7 @@ std::string HeaderSearch::getCachedModuleFileName(Module 
*Module) {
   // *.modulemap file. In this case, just return an empty string.
   if (!ModuleMap)
 return {};
-  return getCachedModuleFileName(Module->Name, ModuleMap->getName());
+  return getCachedModuleFileName(Module->Name, 
ModuleMap->getNameAsRequested());
 }
 
 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,

diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 8b0015f1ee9f6c..289c0383cd4b0e 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1327,7 +1327,8 @@ void ASTWriter::WriteControlBlock(Preprocessor &PP, 
ASTContext &Context,
 
 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
 AddPath(WritingModule->PresumedModuleMapFile.empty()
-? Map.getModuleMapFileForUniquing(WritingModule)->getName()
+? Map.getModuleMapFileForUniquing(WritingModule)
+  ->getNameAsRequested()
 : StringRef(WritingModule->PresumedModuleMapFile),
 Record);
 

diff  --git a/clang/test/VFS/module-map-path.m 
b/clang/test/VFS/module-map-path.m
new file mode 100644
index 00..da7fb3f0089578
--- /dev/null
+++ b/clang/test/VFS/module-map-path.m
@@ -0,0 +1,110 @@
+// Test the module map path is consistent between clang invocations when using 
VFS overlays.
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+// Pre-populate the module cache with the modules that don't use VFS overlays.
+// RUN: %clang_cc1 -fsyntax-only -F%/t/Frameworks -I%/t/include 
%t/prepopulate_module_cache.m \
+// RUN: -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules.cache
+
+// Execute a compilation with VFS overlay. .pcm file path looks like 
/ModuleName-.pcm.
+//  corresponds to the compilation settings like language options.
+//  corresponds to the module map path. So if any of those change, we 
should use a 
diff erent module.
+// But for VFS overlay we make an exception that it's not a part of  to 
reduce the number of built .pcm files.
+// Test that paths in overlays don't leak into  and don't cause using 2 
.pcm files for the same module.
+// DEFINE: %{command} = %clang_cc1 -fsyntax-only -verify -F%/t/Frameworks 
-I%/t/include %t/test.m \
+// DEFINE:-fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules.cache
+// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@@g" %t/overlay.yaml.template > 
%t/external-names-default.yaml
+// RUN: %{command} -ivfsoverlay %t/external-names-default.yaml
+
+// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': true,@g" 
%t/overlay.yaml.template > %t/external-names-true.yaml
+// RUN: %{command} -ivfsoverlay %t/external-names-true.yaml
+
+// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': false,@g" 
%t/overlay.yaml.template > %t/external-names-false.yaml
+// RUN: %{command} -ivfsoverlay %t/external-names-false.yaml
+
+//--- prepopulate_module_cache.m
+#import 
+
+//--- test.m
+// At first import multi-path modules directly, so clang decides which .pcm 
file they should belong to.
+#import 
+#import 
+
+// Then import a mod

[PATCH] D155833: [Clang][Sema][RFC] Add Sema support for C++ Parallel Algorithm Offload

2023-08-10 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: clang/test/SemaStdPar/device-can-call-host.cpp:1
+// RUN: %clang %s --stdpar --stdpar-path=%S/Inputs \
+// RUN:   --stdpar-thrust-path=%S/Inputs --stdpar-prim-path=%S/Inputs \

can we use %clang_cc1 and omit the stdpar path options?


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

https://reviews.llvm.org/D155833

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


[clang] fe9c332 - Revert "Reland "[modules] Fix error about the same module being defined in different .pcm files when using VFS overlays.""

2023-08-10 Thread Volodymyr Sapsai via cfe-commits

Author: Volodymyr Sapsai
Date: 2023-08-10T15:14:26-07:00
New Revision: fe9c332408603e50ab846c1ad8aeb705df2950b1

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

LOG: Revert "Reland "[modules] Fix error about the same module being defined in 
different .pcm files when using VFS overlays.""

This reverts commit b070be82bb8fb4414a8a6eb4fbfc77921d89fa4b.

Added: 


Modified: 
clang/lib/Lex/HeaderSearch.cpp
clang/lib/Serialization/ASTWriter.cpp

Removed: 
clang/test/VFS/module-map-path.m



diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index 80e1bad72ce9b7..f42d51d65dcdf3 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -177,7 +177,7 @@ std::string HeaderSearch::getCachedModuleFileName(Module 
*Module) {
   // *.modulemap file. In this case, just return an empty string.
   if (!ModuleMap)
 return {};
-  return getCachedModuleFileName(Module->Name, 
ModuleMap->getNameAsRequested());
+  return getCachedModuleFileName(Module->Name, ModuleMap->getName());
 }
 
 std::string HeaderSearch::getPrebuiltModuleFileName(StringRef ModuleName,

diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 289c0383cd4b0e..8b0015f1ee9f6c 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -1327,8 +1327,7 @@ void ASTWriter::WriteControlBlock(Preprocessor &PP, 
ASTContext &Context,
 
 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
 AddPath(WritingModule->PresumedModuleMapFile.empty()
-? Map.getModuleMapFileForUniquing(WritingModule)
-  ->getNameAsRequested()
+? Map.getModuleMapFileForUniquing(WritingModule)->getName()
 : StringRef(WritingModule->PresumedModuleMapFile),
 Record);
 

diff  --git a/clang/test/VFS/module-map-path.m 
b/clang/test/VFS/module-map-path.m
deleted file mode 100644
index da7fb3f0089578..00
--- a/clang/test/VFS/module-map-path.m
+++ /dev/null
@@ -1,110 +0,0 @@
-// Test the module map path is consistent between clang invocations when using 
VFS overlays.
-
-// RUN: rm -rf %t
-// RUN: split-file %s %t
-
-// Pre-populate the module cache with the modules that don't use VFS overlays.
-// RUN: %clang_cc1 -fsyntax-only -F%/t/Frameworks -I%/t/include 
%t/prepopulate_module_cache.m \
-// RUN: -fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules.cache
-
-// Execute a compilation with VFS overlay. .pcm file path looks like 
/ModuleName-.pcm.
-//  corresponds to the compilation settings like language options.
-//  corresponds to the module map path. So if any of those change, we 
should use a 
diff erent module.
-// But for VFS overlay we make an exception that it's not a part of  to 
reduce the number of built .pcm files.
-// Test that paths in overlays don't leak into  and don't cause using 2 
.pcm files for the same module.
-// DEFINE: %{command} = %clang_cc1 -fsyntax-only -verify -F%/t/Frameworks 
-I%/t/include %t/test.m \
-// DEFINE:-fmodules -fimplicit-module-maps 
-fmodules-cache-path=%t/modules.cache
-// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@@g" %t/overlay.yaml.template > 
%t/external-names-default.yaml
-// RUN: %{command} -ivfsoverlay %t/external-names-default.yaml
-
-// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': true,@g" 
%t/overlay.yaml.template > %t/external-names-true.yaml
-// RUN: %{command} -ivfsoverlay %t/external-names-true.yaml
-
-// RUN: sed -e "s@TMP_DIR@%{/t:regex_replacement}@g" -e 
"s@USE_EXTERNAL_NAMES_OPTION@'use-external-names': false,@g" 
%t/overlay.yaml.template > %t/external-names-false.yaml
-// RUN: %{command} -ivfsoverlay %t/external-names-false.yaml
-
-//--- prepopulate_module_cache.m
-#import 
-
-//--- test.m
-// At first import multi-path modules directly, so clang decides which .pcm 
file they should belong to.
-#import 
-#import 
-
-// Then import a module from the module cache and all its transitive 
dependencies.
-// Make sure the .pcm files loaded directly are the same as 'Redirecting' is 
referencing.
-#import 
-// expected-no-diagnostics
-
-
-//--- Frameworks/MultiPath.framework/Headers/MultiPath.h
-void multiPathFramework(void);
-
-//--- Frameworks/MultiPath.framework/Modules/module.modulemap
-framework module MultiPath {
-header "MultiPath.h"
-export *
-}
-
-
-//--- include/MultiPathHeader.h
-void multiPathHeader(void);
-
-//--- include/module.modulemap
-module MultiPathHeader {
-header "MultiPathHeader.h"
-export *
-}
-
-
-//--- Frameworks/Redirecting.framework/Headers/Redirecting.h
-#import 
-#import 
-
-//--- Frameworks/Redirecting.framework/M

[PATCH] D151373: [libclang] Expose arguments of clang::annotate

2023-08-10 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added inline comments.



Comment at: clang/tools/libclang/CIndex.cpp:3656
+  VisitorWorkList *WL = nullptr;
+  if (!WorkListFreeList.empty()) {
+WL = WorkListFreeList.back();

There is a leak here https://lab.llvm.org/buildbot/#/builders/5/builds/35725




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151373

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


[PATCH] D157632: [Profile] Allow online merging with debug info correlation.

2023-08-10 Thread Ellis Hoag via Phabricator via cfe-commits
ellis added a comment.

Thanks for working on this!




Comment at: compiler-rt/lib/profile/InstrProfilingMerge.c:103-104
 COMPILER_RT_VISIBILITY
 int __llvm_profile_merge_from_buffer(const char *ProfileData,
  uint64_t ProfileSize) {
   __llvm_profile_data *SrcDataStart, *SrcDataEnd, *SrcData, *DstData;

I just realized that I need to throw an error here for temporal profiles since 
online merging won't work for that case.



Comment at: compiler-rt/lib/profile/InstrProfilingMerge.c:129
+  // enabled.
+  if (Header->DataSize == 0) {
+if (!(__llvm_profile_get_version() & VARIANT_MASK_DBG_CORRELATE)) {

Since we don't have the data section, we need to be confident that existing 
profile comes from the same binary (so that the counter section is identical). 
Can we add some extra checks here? I'm thinking we can verify that some fields 
in the headers match and that the variant flags are identical.



Comment at: compiler-rt/lib/profile/InstrProfilingMerge.c:134-136
+for (SrcCounter = SrcCountersStart,
+DstCounter = __llvm_profile_begin_counters();
+ SrcCounter < SrcCountersEnd;) {

Can you add a check to make sure src and dst have the same number of counters 
(`SrcCountersEnd - SrcCountersStart`)?



Comment at: compiler-rt/test/profile/Darwin/instrprof-debug-info-correlate.c:26
+// RUN: %clang_pgogen -o %t -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %S/../Inputs/instrprof-debug-info-correlate-main.cpp 
%S/../Inputs/instrprof-debug-info-correlate-foo.cpp
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.proflite %run %t
+// RUN: llvm-profdata merge -o %t.profdata --debug-info=%t.dSYM %t.profdir/

We need to run this line twice to correctly test 
`__llvm_profile_merge_from_buffer()`



Comment at: compiler-rt/test/profile/Linux/instrprof-debug-info-correlate.c:35
+
+// RUN: diff <(llvm-profdata show %t.normal.profdata) <(llvm-profdata show 
%t.profdata)
+

I know this is outside the scope of this patch, but I don't think simply 
`llvm-profdata show` is sufficient to compare profiles. I'll try to fix this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157632

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


[PATCH] D151373: [libclang] Expose arguments of clang::annotate

2023-08-10 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

Not sure why the similar code above does not leak, so I will revert and leave 
to author to investigate


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151373

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


[clang] 332a34c - Revert "[libclang] Expose arguments of clang::annotate"

2023-08-10 Thread Vitaly Buka via cfe-commits

Author: Vitaly Buka
Date: 2023-08-10T15:25:02-07:00
New Revision: 332a34c71e7675ab4e0ebd28b0d2c15302a81a51

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

LOG: Revert "[libclang] Expose arguments of clang::annotate"

Introduced a memory leak.

This reverts commit 5aa06b18940c9b96cbf1c31da6aee3fbb92183ed.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/CursorVisitor.h
clang/unittests/libclang/LibclangTest.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c438db074a19b7..22f7a08ae03c67 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -249,8 +249,6 @@ clang-format
 libclang
 
 
-- Exposed arguments of ``clang::annotate``.
-
 Static Analyzer
 ---
 

diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index ca9467eb1ac23e..1bdc0bf742a8ce 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -23,7 +23,6 @@
 #include "CursorVisitor.h"
 #include "clang-c/FatalErrorHandler.h"
 #include "clang/AST/Attr.h"
-#include "clang/AST/AttrVisitor.h"
 #include "clang/AST/DeclObjCCommon.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
@@ -576,13 +575,6 @@ bool CursorVisitor::VisitChildren(CXCursor Cursor) {
   A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
   }
 
-  if (clang_isAttribute(Cursor.kind)) {
-if (const Attr *A = getCursorAttr(Cursor))
-  return Visit(A);
-
-return false;
-  }
-
   // If pointing inside a macro definition, check if the token is an identifier
   // that was ever defined as a macro. In such a case, create a "pseudo" macro
   // expansion cursor for that token.
@@ -2097,8 +2089,7 @@ class MemberRefVisit : public VisitorJob {
 (SourceLocation::UIntTy)(uintptr_t)data[1]);
   }
 };
-class EnqueueVisitor : public ConstStmtVisitor,
-   public ConstAttrVisitor {
+class EnqueueVisitor : public ConstStmtVisitor {
   friend class OMPClauseEnqueue;
   VisitorWorkList &WL;
   CXCursor Parent;
@@ -2240,9 +2231,6 @@ class EnqueueVisitor : public 
ConstStmtVisitor,
   void VisitOMPTargetTeamsDistributeSimdDirective(
   const OMPTargetTeamsDistributeSimdDirective *D);
 
-  // Attributes
-  void VisitAnnotateAttr(const AnnotateAttr *A);
-
 private:
   void AddDeclarationNameInfo(const Stmt *S);
   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
@@ -2254,7 +2242,6 @@ class EnqueueVisitor : public 
ConstStmtVisitor,
   void AddTypeLoc(TypeSourceInfo *TI);
   void EnqueueChildren(const Stmt *S);
   void EnqueueChildren(const OMPClause *S);
-  void EnqueueChildren(const AnnotateAttr *A);
 };
 } // namespace
 
@@ -2749,20 +2736,6 @@ void EnqueueVisitor::EnqueueChildren(const OMPClause *S) 
{
   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
   std::reverse(I, E);
 }
-
-void EnqueueVisitor::EnqueueChildren(const AnnotateAttr *A) {
-  unsigned size = WL.size();
-  for (const Expr *Arg : A->args()) {
-VisitStmt(Arg);
-  }
-  if (size == WL.size())
-return;
-  // Now reverse the entries we just added.  This will match the DFS
-  // ordering performed by the worklist.
-  VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
-  std::reverse(I, E);
-}
-
 void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
   WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
 }
@@ -3035,7 +3008,7 @@ void EnqueueVisitor::VisitOpaqueValueExpr(const 
OpaqueValueExpr *E) {
   // If the opaque value has a source expression, just transparently
   // visit that.  This is useful for (e.g.) pseudo-object expressions.
   if (Expr *SourceExpr = E->getSourceExpr())
-return ConstStmtVisitor::Visit(SourceExpr);
+return Visit(SourceExpr);
 }
 void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
   AddStmt(E->getBody());
@@ -3055,7 +3028,7 @@ void EnqueueVisitor::VisitCXXParenListInitExpr(const 
CXXParenListInitExpr *E) {
 }
 void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
   // Treat the expression like its syntactic form.
-  ConstStmtVisitor::Visit(E->getSyntacticForm());
+  Visit(E->getSyntacticForm());
 }
 
 void EnqueueVisitor::VisitOMPExecutableDirective(
@@ -3365,28 +3338,9 @@ void 
EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
   VisitOMPLoopDirective(D);
 }
 
-void EnqueueVisitor::VisitAnnotateAttr(const AnnotateAttr *A) {
-  EnqueueChildren(A);
-}
-
 void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
   EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest))
-  .ConstStmtVisitor::Visit(S);
-}
-
-void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, co

[PATCH] D157040: [OpenMP][IR] Set correct alignment for internal variables

2023-08-10 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 accepted this revision.
tianshilei1992 added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157040

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


[PATCH] D151373: [libclang] Expose arguments of clang::annotate

2023-08-10 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added inline comments.



Comment at: clang/tools/libclang/CIndex.cpp:3656
+  VisitorWorkList *WL = nullptr;
+  if (!WorkListFreeList.empty()) {
+WL = WorkListFreeList.back();

vitalybuka wrote:
> There is a leak here https://lab.llvm.org/buildbot/#/builders/5/builds/35725
> 
> 
Please ignore the location of this comment.
I don't know which part of the patch is responsible for the leak
Another trace here 
https://lab.llvm.org/buildbot/#/builders/236/builds/5562/steps/13/logs/stdio


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151373

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


[PATCH] D157151: [Driver] Refactor to use llvm Option's new Visibility flags

2023-08-10 Thread Justin Bogner via Phabricator via cfe-commits
bogner added a comment.

In D157151#4577790 , @awarzynski 
wrote:

> Hey @bogner , I've only skimmed through so far and it's looking great! That 
> Include/Exclude API was not fun to use. What you are proposing here takes 
> Options.td to a much a better place - this is a much needed and long overdue 
> refactor.
>
> There's quite a bit of churn here, so I will need a few days to scan. In the 
> meantime, could you update flang/docs/FlangDriver.md? And in general, please 
> note that this updates (primarily) `clangDriver` logic, which is used by both 
> by Clang and Flang. In particular, Options.td is shared. I think that it's 
> worth highlighting that this change benefits both sub-projects.

Yep, sorry about that. I tried to break this up as much as I could but given 
the number of places that depend on Options.td it was tricky. I do think this 
should makes things much easier for flang's driver in particular, as well as 
making clang-cl and clang-dxc easier to deal with.

Sorry I missed updating FlangDriver.md - FWIW I did build flang and run those 
tests with this change. I'll update the patch with doc updates momentarily.

>> introduced in llvm Option
>
> Could you add a link?

I've updated the description to mention https://reviews.llvm.org/D157149.




Comment at: clang/include/clang/Driver/Options.h:25-37
-  CoreOption = (1 << 8),
-  CLOption = (1 << 9),
-  CC1Option = (1 << 10),
-  CC1AsOption = (1 << 11),
-  NoDriverOption = (1 << 12),
-  LinkOption = (1 << 13),
-  FlangOption = (1 << 14),

awarzynski wrote:
> What happens to `CoreOption`s? Same for `NoDriverOption`s?
- `CoreOption` meant "available in clang and clang-cl (and maybe dxc...)", so 
it's now `[Default, CLOption]`.
- `NoDriverOption` is `!Default` - negative flags were a big part of why the 
include/exclude thing was awkward, so the change in 
https://reviews.llvm.org/D157149 introduced a bit for options where you don't 
say anything specific, which meant the clang driver in practice.

For a complete map, see `flag_to_vis` in the `update_options_td_flags.py` 
helper script I provided for downstreams: 
https://reviews.llvm.org/D157151#change-FMUYy4yRDQLQ



Comment at: clang/include/clang/Driver/Options.td:193
 def m_x86_Features_Group : OptionGroup<"">,
-   Group, Flags<[CoreOption]>, DocName<"X86">;
+   Group, Vis<[Default, CLOption, DXCOption]>,
+   DocName<"X86">;

awarzynski wrote:
> What's `Default` in `Vis<[Default, CLOption, DXCOption]>,`?
If you don't specify any visibility, the visibility is "Default" (See 
https://reviews.llvm.org/D157149). For all intents and purposes this means 
"Clang Driver" in this file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157151

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


[PATCH] D154359: [clang] Reset FP options before template instantiation

2023-08-10 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

This patch seems to be direct cause of a regression: 
https://github.com/llvm/llvm-project/issues/64605.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154359

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


[clang] 2b8542c - [clang-format] Correctly count annoated lines of a namespace body

2023-08-10 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-08-10T15:55:01-07:00
New Revision: 2b8542ce8e8c24dfcdd0433542cf733556b8

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

LOG: [clang-format] Correctly count annoated lines of a namespace body

Fixes #63882.

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

Added: 


Modified: 
clang/lib/Format/NamespaceEndCommentsFixer.cpp
clang/lib/Format/TokenAnnotator.h
clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/NamespaceEndCommentsFixer.cpp 
b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
index 95eb058d09e198..32c2592834555a 100644
--- a/clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -359,8 +359,10 @@ std::pair 
NamespaceEndCommentsFixer::analyze(
 computeEndCommentText(NamespaceName, AddNewline, NamespaceTok,
   Style.SpacesInLineCommentPrefix.Minimum);
 if (!hasEndComment(EndCommentPrevTok)) {
-  bool isShort = I - StartLineIndex <= Style.ShortNamespaceLines + 1;
-  if (!isShort) {
+  unsigned LineCount = 0;
+  for (auto J = StartLineIndex + 1; J < I; ++J)
+LineCount += AnnotatedLines[J]->size();
+  if (LineCount > Style.ShortNamespaceLines) {
 addEndComment(EndCommentPrevTok,
   std::string(Style.SpacesBeforeTrailingComments, ' ') +
   EndCommentText,

diff  --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index 611e95ba11b017..f3e5b397aa78b3 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -91,6 +91,13 @@ class AnnotatedLine {
 }
   }
 
+  size_t size() const {
+size_t Size = 1;
+for (const auto *Child : Children)
+  Size += Child->size();
+return Size;
+  }
+
   ~AnnotatedLine() {
 for (AnnotatedLine *Child : Children)
   delete Child;

diff  --git a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp 
b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
index b47435787591dd..65876a3c668650 100644
--- a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -1376,6 +1376,22 @@ TEST_F(ShortNamespaceLinesTest, MultipleUnwrappedLine) {
 "int k;\n"
 "}\n",
 Style));
+
+  // The namespace body has 5 unwrapped/annotated lines.
+  const std::string NestedLambdas{"namespace foo {\n"
+  "auto bar = [] {\n" // line 1
+  "  int i;\n"// line 2
+  "  return [] {\n"   // line 3
+  "  int j;"  // line 4
+  "  return 0;\n" // line 5
+  "  };\n"// part of line 3
+  "};\n"  // part of line 1
+  "}"};
+  Style.ShortNamespaceLines = 4;
+  EXPECT_EQ(NestedLambdas + " // namespace foo",
+fixNamespaceEndComments(NestedLambdas, Style));
+  ++Style.ShortNamespaceLines;
+  EXPECT_EQ(NestedLambdas, fixNamespaceEndComments(NestedLambdas, Style));
 }
 
 TEST_F(ShortNamespaceLinesTest, NamespaceAlias) {



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


[PATCH] D157244: [clang-format] Correctly count annoated lines in a namespace body

2023-08-10 Thread Owen Pan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2b8542ce8e8c: [clang-format] Correctly count annoated lines 
of a namespace body (authored by owenpan).

Changed prior to commit:
  https://reviews.llvm.org/D157244?vs=547612&id=549190#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157244

Files:
  clang/lib/Format/NamespaceEndCommentsFixer.cpp
  clang/lib/Format/TokenAnnotator.h
  clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp


Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -1376,6 +1376,22 @@
 "int k;\n"
 "}\n",
 Style));
+
+  // The namespace body has 5 unwrapped/annotated lines.
+  const std::string NestedLambdas{"namespace foo {\n"
+  "auto bar = [] {\n" // line 1
+  "  int i;\n"// line 2
+  "  return [] {\n"   // line 3
+  "  int j;"  // line 4
+  "  return 0;\n" // line 5
+  "  };\n"// part of line 3
+  "};\n"  // part of line 1
+  "}"};
+  Style.ShortNamespaceLines = 4;
+  EXPECT_EQ(NestedLambdas + " // namespace foo",
+fixNamespaceEndComments(NestedLambdas, Style));
+  ++Style.ShortNamespaceLines;
+  EXPECT_EQ(NestedLambdas, fixNamespaceEndComments(NestedLambdas, Style));
 }
 
 TEST_F(ShortNamespaceLinesTest, NamespaceAlias) {
Index: clang/lib/Format/TokenAnnotator.h
===
--- clang/lib/Format/TokenAnnotator.h
+++ clang/lib/Format/TokenAnnotator.h
@@ -91,6 +91,13 @@
 }
   }
 
+  size_t size() const {
+size_t Size = 1;
+for (const auto *Child : Children)
+  Size += Child->size();
+return Size;
+  }
+
   ~AnnotatedLine() {
 for (AnnotatedLine *Child : Children)
   delete Child;
Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp
===
--- clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -359,8 +359,10 @@
 computeEndCommentText(NamespaceName, AddNewline, NamespaceTok,
   Style.SpacesInLineCommentPrefix.Minimum);
 if (!hasEndComment(EndCommentPrevTok)) {
-  bool isShort = I - StartLineIndex <= Style.ShortNamespaceLines + 1;
-  if (!isShort) {
+  unsigned LineCount = 0;
+  for (auto J = StartLineIndex + 1; J < I; ++J)
+LineCount += AnnotatedLines[J]->size();
+  if (LineCount > Style.ShortNamespaceLines) {
 addEndComment(EndCommentPrevTok,
   std::string(Style.SpacesBeforeTrailingComments, ' ') +
   EndCommentText,


Index: clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
===
--- clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -1376,6 +1376,22 @@
 "int k;\n"
 "}\n",
 Style));
+
+  // The namespace body has 5 unwrapped/annotated lines.
+  const std::string NestedLambdas{"namespace foo {\n"
+  "auto bar = [] {\n" // line 1
+  "  int i;\n"// line 2
+  "  return [] {\n"   // line 3
+  "  int j;"  // line 4
+  "  return 0;\n" // line 5
+  "  };\n"// part of line 3
+  "};\n"  // part of line 1
+  "}"};
+  Style.ShortNamespaceLines = 4;
+  EXPECT_EQ(NestedLambdas + " // namespace foo",
+fixNamespaceEndComments(NestedLambdas, Style));
+  ++Style.ShortNamespaceLines;
+  EXPECT_EQ(NestedLambdas, fixNamespaceEndComments(NestedLambdas, Style));
 }
 
 TEST_F(ShortNamespaceLinesTest, NamespaceAlias) {
Index: clang/lib/Format/TokenAnnotator.h
===
--- clang/lib/Format/TokenAnnotator.h
+++ clang/lib/Format/TokenAnnotator.h
@@ -91,6 +91,13 @@
 }
   }
 
+  size_t size() const {
+size_t Size = 1;
+for (const auto *Child : Children)
+  Size += Child->size();
+return Size;
+  }
+
   ~AnnotatedLine() {
 for 

[PATCH] D157663: [Driver] Default riscv*-linux* to -fdebug-default-version=4

2023-08-10 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay created this revision.
MaskRay added reviewers: asb, dblaikie, jrtc27, kito-cheng.
Herald added subscribers: VincentWu, vkmr, luismarques, sameer.abuasal, 
s.egerton, Jim, benna, psnobl, PkmX, rogfer01, shiva0217, simoncook, 
arichardson.
Herald added a project: All.
MaskRay requested review of this revision.
Herald added subscribers: cfe-commits, wangpc, eopXD.
Herald added a project: clang.

DWARF v5 .debug_loclists/.debug_rnglists's
DW_LLE_offset_pair/DW_RLE_offset_pair entry kinds utilitize `.uleb128 A-B`
directives where A and B reference local labels in code sections.
When A and B are separated by a RISC-V linker-relaxable instruction,
A-B is incorrectly folded without a relocation, causing incorrect debug
information.

  void ext(void);
  int foo(int x) {ext(); return 0;}
  // DW_AT_location [DW_FORM_loclistx] of a DW_TAG_formal_parameter references 
a DW_LLE_offset_pair that can be incorrect after linker relaxation.
  
  int ext(void);
  void foo() { {
int ret = ext();
if (__builtin_expect(ret, 0))
  ext();
  } }
  // DW_AT_ranges [DW_FORM_rnglistx] of a DW_TAG_lexical_block references a 
DW_RLE_offset_pair that can be incorrect after linker relaxation.

D157657  will implement 
R_RISCV_SET_ULEB128/R_RISCV_SUB_ULEB128
relocations, fixing the issue, but the relocation is only supported by
bleeding-edge binutils 2.41 and not by lld/ELF yet.

The goal is to make the emitted DWARF correct after linking.
Many users don't care about the default DWARF version, but a linker
error will be unacceptable. Let's just downgrade the default DWARF
version, before binutils>=2.41 is more widely available.

An alternative compatibility option is to add a toggle to DwarfDebug.cpp,
but that doesn't seem like a good idea.

This patch is planned for the main and release/17.x branches.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D157663

Files:
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/Driver/clang-g-opts.c


Index: clang/test/Driver/clang-g-opts.c
===
--- clang/test/Driver/clang-g-opts.c
+++ clang/test/Driver/clang-g-opts.c
@@ -37,3 +37,7 @@
 
 // CHECK-WITH-G-STANDALONE: "-debug-info-kind=standalone"
 // CHECK-WITH-G-STANDALONE: "-dwarf-version=2"
+
+// RUN: %clang -### -S %s -g --target=riscv64-linux-gnu 2>&1 \
+// RUN:   | FileCheck --check-prefix=VERSION4 %s
+// VERSION4: "-dwarf-version=4"
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -343,7 +343,7 @@
 }
 
 unsigned Linux::GetDefaultDwarfVersion() const {
-  if (getTriple().isAndroid())
+  if (getTriple().isAndroid() || getTriple().isRISCV())
 return 4;
   return ToolChain::GetDefaultDwarfVersion();
 }


Index: clang/test/Driver/clang-g-opts.c
===
--- clang/test/Driver/clang-g-opts.c
+++ clang/test/Driver/clang-g-opts.c
@@ -37,3 +37,7 @@
 
 // CHECK-WITH-G-STANDALONE: "-debug-info-kind=standalone"
 // CHECK-WITH-G-STANDALONE: "-dwarf-version=2"
+
+// RUN: %clang -### -S %s -g --target=riscv64-linux-gnu 2>&1 \
+// RUN:   | FileCheck --check-prefix=VERSION4 %s
+// VERSION4: "-dwarf-version=4"
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -343,7 +343,7 @@
 }
 
 unsigned Linux::GetDefaultDwarfVersion() const {
-  if (getTriple().isAndroid())
+  if (getTriple().isAndroid() || getTriple().isRISCV())
 return 4;
   return ToolChain::GetDefaultDwarfVersion();
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157663: [Driver] Default riscv*-linux* to -fdebug-default-version=4

2023-08-10 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 549192.
MaskRay added a comment.

add a comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157663

Files:
  clang/lib/Driver/ToolChains/Linux.cpp
  clang/test/Driver/clang-g-opts.c


Index: clang/test/Driver/clang-g-opts.c
===
--- clang/test/Driver/clang-g-opts.c
+++ clang/test/Driver/clang-g-opts.c
@@ -37,3 +37,7 @@
 
 // CHECK-WITH-G-STANDALONE: "-debug-info-kind=standalone"
 // CHECK-WITH-G-STANDALONE: "-dwarf-version=2"
+
+// RUN: %clang -### -S %s -g --target=riscv64-linux-gnu 2>&1 \
+// RUN:   | FileCheck --check-prefix=VERSION4 %s
+// VERSION4: "-dwarf-version=4"
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -343,7 +343,8 @@
 }
 
 unsigned Linux::GetDefaultDwarfVersion() const {
-  if (getTriple().isAndroid())
+  // TODO Remove isRISCV when R_RISCV_SET_ULEB128 linker support is better.
+  if (getTriple().isAndroid() || getTriple().isRISCV())
 return 4;
   return ToolChain::GetDefaultDwarfVersion();
 }


Index: clang/test/Driver/clang-g-opts.c
===
--- clang/test/Driver/clang-g-opts.c
+++ clang/test/Driver/clang-g-opts.c
@@ -37,3 +37,7 @@
 
 // CHECK-WITH-G-STANDALONE: "-debug-info-kind=standalone"
 // CHECK-WITH-G-STANDALONE: "-dwarf-version=2"
+
+// RUN: %clang -### -S %s -g --target=riscv64-linux-gnu 2>&1 \
+// RUN:   | FileCheck --check-prefix=VERSION4 %s
+// VERSION4: "-dwarf-version=4"
Index: clang/lib/Driver/ToolChains/Linux.cpp
===
--- clang/lib/Driver/ToolChains/Linux.cpp
+++ clang/lib/Driver/ToolChains/Linux.cpp
@@ -343,7 +343,8 @@
 }
 
 unsigned Linux::GetDefaultDwarfVersion() const {
-  if (getTriple().isAndroid())
+  // TODO Remove isRISCV when R_RISCV_SET_ULEB128 linker support is better.
+  if (getTriple().isAndroid() || getTriple().isRISCV())
 return 4;
   return ToolChain::GetDefaultDwarfVersion();
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D157663: [Driver] Default riscv*-linux* to -fdebug-default-version=4

2023-08-10 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

RISCVToolchain also needs an override


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157663

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


[PATCH] D157663: [Driver] Default riscv*-linux* to -fdebug-default-version=4

2023-08-10 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

Also Haiku I guess, as another OS that has a somewhat working RISC-V port but 
falls back on ToolChain's default implementation. So maybe this just belongs in 
the default implementation, given all the ones that need modifying are the ones 
that end up there.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157663

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


[clang] 9c9e8b4 - Fix test clang/test/AST/Interp/builtin-functions.cpp for compilers that default to a C++ standard earlier than C++17.

2023-08-10 Thread Douglas Yung via cfe-commits

Author: Douglas Yung
Date: 2023-08-10T16:21:41-07:00
New Revision: 9c9e8b4797a4305d4273c63b0ab4ce84e3a79e7d

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

LOG: Fix test clang/test/AST/Interp/builtin-functions.cpp for compilers that 
default to a C++ standard earlier than C++17.

Added: 


Modified: 
clang/test/AST/Interp/builtin-functions.cpp

Removed: 




diff  --git a/clang/test/AST/Interp/builtin-functions.cpp 
b/clang/test/AST/Interp/builtin-functions.cpp
index 5b8b2dbf09ce5e..85f10d7594d8c9 100644
--- a/clang/test/AST/Interp/builtin-functions.cpp
+++ b/clang/test/AST/Interp/builtin-functions.cpp
@@ -43,6 +43,9 @@ namespace nan {
 
   /// The current interpreter does not accept this, but it should.
   constexpr float NaN2 = __builtin_nans([](){return "0xAE98";}()); // 
ref-error {{must be initialized by a constant expression}}
+#if __cplusplus < 201703L
+  // expected-error@-2 {{must be initialized by a constant expression}}
+#endif
 
   constexpr double NaN3 = __builtin_nan("foo"); // expected-error {{must be 
initialized by a constant expression}} \
 // ref-error {{must be 
initialized by a constant expression}}



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


[PATCH] D151373: [libclang] Expose arguments of clang::annotate

2023-08-10 Thread Fridtjof Mund via Phabricator via cfe-commits
fridtjof updated this revision to Diff 549197.
fridtjof added a comment.

It was the unit test I added - I forgot to properly dispose of the EvalResult 
there


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

https://reviews.llvm.org/D151373

Files:
  clang/docs/ReleaseNotes.rst
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/CursorVisitor.h
  clang/unittests/libclang/LibclangTest.cpp

Index: clang/unittests/libclang/LibclangTest.cpp
===
--- clang/unittests/libclang/LibclangTest.cpp
+++ clang/unittests/libclang/LibclangTest.cpp
@@ -1246,6 +1246,52 @@
   EXPECT_EQ(fromCXString(clang_getCursorSpelling(*staticAssertCsr)), "");
 }
 
+TEST_F(LibclangParseTest, ExposesAnnotateArgs) {
+  const char testSource[] = R"cpp(
+[[clang::annotate("category", 42)]]
+void func() {}
+)cpp";
+  std::string fileName = "main.cpp";
+  WriteFile(fileName, testSource);
+
+  const char *Args[] = {"-xc++"};
+  ClangTU = clang_parseTranslationUnit(Index, fileName.c_str(), Args, 1,
+   nullptr, 0, TUFlags);
+
+  int attrCount = 0;
+
+  Traverse(
+  [&attrCount](CXCursor cursor, CXCursor parent) -> CXChildVisitResult {
+if (cursor.kind == CXCursor_AnnotateAttr) {
+  int childCount = 0;
+  clang_visitChildren(
+  cursor,
+  [](CXCursor child, CXCursor,
+ CXClientData data) -> CXChildVisitResult {
+int *pcount = static_cast(data);
+
+// we only expect one argument here, so bail otherwise
+EXPECT_EQ(*pcount, 0);
+
+auto *result = clang_Cursor_Evaluate(child);
+EXPECT_NE(result, nullptr);
+EXPECT_EQ(clang_EvalResult_getAsInt(result), 42);
+clang_EvalResult_dispose(result);
+
+++*pcount;
+
+return CXChildVisit_Recurse;
+  },
+  &childCount);
+  attrCount++;
+  return CXChildVisit_Continue;
+}
+return CXChildVisit_Recurse;
+  });
+
+  EXPECT_EQ(attrCount, 1);
+}
+
 class LibclangRewriteTest : public LibclangParseTest {
 public:
   CXRewriter Rew = nullptr;
Index: clang/tools/libclang/CursorVisitor.h
===
--- clang/tools/libclang/CursorVisitor.h
+++ clang/tools/libclang/CursorVisitor.h
@@ -276,7 +276,9 @@
   bool IsInRegionOfInterest(CXCursor C);
   bool RunVisitorWorkList(VisitorWorkList &WL);
   void EnqueueWorkList(VisitorWorkList &WL, const Stmt *S);
+  void EnqueueWorkList(VisitorWorkList &WL, const Attr *A);
   LLVM_ATTRIBUTE_NOINLINE bool Visit(const Stmt *S);
+  LLVM_ATTRIBUTE_NOINLINE bool Visit(const Attr *A);
 
 private:
   std::optional handleDeclForVisitation(const Decl *D);
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -23,6 +23,7 @@
 #include "CursorVisitor.h"
 #include "clang-c/FatalErrorHandler.h"
 #include "clang/AST/Attr.h"
+#include "clang/AST/AttrVisitor.h"
 #include "clang/AST/DeclObjCCommon.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
@@ -575,6 +576,13 @@
   A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
   }
 
+  if (clang_isAttribute(Cursor.kind)) {
+if (const Attr *A = getCursorAttr(Cursor))
+  return Visit(A);
+
+return false;
+  }
+
   // If pointing inside a macro definition, check if the token is an identifier
   // that was ever defined as a macro. In such a case, create a "pseudo" macro
   // expansion cursor for that token.
@@ -2089,7 +2097,8 @@
 (SourceLocation::UIntTy)(uintptr_t)data[1]);
   }
 };
-class EnqueueVisitor : public ConstStmtVisitor {
+class EnqueueVisitor : public ConstStmtVisitor,
+   public ConstAttrVisitor {
   friend class OMPClauseEnqueue;
   VisitorWorkList &WL;
   CXCursor Parent;
@@ -2231,6 +2240,9 @@
   void VisitOMPTargetTeamsDistributeSimdDirective(
   const OMPTargetTeamsDistributeSimdDirective *D);
 
+  // Attributes
+  void VisitAnnotateAttr(const AnnotateAttr *A);
+
 private:
   void AddDeclarationNameInfo(const Stmt *S);
   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
@@ -2242,6 +2254,7 @@
   void AddTypeLoc(TypeSourceInfo *TI);
   void EnqueueChildren(const Stmt *S);
   void EnqueueChildren(const OMPClause *S);
+  void EnqueueChildren(const AnnotateAttr *A);
 };
 } // namespace
 
@@ -2736,6 +2749,20 @@
   VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
   std::reverse(I, E);
 }
+
+void EnqueueVisitor::EnqueueChildren(const AnnotateAttr *A) {
+  unsigned size = WL.size();
+  for (const Expr *Arg : A->args()) {
+VisitStmt(Arg);
+  }
+  if (size == WL.size())
+return;
+  // Now reverse the entries we just added.  This will match the DFS
+  // ordering performed by the wor

[PATCH] D157632: [Profile] Allow online merging with debug info correlation.

2023-08-10 Thread Ellis Hoag via Phabricator via cfe-commits
ellis added a comment.

I've just published https://reviews.llvm.org/D157664, so you'll want to rebase 
ontop of it if it lands soon. I would also like to see some more tests added to 
`instrprof-merge-error.c` to make sure two different binaries can't merge 
profiles together with `--debug-info-correlate`. I was thinking the test would 
be something like this.

  // RUN: %clang_pgogen -o %t/a -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %t/main.c
  // RUN: %clang_pgogen -o %t/b -g -mllvm --debug-info-correlate -mllvm 
--disable-vp=true %t/main.c %t/foo.c
  // RUN: env LLVM_PROFILE_FILE=%t/default_%m.profdata %run %t/a
  // This next line should fail to merge because the counter sections have 
different sizes
  // RUN: env LLVM_PROFILE_FILE=%t/default_%m.profdata %run %t/b
  
  //--- main.c
  int main() { return 0; }
  //--- foo.c
  int foo() { return 4; }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D157632

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


[PATCH] D155064: [clang][SemaCXX] Diagnose tautological uses of consteval if and is_constant_evaluated

2023-08-10 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 549203.
hazohelet added a comment.

Resolved the constexpr-if init-statement expression evaluation context problem.


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

https://reviews.llvm.org/D155064

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/AST/Interp/builtins.cpp
  clang/test/AST/Interp/if.cpp
  clang/test/AST/Interp/literals.cpp
  clang/test/CXX/expr/expr.const/p2-0x.cpp
  clang/test/CXX/expr/expr.const/p6-2a.cpp
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p3.cpp
  clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p4.cpp
  clang/test/Parser/pragma-fenv_access.c
  clang/test/SemaCXX/constant-conversion.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaCXX/cxx2a-consteval.cpp
  clang/test/SemaCXX/cxx2b-consteval-if.cpp
  clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
  clang/test/SemaCXX/vartemplate-lambda.cpp
  clang/test/SemaCXX/warn-constant-evaluated-constexpr.cpp
  clang/test/SemaCXX/warn-tautological-meta-constant.cpp
  clang/test/SemaTemplate/concepts.cpp
  clang/unittests/Support/TimeProfilerTest.cpp
  libcxx/include/__type_traits/is_constant_evaluated.h
  
libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
  
libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp

Index: libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp
===
--- libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp
+++ libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp
@@ -24,7 +24,7 @@
 #else
   // expected-error-re@+1 (static_assert|static assertion)}} failed}}
   static_assert(!std::is_constant_evaluated(), "");
-  // expected-warning@-1 0-1 {{'std::is_constant_evaluated' will always evaluate to 'true' in a manifestly constant-evaluated expression}}
+  // expected-warning-re@-1 0-1 {{'std::is_constant_evaluated' will always evaluate to {{('true' in a manifestly constant-evaluated expression|true in this context)
 #endif
   return 0;
 }
Index: libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
===
--- libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
+++ libcxx/test/std/algorithms/alg.modifying.operations/alg.copy/ranges.copy.segmented.pass.cpp
@@ -93,12 +93,10 @@
 }
 
 int main(int, char**) {
-  if (!std::is_constant_evaluated()) {
-test_containers, std::deque>();
-test_containers, std::vector>();
-test_containers, std::deque>();
-test_containers, std::vector>();
-  }
+  test_containers, std::deque>();
+  test_containers, std::vector>();
+  test_containers, std::deque>();
+  test_containers, std::vector>();
 
   types::for_each(types::forward_iterator_list{}, [] {
 test_join_view();
Index: libcxx/include/__type_traits/is_constant_evaluated.h
===
--- libcxx/include/__type_traits/is_constant_evaluated.h
+++ libcxx/include/__type_traits/is_constant_evaluated.h
@@ -24,7 +24,11 @@
 #endif
 
 _LIBCPP_HIDE_FROM_ABI inline _LIBCPP_CONSTEXPR bool __libcpp_is_constant_evaluated() _NOEXCEPT {
+#ifndef _LIBCPP_CXX03_LANG
   return __builtin_is_constant_evaluated();
+#else
+  return false;
+#endif
 }
 
 _LIBCPP_END_NAMESPACE_STD
Index: clang/unittests/Support/TimeProfilerTest.cpp
===
--- clang/unittests/Support/TimeProfilerTest.cpp
+++ clang/unittests/Support/TimeProfilerTest.cpp
@@ -188,7 +188,6 @@
 | EvaluateAsBooleanCondition ()
 | | EvaluateAsRValue ()
 | EvaluateAsInitializer (slow_value)
-| EvaluateAsConstantExpr ()
 | EvaluateAsConstantExpr ()
 | EvaluateAsRValue ()
 | EvaluateAsInitializer (slow_init_list)
Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -135,21 +135,21 @@
 
 namespace BuiltinIsConstantEvaluated {
   // Check that we do all satisfaction and diagnostic checks in a constant context.
-  template concept C = __builtin_is_constant_evaluated(); // expected-warning {{always}}
+  template concept C = __builtin_is_constan

  1   2   >