[PATCH] D122981: [Clang] CWG 1394: Incomplete types as parameters of deleted functions

2022-04-07 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao marked 2 inline comments as done.
rZhBoYao added inline comments.



Comment at: clang/include/clang/Sema/Sema.h:2899-2909
+/// C++ [dcl.fct.def.general]p1
+/// function-body:
+///   = delete ;
+///   = default ;
+Delete,
+Default,
+

ChuanqiXu wrote:
> rZhBoYao wrote:
> > ChuanqiXu wrote:
> > > Agree to @erichkeane 
> > With all due respect, this code suggestion doesn't make any sense to me. My 
> > best guess is @ChuanqiXu was thinking the order specified by the grammar as 
> > noted in [[ https://eel.is/c++draft/dcl.fct.def.general#nt:function-body | 
> > dcl.fct.def.general p1 ]]. Even if that was the case, `CompoundStmt` is not 
> > quite right either. Also, differentiating `ctor-initializer[opt] 
> > compound-statement` and `function-try-block` is meaningless here, hence the 
> > name `Other`.
> > 
> > I adopted the same order as to how `Parser::ParseFunctionDefinition` has 
> > always been parsing `function-body`. The order is not significant in any 
> > meaningful way as each of the 4 grammar productions of `function-body` is 
> > VERY different and mutually exclusive. Putting `Delete` and `Default` 
> > upfront not only emphasizes the "specialness" of them but also conveys how 
> > we handle `function-body`.
> > 
> > What say you, @erichkeane ?
> Yeah, the order comes from the standard. I think the comment should be 
> consistent with the spec. And for the name, I agree `CompoundStmt` is not 
> accurate indeed... I thought Default should be a good name but there is 
> `Default` already. But I don't feel `Other` is good since the 
> compound-statement is much more common.
> 
> > Putting Delete and Default upfront not only emphasizes the "specialness" of 
> > them but also conveys how we handle function-body.
> 
> This don't makes sense. Generally, we would put common items in front. And 
> the order here shouldn't be related to the implementation.
> But I don't feel `Other` is good since the compound-statement is much more 
> common.
`Other` reads "not special like `Delete` and `Default`".
> This don't makes sense. Generally, we would put common items in front. And 
> the order here shouldn't be related to the implementation.
Think of it as a not-so-special else clause at the end of an if/else chain. We 
tend to process special cases upfront. It is only natural.

I'll await @erichkeane 's final verdict.


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

https://reviews.llvm.org/D122981

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


[PATCH] D123298: [NFC] [AST] Reduce the size of TemplateParmPosition

2022-04-07 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

> On the other hand, why not use 16 for both?

I am consistent with @aaron.ballman here.




Comment at: clang/include/clang/AST/DeclTemplate.h:1156-1157
 
-  TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
+  static constexpr unsigned MaxDepth = (1l << DEPTH_BITWIDTH) - 1;
+  static constexpr unsigned MaxPosition = (1l << POSITION_BITWIDTH) - 1;
+

I don't find standard way to generate the maximum value for bit fields.. So I 
choose to calculate it by hand. 



Comment at: clang/include/clang/AST/DeclTemplate.h:1163-1164
+  TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {
+// The input may fill maximum values to show that it is invalid.
+// Add one here to convert it to zero.
+assert((D + 1) <= MaxDepth &&

I find it is possible if ast-dump is going to dump from JSON files.


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

https://reviews.llvm.org/D123298

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


[PATCH] D123298: [NFC] [AST] Reduce the size of TemplateParmPosition

2022-04-07 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu updated this revision to Diff 421419.
ChuanqiXu added a comment.

Address comments:

- Add assertions to show the input wouldn't hit the boundaries.


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

https://reviews.llvm.org/D123298

Files:
  clang/include/clang/AST/DeclTemplate.h


Index: clang/include/clang/AST/DeclTemplate.h
===
--- clang/include/clang/AST/DeclTemplate.h
+++ clang/include/clang/AST/DeclTemplate.h
@@ -1148,23 +1148,44 @@
 /// parameters and is not part of the Decl hierarchy. Just a facility.
 class TemplateParmPosition {
 protected:
-  // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
-  // position? Maybe?
-  unsigned Depth;
-  unsigned Position;
+#define DEPTH_BITWIDTH 20
+#define POSITION_BITWIDTH 12
+  unsigned Depth : DEPTH_BITWIDTH;
+  unsigned Position : POSITION_BITWIDTH;
 
-  TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
+  static constexpr unsigned MaxDepth = (1l << DEPTH_BITWIDTH) - 1;
+  static constexpr unsigned MaxPosition = (1l << POSITION_BITWIDTH) - 1;
+
+#undef DEPTH_BITWIDTH
+#undef POSITION_BITWIDTH
+
+  TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {
+// The input may fill maximum values to show that it is invalid.
+// Add one here to convert it to zero.
+assert((D + 1) <= MaxDepth &&
+   "The depth of template parmeter position is more than 2^20!");
+assert((P + 1) <= MaxPosition &&
+   "The position of template parmeter position is more than 2^12!");
+  }
 
 public:
   TemplateParmPosition() = delete;
 
   /// Get the nesting depth of the template parameter.
   unsigned getDepth() const { return Depth; }
-  void setDepth(unsigned D) { Depth = D; }
+  void setDepth(unsigned D) {
+assert((D + 1) <= MaxDepth &&
+   "The depth of template parmeter position is more than 2^20!");
+Depth = D;
+  }
 
   /// Get the position of the template parameter within its parameter list.
   unsigned getPosition() const { return Position; }
-  void setPosition(unsigned P) { Position = P; }
+  void setPosition(unsigned P) {
+assert((P + 1) <= MaxPosition &&
+   "The position of template parmeter position is more than 2^12!");
+Position = P;
+  }
 
   /// Get the index of the template parameter within its parameter list.
   unsigned getIndex() const { return Position; }


Index: clang/include/clang/AST/DeclTemplate.h
===
--- clang/include/clang/AST/DeclTemplate.h
+++ clang/include/clang/AST/DeclTemplate.h
@@ -1148,23 +1148,44 @@
 /// parameters and is not part of the Decl hierarchy. Just a facility.
 class TemplateParmPosition {
 protected:
-  // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
-  // position? Maybe?
-  unsigned Depth;
-  unsigned Position;
+#define DEPTH_BITWIDTH 20
+#define POSITION_BITWIDTH 12
+  unsigned Depth : DEPTH_BITWIDTH;
+  unsigned Position : POSITION_BITWIDTH;
 
-  TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
+  static constexpr unsigned MaxDepth = (1l << DEPTH_BITWIDTH) - 1;
+  static constexpr unsigned MaxPosition = (1l << POSITION_BITWIDTH) - 1;
+
+#undef DEPTH_BITWIDTH
+#undef POSITION_BITWIDTH
+
+  TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {
+// The input may fill maximum values to show that it is invalid.
+// Add one here to convert it to zero.
+assert((D + 1) <= MaxDepth &&
+   "The depth of template parmeter position is more than 2^20!");
+assert((P + 1) <= MaxPosition &&
+   "The position of template parmeter position is more than 2^12!");
+  }
 
 public:
   TemplateParmPosition() = delete;
 
   /// Get the nesting depth of the template parameter.
   unsigned getDepth() const { return Depth; }
-  void setDepth(unsigned D) { Depth = D; }
+  void setDepth(unsigned D) {
+assert((D + 1) <= MaxDepth &&
+   "The depth of template parmeter position is more than 2^20!");
+Depth = D;
+  }
 
   /// Get the position of the template parameter within its parameter list.
   unsigned getPosition() const { return Position; }
-  void setPosition(unsigned P) { Position = P; }
+  void setPosition(unsigned P) {
+assert((P + 1) <= MaxPosition &&
+   "The position of template parmeter position is more than 2^12!");
+Position = P;
+  }
 
   /// Get the index of the template parameter within its parameter list.
   unsigned getIndex() const { return Position; }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122981: [Clang] CWG 1394: Incomplete types as parameters of deleted functions

2022-04-07 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/include/clang/Sema/Sema.h:2899-2909
+/// C++ [dcl.fct.def.general]p1
+/// function-body:
+///   = delete ;
+///   = default ;
+Delete,
+Default,
+

rZhBoYao wrote:
> ChuanqiXu wrote:
> > Agree to @erichkeane 
> With all due respect, this code suggestion doesn't make any sense to me. My 
> best guess is @ChuanqiXu was thinking the order specified by the grammar as 
> noted in [[ https://eel.is/c++draft/dcl.fct.def.general#nt:function-body | 
> dcl.fct.def.general p1 ]]. Even if that was the case, `CompoundStmt` is not 
> quite right either. Also, differentiating `ctor-initializer[opt] 
> compound-statement` and `function-try-block` is meaningless here, hence the 
> name `Other`.
> 
> I adopted the same order as to how `Parser::ParseFunctionDefinition` has 
> always been parsing `function-body`. The order is not significant in any 
> meaningful way as each of the 4 grammar productions of `function-body` is 
> VERY different and mutually exclusive. Putting `Delete` and `Default` upfront 
> not only emphasizes the "specialness" of them but also conveys how we handle 
> `function-body`.
> 
> What say you, @erichkeane ?
Yeah, the order comes from the standard. I think the comment should be 
consistent with the spec. And for the name, I agree `CompoundStmt` is not 
accurate indeed... I thought Default should be a good name but there is 
`Default` already. But I don't feel `Other` is good since the 
compound-statement is much more common.

> Putting Delete and Default upfront not only emphasizes the "specialness" of 
> them but also conveys how we handle function-body.

This don't makes sense. Generally, we would put common items in front. And the 
order here shouldn't be related to the implementation.


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

https://reviews.llvm.org/D122981

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


[PATCH] D122981: [Clang] CWG 1394: Incomplete types as parameters of deleted functions

2022-04-07 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao marked an inline comment as done.
rZhBoYao added inline comments.



Comment at: clang/include/clang/Sema/Sema.h:2899-2909
+/// C++ [dcl.fct.def.general]p1
+/// function-body:
+///   = delete ;
+///   = default ;
+Delete,
+Default,
+

ChuanqiXu wrote:
> Agree to @erichkeane 
With all due respect, this code suggestion doesn't make any sense to me. My 
best guess is @ChuanqiXu was thinking the order specified by the grammar as 
noted in [[ https://eel.is/c++draft/dcl.fct.def.general#nt:function-body | 
dcl.fct.def.general p1 ]]. Even if that was the case, `CompoundStmt` is not 
quite right either. Also, differentiating `ctor-initializer[opt] 
compound-statement` and `function-try-block` is meaningless here, hence the 
name `Other`.

I adopted the same order as to how `Parser::ParseFunctionDefinition` has always 
been parsing `function-body`. The order is not significant in any meaningful 
way as each of the 4 grammar productions of `function-body` is VERY different 
and mutually exclusive. Putting `Delete` and `Default` upfront not only 
emphasizes the "specialness" of them but also conveys how we handle 
`function-body`.

What say you, @erichkeane ?


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

https://reviews.llvm.org/D122981

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


[PATCH] D118948: [MTE] Add -fsanitize=memtag* and friends.

2022-04-07 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/include/clang/Basic/DiagnosticDriverKinds.td:475
 def err_stack_tagging_requires_hardware_feature : Error<
-  "'-fsanitize=memtag' requires hardware support (+memtag)">;
+  "'-fsanitize=memtag-stack' requires hardware support (+memtag). For Armv8, "
+  "try compiling with -march=armv8a+memtag.">;

hctim wrote:
> eugenis wrote:
> > Split out renaming of memtag to memtag-stack first? This will remove a lot 
> > of diff from this patch.
> splitting into elf -> lld -> clang as per Ray's suggestion, should reduce the 
> diff enough.
The convention is to omit period for the last sentence.



Comment at: clang/include/clang/Driver/Options.td:1619
+Group,
+HelpText<"Set default MTE mode to 
'async' (default) or 'sync'.">;
 def fsanitize_hwaddress_experimental_aliasing

eugenis wrote:
> Let's make "sync" the default mode.
Omit period for the last sentence



Comment at: clang/lib/Driver/ToolChains/CommonArgs.cpp:1013
+  TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
+  << ("-fsanitize=memtag*") << TC.getTriple().str();
+}





Comment at: clang/test/Lexer/has_feature_memtag.cpp:5
+// RUN: | FileCheck --check-prefixes=CHECK-MEMTAG-STACK,CHECK-MEMTAG-HEAP 
%s
+// RUN: %clang_cc1 -E  %s -o - | FileCheck --check-prefix=CHECK-NO-MEMTAG %s
+




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118948

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


[PATCH] D121556: [randstruct] Add randomize structure layout support

2022-04-07 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 421416.
void added a comment.

Fix bad formatting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121556

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/Randstruct.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Decl.cpp
  clang/lib/AST/Randstruct.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/RandstructTest.cpp

Index: clang/unittests/AST/RandstructTest.cpp
===
--- /dev/null
+++ clang/unittests/AST/RandstructTest.cpp
@@ -0,0 +1,458 @@
+//===- unittest/AST/RandstructTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file contains tests for Clang's structure field layout randomization.
+//
+//===--===//
+
+/*
+ * Build this test suite by running `make ASTTests` in the build folder.
+ *
+ * Run this test suite by running the following in the build folder:
+ * ` ./tools/clang/unittests/AST/ASTTests
+ * --gtest_filter=StructureLayoutRandomization*`
+ */
+
+#include "clang/AST/Randstruct.h"
+#include "gtest/gtest.h"
+
+#include "DeclMatcher.h"
+#include "clang/AST/RecordLayout.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Testing/CommandLineArgs.h"
+#include "clang/Tooling/Tooling.h"
+
+#include 
+
+using namespace clang;
+using namespace clang::ast_matchers;
+using namespace clang::randstruct;
+
+using field_names = std::vector;
+
+namespace {
+
+std::unique_ptr makeAST(const std::string ,
+ bool ExpectErr = false) {
+  std::vector Args = getCommandLineArgsForTesting(Lang_C99);
+  Args.push_back("-frandomize-layout-seed=1234567890abcdef");
+
+  IgnoringDiagConsumer IgnoringConsumer = IgnoringDiagConsumer();
+
+  std::unique_ptr AST = tooling::buildASTFromCodeWithArgs(
+  SourceCode, Args, "input.c", "clang-tool",
+  std::make_shared(),
+  tooling::getClangStripDependencyFileAdjuster(),
+  tooling::FileContentMappings(), );
+
+  if (ExpectErr)
+EXPECT_TRUE(AST->getDiagnostics().hasErrorOccurred());
+  else
+EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  return AST;
+}
+
+RecordDecl *getRecordDeclFromAST(const ASTContext , const std::string ) {
+  RecordDecl *RD = FirstDeclMatcher().match(
+  C.getTranslationUnitDecl(), recordDecl(hasName(Name)));
+  return RD;
+}
+
+std::vector getFieldNamesFromRecord(const RecordDecl *RD) {
+  std::vector Fields;
+
+  Fields.reserve(8);
+  for (auto *Field : RD->fields())
+Fields.push_back(Field->getNameAsString());
+
+  return Fields;
+}
+
+bool isSubsequence(const field_names , const field_names ) {
+  unsigned SeqLen = Seq.size();
+  unsigned SubLen = Subseq.size();
+
+  bool IsSubseq = false;
+  for (unsigned I = 0; I < SeqLen; ++I)
+if (Seq[I] == Subseq[0]) {
+  IsSubseq = true;
+  for (unsigned J = 0; J + I < SeqLen && J < SubLen; ++J) {
+if (Seq[J + I] != Subseq[J]) {
+  IsSubseq = false;
+  break;
+}
+  }
+}
+
+  return IsSubseq;
+}
+
+} // end anonymous namespace
+
+namespace clang {
+namespace ast_matchers {
+
+#define RANDSTRUCT_TEST_SUITE_TEST StructureLayoutRandomizationTestSuiteTest
+
+TEST(RANDSTRUCT_TEST_SUITE_TEST, CanDetermineIfSubsequenceExists) {
+  const field_names Seq = {"a", "b", "c", "d"};
+
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a", "b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a"}));
+  ASSERT_FALSE(isSubsequence(Seq, {"a", "d"}));
+}
+
+#define RANDSTRUCT_TEST StructureLayoutRandomization
+
+TEST(RANDSTRUCT_TEST, UnmarkedStruct) {
+  const std::unique_ptr AST = makeAST(R"c(
+struct test {
+int bacon;
+long lettuce;
+long long tomato;
+float mayonnaise;
+};
+  )c");
+
+  const RecordDecl *RD = getRecordDeclFromAST(AST->getASTContext(), "test");
+  const field_names Expected = 

[clang] 74b56e0 - [NFC] Remove unused variable in CodeGenModules

2022-04-07 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-04-08T11:52:31+08:00
New Revision: 74b56e02bda09ae735c6aeca583a2078375f2da1

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

LOG: [NFC] Remove unused variable in CodeGenModules

This eliminates an unused-variable warning

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index ec34d91e65372..c9e5354d3269a 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -5183,11 +5183,9 @@ void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
   SetCommonAttributes(GD, GA);
 
   // Emit global alias debug information.
-  if (const auto *VD = dyn_cast(D)) {
-if (CGDebugInfo *DI = getModuleDebugInfo()) {
+  if (isa(D))
+if (CGDebugInfo *DI = getModuleDebugInfo())
   DI->EmitGlobalAlias(cast(GA->getAliasee()), GD);
-}
-  }
 }
 
 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {



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


[PATCH] D122734: [HIP] Fix mangling number for local struct

2022-04-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D122734#3437344 , @tra wrote:

> In D122734#3435086 , @yaxunl wrote:
>
>> This patch takes a similar approach as https://reviews.llvm.org/D69322 has 
>> done for lambda. When doing host compilation for CUDA/HIP on Windows with 
>> MSVC toolchain, mangling number of lambda always uses Itanium mangling 
>> number. In this case, mangling number of local struct types always uses 
>> Itanium mangling number. I assume this should be fine as long as it is 
>> consistent for all HIP programs.
>
> I'm fairly sure that the code does what you need it to do for HIP. What I'm 
> not sure is whether it will impact other users.
>
> I've missed that `getManglingNumber` is part of `MSHIPNumberingContext`, so 
> it is HIP-specific and should not change mangling for non-HIP users.
>
> Would it make it possible to end up with different mangling for the shared 
> code compiled as regular C++ code and host-side code in HIP sources? E.g. 
> from a common header included in both.

It may cause a template instantiation of host functions to have different 
mangled names when compiled as HIP program, versus compiled as C++ program.

To avoid that, I need to restrict using of Itanium mangling number for mangling 
device side names only, then the mangling of host functions will not be 
affected in HIP programs.


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

https://reviews.llvm.org/D122734

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


[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-07 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/include/clang/Sema/ScopeInfo.h:843
+  /// and the capture should not be visible before.
+  llvm::DenseMap DelayedCaptures;
+

I hope the comment explains the meaning of unsigned here. If it means index, I 
think `SmallVector` would make code simpler.



Comment at: clang/include/clang/Sema/ScopeInfo.h:842
+
+  bool BeforeLambdaQualifiersScope = false;
+

cor3ntin wrote:
> ChuanqiXu wrote:
> > I think the name `Before*` is a little bit confusing. From the context, it 
> > would be set to true in `ActOnLambdaIntroducer`and be set to false in 
> > `ActOnLambdaClosureQualifiers`. So it looks like something 
> > `IsInRangeOf...`. The name before implies that it should be true by default 
> > and be false after some point...
> > 
> > I am not sure if my point is clear...
> I struggle to find a better name, but I added a comment. Does that help? 
I'm not good at naming too... I am wondering a name with words like `range` 
could be fine.



Comment at: clang/lib/Sema/Scope.cpp:72
+  // Lambdas have an extra prototype scope that doesn't add any depth
+  if (flags & FunctionPrototypeScope && !(flags & LambdaScope))
+PrototypeDepth++;

cor3ntin wrote:
> ChuanqiXu wrote:
> > ChuanqiXu wrote:
> > > This looks like:
> > This isn't addressed. I mean the flags would always be true if the last 
> > clause get evaluated.
> I'm not sure I understand your point. We are checking that it's a function 
> scope that is not a lambda scope.
> They are probably other ways to write that but they aren't clearer
I mean the suggested change is equal to the original one and it is shorter. I 
don't think it would lost any information since they are all in the same line.



Comment at: clang/lib/Sema/SemaExpr.cpp:18411
+Loc = C.second.Loc;
+Explicitly = 1;
+break;





Comment at: clang/lib/Sema/SemaLambda.cpp:892
 
-void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer ,
-Declarator ,
-Scope *CurScope) {
+static LambdaScopeInfo *getCurrentLambdaScopeUnsafe(Sema ) {
+  assert(!S.FunctionScopes.empty());

I guess it is needed to explain the meaning of `Unsafe`



Comment at: clang/lib/Sema/SemaLambda.cpp:894-897
+  auto *CurLSI =
+  dyn_cast(S.FunctionScopes[S.FunctionScopes.size() - 1]);
+  assert(CurLSI);
+  return CurLSI;





Comment at: clang/lib/Sema/SemaLambda.cpp:1076-1078
   Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
C->EllipsisLoc, C->Id, InitStyle,
+   C->Init.get(), Method);

I suggest to add a assertion for `Var` to check it is not null



Comment at: clang/lib/Sema/SemaLambda.cpp:1127-1133
+  auto FindVar = [LSI](VarDecl *V) {
+auto it = std::find_if(
+LSI->DelayedCaptures.begin(), LSI->DelayedCaptures.end(),
+[&](auto &) { return Pair.second.Var == V; });
+return it;
+  };
+  auto it = FindVar(Var);





Comment at: clang/lib/Sema/SemaLambda.cpp:1182-1184
+if (Var)
+  LSI->DelayedCaptures[I] = LambdaScopeInfo::DelayedCapture{
+  Var, C->ExplicitRange.getBegin(), C->Kind};

If `DelayedCaptures` is SmallVector, we could write:

---

I observed there a lot `continue` in the loop. So we could hoist the definition 
of `Var` to the start of the loop. And we could fill `DelayedCaptures` by RAII.



Comment at: clang/lib/Sema/SemaLambda.cpp:1193
+ LambdaIntroducer ) {
+  unsigned I = 0;
+  SourceLocation PrevCaptureLoc;

Do you think it is better to replace `I` with 
`std:distance(Intro.Captures.begin(), C)`? I prefer it since  we could reduce 
the scope of `I` in the style.



Comment at: clang/lib/Sema/SemaLambda.cpp:1194
+  unsigned I = 0;
+  SourceLocation PrevCaptureLoc;
+  for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;

It looks like we could define `PrevCaptureLoc` in the loop.



Comment at: clang/lib/Sema/SemaLambda.cpp:1214
+
+  // C++2a [expr.prim.lambda]p8:
+  //  If a lambda-capture includes a capture-default that is =,

We prefer C++20 than C++2a now.



Comment at: clang/lib/Sema/SemaLambda.cpp:1311-1312
+
+  if (ParamInfo.getTrailingRequiresClause())
+Method->setTrailingRequiresClause(ParamInfo.getTrailingRequiresClause());
+




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136


[PATCH] D123353: [CUDA][HIP] Externalize kernels in anonymous name space

2022-04-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added a reviewer: tra.
Herald added a project: All.
yaxunl requested review of this revision.

kernels in anonymous name space needs to have unique name
to avoid duplicate symbols.

Fixes: https://github.com/llvm/llvm-project/issues/54560


https://reviews.llvm.org/D123353

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CGCUDANV.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/test/CodeGenCUDA/kernel-in-anon-ns.cu

Index: clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -fcuda-is-device -cuid=abc \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu -std=c++11 -fgpu-rdc \
+// RUN:   -emit-llvm -o - -x hip %s > %t.dev
+
+// RUN: %clang_cc1 -triple x86_64-gnu-linux -cuid=abc \
+// RUN:   -aux-triple amdgcn-amd-amdhsa -std=c++11 -fgpu-rdc \
+// RUN:   -emit-llvm -o - -x hip %s > %t.host
+
+// RUN: cat %t.dev %t.host | FileCheck %s
+
+#include "Inputs/cuda.h"
+
+// CHECK: define weak_odr {{.*}}void @[[KERN:_ZN12_GLOBAL__N_16kernelEv\.anon\..*]](
+// CHECK: @[[STR:.*]] = {{.*}} c"[[KERN]]\00"
+// CHECK: call i32 @__hipRegisterFunction({{.*}}@[[STR]] 
+
+namespace {
+__global__ void kernel() {
+}
+}
+
+void test() {
+  kernel<<<1, 1>>>();
+}
Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -1457,9 +1457,10 @@
TBAAAccessInfo *TBAAInfo = nullptr);
   bool stopAutoInit();
 
-  /// Print the postfix for externalized static variable for single source
-  /// offloading languages CUDA and HIP.
-  void printPostfixForExternalizedStaticVar(llvm::raw_ostream ) const;
+  /// Print the postfix for externalized static variable or kernels for single
+  /// source offloading languages CUDA and HIP.
+  void printPostfixForExternalizedDecl(llvm::raw_ostream ,
+   const Decl *D) const;
 
   /// Helper functions for generating a NoLoop kernel
   /// For a captured statement, get the single For statement, if it exists,
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -1382,10 +1382,10 @@
 }
 
   // Make unique name for device side static file-scope variable for HIP.
-  if (CGM.getContext().shouldExternalizeStaticVar(ND) &&
+  if (CGM.getContext().shouldExternalize(ND) &&
   CGM.getLangOpts().GPURelocatableDeviceCode &&
   CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty())
-CGM.printPostfixForExternalizedStaticVar(Out);
+CGM.printPostfixForExternalizedDecl(Out, ND);
   return std::string(Out.str());
 }
 
@@ -1452,8 +1452,7 @@
   // static device variable depends on whether the variable is referenced by
   // a host or device host function. Therefore the mangled name cannot be
   // cached.
-  if (!LangOpts.CUDAIsDevice ||
-  !getContext().mayExternalizeStaticVar(GD.getDecl())) {
+  if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) {
 auto FoundName = MangledDeclNames.find(CanonicalGD);
 if (FoundName != MangledDeclNames.end())
   return FoundName->second;
@@ -1473,7 +1472,7 @@
   // directly between host- and device-compilations, the host- and
   // device-mangling in host compilation could help catching certain ones.
   assert(!isa(ND) || !ND->hasAttr() ||
- getLangOpts().CUDAIsDevice ||
+ getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice ||
  (getContext().getAuxTargetInfo() &&
   (getContext().getAuxTargetInfo()->getCXXABI() !=
getContext().getTargetInfo().getCXXABI())) ||
@@ -6798,9 +6797,10 @@
   return false;
 }
 
-void CodeGenModule::printPostfixForExternalizedStaticVar(
-llvm::raw_ostream ) const {
-  OS << "__static__" << getContext().getCUIDHash();
+void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream ,
+const Decl *D) const {
+  OS << (isa(D) ? "__static__" : ".anon.")
+ << getContext().getCUIDHash();
 }
 
 namespace {
Index: clang/lib/CodeGen/CGCUDANV.cpp
===
--- clang/lib/CodeGen/CGCUDANV.cpp
+++ clang/lib/CodeGen/CGCUDANV.cpp
@@ -281,13 +281,13 @@
 DeviceSideName = std::string(ND->getIdentifier()->getName());
 
   // Make unique name for device side static file-scope variable for HIP.
-  if (CGM.getContext().shouldExternalizeStaticVar(ND) &&
+  if (CGM.getContext().shouldExternalize(ND) &&
   CGM.getLangOpts().GPURelocatableDeviceCode &&
   !CGM.getLangOpts().CUID.empty()) {
  

[PATCH] D122981: [Clang] CWG 1394: Incomplete types as parameters of deleted functions

2022-04-07 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

I agree this one is better.




Comment at: clang/include/clang/Sema/Sema.h:2899-2909
+/// C++ [dcl.fct.def.general]p1
+/// function-body:
+///   = delete ;
+///   = default ;
+Delete,
+Default,
+

Agree to @erichkeane 


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

https://reviews.llvm.org/D122981

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


[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-04-07 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu accepted this revision.
ChuanqiXu added a comment.
This revision is now accepted and ready to land.

LGTM basically. Please wait for 1~2 weeks to land this in case there are other 
comments.




Comment at: clang/lib/Sema/SemaConcept.cpp:496-497
+
+  // Attn Reviewers: we need to do this for the function constraints for
+  // comparison of constraints to work, but do we also need to do it for
+  // CheckInstantiatedFunctionConstraints?  That one is more difficult, but we

We need to edit the `Attn Reviewers` to `TODO` before landing. The content need 
to be rewording too. Your English is much better than me. So no concrete 
suggestion here : )



Comment at: clang/lib/Sema/SemaTemplate.cpp:4705
   CheckConstraintSatisfaction(
-  NamedConcept, {NamedConcept->getConstraintExpr()}, Converted,
+  NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
   SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),

erichkeane wrote:
> ChuanqiXu wrote:
> > I would feel better if we could write:
> > ```
> > CheckConstraintSatisfaction(
> >   NamedConcept, {NamedConcept->getConstraintExpr()}, {MLTAL},
> >   SourceRange(SS.isSet() ? SS.getBeginLoc() : 
> > ConceptNameInfo.getLoc(),
> >   TemplateArgs->getRAngleLoc()),
> >   Satisfaction)
> > ```
> > 
> > But it looks unimplementable.
> I'm not sure I get the suggestion?  Why would you want to put the 
> `MultiLevelTemplateArgumentList` in curleys?  
I just feel like the style is more cleaner. But I found the constructor might 
not allow us to do so... So this one might not be a suggestion.


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

https://reviews.llvm.org/D119544

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


[PATCH] D123352: [analyzer] Add FixItHint to `nullability.NullReturnedFromNonnull` and `nullability.NullableReturnedFromNonnull`

2022-04-07 Thread Moshe via Phabricator via cfe-commits
MosheBerman created this revision.
Herald added subscribers: manas, steakhal, ASDenysPetrov, martong, dkrupp, 
donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, baloghadamsoftware, 
xazax.hun.
Herald added a project: All.
MosheBerman requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This diff adds:

- A `CmdLineOption` called `ShowFixIts` to the all of nullability checks.  (We 
add to all of them because of the way `NullabilityChecker.cpp` registers all of 
the checkers.)
- For each of the two `*ReturnedFromNonnull` methods, attaches a `FixItHint` to 
the output.

Use Case:
This enables us to automate the process of annotating headers with 
`NS_ASSUME_NONNULL_BEGIN/END` because the checker can fix callsites where we 
would otherwise break the nullability contract.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123352

Files:
  clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
  clang/test/Analysis/nullability-fixits.mm

Index: clang/test/Analysis/nullability-fixits.mm
===
--- /dev/null
+++ clang/test/Analysis/nullability-fixits.mm
@@ -0,0 +1,56 @@
+// RUN: %clang_analyze_cc1 %s -analyzer-checker=core,nullability.NullReturnedFromNonnull,nullability.NullableReturnedFromNonnull \
+// RUN:   -analyzer-config nullability.NullReturnedFromNonnull:ShowFixIts=true \
+// RUN:   -analyzer-config nullability.NullableReturnedFromNonnull:ShowFixIts=true \
+// RUN:   -analyzer-config apply-fixits=true \
+// RUN:   -analyzer-output=plist \
+// RUN:   -fobjc-arc \
+// RUN:   -o - | FileCheck %s
+
+#define nil 0
+
+@protocol NSObject
++ (id)alloc;
+- (id)init;
+- (instancetype)autorelease;
+- (void)release;
+@end
+
+__attribute__((objc_root_class))
+@interface
+NSObject
+@end
+
+
+@interface TestObject : NSObject
+@end
+
+// CHECK: TestObject *_Nullable
+TestObject *_Nonnull returnsNilObjCInstanceIndirectly() {
+  TestObject *local = nil;
+  return local; // expected-warning {{nil returned from a function that is expected to return a non-null value}}
+}
+
+TestObject *_Nonnull returnsNilObjCInstanceDirectly() {
+  return nil; // expected-warning {{nil returned from a function that is expected to return a non-null value}}
+}
+
+@interface ClassWithInitializers : NSObject
+@end
+
+@implementation ClassWithInitializers
+
+// FIXME: We want this check for when we add support for syntactic sugar, and
+// put the annotation before the type name. `nullable` vs `_Nonnull`.
+// CHECK: - (TestObject *_Nonnull) returnsNilUnsuppressed {
+- (TestObject *_Nonnull)returnsNilUnsuppressed {
+  return nil; // expected-warning {{nil returned from a method that is expected to return a non-null value}}
+}
+
+- (TestObject *_Nullable)returnsNil {
+  return (TestObject *_Nonnull)nil;
+}
+- (TestObject *_Nonnull)inlineOfReturnsNilObjCInstanceDirectlyWithSuppressingCast {
+  TestObject *o = [self returnsNil];
+  return o;
+}
+@end
Index: clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/NullabilityChecker.cpp
@@ -92,6 +92,11 @@
   // libraries.
   DefaultBool NoDiagnoseCallsToSystemHeaders;
 
+  // If true, the checker will generate Fix-it-hints for *ReturnedToNonnull
+  // warnings. Should we consider changing the invariant behavior for `nil`
+  // and/or NS collection classes if this is enabled?
+  DefaultBool ShowFixIts;
+
   void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext ) const;
   void checkPostStmt(const ExplicitCastExpr *CE, CheckerContext ) const;
   void checkPreStmt(const ReturnStmt *S, CheckerContext ) const;
@@ -152,6 +157,14 @@
 const MemRegion *Region;
   };
 
+  // `getReturnTypeSourceRange` does not include qualifiers. As a result, the
+  // nullability annotation will precede the asterisk, instead of following it.
+  // This helper function accounts for that.
+  SourceLocation getInsertionLocForTypeInfo(TypeSourceInfo *typeSourceInfo,
+const size_t offset = 0) const {
+return typeSourceInfo->getTypeLoc().getBeginLoc().getLocWithOffset(offset);
+  }
+
   /// When any of the nonnull arguments of the analyzed function is null, do not
   /// report anything and turn off the check.
   ///
@@ -160,12 +173,13 @@
   void reportBugIfInvariantHolds(StringRef Msg, ErrorKind Error, CheckKind CK,
  ExplodedNode *N, const MemRegion *Region,
  CheckerContext ,
- const Stmt *ValueExpr = nullptr,
- bool SuppressPath = false) const;
+  const Stmt 

[PATCH] D122377: [PowerPC] Support 16-byte lock free atomics on pwr8 and up

2022-04-07 Thread Kai Luo via Phabricator via cfe-commits
lkail updated this revision to Diff 421385.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122377

Files:
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Basic/Targets/PPC.h
  clang/test/CodeGen/PowerPC/atomic-alignment.c
  clang/test/CodeGen/PowerPC/quadword-atomics.c
  clang/test/Sema/atomic-ops.c
  llvm/lib/Target/PowerPC/PPCISelLowering.cpp
  llvm/lib/Target/PowerPC/PPCISelLowering.h
  llvm/test/CodeGen/PowerPC/atomics-i128.ll

Index: llvm/test/CodeGen/PowerPC/atomics-i128.ll
===
--- llvm/test/CodeGen/PowerPC/atomics-i128.ll
+++ llvm/test/CodeGen/PowerPC/atomics-i128.ll
@@ -5,6 +5,22 @@
 ; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-unknown -mcpu=pwr7 \
 ; RUN:   -ppc-asm-full-reg-names -ppc-quadword-atomics \
 ; RUN:   -ppc-track-subreg-liveness < %s | FileCheck --check-prefix=PWR7 %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu -mcpu=pwr8 \
+; RUN:   -ppc-asm-full-reg-names -ppc-track-subreg-liveness < %s | FileCheck \
+; RUN:   --check-prefix=LE-PWR8 %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-freebsd -mcpu=pwr8 \
+; RUN:   -ppc-asm-full-reg-names -ppc-track-subreg-liveness < %s | FileCheck \
+; RUN:   --check-prefix=LE-PWR8 %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-aix -mcpu=pwr8 \
+; RUN:   -ppc-asm-full-reg-names -ppc-track-subreg-liveness < %s | FileCheck \
+; RUN:   --check-prefix=AIX64-PWR8 %s
+
+; On 32-bit PPC platform, 16-byte lock free atomic instructions are not available,
+; it's expected not to generate inlined lock-free code on such platforms, even arch level
+; is pwr8+ and `-ppc-quadword-atomics` is on.
+; RUN: llc -verify-machineinstrs -mtriple=powerpc-unknown-unknown -mcpu=pwr8 \
+; RUN:   -ppc-quadword-atomics -ppc-asm-full-reg-names -ppc-track-subreg-liveness < %s \
+; RUN: | FileCheck --check-prefix=PPC-PWR8 %s
 
 
 define i128 @swap(i128* %a, i128 %x) {
@@ -39,6 +55,62 @@
 ; PWR7-NEXT:ld r0, 16(r1)
 ; PWR7-NEXT:mtlr r0
 ; PWR7-NEXT:blr
+;
+; LE-PWR8-LABEL: swap:
+; LE-PWR8:   # %bb.0: # %entry
+; LE-PWR8-NEXT:sync
+; LE-PWR8-NEXT:  .LBB0_1: # %entry
+; LE-PWR8-NEXT:#
+; LE-PWR8-NEXT:lqarx r6, 0, r3
+; LE-PWR8-NEXT:mr r9, r4
+; LE-PWR8-NEXT:mr r8, r5
+; LE-PWR8-NEXT:stqcx. r8, 0, r3
+; LE-PWR8-NEXT:bne cr0, .LBB0_1
+; LE-PWR8-NEXT:  # %bb.2: # %entry
+; LE-PWR8-NEXT:lwsync
+; LE-PWR8-NEXT:mr r3, r7
+; LE-PWR8-NEXT:mr r4, r6
+; LE-PWR8-NEXT:blr
+;
+; AIX64-PWR8-LABEL: swap:
+; AIX64-PWR8:   # %bb.0: # %entry
+; AIX64-PWR8-NEXT:mflr r0
+; AIX64-PWR8-NEXT:std r0, 16(r1)
+; AIX64-PWR8-NEXT:stdu r1, -112(r1)
+; AIX64-PWR8-NEXT:sync
+; AIX64-PWR8-NEXT:bl .__sync_lock_test_and_set_16[PR]
+; AIX64-PWR8-NEXT:nop
+; AIX64-PWR8-NEXT:lwsync
+; AIX64-PWR8-NEXT:addi r1, r1, 112
+; AIX64-PWR8-NEXT:ld r0, 16(r1)
+; AIX64-PWR8-NEXT:mtlr r0
+; AIX64-PWR8-NEXT:blr
+;
+; PPC-PWR8-LABEL: swap:
+; PPC-PWR8:   # %bb.0: # %entry
+; PPC-PWR8-NEXT:mflr r0
+; PPC-PWR8-NEXT:stw r0, 4(r1)
+; PPC-PWR8-NEXT:stwu r1, -48(r1)
+; PPC-PWR8-NEXT:.cfi_def_cfa_offset 48
+; PPC-PWR8-NEXT:.cfi_offset lr, 4
+; PPC-PWR8-NEXT:mr r4, r3
+; PPC-PWR8-NEXT:stw r7, 40(r1)
+; PPC-PWR8-NEXT:stw r6, 36(r1)
+; PPC-PWR8-NEXT:addi r6, r1, 16
+; PPC-PWR8-NEXT:li r3, 16
+; PPC-PWR8-NEXT:li r7, 5
+; PPC-PWR8-NEXT:stw r5, 32(r1)
+; PPC-PWR8-NEXT:addi r5, r1, 32
+; PPC-PWR8-NEXT:stw r8, 44(r1)
+; PPC-PWR8-NEXT:bl __atomic_exchange
+; PPC-PWR8-NEXT:lwz r6, 28(r1)
+; PPC-PWR8-NEXT:lwz r5, 24(r1)
+; PPC-PWR8-NEXT:lwz r4, 20(r1)
+; PPC-PWR8-NEXT:lwz r3, 16(r1)
+; PPC-PWR8-NEXT:lwz r0, 52(r1)
+; PPC-PWR8-NEXT:addi r1, r1, 48
+; PPC-PWR8-NEXT:mtlr r0
+; PPC-PWR8-NEXT:blr
 entry:
   %0 = atomicrmw xchg i128* %a, i128 %x seq_cst, align 16
   ret i128 %0
@@ -76,6 +148,109 @@
 ; PWR7-NEXT:ld r0, 16(r1)
 ; PWR7-NEXT:mtlr r0
 ; PWR7-NEXT:blr
+;
+; LE-PWR8-LABEL: add:
+; LE-PWR8:   # %bb.0: # %entry
+; LE-PWR8-NEXT:sync
+; LE-PWR8-NEXT:  .LBB1_1: # %entry
+; LE-PWR8-NEXT:#
+; LE-PWR8-NEXT:lqarx r6, 0, r3
+; LE-PWR8-NEXT:addc r9, r4, r7
+; LE-PWR8-NEXT:adde r8, r5, r6
+; LE-PWR8-NEXT:stqcx. r8, 0, r3
+; LE-PWR8-NEXT:bne cr0, .LBB1_1
+; LE-PWR8-NEXT:  # %bb.2: # %entry
+; LE-PWR8-NEXT:lwsync
+; LE-PWR8-NEXT:mr r3, r7
+; LE-PWR8-NEXT:mr r4, r6
+; LE-PWR8-NEXT:blr
+;
+; AIX64-PWR8-LABEL: add:
+; AIX64-PWR8:   # %bb.0: # %entry
+; AIX64-PWR8-NEXT:mflr r0
+; AIX64-PWR8-NEXT:std r0, 16(r1)
+; AIX64-PWR8-NEXT:stdu r1, -112(r1)
+; AIX64-PWR8-NEXT:sync
+; AIX64-PWR8-NEXT:bl .__sync_fetch_and_add_16[PR]
+; AIX64-PWR8-NEXT:nop
+; AIX64-PWR8-NEXT:lwsync
+; AIX64-PWR8-NEXT:addi r1, r1, 112
+; AIX64-PWR8-NEXT:ld r0, 16(r1)
+; 

[PATCH] D122377: [PowerPC] Support 16-byte lock free atomics on pwr8 and up

2022-04-07 Thread Kai Luo via Phabricator via cfe-commits
lkail updated this revision to Diff 421384.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122377

Files:
  clang/lib/Basic/Targets/PPC.cpp
  clang/lib/Basic/Targets/PPC.h
  clang/test/CodeGen/PowerPC/atomic-alignment.c
  clang/test/CodeGen/PowerPC/quadword-atomics.c
  clang/test/Sema/atomic-ops.c
  llvm/lib/Target/PowerPC/PPCISelLowering.cpp
  llvm/lib/Target/PowerPC/PPCISelLowering.h
  llvm/test/CodeGen/PowerPC/atomics-i128.ll

Index: llvm/test/CodeGen/PowerPC/atomics-i128.ll
===
--- llvm/test/CodeGen/PowerPC/atomics-i128.ll
+++ llvm/test/CodeGen/PowerPC/atomics-i128.ll
@@ -5,6 +5,22 @@
 ; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-unknown -mcpu=pwr7 \
 ; RUN:   -ppc-asm-full-reg-names -ppc-quadword-atomics \
 ; RUN:   -ppc-track-subreg-liveness < %s | FileCheck --check-prefix=PWR7 %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-linux-gnu -mcpu=pwr8 \
+; RUN:   -ppc-asm-full-reg-names -ppc-track-subreg-liveness < %s | FileCheck \
+; RUN:   --check-prefix=LE-PWR8 %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64le-unknown-freebsd -mcpu=pwr8 \
+; RUN:   -ppc-asm-full-reg-names -ppc-track-subreg-liveness < %s | FileCheck \
+; RUN:   --check-prefix=LE-PWR8 %s
+; RUN: llc -verify-machineinstrs -mtriple=powerpc64-unknown-aix -mcpu=pwr8 \
+; RUN:   -ppc-asm-full-reg-names -ppc-track-subreg-liveness < %s | FileCheck \
+; RUN:   --check-prefix=AIX64-PWR8 %s
+
+; On 32-bit PPC platform, 16-byte lock free atomic instructions are not available,
+; it's expected not to generate inlined lock-free code on such platforms, even arch level
+; is pwr8+ and `-ppc-quadword-atomics` is on.
+; RUN: llc -verify-machineinstrs -mtriple=powerpc-unknown-unknown -mcpu=pwr8 \
+; RUN:   -ppc-quadword-atomics -ppc-asm-full-reg-names -ppc-track-subreg-liveness < %s \
+; RUN: | FileCheck --check-prefix=PPC-PWR8 %s
 
 
 define i128 @swap(i128* %a, i128 %x) {
@@ -39,6 +55,62 @@
 ; PWR7-NEXT:ld r0, 16(r1)
 ; PWR7-NEXT:mtlr r0
 ; PWR7-NEXT:blr
+;
+; LE-PWR8-LABEL: swap:
+; LE-PWR8:   # %bb.0: # %entry
+; LE-PWR8-NEXT:sync
+; LE-PWR8-NEXT:  .LBB0_1: # %entry
+; LE-PWR8-NEXT:#
+; LE-PWR8-NEXT:lqarx r6, 0, r3
+; LE-PWR8-NEXT:mr r9, r4
+; LE-PWR8-NEXT:mr r8, r5
+; LE-PWR8-NEXT:stqcx. r8, 0, r3
+; LE-PWR8-NEXT:bne cr0, .LBB0_1
+; LE-PWR8-NEXT:  # %bb.2: # %entry
+; LE-PWR8-NEXT:lwsync
+; LE-PWR8-NEXT:mr r3, r7
+; LE-PWR8-NEXT:mr r4, r6
+; LE-PWR8-NEXT:blr
+;
+; AIX64-PWR8-LABEL: swap:
+; AIX64-PWR8:   # %bb.0: # %entry
+; AIX64-PWR8-NEXT:mflr r0
+; AIX64-PWR8-NEXT:std r0, 16(r1)
+; AIX64-PWR8-NEXT:stdu r1, -112(r1)
+; AIX64-PWR8-NEXT:sync
+; AIX64-PWR8-NEXT:bl .__sync_lock_test_and_set_16[PR]
+; AIX64-PWR8-NEXT:nop
+; AIX64-PWR8-NEXT:lwsync
+; AIX64-PWR8-NEXT:addi r1, r1, 112
+; AIX64-PWR8-NEXT:ld r0, 16(r1)
+; AIX64-PWR8-NEXT:mtlr r0
+; AIX64-PWR8-NEXT:blr
+;
+; PPC-PWR8-LABEL: swap:
+; PPC-PWR8:   # %bb.0: # %entry
+; PPC-PWR8-NEXT:mflr r0
+; PPC-PWR8-NEXT:stw r0, 4(r1)
+; PPC-PWR8-NEXT:stwu r1, -48(r1)
+; PPC-PWR8-NEXT:.cfi_def_cfa_offset 48
+; PPC-PWR8-NEXT:.cfi_offset lr, 4
+; PPC-PWR8-NEXT:mr r4, r3
+; PPC-PWR8-NEXT:stw r7, 40(r1)
+; PPC-PWR8-NEXT:stw r6, 36(r1)
+; PPC-PWR8-NEXT:addi r6, r1, 16
+; PPC-PWR8-NEXT:li r3, 16
+; PPC-PWR8-NEXT:li r7, 5
+; PPC-PWR8-NEXT:stw r5, 32(r1)
+; PPC-PWR8-NEXT:addi r5, r1, 32
+; PPC-PWR8-NEXT:stw r8, 44(r1)
+; PPC-PWR8-NEXT:bl __atomic_exchange
+; PPC-PWR8-NEXT:lwz r6, 28(r1)
+; PPC-PWR8-NEXT:lwz r5, 24(r1)
+; PPC-PWR8-NEXT:lwz r4, 20(r1)
+; PPC-PWR8-NEXT:lwz r3, 16(r1)
+; PPC-PWR8-NEXT:lwz r0, 52(r1)
+; PPC-PWR8-NEXT:addi r1, r1, 48
+; PPC-PWR8-NEXT:mtlr r0
+; PPC-PWR8-NEXT:blr
 entry:
   %0 = atomicrmw xchg i128* %a, i128 %x seq_cst, align 16
   ret i128 %0
@@ -76,6 +148,109 @@
 ; PWR7-NEXT:ld r0, 16(r1)
 ; PWR7-NEXT:mtlr r0
 ; PWR7-NEXT:blr
+;
+; LE-PWR8-LABEL: add:
+; LE-PWR8:   # %bb.0: # %entry
+; LE-PWR8-NEXT:sync
+; LE-PWR8-NEXT:  .LBB1_1: # %entry
+; LE-PWR8-NEXT:#
+; LE-PWR8-NEXT:lqarx r6, 0, r3
+; LE-PWR8-NEXT:addc r9, r4, r7
+; LE-PWR8-NEXT:adde r8, r5, r6
+; LE-PWR8-NEXT:stqcx. r8, 0, r3
+; LE-PWR8-NEXT:bne cr0, .LBB1_1
+; LE-PWR8-NEXT:  # %bb.2: # %entry
+; LE-PWR8-NEXT:lwsync
+; LE-PWR8-NEXT:mr r3, r7
+; LE-PWR8-NEXT:mr r4, r6
+; LE-PWR8-NEXT:blr
+;
+; AIX64-PWR8-LABEL: add:
+; AIX64-PWR8:   # %bb.0: # %entry
+; AIX64-PWR8-NEXT:mflr r0
+; AIX64-PWR8-NEXT:std r0, 16(r1)
+; AIX64-PWR8-NEXT:stdu r1, -112(r1)
+; AIX64-PWR8-NEXT:sync
+; AIX64-PWR8-NEXT:bl .__sync_fetch_and_add_16[PR]
+; AIX64-PWR8-NEXT:nop
+; AIX64-PWR8-NEXT:lwsync
+; AIX64-PWR8-NEXT:addi r1, r1, 112
+; AIX64-PWR8-NEXT:ld r0, 16(r1)
+; 

[PATCH] D123349: [clang-tidy] Deal with keyword tokens in preprocessor conditions

2022-04-07 Thread Nathan James via Phabricator via cfe-commits
njames93 added inline comments.



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:281
 
+inline StringRef getTokenName(const Token ) {
+  return Tok.is(tok::raw_identifier) ? Tok.getRawIdentifier()

inline is pretty redundant here. Did you mean to make this static?



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:287
 void MacroToEnumCallbacks::checkName(const Token ) {
-  std::string Id;
-  if (MacroNameTok.is(tok::raw_identifier))
-Id = MacroNameTok.getRawIdentifier().str();
-  else if (MacroNameTok.is(tok::identifier))
-Id = MacroNameTok.getIdentifierInfo()->getName().str();
-  else {
-assert(false && "Expected either an identifier or raw identifier token");
-return;
-  }
+  std::string Id = getTokenName(MacroNameTok).str();
 

Building a std::string here seems unnecessary, Why can't we just keep the 
StringRef.



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:291
 return llvm::any_of(MacroList, [](const EnumMacro ) {
-  return Macro.Name.getIdentifierInfo()->getName().str() == Id;
+  return getTokenName(Macro.Name).str() == Id;
 });

Again, building a string is unnecessary, the StringRef equality operators will 
do the job nicely.



Comment at: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp:432
+  "macro '%0' defines an integral constant; prefer an enum 
instead")
+  << getTokenName(Macro.Name).str();
 }

ditto.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123349

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


[PATCH] D123349: [clang-tidy] Deal with keyword tokens in preprocessor conditions

2022-04-07 Thread Richard via Phabricator via cfe-commits
LegalizeAdulthood created this revision.
LegalizeAdulthood added a reviewer: aaron.ballman.
LegalizeAdulthood added a project: clang-tools-extra.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
LegalizeAdulthood requested review of this revision.

When a "keyword" token like __restrict was present in a macro condition,
modernize-macro-to-enum would assert in non-release builds.  However,
even for a "keyword" token, calling getIdentifierInfo()->getName() would
retrieve the text of the token, which is what we want.  Our intention is
to scan names that appear in conditional expressions in potential enum
clusters and invalidate those clusters if they contain the name.

Also, guard against "raw identifiers" appearing as potential enums.
This shouldn't happen, but it doesn't hurt to generalize the code.

Fixes #54775


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123349

Files:
  clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
@@ -208,6 +208,10 @@
 #define IFNDEF3 3
 #endif
 
+// Sometimes an argument to ifdef can be classified as a keyword token.
+#ifdef __restrict
+#endif
+
 // These macros do not expand to integral constants.
 #define HELLO "Hello, "
 #define WORLD "World"
Index: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
@@ -278,20 +278,17 @@
   }
 }
 
+inline StringRef getTokenName(const Token ) {
+  return Tok.is(tok::raw_identifier) ? Tok.getRawIdentifier()
+ : Tok.getIdentifierInfo()->getName();
+}
+
 void MacroToEnumCallbacks::checkName(const Token ) {
-  std::string Id;
-  if (MacroNameTok.is(tok::raw_identifier))
-Id = MacroNameTok.getRawIdentifier().str();
-  else if (MacroNameTok.is(tok::identifier))
-Id = MacroNameTok.getIdentifierInfo()->getName().str();
-  else {
-assert(false && "Expected either an identifier or raw identifier token");
-return;
-  }
+  std::string Id = getTokenName(MacroNameTok).str();
 
   llvm::erase_if(Enums, [](const MacroList ) {
 return llvm::any_of(MacroList, [](const EnumMacro ) {
-  return Macro.Name.getIdentifierInfo()->getName().str() == Id;
+  return getTokenName(Macro.Name).str() == Id;
 });
   });
 }
@@ -355,8 +352,7 @@
   const MacroDefinition ,
   const MacroDirective *Undef) {
   auto MatchesToken = [](const EnumMacro ) {
-return Macro.Name.getIdentifierInfo()->getName() ==
-   MacroNameTok.getIdentifierInfo()->getName();
+return getTokenName(Macro.Name) == getTokenName(MacroNameTok);
   };
 
   auto It = llvm::find_if(Enums, [MatchesToken](const MacroList ) {
@@ -432,8 +428,8 @@
 
 void MacroToEnumCallbacks::warnMacroEnum(const EnumMacro ) const {
   Check->diag(Macro.Directive->getLocation(),
-  "macro %0 defines an integral constant; prefer an enum instead")
-  << Macro.Name.getIdentifierInfo();
+  "macro '%0' defines an integral constant; prefer an enum 
instead")
+  << getTokenName(Macro.Name).str();
 }
 
 void MacroToEnumCallbacks::fixEnumMacro(const MacroList ) const {


Index: clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-macro-to-enum.cpp
@@ -208,6 +208,10 @@
 #define IFNDEF3 3
 #endif
 
+// Sometimes an argument to ifdef can be classified as a keyword token.
+#ifdef __restrict
+#endif
+
 // These macros do not expand to integral constants.
 #define HELLO "Hello, "
 #define WORLD "World"
Index: clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp
@@ -278,20 +278,17 @@
   }
 }
 
+inline StringRef getTokenName(const Token ) {
+  return Tok.is(tok::raw_identifier) ? Tok.getRawIdentifier()
+ : Tok.getIdentifierInfo()->getName();
+}
+
 void MacroToEnumCallbacks::checkName(const Token ) {
-  std::string Id;
-  if (MacroNameTok.is(tok::raw_identifier))
-Id = MacroNameTok.getRawIdentifier().str();
-  else if (MacroNameTok.is(tok::identifier))
-Id = 

[PATCH] D123278: [Clang] [Docs] Add HLSLSupport page

2022-04-07 Thread Chris Bieneman via Phabricator via cfe-commits
beanz updated this revision to Diff 421373.
beanz added a comment.

Updating with edits based on review feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123278

Files:
  clang/docs/HLSLSupport.rst
  clang/docs/index.rst

Index: clang/docs/index.rst
===
--- clang/docs/index.rst
+++ clang/docs/index.rst
@@ -45,6 +45,7 @@
OpenCLSupport
OpenMPSupport
SYCLSupport
+   HLSLSupport
ThinLTO
APINotes
CommandGuide/index
Index: clang/docs/HLSLSupport.rst
===
--- /dev/null
+++ clang/docs/HLSLSupport.rst
@@ -0,0 +1,240 @@
+
+HLSL Support
+
+
+.. contents::
+   :local:
+
+Introduction
+
+
+HLSL Support is under active development in the Clang codebase. This document
+describes the high level goals of the project, the guiding principles, as well
+as some idiosyncrasies of the HLSL language and how we intend to support them in
+Clang.
+
+Project Goals
+=
+
+The long term goal of this project is to enable Clang to function as a
+replacement for the `DirectXShaderCompiler (DXC)
+`_ in all its supported
+use cases. Accomplishing that goal will require Clang to be able to process most
+existing HLSL programs with a high degree of source compatibility.
+
+Non-Goals
+-
+
+HLSL ASTs do not need to be compatible between DXC and Clang. We do not expect
+identical code generation or that features will resemble DXC's implementation or
+architecture. In fact, we explicitly expect to deviate from DXC's implementation
+in key ways.
+
+Guiding Principles
+==
+
+This document lacks details for architectural decisions that are not yet
+finalized. Our top priorities are quality, maintainability, and flexibility. In
+accordance with community standards we are expecting a high level of test
+coverage, and we will engineer our solutions with long term maintenance in mind.
+We are also working to limit modifications to the Clang C++ code paths and
+share as much functionality as possible.
+
+Architectural Direction
+===
+
+HLSL support in Clang is expressed as C++ minus unsupported C and C++ features.
+This is different from how other Clang languages are implemented. Most languages
+in Clang are additive on top of C.
+
+HLSL is not a formally or fully specified language, and while our goals require
+a high level of source compatibility, implementations can vary and we have some
+flexibility to be more or less permissive in some cases. For modern HLSL DXC is
+the reference implementation.
+
+The HLSL effort prioritizes following similar patterns for other languages,
+drivers, runtimes and targets. Specifically, We will maintain separation between
+HSLS-specific code and the rest of Clang as much as possible following patterns
+in use in Clang code today (i.e. ParseHLSL.cpp, SemaHLSL.cpp, CGHLSL*.cpp...).
+We will use inline checks on language options where the code is simple and
+isolated, and prefer HLSL-specific implementation files for any code of
+reasonable complexity.
+
+In places where the HLSL language is in conflict with C and C++, we will seek to
+make minimally invasive changes guarded under the HLSL language options. We will
+seek to make HLSL language support as minimal a maintenance burden as possible.
+
+DXC Driver
+--
+
+A DXC driver mode will provide command-line compatibility with DXC, supporting
+DXC's options and flags. The DXC driver is HLSL-specific and will create an
+HLSLToolchain which will provide the basis to support targeting both DirectX and
+Vulkan.
+
+Parser
+--
+
+Following the examples of other parser extensions HLSL will add a ParseHLSL.cpp
+file to contain the implementations of HLSL-specific extensions to the Clang
+parser. The HLSL grammar shares most of its structure with C and C++, so we will
+use the existing C/C++ parsing code paths.
+
+Sema
+
+
+HLSL's Sema implementation will also provide an ``ExternalSemaSource``. In DXC,
+an ``ExternalSemaSource`` is used to provide definitions for HLSL built-in data
+types and built-in templates. Clang is already designed to allow an attached
+``ExternalSemaSource`` to lazily complete data types, which is a **huge**
+performance win for HLSL.
+
+CodeGen
+---
+
+Like OpenCL, HLSL relies on capturing a lot of information into IR metadata.
+*hand wave* *hand wave* *hand wave* As a design principle here we want our IR to
+be idiomatic Clang IR as much as possible. We will use IR attributes wherever we
+can, and use metadata as sparingly as possible. One example of a difference from
+DXC already implemented in Clang is the use of target triples to communicate
+shader model versions and shader stages.
+
+Our HLSL CodeGen implementation should also have an eye toward 

[PATCH] D94942: [clangd] Add tweak for implementing abstract class

2022-04-07 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 421371.
njames93 added a comment.

Use new tweak InsertionPoint logic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D94942

Files:
  clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
  clang-tools-extra/clangd/refactor/tweaks/ImplementAbstract.cpp
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/tweaks/ImplementAbstractTests.cpp

Index: clang-tools-extra/clangd/unittests/tweaks/ImplementAbstractTests.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/tweaks/ImplementAbstractTests.cpp
@@ -0,0 +1,427 @@
+//===-- ImplementAbstractTests.cpp --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestTU.h"
+#include "TweakTesting.h"
+#include "gmock/gmock-matchers.h"
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using ::testing::Not;
+
+namespace clang {
+namespace clangd {
+namespace {
+
+bool stringEqIgnoreWs(StringRef LHS, StringRef RHS) {
+  auto TrimmedL = LHS.trim();
+  auto TrimmedR = RHS.trim();
+  static constexpr llvm::StringLiteral WS(" \t\r\n\f\v");
+
+  while (!TrimmedL.empty() && !TrimmedR.empty()) {
+auto LPos = TrimmedL.find_first_of(WS);
+auto RPos = TrimmedR.find_first_of(WS);
+if (TrimmedL.take_front(LPos) != TrimmedR.take_front(RPos))
+  return false;
+TrimmedL =
+TrimmedL.substr(LPos).drop_while([](char C) { return WS.contains(C); });
+TrimmedR =
+TrimmedR.substr(RPos).drop_while([](char C) { return WS.contains(C); });
+  }
+  return TrimmedL == TrimmedR;
+}
+
+MATCHER_P(STREQWS, EqualTo, "") {
+  if (stringEqIgnoreWs(arg, EqualTo))
+return true;
+
+  auto Result =
+  testing::internal::EqFailure("", "", arg, std::string(EqualTo), false);
+  *result_listener << Result.message();
+  return false;
+}
+
+TWEAK_TEST(ImplementAbstract);
+
+TEST_F(ImplementAbstractTest, TestUnavailable) {
+
+  StringRef Cases[]{
+  // Not a pure virtual method.
+  R"cpp(
+class A {
+  virtual void Foo();
+};
+class ^B : public A {};
+  )cpp",
+  // Pure virtual method overridden in class.
+  R"cpp(
+class A {
+  virtual void Foo() = 0;
+};
+class ^B : public A {
+  void Foo() override;
+};
+  )cpp",
+  // Pure virtual method overridden in class with virtual keyword
+  R"cpp(
+class A {
+  virtual void Foo() = 0;
+};
+class ^B : public A {
+  virtual void Foo() override;
+};
+  )cpp",
+  // Pure virtual method overridden in class without override keyword
+  R"cpp(
+class A {
+  virtual void Foo() = 0;
+};
+class ^B : public A {
+  void Foo();
+};
+  )cpp",
+  // Pure virtual method overriden in base class.
+  R"cpp(
+class A {
+  virtual void Foo() = 0;
+};
+class B : public A {
+  void Foo() override;
+};
+class ^C : public B {};
+  )cpp"};
+  for (const auto  : Cases) {
+EXPECT_THAT(Case, Not(isAvailable()));
+  }
+}
+
+TEST_F(ImplementAbstractTest, NormalAvailable) {
+  struct Case {
+llvm::StringRef TestHeader;
+llvm::StringRef TestSource;
+llvm::StringRef ExpectedSource;
+  };
+
+  Case Cases[]{
+  {
+  R"cpp(
+class A {
+  virtual void Foo() = 0;
+};)cpp",
+  R"cpp(
+class B : public A {
+^};
+  )cpp",
+  R"cpp(
+class B : public A {
+  void Foo() override {
+  }
+};
+  )cpp",
+  },
+  {
+  R"cpp(
+class A {
+public:
+  virtual int Foo() = 0;
+};)cpp",
+  R"cpp(
+class ^B : public A {
+};
+  )cpp",
+  R"cpp(
+class B : public A {
+public:
+  int Foo() override {
+return {};
+  }
+};
+  )cpp",
+  },
+  {
+  R"cpp(
+class A {
+  virtual void Foo(int Param) = 0;
+};)cpp",
+  R"cpp(
+class ^B : public A {
+};
+  )cpp",
+  R"cpp(
+class B : public A {
+  void Foo(int Param) override {
+  }
+};
+  )cpp",
+  },
+  {
+  R"cpp(
+class A {
+  virtual void Foo(int Param) = 0;
+

[PATCH] D119296: KCFI sanitizer

2022-04-07 Thread Sami Tolvanen via Phabricator via cfe-commits
samitolvanen added a comment.

In D119296#3437604 , @pcc wrote:

>> Note that if additional data has been injected between the KCFI
>> type identifier and the start of the function, e.g. by using
>> -fpatchable-function-entry, the offset in bytes must be specified
>> using -fsanitize-kcfi-offset= to avoid errors. The offset
>> must be the same for all indirectly called functions in every
>> translation unit.
>
> On x86 the specific constant 6 is necessary to ensure that the constant 
> embedded in the cmpl operand can't be used as a gadget. So any value other 
> than 6 will potentially impact the security of KCFI.
>
> I would prefer not to design an interaction between 
> -fpatchable-function-entry and KCFI until the specific use case is known.

Sure, that's a valid point. In the Linux kernel, only PA-RISC currently injects 
nops before function entry, so this isn't an issue for any of the architectures 
we currently plan to support. I'll drop the flag from the next version and we 
can revisit this when we have an actual use case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119296

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


[clang] 1cee3d9 - DebugInfo: Consider the type of NTTP when simplifying template names

2022-04-07 Thread David Blaikie via cfe-commits

Author: David Blaikie
Date: 2022-04-08T00:00:46Z
New Revision: 1cee3d9db77b2c62a03efe1cce45f627dcbe6457

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

LOG: DebugInfo: Consider the type of NTTP when simplifying template names

Since the NTTP may need to be cast to the type when rebuilding the name,
check that the type can be rebuilt when determining whether a template
name can be simplified.

Added: 


Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp
clang/test/CodeGenCXX/debug-info-simple-template-names.cpp

cross-project-tests/debuginfo-tests/clang_llvm_roundtrip/simplified_template_names.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 63b89f258a8ac..c18dbccf82936 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -5167,7 +5167,8 @@ std::string CGDebugInfo::GetName(const Decl *D, bool 
Qualified) const {
 // harder to parse back into a large integer, etc - so punting on
 // this for now. Re-parsing the integers back into APInt is 
probably
 // feasible some day.
-return TA.getAsIntegral().getBitWidth() <= 64;
+return TA.getAsIntegral().getBitWidth() <= 64 &&
+   IsReconstitutableType(TA.getIntegralType());
   case TemplateArgument::Type:
 return IsReconstitutableType(TA.getAsType());
   default:

diff  --git a/clang/test/CodeGenCXX/debug-info-simple-template-names.cpp 
b/clang/test/CodeGenCXX/debug-info-simple-template-names.cpp
index 190d121937a03..98faa0fc6f0bb 100644
--- a/clang/test/CodeGenCXX/debug-info-simple-template-names.cpp
+++ b/clang/test/CodeGenCXX/debug-info-simple-template-names.cpp
@@ -31,6 +31,10 @@ struct t4 {
 };
   
 t4 v1;
+enum { UnnamedEnum1 };
+template
+void f4() {
+}
 // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "t3<(anonymous 
namespace)::LocalEnum, ((anonymous namespace)::LocalEnum)0>"
 void f() {
   // Basic examples of simplifiable/rebuildable names
@@ -122,4 +126,7 @@ void f() {
   int fnrt() __attribute__((noreturn));
   f1();
   // CHECK: !DISubprogram(name: "f1",
+  
+  f4();
+  // CHECK: !DISubprogram(name: "f4<((unnamed enum at {{.*}}))0>"
 }

diff  --git 
a/cross-project-tests/debuginfo-tests/clang_llvm_roundtrip/simplified_template_names.cpp
 
b/cross-project-tests/debuginfo-tests/clang_llvm_roundtrip/simplified_template_names.cpp
index 9bc14f8ce6577..b68d4e8c04b94 100644
--- 
a/cross-project-tests/debuginfo-tests/clang_llvm_roundtrip/simplified_template_names.cpp
+++ 
b/cross-project-tests/debuginfo-tests/clang_llvm_roundtrip/simplified_template_names.cpp
@@ -179,6 +179,10 @@ struct t12 {
   t11 v1;
 };
 
+template
+void f10() {
+}
+
 int main() {
   struct { } A;
   auto L = []{};
@@ -327,6 +331,7 @@ int main() {
   f1();
   int fnrt() __attribute__((noreturn));
   f1();
+  f10();
 }
 void t8::mem() {
   struct t7 { };



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


[PATCH] D123345: Treat `std::move`, `forward`, and `move_if_noexcept` as builtins.

2022-04-07 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith created this revision.
rsmith added reviewers: aaron.ballman, rnk.
Herald added a project: All.
rsmith requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

We still require these functions to be declared before they can be used,
but don't instantiate their definitions unless their addresses are
taken. Instead, code generation, constant evaluation, and static
analysis are given direct knowledge of their effect.

This change aims to reduce various costs associated with these functions

- per-instantiation memory costs, compile time and memory costs due to

creating out-of-line copies and inlining them, code size at -O0, and so
on -- so that they are not substantially more expensive than a cast.
Most of these improvements are very small, but I measured a 3% decrease
in -O0 object file size for a simple C++ source file using the standard
library after this change.

We now automatically infer the `const` and `nothrow` attributes on these
now-builtin functions, in particular meaning that we get a warning for
an unused call to one of these functions.

In C++20 onwards, we disallow taking the addresses of these functions,
per the C++20 "addressable function" rule. In earlier language modes, a
compatibility warning is produced but the address can still be taken.

The same infrastructure is extended to the existing MSVC builtin
`__GetExceptionInfo`, which is now only recognized in namespace `std`
like it always should have been.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123345

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Builtins.def
  clang/include/clang/Basic/Builtins.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Analysis/BodyFarm.cpp
  clang/lib/Basic/Builtins.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaInit.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/Analysis/use-after-move.cpp
  clang/test/CodeGenCXX/builtin-std-move.cpp
  clang/test/CodeGenCXX/microsoft-abi-throw.cpp
  clang/test/SemaCXX/builtin-std-move.cpp
  clang/test/SemaCXX/unqualified-std-call-fixits.cpp
  clang/test/SemaCXX/unqualified-std-call.cpp
  clang/test/SemaCXX/warn-consumed-analysis.cpp

Index: clang/test/SemaCXX/warn-consumed-analysis.cpp
===
--- clang/test/SemaCXX/warn-consumed-analysis.cpp
+++ clang/test/SemaCXX/warn-consumed-analysis.cpp
@@ -953,12 +953,12 @@
 namespace std {
   void move();
   template
-  void move(T&&);
+  T &(T&);
 
   namespace __1 {
 void move();
 template
-void move(T&&);
+T &(T&);
   }
 }
 
@@ -971,7 +971,7 @@
   void test() {
 x.move();
 std::move();
-std::move(x);
+std::move(x); // expected-warning {{ignoring return value}}
 std::__1::move();
 std::__1::move(x);
   }
Index: clang/test/SemaCXX/unqualified-std-call.cpp
===
--- clang/test/SemaCXX/unqualified-std-call.cpp
+++ clang/test/SemaCXX/unqualified-std-call.cpp
@@ -1,17 +1,17 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -Wall -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -verify -Wall -std=c++11 %s -Wno-unused-value
 
 namespace std {
 
 template 
 void dummy(T &&) {}
 template 
-void move(T &&) {}
+T &(T &) { return x; }
 template 
 void move(T &&, U &&) {}
 
 inline namespace __1 {
 template 
-void forward(T &) {}
+T (T ) { return x; }
 } // namespace __1
 
 struct foo {};
Index: clang/test/SemaCXX/unqualified-std-call-fixits.cpp
===
--- clang/test/SemaCXX/unqualified-std-call-fixits.cpp
+++ clang/test/SemaCXX/unqualified-std-call-fixits.cpp
@@ -6,9 +6,9 @@
 
 namespace std {
 
-void move(auto &) {}
+int &(auto &) { return a; }
 
-void forward(auto ) {}
+int &(auto ) { return a; }
 
 } // namespace std
 
@@ -16,8 +16,8 @@
 
 void f() {
   int i = 0;
-  move(i); // expected-warning {{unqualified call to std::move}}
-  // CHECK: {{^}}  std::
-  forward(i); // expected-warning {{unqualified call to std::forward}}
-  // CHECK: {{^}}  std::
+  (void)move(i); // expected-warning {{unqualified call to std::move}}
+  // CHECK: {{^}}  (void)std::move
+  (void)forward(i); // expected-warning {{unqualified call to std::forward}}
+  // CHECK: {{^}}  (void)std::forward
 }
Index: clang/test/SemaCXX/builtin-std-move.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/builtin-std-move.cpp
@@ -0,0 +1,90 @@
+// RUN: %clang_cc1 -std=c++17 -verify %s
+// RUN: %clang_cc1 -std=c++17 -verify %s -DNO_CONSTEXPR
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+namespace std {
+#ifndef NO_CONSTEXPR
+#define 

[PATCH] D119296: KCFI sanitizer

2022-04-07 Thread Peter Collingbourne via Phabricator via cfe-commits
pcc added a comment.

> Note that if additional data has been injected between the KCFI
> type identifier and the start of the function, e.g. by using
> -fpatchable-function-entry, the offset in bytes must be specified
> using -fsanitize-kcfi-offset= to avoid errors. The offset
> must be the same for all indirectly called functions in every
> translation unit.

On x86 the specific constant 6 is necessary to ensure that the constant 
embedded in the cmpl operand can't be used as a gadget. So any value other than 
6 will potentially impact the security of KCFI.

I would prefer not to design an interaction between -fpatchable-function-entry 
and KCFI until the specific use case is known.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119296

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


[PATCH] D121556: [randstruct] Add randomize structure layout support

2022-04-07 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 421358.
void added a comment.

Make the randomize_layout and no_randomize_layout attributes mutually 
exclutsive.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121556

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/AST/Randstruct.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Decl.cpp
  clang/lib/AST/Randstruct.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Sema/SemaCast.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/unittests/AST/CMakeLists.txt
  clang/unittests/AST/RandstructTest.cpp

Index: clang/unittests/AST/RandstructTest.cpp
===
--- /dev/null
+++ clang/unittests/AST/RandstructTest.cpp
@@ -0,0 +1,460 @@
+//===- unittest/AST/RandstructTest.cpp ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file contains tests for Clang's structure field layout randomization.
+//
+//===--===//
+
+/*
+ * Build this test suite by running `make ASTTests` in the build folder.
+ *
+ * Run this test suite by running the following in the build folder:
+ * ` ./tools/clang/unittests/AST/ASTTests
+ * --gtest_filter=StructureLayoutRandomization*`
+ */
+
+#include "clang/AST/Randstruct.h"
+#include "gtest/gtest.h"
+
+#include "DeclMatcher.h"
+#include "clang/AST/RecordLayout.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Frontend/ASTUnit.h"
+#include "clang/Testing/CommandLineArgs.h"
+#include "clang/Tooling/Tooling.h"
+
+#include 
+
+using namespace clang;
+using namespace clang::ast_matchers;
+using namespace clang::randstruct;
+
+using field_names = std::vector;
+
+namespace {
+
+std::unique_ptr makeAST(const std::string ,
+ bool ExpectErr = false) {
+  std::vector Args = getCommandLineArgsForTesting(Lang_C99);
+  Args.push_back("-frandomize-layout-seed=1234567890abcdef");
+
+  IgnoringDiagConsumer IgnoringConsumer = IgnoringDiagConsumer();
+
+  std::unique_ptr AST = tooling::buildASTFromCodeWithArgs(
+  SourceCode, Args, "input.c", "clang-tool",
+  std::make_shared(),
+  tooling::getClangStripDependencyFileAdjuster(),
+  tooling::FileContentMappings(), );
+
+  if (ExpectErr)
+EXPECT_TRUE(AST->getDiagnostics().hasErrorOccurred());
+  else
+EXPECT_FALSE(AST->getDiagnostics().hasErrorOccurred());
+
+  return AST;
+}
+
+RecordDecl *getRecordDeclFromAST(const ASTContext , const std::string ) {
+  RecordDecl *RD = FirstDeclMatcher().match(
+  C.getTranslationUnitDecl(), recordDecl(hasName(Name)));
+  return RD;
+}
+
+std::vector getFieldNamesFromRecord(const RecordDecl *RD) {
+  std::vector Fields;
+
+  Fields.reserve(8);
+  for (auto *Field : RD->fields())
+Fields.push_back(Field->getNameAsString());
+
+  return Fields;
+}
+
+bool isSubsequence(const field_names , const field_names ) {
+  unsigned SeqLen = Seq.size();
+  unsigned SubLen = Subseq.size();
+
+  bool IsSubseq = false;
+  for (unsigned I = 0; I < SeqLen; ++I)
+if (Seq[I] == Subseq[0]) {
+  IsSubseq = true;
+  for (unsigned J = 0; J + I < SeqLen && J < SubLen; ++J) {
+if (Seq[J + I] != Subseq[J]) {
+  IsSubseq = false;
+  break;
+}
+  }
+}
+
+  return IsSubseq;
+}
+
+} // end anonymous namespace
+
+namespace clang {
+namespace ast_matchers {
+
+#define RANDSTRUCT_TEST_SUITE_TEST StructureLayoutRandomizationTestSuiteTest
+
+TEST(RANDSTRUCT_TEST_SUITE_TEST, CanDetermineIfSubsequenceExists) {
+  const field_names Seq = {"a", "b", "c", "d"};
+
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a", "b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"b", "c", "d"}));
+  ASSERT_TRUE(isSubsequence(Seq, {"a"}));
+  ASSERT_FALSE(isSubsequence(Seq, {"a", "d"}));
+}
+
+#define RANDSTRUCT_TEST StructureLayoutRandomization
+
+TEST(RANDSTRUCT_TEST, UnmarkedStruct) {
+  const std::unique_ptr AST = makeAST(R"c(
+struct test {
+int bacon;
+long lettuce;
+long long tomato;
+float mayonnaise;
+};
+  )c");
+
+  const RecordDecl *RD = 

[PATCH] D122981: [Clang] CWG 1394: Incomplete types as parameters of deleted functions

2022-04-07 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao updated this revision to Diff 421345.
rZhBoYao added a comment.

Added release note.

Also, push to my repo to make sure the release note is correctly rendered:
https://github.com/poyaoc97/llvm-project/commit/1167f0fc6b91


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

https://reviews.llvm.org/D122981

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.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
@@ -8178,7 +8178,7 @@
 https://wg21.link/cwg1394;>1394
 CD3
 Incomplete types as parameters of deleted functions
-Unknown
+Clang 15
   
   
 https://wg21.link/cwg1395;>1395
Index: clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp
===
--- /dev/null
+++ clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+struct Incomplete; // expected-note 2{{forward declaration of 'Incomplete'}}
+Incomplete f(Incomplete) = delete; // well-formed
+Incomplete g(Incomplete) {}// expected-error{{incomplete result type 'Incomplete' in function definition}}\
+// expected-error{{variable has incomplete type 'Incomplete'}}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -17379,6 +17379,21 @@
   }
 }
 
+void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
+   FnBodyKind BodyKind) {
+  switch (BodyKind) {
+  case FnBodyKind::Delete:
+SetDeclDeleted(D, Loc);
+break;
+  case FnBodyKind::Default:
+SetDeclDefaulted(D, Loc);
+break;
+  case FnBodyKind::Other:
+llvm_unreachable(
+"Parsed function body should be '= delete;' or '= default;'");
+  }
+}
+
 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  const CXXMethodDecl *Old) {
   const auto *NewFT = New->getType()->castAs();
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -14185,7 +14185,7 @@
 Decl *
 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator ,
   MultiTemplateParamsArg TemplateParameterLists,
-  SkipBodyInfo *SkipBody) {
+  SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
   assert(D.isFunctionDeclarator() && "Not a function declarator!");
   Scope *ParentScope = FnBodyScope->getParent();
@@ -14204,7 +14204,7 @@
 
   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
-  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
+  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
 
   if (!Bases.empty())
 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
@@ -14380,7 +14380,8 @@
 }
 
 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
-SkipBodyInfo *SkipBody) {
+SkipBodyInfo *SkipBody,
+FnBodyKind BodyKind) {
   if (!D) {
 // Parsing the function declaration failed in some way. Push on a fake scope
 // anyway so we can try to parse the function body.
@@ -14469,11 +14470,11 @@
 }
   }
 
-  // The return type of a function definition must be complete
-  // (C99 6.9.1p3, C++ [dcl.fct]p6).
+  // The return type of a function definition must be complete (C99 6.9.1p3),
+  // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
   QualType ResultType = FD->getReturnType();
   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
-  !FD->isInvalidDecl() &&
+  !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
   RequireCompleteType(FD->getLocation(), ResultType,
   diag::err_func_def_incomplete_result))
 FD->setInvalidDecl();
@@ -14482,8 +14483,9 @@
 PushDeclContext(FnBodyScope, FD);
 
   // Check the validity of our function parameters
-  CheckParmsForFunctionDef(FD->parameters(),
-   /*CheckParameterNames=*/true);
+  if (BodyKind != FnBodyKind::Delete)
+CheckParmsForFunctionDef(FD->parameters(),
+ /*CheckParameterNames=*/true);
 
   // Add non-parameter declarations already in the function 

[PATCH] D121637: [PowerPC] Fix EmitPPCBuiltinExpr to emit arguments once

2022-04-07 Thread Quinn Pham via Phabricator via cfe-commits
quinnp added a comment.

In D121637#3437371 , @thakis wrote:

> Looks like this breaks tests on windows: 
> http://45.33.8.238/win/55893/step_7.txt
>
> Please take a look and revert for now if it takes a while to fix.

Thanks for finding this, not sure what the cause is. I reverted the commit 
here: https://reviews.llvm.org/rGfef56f79ac8c4a4985774ea9fb1faa83a74866d3.

I'll look into a fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121637

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


[PATCH] D122981: [Clang] CWG 1394: Incomplete types as parameters of deleted functions

2022-04-07 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao updated this revision to Diff 421338.
rZhBoYao retitled this revision from "[Clang] Diagnose incomplete return/param 
types only when function is not deleted" to "[Clang] CWG 1394: Incomplete types 
as parameters of deleted functions".
rZhBoYao edited the summary of this revision.
rZhBoYao removed a reviewer: rtrieu.
rZhBoYao set the repository for this revision to rG LLVM Github Monorepo.
rZhBoYao added a comment.

Updating the status of CWG 1394 is the only change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122981

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.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
@@ -8178,7 +8178,7 @@
 https://wg21.link/cwg1394;>1394
 CD3
 Incomplete types as parameters of deleted functions
-Unknown
+Clang 15
   
   
 https://wg21.link/cwg1395;>1395
Index: clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp
===
--- /dev/null
+++ clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+struct Incomplete; // expected-note 2{{forward declaration of 'Incomplete'}}
+Incomplete f(Incomplete) = delete; // well-formed
+Incomplete g(Incomplete) {}// expected-error{{incomplete result type 'Incomplete' in function definition}}\
+// expected-error{{variable has incomplete type 'Incomplete'}}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -17379,6 +17379,21 @@
   }
 }
 
+void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
+   FnBodyKind BodyKind) {
+  switch (BodyKind) {
+  case FnBodyKind::Delete:
+SetDeclDeleted(D, Loc);
+break;
+  case FnBodyKind::Default:
+SetDeclDefaulted(D, Loc);
+break;
+  case FnBodyKind::Other:
+llvm_unreachable(
+"Parsed function body should be '= delete;' or '= default;'");
+  }
+}
+
 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  const CXXMethodDecl *Old) {
   const auto *NewFT = New->getType()->castAs();
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -14185,7 +14185,7 @@
 Decl *
 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator ,
   MultiTemplateParamsArg TemplateParameterLists,
-  SkipBodyInfo *SkipBody) {
+  SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
   assert(D.isFunctionDeclarator() && "Not a function declarator!");
   Scope *ParentScope = FnBodyScope->getParent();
@@ -14204,7 +14204,7 @@
 
   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
-  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
+  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
 
   if (!Bases.empty())
 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
@@ -14380,7 +14380,8 @@
 }
 
 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
-SkipBodyInfo *SkipBody) {
+SkipBodyInfo *SkipBody,
+FnBodyKind BodyKind) {
   if (!D) {
 // Parsing the function declaration failed in some way. Push on a fake scope
 // anyway so we can try to parse the function body.
@@ -14469,11 +14470,11 @@
 }
   }
 
-  // The return type of a function definition must be complete
-  // (C99 6.9.1p3, C++ [dcl.fct]p6).
+  // The return type of a function definition must be complete (C99 6.9.1p3),
+  // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
   QualType ResultType = FD->getReturnType();
   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
-  !FD->isInvalidDecl() &&
+  !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
   RequireCompleteType(FD->getLocation(), ResultType,
   diag::err_func_def_incomplete_result))
 FD->setInvalidDecl();
@@ -14482,8 +14483,9 @@
 PushDeclContext(FnBodyScope, FD);
 
   // Check the validity of our function parameters
-  CheckParmsForFunctionDef(FD->parameters(),
-

[PATCH] D123278: [Clang] [Docs] Add HLSLSupport page

2022-04-07 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added a comment.

I'll do an edit pass tonight and update. I've also gone through and replied to 
some of the questions and comments inline.

Thank you!




Comment at: clang/docs/HLSLSupport.rst:22-23
+`_. in all its supported
+use cases. Accomplishing that goal will require a high level of source
+compatibility.
+

kuhar wrote:
> What do you mean by source compatibility in this case? In terms of the input 
> source language (HLSL), or the source code of both implementations?
> 
> Perhaps we could make it more direct? E.g., 'This requires us to add the HLSL 
> language support to Clang.'
I see the confusion there. I mean in terms of the input source, not the 
implementation. We do vend the compiler as a library too with a COM API to 
invoke the compiler on in-memory sources (which is slightly terrifying to me).

I don't yet know how much flexibility we have to radically change the API, but 
that shouldn't have any impact on the implementations in clang because we'll do 
it in a wrapper library.



Comment at: clang/docs/HLSLSupport.rst:50-52
+HLSL is not a formally or fully specified language, and while our goals require
+a high level of source compatibility, implementations can vary and we have some
+flexibility to be more or less permissive in some cases.

kuhar wrote:
> Is DXC the reference implementation?
Yes, with the caveat that it doesn't actually support older language versions 
(for that we have FXC).



Comment at: clang/docs/HLSLSupport.rst:73
+Following the examples of other parser extensions HLSL will add a ParseHLSL.cpp
+file to contain the implementations of HLSL-specific extensions to the clang
+parser.

aaron.ballman wrote:
> Probably also worth pointing out that most HLSL parsing is expected to be the 
> usual C and C++ code paths, or is that not your expectation?
Yea, that is the expectation.



Comment at: clang/docs/HLSLSupport.rst:90-91
+metadata. *hand wave* *hand wave* *hand wave* As a design principle here we 
want
+our IR to be idiomatic Clang IR as much as possible. We will use IR attributes
+wherever we can, and use metadata as sparingly as possible. One example of a
+difference from DXC already implemented in Clang is the use of target triples 
to

kuhar wrote:
> Are all attributes guaranteed to be preserved? I thought some might get 
> dropped by opt.
Some attributes do get dropped in optimization. We are going to need to 
evaluate a bit case by case. DXC (and DXIL) puts a lot of information in 
metadata, which is a pain to work with through compiler layers. We actually 
have a set of helpers to read data in and out of the IR metadata... I'm trying 
to avoid needing any of that.



Comment at: clang/docs/HLSLSupport.rst:121-122
+operators (unary ``*``, and ``->``), as well as the address of operator (unary
+&). While HLSL disallows pointers and references in the syntax, HLSL does use
+reference types in the AST.
+

aaron.ballman wrote:
> Presumably it also uses pointer types in the AST for things like array and 
> function decay?
That is my plan for in Clang. In DXC they prevent array->pointer decay in the 
AST which IMO causes more problems than it solves, especially since the IR 
decays to pointers anyways.



Comment at: clang/docs/HLSLSupport.rst:143-145
+In HLSL 2018 and earlier, HLSL supported logical operators (and the ternary
+operator) on vector types. This behavior required that operators not short
+circuit.

aaron.ballman wrote:
> It's not clear whether the behavior will vary for all types or just vector 
> types. Also, does this apply in preprocessor conditionals the same as runtime 
> expressions?
It only applies in runtime expressions, and does apply to all types not just 
vectors. Vectors are the motivation for it because short circuiting would be 
unwieldy for vector types.

With HLSL 2021, operators follow C short circuit rules and are not allowed to 
operate on vector types, instead there are builtin functions to handle the 
vector cases.



Comment at: clang/docs/HLSLSupport.rst:150-152
+HLSL has a ``precise`` qualifier that behaves unlike anything else in the C
+language. The support for this qualifier in DXC is buggy, so our bar for
+compatibility is low.

aaron.ballman wrote:
> Is it worth supporting at all (I know you want source compatibility...)? Type 
> system changes are generally expensive and invasive, largely because changing 
> the type system in C++ is complicated. For example, does this qualifier 
> impact overload sets or template specializations? Does it get name mangled? 
> That sort of thing.
Unfortunately we do need to implement it to some degree. In DXC it is 
implemented as an attribute rather than a qualifier, so it shouldn't impact 
overloads, template 

[PATCH] D121637: [PowerPC] Fix EmitPPCBuiltinExpr to emit arguments once

2022-04-07 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Looks like this breaks tests on windows: http://45.33.8.238/win/55893/step_7.txt

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


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121637

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


[PATCH] D121637: [PowerPC] Fix EmitPPCBuiltinExpr to emit arguments once

2022-04-07 Thread Quinn Pham 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 rG2aae5b1fac38: [PowerPC] Fix EmitPPCBuiltinExpr to emit 
arguments once (authored by quinnp).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121637

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/PowerPC/builtins-ppc-fastmath.c
  clang/test/CodeGen/PowerPC/builtins-ppc-pair-mma-types.c
  clang/test/CodeGen/PowerPC/builtins-ppc-stmtexpr-argument.c
  clang/test/CodeGen/PowerPC/builtins-ppc-vsx.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cas.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-fetch.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-fp.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-math.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync.c
  clang/test/CodeGen/PowerPC/ppc-mma-types.c
  clang/test/Sema/ppc-pair-mma-types.c

Index: clang/test/Sema/ppc-pair-mma-types.c
===
--- clang/test/Sema/ppc-pair-mma-types.c
+++ clang/test/Sema/ppc-pair-mma-types.c
@@ -12,11 +12,6 @@
 
 // typedef
 typedef __vector_quad vq_t;
-void testVQTypedef(int *inp, int *outp) {
-  vq_t *vqin = (vq_t *)inp;
-  vq_t *vqout = (vq_t *)outp;
-  *vqout = *vqin;
-}
 
 // function argument
 void testVQArg1(__vector_quad vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
@@ -29,57 +24,22 @@
   *vqp = vq;
 }
 
-void testVQArg3(__vector_quad *vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
-void testVQArg4(const __vector_quad *const vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
-void testVQArg5(__vector_quad vqa[], int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = vqa[0];
-}
-
 void testVQArg6(const vq_t vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   *vqp = vq;
 }
 
-void testVQArg7(const vq_t *vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
 // function return
 __vector_quad testVQRet1(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   return *vqp; // expected-error {{invalid use of PPC MMA type}}
 }
 
-__vector_quad *testVQRet2(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
-const __vector_quad *testVQRet3(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
 const vq_t testVQRet4(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   return *vqp; // expected-error {{invalid use of PPC MMA type}}
 }
 
-const vq_t *testVQRet5(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
 // global
 __vector_quad globalvq;// expected-error {{invalid use of PPC MMA type}}
 const __vector_quad globalvq2; // expected-error {{invalid use of PPC MMA type}}
@@ -87,16 +47,6 @@
 const __vector_quad *const globalvqp2;
 vq_t globalvq_t; // expected-error {{invalid use of PPC MMA type}}
 
-// local
-void testVQLocal(int *ptr, vector unsigned char vc) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  __vector_quad vq1 = *vqp;
-  __vector_quad vq2;
-  __builtin_mma_xxsetaccz();
-  __vector_quad vq3;
-  __builtin_mma_xvi4ger8(, vc, vc);
-  *vqp = vq3;
-}
 
 // struct field
 struct TestVQStruct {
@@ -106,17 +56,6 @@
   __vector_quad *vq;
 };
 
-// sizeof / alignof
-int testVQSizeofAlignof(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  __vector_quad vq = *vqp;
-  unsigned sizet = sizeof(__vector_quad);
-  unsigned alignt = __alignof__(__vector_quad);
-  unsigned sizev = sizeof(vq);
-  unsigned alignv = __alignof__(vq);
-  return sizet + alignt + sizev + alignv;
-}
-
 // operators
 int testVQOperators1(int *ptr) {
   __vector_quad *vqp = (__vector_quad *)ptr;
@@ -168,11 +107,6 @@
 
 // typedef
 typedef __vector_pair vp_t;
-void testVPTypedef(int *inp, int *outp) {
-  vp_t *vpin = (vp_t *)inp;
-  vp_t *vpout = (vp_t *)outp;
-  *vpout = *vpin;
-}
 
 // function argument
 void testVPArg1(__vector_pair vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
@@ -185,57 +119,22 @@
   *vpp = vp;
 }
 
-void testVPArg3(__vector_pair *vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
-void testVPArg4(const __vector_pair *const vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
-void testVPArg5(__vector_pair vpa[], int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = vpa[0];
-}
-
 void testVPArg6(const vp_t vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_pair *vpp = (__vector_pair *)ptr;
   *vpp = vp;
 }
 
-void testVPArg7(const vp_t *vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair 

[PATCH] D122734: [HIP] Fix mangling number for local struct

2022-04-07 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

In D122734#3435086 , @yaxunl wrote:

> This patch takes a similar approach as https://reviews.llvm.org/D69322 has 
> done for lambda. When doing host compilation for CUDA/HIP on Windows with 
> MSVC toolchain, mangling number of lambda always uses Itanium mangling 
> number. In this case, mangling number of local struct types always uses 
> Itanium mangling number. I assume this should be fine as long as it is 
> consistent for all HIP programs.

I'm fairly sure that the code does what you need it to do for HIP. What I'm not 
sure is whether it will impact other users.

I've missed that `getManglingNumber` is part of `MSHIPNumberingContext`, so it 
is HIP-specific and should not change mangling for non-HIP users.

Would it make it possible to end up with different mangling for the shared code 
compiled as regular C++ code and host-side code in HIP sources? E.g. from a 
common header included in both.


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

https://reviews.llvm.org/D122734

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


[PATCH] D122981: [Clang] Diagnose incomplete return/param types only when function is not deleted

2022-04-07 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao updated this revision to Diff 421328.
rZhBoYao marked 5 inline comments as done.
rZhBoYao added a comment.

Removed member function test cases and addressed comments,
which includes:

1. Sema::SetFunctionBodyKind
2. Change enum names
3. Be clear about delete being C++ specific.


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

https://reviews.llvm.org/D122981

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp

Index: clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp
===
--- /dev/null
+++ clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+struct Incomplete; // expected-note 2{{forward declaration of 'Incomplete'}}
+Incomplete f(Incomplete) = delete; // well-formed
+Incomplete g(Incomplete) {}// expected-error{{incomplete result type 'Incomplete' in function definition}}\
+// expected-error{{variable has incomplete type 'Incomplete'}}
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -17379,6 +17379,21 @@
   }
 }
 
+void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
+   FnBodyKind BodyKind) {
+  switch (BodyKind) {
+  case FnBodyKind::Delete:
+SetDeclDeleted(D, Loc);
+break;
+  case FnBodyKind::Default:
+SetDeclDefaulted(D, Loc);
+break;
+  case FnBodyKind::Other:
+llvm_unreachable(
+"Parsed function body should be '= delete;' or '= default;'");
+  }
+}
+
 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
  const CXXMethodDecl *Old) {
   const auto *NewFT = New->getType()->castAs();
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -14185,7 +14185,7 @@
 Decl *
 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator ,
   MultiTemplateParamsArg TemplateParameterLists,
-  SkipBodyInfo *SkipBody) {
+  SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
   assert(D.isFunctionDeclarator() && "Not a function declarator!");
   Scope *ParentScope = FnBodyScope->getParent();
@@ -14204,7 +14204,7 @@
 
   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
-  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
+  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
 
   if (!Bases.empty())
 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
@@ -14380,7 +14380,8 @@
 }
 
 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
-SkipBodyInfo *SkipBody) {
+SkipBodyInfo *SkipBody,
+FnBodyKind BodyKind) {
   if (!D) {
 // Parsing the function declaration failed in some way. Push on a fake scope
 // anyway so we can try to parse the function body.
@@ -14469,11 +14470,11 @@
 }
   }
 
-  // The return type of a function definition must be complete
-  // (C99 6.9.1p3, C++ [dcl.fct]p6).
+  // The return type of a function definition must be complete (C99 6.9.1p3),
+  // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
   QualType ResultType = FD->getReturnType();
   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
-  !FD->isInvalidDecl() &&
+  !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
   RequireCompleteType(FD->getLocation(), ResultType,
   diag::err_func_def_incomplete_result))
 FD->setInvalidDecl();
@@ -14482,8 +14483,9 @@
 PushDeclContext(FnBodyScope, FD);
 
   // Check the validity of our function parameters
-  CheckParmsForFunctionDef(FD->parameters(),
-   /*CheckParameterNames=*/true);
+  if (BodyKind != FnBodyKind::Delete)
+CheckParmsForFunctionDef(FD->parameters(),
+ /*CheckParameterNames=*/true);
 
   // Add non-parameter declarations already in the function to the current
   // scope.
Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -1299,6 +1299,41 @@
   ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
  Scope::CompoundStmtScope);
 
+  // Parse function body 

[PATCH] D123319: Change how we handle auto return types for lambda operator() to be consistent with gcc

2022-04-07 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

(@probinson as someone I've disagreed with about this before)

Personally I think there's limited value in expressing 'auto' in DWARF at all - 
we could omit function declarations if the return type is not known (undeduced 
auto) and wouldn't lose much - basically treating them the same as templates 
that aren't instantiated yet. (& I believe Sony does this for all functions 
anyway - only including them when they're defined, not including an exhaustive 
list of member functions in class definitions)

Does anyone have particular DWARF consumer features they have built/would like 
to build that benefit from/require knowing that a function was defined with an 
`auto` return type?

Previously discussed/debated here: https://reviews.llvm.org/D70524


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

https://reviews.llvm.org/D123319

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


[PATCH] D123278: [Clang] [Docs] Add HLSLSupport page

2022-04-07 Thread Jakub Kuderski via Phabricator via cfe-commits
kuhar added inline comments.



Comment at: clang/docs/HLSLSupport.rst:190
+* RTTI
+* Exceptions
+* Multiple inheritance

How about goto and labels? Irreducible control flow? Are infinite loops valid?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123278

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


[PATCH] D123278: [Clang] [Docs] Add HLSLSupport page

2022-04-07 Thread Jakub Kuderski via Phabricator via cfe-commits
kuhar added a comment.

Looks good to me overall, I just left some local comments. Please take my 
writing suggestions with a pinch of salt, English is my second language.




Comment at: clang/docs/HLSLSupport.rst:13
+describes the high level goals of the project, the guiding principals, as well
+as some of the idiosyncrasies of the HLSL language and how we intend to support
+them in Clang.

ubernit: some of the idiosyncrasies -> some idiosyncrasies



Comment at: clang/docs/HLSLSupport.rst:22-23
+`_. in all its supported
+use cases. Accomplishing that goal will require a high level of source
+compatibility.
+

What do you mean by source compatibility in this case? In terms of the input 
source language (HLSL), or the source code of both implementations?

Perhaps we could make it more direct? E.g., 'This requires us to add the HLSL 
language support to Clang.'



Comment at: clang/docs/HLSLSupport.rst:28-31
+HLSL ASTs do not need to be compatible between DXC and Clang. We do not expect
+identical code generation or that features will resemble DXC's implementation 
or
+architecture. In fact, we explicitly expect to deviate from DXC's 
implementation
+in key ways.

It's great you made this so explicit!



Comment at: clang/docs/HLSLSupport.rst:36
+
+This document lacks precise details for architectural decisions that are not 
yet
+finalized. Our top priorities are quality, maintainability, and flexibility. In

ubernit: how about just 'details'?



Comment at: clang/docs/HLSLSupport.rst:50-52
+HLSL is not a formally or fully specified language, and while our goals require
+a high level of source compatibility, implementations can vary and we have some
+flexibility to be more or less permissive in some cases.

Is DXC the reference implementation?



Comment at: clang/docs/HLSLSupport.rst:55-56
+The HLSL effort prioritizes following similar patterns for other languages,
+drivers, runtimes and targets. Specifically, HLSL will create separate
+implementation files to contain the HLSL-specific behavior wherever it makes
+sense (i.e. ParseHLSL.cpp, SemaHLSL.cpp, CGHLSL*.cpp...). We will use inline

This is a bit awkward, as if the language HSLS created files on disk on 
something :P. 

Maybe something like: We will maintain separation between HSLS-specific code 
and the rest of Clang as much as possible (e.g., ParseHSLS.cpp, ...)



Comment at: clang/docs/HLSLSupport.rst:90-91
+metadata. *hand wave* *hand wave* *hand wave* As a design principle here we 
want
+our IR to be idiomatic Clang IR as much as possible. We will use IR attributes
+wherever we can, and use metadata as sparingly as possible. One example of a
+difference from DXC already implemented in Clang is the use of target triples 
to

Are all attributes guaranteed to be preserved? I thought some might get dropped 
by opt.



Comment at: clang/docs/HLSLSupport.rst:128
+HLSL does support member functions, and (in HLSL 2021) limited operator
+overloading. With member function support HLSL also has a ``this`` keyword. The
+``this`` keyword is an example of one of the places where HLSL relies on

nit: With member function support*,* HLSL also



Comment at: clang/docs/HLSLSupport.rst:135
+
+This is a simple one, but it deviates from C so is worth mentioning. HLSL
+bitshifts are defined to mask the shift count by the size of the type. In DXC,

nit: so *it* is worth?



Comment at: clang/docs/HLSLSupport.rst:137
+bitshifts are defined to mask the shift count by the size of the type. In DXC,
+the semantics of LLVM IR were altered to accomodate this, in Clang we intend to
+generate the mask explicitly in the IR.

accommodate



Comment at: clang/docs/HLSLSupport.rst:187
+
+HLSL does not support the following C++ features:
+

These are C++ language features. I assume that all library features are also 
out of the window?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123278

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


[PATCH] D102107: [OpenMP] Codegen aggregate for outlined function captures

2022-04-07 Thread Dhruva Chakrabarti via Phabricator via cfe-commits
dhruvachak added a comment.

In D102107#3434733 , @ggeorgakoudis 
wrote:

> In D102107#3417452 , @dhruvachak 
> wrote:
>
>> I added https://github.com/llvm/llvm-project/issues/54654 documenting what I 
>> found when testing this patch on amdgpu.
>>
>> @ggeorgakoudis Can you please rebase this patch on top of main? Thanks.
>
> Hey @dhruvachak. Unfortunately I can't find time lately to work on this 
> patch. Would you like to take over?

@ggeorgakoudis I rebased the sources on top of main and resolved conflicts in 
my local workspace. I haven't updated the clang/llvm tests. There are tests 
that fail on amdgpu that I am investigating. One example is 
https://github.com/llvm/llvm-project/issues/54654.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102107

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


[PATCH] D122981: [Clang] Diagnose incomplete return/param types only when function is not deleted

2022-04-07 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a comment.

This definitely looks like it is 'nicer' than before,  a few smaller/nit-ish 
comments.

Additionally, Phab made a REAL mess of the diff, if you could give a quick 
summary of what changes were actually made (vs things that were moved slightly 
and causing massive red/green diffs), it would be helpful.




Comment at: clang/include/clang/Sema/Sema.h:2906
+
+/// Not yet parsed
+/// Could be one of:





Comment at: clang/include/clang/Sema/Sema.h:2910
+///   function-try-block
+NotYetParsed
+  };

Might suggest 'Other'?  

Also, the EqDelete and EqDefault could probably just be Delete/Default and be 
equally as clear.



Comment at: clang/lib/Parse/Parser.cpp:1363
+if (BodyKind == Sema::FnBodyKind::EqDelete)
+  Actions.SetDeclDeleted(Res, KWLoc);
+else if (BodyKind == Sema::FnBodyKind::EqDefault)

Since the FnBodyKind is in Sema, I would suggest just adding a new function to 
replace all of this, "SetFunctionBodyKind(Res, BodyKind)", and make Sema do the 
'switch' here.



Comment at: clang/lib/Sema/SemaDecl.cpp:14474
   // The return type of a function definition must be complete
-  // (C99 6.9.1p3, C++ [dcl.fct]p6).
+  // unless the function is deleted
+  // (C99 6.9.1p3, C++ [dcl.fct.def.general]p2).

This is C++ specific, so could we be specific about that here?


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

https://reviews.llvm.org/D122981

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


[PATCH] D101624: [clang-tidy] Make performance-inefficient-vector-operation work on members

2022-04-07 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.
Herald added a project: All.

Ping?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D101624

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


[PATCH] D97121: [clang-tidy] Add a Standalone diagnostics mode to clang-tidy

2022-04-07 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 421310.
njames93 added a comment.
Herald added a project: All.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D97121

Files:
  clang-tools-extra/clang-tidy/ClangTidyCheck.h
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
  clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp
  
clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp
  clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
  
clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp
  clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp
  clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp
  clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/PassByValueCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp
  clang-tools-extra/clang-tidy/modernize/ReplaceRandomShuffleCheck.cpp
  clang-tools-extra/clang-tidy/performance/TypePromotionInMathFnCheck.cpp
  clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
  clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp
  clang-tools-extra/clang-tidy/utils/IncludeInserter.h
  clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/IncludeInserterTest.cpp
@@ -30,8 +30,10 @@
 public:
   IncludeInserterCheckBase(StringRef CheckName, ClangTidyContext *Context,
utils::IncludeSorter::IncludeStyle Style =
-   utils::IncludeSorter::IS_Google)
-  : ClangTidyCheck(CheckName, Context), Inserter(Style) {}
+   utils::IncludeSorter::IS_Google,
+   bool SelfContainedDiags = false)
+  : ClangTidyCheck(CheckName, Context),
+Inserter(Style, SelfContainedDiags) {}
 
   void registerPPCallbacks(const SourceManager , Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override {
@@ -85,6 +87,19 @@
   }
 };
 
+class MultipleHeaderSingleInserterCheck : public IncludeInserterCheckBase {
+public:
+  MultipleHeaderSingleInserterCheck(StringRef CheckName,
+ClangTidyContext *Context)
+  : IncludeInserterCheckBase(CheckName, Context,
+ utils::IncludeSorter::IS_Google,
+ /*SelfContainedDiags=*/true) {}
+
+  std::vector headersToInclude() const override {
+return {"path/to/header.h", "path/to/header2.h", "path/to/header.h"};
+  }
+};
+
 class CSystemIncludeInserterCheck : public IncludeInserterCheckBase {
 public:
   CSystemIncludeInserterCheck(StringRef CheckName, ClangTidyContext *Context)
@@ -246,6 +261,41 @@
 PreCode, "clang_tidy/tests/insert_includes_test_input2.cc"));
 }
 
+TEST(IncludeInserterTest, InsertMultipleIncludesNoDeduplicate) {
+  const char *PreCode = R"(
+#include "clang_tidy/tests/insert_includes_test_header.h"
+
+#include 
+#include 
+
+#include "path/to/a/header.h"
+
+void foo() {
+  int a = 0;
+})";
+  // FIXME: ClangFormat bug - https://bugs.llvm.org/show_bug.cgi?id=49298
+  // clang-format off
+  const char *PostCode = R"(
+#include "clang_tidy/tests/insert_includes_test_header.h"
+
+#include 
+#include 
+
+#include "path/to/a/header.h"
+#include "path/to/header.h"
+#include "path/to/header2.h"
+#include "path/to/header.h"
+
+void foo() {
+  int a = 0;
+})";
+  // clang-format on
+
+  EXPECT_EQ(PostCode,
+runCheckOnCode(
+PreCode, "clang_tidy/tests/insert_includes_test_input2.cc"));
+}
+
 TEST(IncludeInserterTest, InsertBeforeFirstNonSystemInclude) {
   const char *PreCode = R"(
 #include "clang_tidy/tests/insert_includes_test_header.h"
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -678,6 +678,67 @@
   Diag(Main.range(), "do not use 'else' after 'return'";
 }
 
+TEST(DiagnosticTest, ClangTidySelfContainedDiags) {
+  Annotations Main(R"cpp($MathHeader[[]]
+struct Foo{
+  int A, B;
+  Foo()$Fix[[]] {
+$A[[A = 1;]]
+$B[[B = 1;]]
+  }
+};
+void InitVariables() {
+ 

[PATCH] D121176: [ASTStructuralEquivalence] Add support for comparing ObjCCategoryDecl.

2022-04-07 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121176

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


[PATCH] D122981: [Clang] Diagnose incomplete return/param types only when function is not deleted

2022-04-07 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao marked an inline comment as done.
rZhBoYao added inline comments.



Comment at: clang/lib/Parse/Parser.cpp:1306
+  bool Delete =
+  Tok.is(tok::equal) && NextToken().is(tok::kw_delete) ? true : false;
   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,

rZhBoYao wrote:
> erichkeane wrote:
> > rZhBoYao wrote:
> > > erichkeane wrote:
> > > > I'm not sure about doing this 'look ahead' here, this feels dangerous 
> > > > to me.  First, does this work with comments?  Second, it seems we 
> > > > wouldn't normally look at 'deleted' if SkipBody.ShouldSkip (see below 
> > > > with the early exit)?
> > > > 
> > > > Next I'm not a fan of double-parsing these tokens with this lookahead.  
> > > > I wonder, if we should move hte logic from ~1334 and 1338 up here and 
> > > > calculate the 'deleted'/'defaulted' 'earlier', before we 
> > > > 'actOnStartOfFunctionDef`.  
> > > > 
> > > > This would result in us being able to instead change the signature of 
> > > > ActOnStartOfFunctionDef to take some enum as to whether it is 
> > > > deleted/defaulted, AND create the function decl as deleted/defaulted 
> > > > 'in place' (or, at least, call SetDeclDeleted or SetDeclDefaulted 
> > > > immediately).
> > > > 
> > > > 
> > > > 
> > > > 
> > > > I'm not sure about doing this 'look ahead' here, this feels dangerous 
> > > > to me. First, does this work with comments?
> > > Yes, it returns a normal token after phase 5, so comments are long gone.
> > > 
> > > > Second, it seems we wouldn't normally look at 'deleted' if 
> > > > SkipBody.ShouldSkip (see below with the early exit)?
> > > SkipBody.ShouldSkip is an output parameter of `ActOnStartOfFunctionDef`. 
> > > We need to either look ahead or consume "delete" before entering 
> > > `ActOnStartOfFunctionDef` anyway.
> > > 
> > > > Next I'm not a fan of double-parsing these tokens with this lookahead.
> > > It does look weird. Consume them I will. Updated diff coming.
> > > 
> > > > AND create the function decl as deleted/defaulted 'in place' (or, at 
> > > > least, call SetDeclDeleted or SetDeclDefaulted immediately).
> > > SetDecl{Deleted | Defaulted} needs KWLoc tho. I haven't thought of a way 
> > > of doing that "in place" inside `ActOnStartOfFunctionDef`.
> > My point is: do that parsing in this function BEFORE the call to 
> > ActOnStartOfFunctionDef?
> > 
> > Alternatively, we could add a function to Sema to 
> > 'ActOnFunctionDefinition(DefType)' and move this diagnostic THERE instead 
> > of ActOnStartofFunctionDef, and call it AFTER we have handled the '= 
> > delete/=default/etc'.
> > do that parsing in this function BEFORE the call to ActOnStartOfFunctionDef?
> But we need Decl *Res returned by ActOnStartOfFunctionDef.
> 
> I did try to factor out the diagnostic right after `ActOnFunctionDefinition` 
> and 27 tests were failing.
> Furthermore, we are not the only caller of `ActOnFunctionDefinition`.
I meant to say `ActOnStartOfFunctionDef`.


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

https://reviews.llvm.org/D122981

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


[PATCH] D122981: [Clang] Diagnose incomplete return/param types only when function is not deleted

2022-04-07 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao updated this revision to Diff 421305.
rZhBoYao added a comment.

Handling of eagerly parsed deleted or defaulted function must happen AFTER 
`D.complete(Res);`.

A nice looking diff: 
https://github.com/poyaoc97/llvm-project/commit/dc37a262582f6a2d8143c6f1f586dc657b4b5311


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

https://reviews.llvm.org/D122981

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp

Index: clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp
===
--- /dev/null
+++ clang/test/CXX/dcl.decl/dcl.fct.def/dcl.fct.def.general/p2.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+struct Incomplete; // expected-note 4{{forward declaration of 'Incomplete'}}
+Incomplete f(Incomplete) = delete; // well-formed
+Incomplete g(Incomplete) {}// expected-error{{incomplete result type 'Incomplete' in function definition}}\
+// expected-error{{variable has incomplete type 'Incomplete'}}
+
+struct C {
+  Incomplete f(Incomplete) = delete; // well-formed
+  Incomplete g(Incomplete) {}// expected-error{{incomplete result type 'Incomplete' in function definition}}\
+  // expected-error{{variable has incomplete type 'Incomplete'}}
+};
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -14185,7 +14185,7 @@
 Decl *
 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator ,
   MultiTemplateParamsArg TemplateParameterLists,
-  SkipBodyInfo *SkipBody) {
+  SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
   assert(D.isFunctionDeclarator() && "Not a function declarator!");
   Scope *ParentScope = FnBodyScope->getParent();
@@ -14204,7 +14204,7 @@
 
   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
-  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
+  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
 
   if (!Bases.empty())
 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
@@ -14380,7 +14380,8 @@
 }
 
 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
-SkipBodyInfo *SkipBody) {
+SkipBodyInfo *SkipBody,
+FnBodyKind BodyKind) {
   if (!D) {
 // Parsing the function declaration failed in some way. Push on a fake scope
 // anyway so we can try to parse the function body.
@@ -14470,10 +14471,11 @@
   }
 
   // The return type of a function definition must be complete
-  // (C99 6.9.1p3, C++ [dcl.fct]p6).
+  // unless the function is deleted
+  // (C99 6.9.1p3, C++ [dcl.fct.def.general]p2).
   QualType ResultType = FD->getReturnType();
   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
-  !FD->isInvalidDecl() &&
+  !FD->isInvalidDecl() && BodyKind != FnBodyKind::EqDelete &&
   RequireCompleteType(FD->getLocation(), ResultType,
   diag::err_func_def_incomplete_result))
 FD->setInvalidDecl();
@@ -14482,8 +14484,9 @@
 PushDeclContext(FnBodyScope, FD);
 
   // Check the validity of our function parameters
-  CheckParmsForFunctionDef(FD->parameters(),
-   /*CheckParameterNames=*/true);
+  if (BodyKind != FnBodyKind::EqDelete)
+CheckParmsForFunctionDef(FD->parameters(),
+ /*CheckParameterNames=*/true);
 
   // Add non-parameter declarations already in the function to the current
   // scope.
Index: clang/lib/Parse/Parser.cpp
===
--- clang/lib/Parse/Parser.cpp
+++ clang/lib/Parse/Parser.cpp
@@ -1299,6 +1299,41 @@
   ParseScope BodyScope(this, Scope::FnScope | Scope::DeclScope |
  Scope::CompoundStmtScope);
 
+  // Parse function body eagerly if it is either '= delete;' or '= default;' as
+  // ActOnStartOfFunctionDef needs to know whether the function is deleted.
+  Sema::FnBodyKind BodyKind = Sema::FnBodyKind::NotYetParsed;
+  SourceLocation KWLoc;
+  if (TryConsumeToken(tok::equal)) {
+assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='");
+
+if (TryConsumeToken(tok::kw_delete, KWLoc)) {
+  Diag(KWLoc, getLangOpts().CPlusPlus11
+  ? diag::warn_cxx98_compat_defaulted_deleted_function
+  : diag::ext_defaulted_deleted_function)
+  << 1 /* deleted */;
+  BodyKind = Sema::FnBodyKind::EqDelete;
+} else if 

[PATCH] D122981: [Clang] Diagnose incomplete return/param types only when function is not deleted

2022-04-07 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao marked 2 inline comments as done.
rZhBoYao added inline comments.



Comment at: clang/lib/Parse/Parser.cpp:1306
+  bool Delete =
+  Tok.is(tok::equal) && NextToken().is(tok::kw_delete) ? true : false;
   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,

erichkeane wrote:
> rZhBoYao wrote:
> > erichkeane wrote:
> > > I'm not sure about doing this 'look ahead' here, this feels dangerous to 
> > > me.  First, does this work with comments?  Second, it seems we wouldn't 
> > > normally look at 'deleted' if SkipBody.ShouldSkip (see below with the 
> > > early exit)?
> > > 
> > > Next I'm not a fan of double-parsing these tokens with this lookahead.  I 
> > > wonder, if we should move hte logic from ~1334 and 1338 up here and 
> > > calculate the 'deleted'/'defaulted' 'earlier', before we 
> > > 'actOnStartOfFunctionDef`.  
> > > 
> > > This would result in us being able to instead change the signature of 
> > > ActOnStartOfFunctionDef to take some enum as to whether it is 
> > > deleted/defaulted, AND create the function decl as deleted/defaulted 'in 
> > > place' (or, at least, call SetDeclDeleted or SetDeclDefaulted 
> > > immediately).
> > > 
> > > 
> > > 
> > > 
> > > I'm not sure about doing this 'look ahead' here, this feels dangerous to 
> > > me. First, does this work with comments?
> > Yes, it returns a normal token after phase 5, so comments are long gone.
> > 
> > > Second, it seems we wouldn't normally look at 'deleted' if 
> > > SkipBody.ShouldSkip (see below with the early exit)?
> > SkipBody.ShouldSkip is an output parameter of `ActOnStartOfFunctionDef`. We 
> > need to either look ahead or consume "delete" before entering 
> > `ActOnStartOfFunctionDef` anyway.
> > 
> > > Next I'm not a fan of double-parsing these tokens with this lookahead.
> > It does look weird. Consume them I will. Updated diff coming.
> > 
> > > AND create the function decl as deleted/defaulted 'in place' (or, at 
> > > least, call SetDeclDeleted or SetDeclDefaulted immediately).
> > SetDecl{Deleted | Defaulted} needs KWLoc tho. I haven't thought of a way of 
> > doing that "in place" inside `ActOnStartOfFunctionDef`.
> My point is: do that parsing in this function BEFORE the call to 
> ActOnStartOfFunctionDef?
> 
> Alternatively, we could add a function to Sema to 
> 'ActOnFunctionDefinition(DefType)' and move this diagnostic THERE instead of 
> ActOnStartofFunctionDef, and call it AFTER we have handled the '= 
> delete/=default/etc'.
> do that parsing in this function BEFORE the call to ActOnStartOfFunctionDef?
But we need Decl *Res returned by ActOnStartOfFunctionDef.

I did try to factor out the diagnostic right after `ActOnFunctionDefinition` 
and 27 tests were failing.
Furthermore, we are not the only caller of `ActOnFunctionDefinition`.


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

https://reviews.llvm.org/D122981

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


[clang] da1fc3a - [Driver][NFC] Simplify handling of flags in Options.td

2022-04-07 Thread Emil Kieri via cfe-commits

Author: Emil Kieri
Date: 2022-04-07T20:38:51+02:00
New Revision: da1fc3ae955da47dc43d8d2e8f4d5a52deac7cf9

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

LOG: [Driver][NFC] Simplify handling of flags in Options.td

We aim at improving the readability and maintainability of Options.td,
and in particular its handling of 'Flags', by
 - limiting the extent of 'let Flags = [...] in {'s, and
 - adding closing comments to matching '}'s.
 - being more consistent about empty lines around 'let Flags' and '}'.

More concretely,
 - we do not let a 'let Flags' span across several headline comments.
   When all 'def's in two consecutive headlines share the same flags,
   we stil close and start a new 'let Flags' at the intermediate
   headline.
 - when a 'let Flags' span just one or two 'def's, set 'Flags' within
   the 'def's instead.
 - we remove nested 'let Flags'.

Note that nested 'let Flags' can be quite confusing, especially when
the outer was started long before the inner. Moving a 'def' out of the
inner 'let Flags' and setting 'Flags' within the 'def' will not have the
intended effect, as those flags will be overridden by the outer
'let Flags'.

Reviewed By: awarzynski, jansvoboda11, hans

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 0f7cfa7eb883f..2e4b9f347ba5f 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4690,15 +4690,16 @@ def fno_sycl : Flag<["-"], "fno-sycl">, 
Flags<[NoXarchOption, CoreOption]>,
 
//===--===//
 // FLangOption + CoreOption + NoXarchOption
 
//===--===//
-let Flags = [FlangOption, FlangOnlyOption, NoXarchOption, CoreOption] in {
+
 def Xflang : Separate<["-"], "Xflang">,
   HelpText<"Pass  to the flang compiler">, MetaVarName<"">,
-  Flags<[NoXarchOption, CoreOption]>, Group;
-}
+  Flags<[FlangOption, FlangOnlyOption, NoXarchOption, CoreOption]>,
+  Group;
 
 
//===--===//
 // FlangOption and FC1 Options
 
//===--===//
+
 let Flags = [FC1Option, FlangOption, FlangOnlyOption] in {
 
 def cpp : Flag<["-"], "cpp">, Group,
@@ -4745,7 +4746,8 @@ defm implicit_none : OptInFC1FFlag<"implicit-none", "No 
implicit typing allowed
 
 def fno_automatic : Flag<["-"], "fno-automatic">, Group,
   HelpText<"Implies the SAVE attribute for non-automatic local objects in 
subprograms unless RECURSIVE">;
-}
+
+} // let Flags = [FC1Option, FlangOption, FlangOnlyOption]
 
 def J : JoinedOrSeparate<["-"], "J">,
   Flags<[RenderJoined, FlangOption, FC1Option, FlangOnlyOption]>,
@@ -4755,6 +4757,7 @@ def J : JoinedOrSeparate<["-"], "J">,
 
//===--===//
 // FC1 Options
 
//===--===//
+
 let Flags = [FC1Option, FlangOnlyOption] in {
 
 def fget_definition : MultiArg<["-"], "fget-definition", 3>,
@@ -4809,13 +4812,7 @@ def emit_mlir : Flag<["-"], "emit-mlir">, 
Group,
   HelpText<"Build the parse tree, then lower it to MLIR">;
 def emit_fir : Flag<["-"], "emit-fir">, Alias;
 
-}
-
-//===--===//
-// CC1 Options
-//===--===//
-
-let Flags = [CC1Option, NoDriverOption] in {
+} // let Flags = [FC1Option, FlangOnlyOption]
 
 
//===--===//
 // Target Options (cc1 + cc1as)
@@ -4850,6 +4847,7 @@ def darwin_target_variant_sdk_version_EQ : Joined<["-"],
 
//===--===//
 // Target Options (cc1 + cc1as + fc1)
 
//===--===//
+
 let Flags = [CC1Option, CC1AsOption, FC1Option, NoDriverOption] in {
 
 def triple : Separate<["-"], "triple">,
@@ -4863,6 +4861,8 @@ def triple : Separate<["-"], "triple">,
 // Target Options (other)
 
//===--===//
 
+let Flags = [CC1Option, NoDriverOption] in {
+
 def target_linker_version : Separate<["-"], "target-linker-version">,
   HelpText<"Target linker version">,
   MarshallingInfoString>;
@@ -4877,10 +4877,14 @@ defm padding_on_unsigned_fixed_point : BoolOption<"f", 
"padding-on-unsigned-fixe
   NegFlag>,
   ShouldParseIf;
 
+} // 

[PATCH] D123070: [Driver][NFC] Simplify handling of flags in Options.td

2022-04-07 Thread Emil Kieri via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGda1fc3ae955d: [Driver][NFC] Simplify handling of flags in 
Options.td (authored by ekieri).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123070

Files:
  clang/include/clang/Driver/Options.td

Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -4690,15 +4690,16 @@
 //===--===//
 // FLangOption + CoreOption + NoXarchOption
 //===--===//
-let Flags = [FlangOption, FlangOnlyOption, NoXarchOption, CoreOption] in {
+
 def Xflang : Separate<["-"], "Xflang">,
   HelpText<"Pass  to the flang compiler">, MetaVarName<"">,
-  Flags<[NoXarchOption, CoreOption]>, Group;
-}
+  Flags<[FlangOption, FlangOnlyOption, NoXarchOption, CoreOption]>,
+  Group;
 
 //===--===//
 // FlangOption and FC1 Options
 //===--===//
+
 let Flags = [FC1Option, FlangOption, FlangOnlyOption] in {
 
 def cpp : Flag<["-"], "cpp">, Group,
@@ -4745,7 +4746,8 @@
 
 def fno_automatic : Flag<["-"], "fno-automatic">, Group,
   HelpText<"Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE">;
-}
+
+} // let Flags = [FC1Option, FlangOption, FlangOnlyOption]
 
 def J : JoinedOrSeparate<["-"], "J">,
   Flags<[RenderJoined, FlangOption, FC1Option, FlangOnlyOption]>,
@@ -4755,6 +4757,7 @@
 //===--===//
 // FC1 Options
 //===--===//
+
 let Flags = [FC1Option, FlangOnlyOption] in {
 
 def fget_definition : MultiArg<["-"], "fget-definition", 3>,
@@ -4809,13 +4812,7 @@
   HelpText<"Build the parse tree, then lower it to MLIR">;
 def emit_fir : Flag<["-"], "emit-fir">, Alias;
 
-}
-
-//===--===//
-// CC1 Options
-//===--===//
-
-let Flags = [CC1Option, NoDriverOption] in {
+} // let Flags = [FC1Option, FlangOnlyOption]
 
 //===--===//
 // Target Options (cc1 + cc1as)
@@ -4850,6 +4847,7 @@
 //===--===//
 // Target Options (cc1 + cc1as + fc1)
 //===--===//
+
 let Flags = [CC1Option, CC1AsOption, FC1Option, NoDriverOption] in {
 
 def triple : Separate<["-"], "triple">,
@@ -4863,6 +4861,8 @@
 // Target Options (other)
 //===--===//
 
+let Flags = [CC1Option, NoDriverOption] in {
+
 def target_linker_version : Separate<["-"], "target-linker-version">,
   HelpText<"Target linker version">,
   MarshallingInfoString>;
@@ -4877,10 +4877,14 @@
   NegFlag>,
   ShouldParseIf;
 
+} // let Flags = [CC1Option, NoDriverOption]
+
 //===--===//
 // Analyzer Options
 //===--===//
 
+let Flags = [CC1Option, NoDriverOption] in {
+
 def analysis_UnoptimizedCFG : Flag<["-"], "unoptimized-cfg">,
   HelpText<"Generate unoptimized CFGs for all analyses">,
   MarshallingInfoFlag>;
@@ -5031,15 +5035,20 @@
   HelpText<"Emit analyzer results as errors rather than warnings">,
   MarshallingInfoFlag>;
 
+} // let Flags = [CC1Option, NoDriverOption]
+
 //===--===//
 // Migrator Options
 //===--===//
+
 def migrator_no_nsalloc_error : Flag<["-"], "no-ns-alloc-error">,
   HelpText<"Do not error on use of NSAllocateCollectable/NSReallocateCollectable">,
+  Flags<[CC1Option, NoDriverOption]>,
   MarshallingInfoFlag>;
 
 def migrator_no_finalize_removal : Flag<["-"], "no-finalize-removal">,
   HelpText<"Do not remove finalize method in gc mode">,
+  Flags<[CC1Option, NoDriverOption]>,
   MarshallingInfoFlag>;
 
 //===--===//
@@ -5047,6 +5056,7 @@
 //===--===//
 
 let Flags = [CC1Option, CC1AsOption, NoDriverOption] in {
+
 def debug_info_kind_EQ : Joined<["-"], "debug-info-kind=">;
 def debug_info_macro : Flag<["-"], "debug-info-macro">,
   HelpText<"Emit macro debug information">,
@@ -5101,7 +5111,10 @@
 HelpText<"Don't use 

[PATCH] D123304: [clang][extract-api] Emit "functionSignature" in SGF for ObjC methods.

2022-04-07 Thread Zixu Wang via Phabricator via cfe-commits
zixuw added inline comments.



Comment at: clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp:495
 
+if (const auto *Method = dyn_cast(Member.get()))
+  serializeObject(*MemberRecord, "functionSignature",

I'd prefer not to use `dyn_cast` as `MemberTy` here is a concrete type. So 
maybe a type trait `has_function_signature` and a `if constexpr`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123304

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


[PATCH] D121637: [PowerPC] Fix EmitPPCBuiltinExpr to emit arguments once

2022-04-07 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 421303.
quinnp added a comment.

Fixing a set of builtins added by the rebase with main.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121637

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/PowerPC/builtins-ppc-fastmath.c
  clang/test/CodeGen/PowerPC/builtins-ppc-pair-mma-types.c
  clang/test/CodeGen/PowerPC/builtins-ppc-stmtexpr-argument.c
  clang/test/CodeGen/PowerPC/builtins-ppc-vsx.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cas.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-fetch.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-fp.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-math.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync.c
  clang/test/CodeGen/PowerPC/ppc-mma-types.c
  clang/test/Sema/ppc-pair-mma-types.c

Index: clang/test/Sema/ppc-pair-mma-types.c
===
--- clang/test/Sema/ppc-pair-mma-types.c
+++ clang/test/Sema/ppc-pair-mma-types.c
@@ -12,11 +12,6 @@
 
 // typedef
 typedef __vector_quad vq_t;
-void testVQTypedef(int *inp, int *outp) {
-  vq_t *vqin = (vq_t *)inp;
-  vq_t *vqout = (vq_t *)outp;
-  *vqout = *vqin;
-}
 
 // function argument
 void testVQArg1(__vector_quad vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
@@ -29,57 +24,22 @@
   *vqp = vq;
 }
 
-void testVQArg3(__vector_quad *vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
-void testVQArg4(const __vector_quad *const vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
-void testVQArg5(__vector_quad vqa[], int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = vqa[0];
-}
-
 void testVQArg6(const vq_t vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   *vqp = vq;
 }
 
-void testVQArg7(const vq_t *vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
 // function return
 __vector_quad testVQRet1(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   return *vqp; // expected-error {{invalid use of PPC MMA type}}
 }
 
-__vector_quad *testVQRet2(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
-const __vector_quad *testVQRet3(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
 const vq_t testVQRet4(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   return *vqp; // expected-error {{invalid use of PPC MMA type}}
 }
 
-const vq_t *testVQRet5(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
 // global
 __vector_quad globalvq;// expected-error {{invalid use of PPC MMA type}}
 const __vector_quad globalvq2; // expected-error {{invalid use of PPC MMA type}}
@@ -87,16 +47,6 @@
 const __vector_quad *const globalvqp2;
 vq_t globalvq_t; // expected-error {{invalid use of PPC MMA type}}
 
-// local
-void testVQLocal(int *ptr, vector unsigned char vc) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  __vector_quad vq1 = *vqp;
-  __vector_quad vq2;
-  __builtin_mma_xxsetaccz();
-  __vector_quad vq3;
-  __builtin_mma_xvi4ger8(, vc, vc);
-  *vqp = vq3;
-}
 
 // struct field
 struct TestVQStruct {
@@ -106,17 +56,6 @@
   __vector_quad *vq;
 };
 
-// sizeof / alignof
-int testVQSizeofAlignof(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  __vector_quad vq = *vqp;
-  unsigned sizet = sizeof(__vector_quad);
-  unsigned alignt = __alignof__(__vector_quad);
-  unsigned sizev = sizeof(vq);
-  unsigned alignv = __alignof__(vq);
-  return sizet + alignt + sizev + alignv;
-}
-
 // operators
 int testVQOperators1(int *ptr) {
   __vector_quad *vqp = (__vector_quad *)ptr;
@@ -168,11 +107,6 @@
 
 // typedef
 typedef __vector_pair vp_t;
-void testVPTypedef(int *inp, int *outp) {
-  vp_t *vpin = (vp_t *)inp;
-  vp_t *vpout = (vp_t *)outp;
-  *vpout = *vpin;
-}
 
 // function argument
 void testVPArg1(__vector_pair vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
@@ -185,57 +119,22 @@
   *vpp = vp;
 }
 
-void testVPArg3(__vector_pair *vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
-void testVPArg4(const __vector_pair *const vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
-void testVPArg5(__vector_pair vpa[], int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = vpa[0];
-}
-
 void testVPArg6(const vp_t vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_pair *vpp = (__vector_pair *)ptr;
   *vpp = vp;
 }
 
-void testVPArg7(const vp_t *vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
 // function return
 __vector_pair testVPRet1(int *ptr) { // expected-error {{invalid 

[PATCH] D122981: [Clang] Diagnose incomplete return/param types only when function is not deleted

2022-04-07 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Parse/Parser.cpp:1306
+  bool Delete =
+  Tok.is(tok::equal) && NextToken().is(tok::kw_delete) ? true : false;
   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,

rZhBoYao wrote:
> erichkeane wrote:
> > I'm not sure about doing this 'look ahead' here, this feels dangerous to 
> > me.  First, does this work with comments?  Second, it seems we wouldn't 
> > normally look at 'deleted' if SkipBody.ShouldSkip (see below with the early 
> > exit)?
> > 
> > Next I'm not a fan of double-parsing these tokens with this lookahead.  I 
> > wonder, if we should move hte logic from ~1334 and 1338 up here and 
> > calculate the 'deleted'/'defaulted' 'earlier', before we 
> > 'actOnStartOfFunctionDef`.  
> > 
> > This would result in us being able to instead change the signature of 
> > ActOnStartOfFunctionDef to take some enum as to whether it is 
> > deleted/defaulted, AND create the function decl as deleted/defaulted 'in 
> > place' (or, at least, call SetDeclDeleted or SetDeclDefaulted immediately).
> > 
> > 
> > 
> > 
> > I'm not sure about doing this 'look ahead' here, this feels dangerous to 
> > me. First, does this work with comments?
> Yes, it returns a normal token after phase 5, so comments are long gone.
> 
> > Second, it seems we wouldn't normally look at 'deleted' if 
> > SkipBody.ShouldSkip (see below with the early exit)?
> SkipBody.ShouldSkip is an output parameter of `ActOnStartOfFunctionDef`. We 
> need to either look ahead or consume "delete" before entering 
> `ActOnStartOfFunctionDef` anyway.
> 
> > Next I'm not a fan of double-parsing these tokens with this lookahead.
> It does look weird. Consume them I will. Updated diff coming.
> 
> > AND create the function decl as deleted/defaulted 'in place' (or, at least, 
> > call SetDeclDeleted or SetDeclDefaulted immediately).
> SetDecl{Deleted | Defaulted} needs KWLoc tho. I haven't thought of a way of 
> doing that "in place" inside `ActOnStartOfFunctionDef`.
My point is: do that parsing in this function BEFORE the call to 
ActOnStartOfFunctionDef?

Alternatively, we could add a function to Sema to 
'ActOnFunctionDefinition(DefType)' and move this diagnostic THERE instead of 
ActOnStartofFunctionDef, and call it AFTER we have handled the '= 
delete/=default/etc'.


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

https://reviews.llvm.org/D122981

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


[clang] 50de659 - [clang] Use -triple, not -target for %clang_cc1

2022-04-07 Thread Alex Brachet via cfe-commits

Author: Alex Brachet
Date: 2022-04-07T18:19:54Z
New Revision: 50de659adcc19c4c197ba5e9a7719325af7151ee

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

LOG: [clang] Use -triple, not -target for %clang_cc1

Added: 


Modified: 
clang/test/CodeGen/debug-info-alias.c

Removed: 




diff  --git a/clang/test/CodeGen/debug-info-alias.c 
b/clang/test/CodeGen/debug-info-alias.c
index 5d26b4b8f93d4..1f5e477af96aa 100644
--- a/clang/test/CodeGen/debug-info-alias.c
+++ b/clang/test/CodeGen/debug-info-alias.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited %s -target 
x86_64-unknown-linux-gnu -o - | FileCheck %s
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited %s -triple 
x86_64-unknown-linux-gnu -o - | FileCheck %s
 
 // CHECK-DAG: [[ENTITY1:![0-9]+]] = distinct !DIGlobalVariable(name: 
"aliased_global"
 // CHECK-DAG: [[ENTITY2:![0-9]+]] = distinct !DIGlobalVariable(name: 
"aliased_global_2"



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


[clang] 3329dae - [clang] Fix macos build broken after D120989

2022-04-07 Thread Alex Brachet via cfe-commits

Author: Alex Brachet
Date: 2022-04-07T18:17:29Z
New Revision: 3329dae5cb8a8c91c518dd87c09e88c4fad507bd

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

LOG: [clang] Fix macos build broken after D120989

Added: 


Modified: 
clang/test/CodeGen/debug-info-alias.c

Removed: 




diff  --git a/clang/test/CodeGen/debug-info-alias.c 
b/clang/test/CodeGen/debug-info-alias.c
index 45e9fbec83d70..5d26b4b8f93d4 100644
--- a/clang/test/CodeGen/debug-info-alias.c
+++ b/clang/test/CodeGen/debug-info-alias.c
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited %s -target 
x86_64-unknown-linux-gnu -o - | FileCheck %s
 
 // CHECK-DAG: [[ENTITY1:![0-9]+]] = distinct !DIGlobalVariable(name: 
"aliased_global"
 // CHECK-DAG: [[ENTITY2:![0-9]+]] = distinct !DIGlobalVariable(name: 
"aliased_global_2"



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


[PATCH] D122981: [Clang] Diagnose incomplete return/param types only when function is not deleted

2022-04-07 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao marked 3 inline comments as done.
rZhBoYao added inline comments.



Comment at: clang/lib/Parse/Parser.cpp:1306
+  bool Delete =
+  Tok.is(tok::equal) && NextToken().is(tok::kw_delete) ? true : false;
   Decl *Res = Actions.ActOnStartOfFunctionDef(getCurScope(), D,

erichkeane wrote:
> I'm not sure about doing this 'look ahead' here, this feels dangerous to me.  
> First, does this work with comments?  Second, it seems we wouldn't normally 
> look at 'deleted' if SkipBody.ShouldSkip (see below with the early exit)?
> 
> Next I'm not a fan of double-parsing these tokens with this lookahead.  I 
> wonder, if we should move hte logic from ~1334 and 1338 up here and calculate 
> the 'deleted'/'defaulted' 'earlier', before we 'actOnStartOfFunctionDef`.  
> 
> This would result in us being able to instead change the signature of 
> ActOnStartOfFunctionDef to take some enum as to whether it is 
> deleted/defaulted, AND create the function decl as deleted/defaulted 'in 
> place' (or, at least, call SetDeclDeleted or SetDeclDefaulted immediately).
> 
> 
> 
> 
> I'm not sure about doing this 'look ahead' here, this feels dangerous to me. 
> First, does this work with comments?
Yes, it returns a normal token after phase 5, so comments are long gone.

> Second, it seems we wouldn't normally look at 'deleted' if 
> SkipBody.ShouldSkip (see below with the early exit)?
SkipBody.ShouldSkip is an output parameter of `ActOnStartOfFunctionDef`. We 
need to either look ahead or consume "delete" before entering 
`ActOnStartOfFunctionDef` anyway.

> Next I'm not a fan of double-parsing these tokens with this lookahead.
It does look weird. Consume them I will. Updated diff coming.

> AND create the function decl as deleted/defaulted 'in place' (or, at least, 
> call SetDeclDeleted or SetDeclDefaulted immediately).
SetDecl{Deleted | Defaulted} needs KWLoc tho. I haven't thought of a way of 
doing that "in place" inside `ActOnStartOfFunctionDef`.



Comment at: clang/lib/Sema/SemaDecl.cpp:14461
   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
-  !FD->isInvalidDecl() &&
+  !FD->isInvalidDecl() && !FnDeleted &&
   RequireCompleteType(FD->getLocation(), ResultType,

erichkeane wrote:
> ChuanqiXu wrote:
> > rZhBoYao wrote:
> > > ChuanqiXu wrote:
> > > > I think we could remove the use of `FnDeleted` by the use of 
> > > > `FD->isDeleted()`. Also we should constrain the behavior only if std >= 
> > > > 11.
> > > I tried `FD->isDeleted()` at first only to find out it always returns 
> > > `false`. Looks like it's not handled until [[ 
> > > https://github.com/llvm/llvm-project/blob/634bf829a8d289371d5b5a50b787596124228898/clang/lib/Parse/Parser.cpp#L1342
> > >  | Parser.cpp:1342 ]]
> > > 
> > > Also, looks like deleted functions are implemented as an extension. A 
> > > warning is issued at [[ 
> > > https://github.com/llvm/llvm-project/blob/634bf829a8d289371d5b5a50b787596124228898/clang/lib/Parse/Parser.cpp#L1338-L1341
> > >  | Parser.cpp:1338 ]] if language mode < C++11
> > I see. My suggestion might be to defer the diagnose message after we set 
> > `FD->setDeletedAsWritten()`. I understand it might be harder. But the 
> > current implementation looks a little bit not good... (redundant variables 
> > and passing information by argument)
> I disagree on doing this for C++11 mode.  As we allow them as an extension, 
> we want this to work in the extension mode as well.
Thanks for the endorsement.


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

https://reviews.llvm.org/D122981

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


[clang-tools-extra] d0fcbb3 - [clang-tidy] Fix invalid fix-it for cppcoreguidelines-prefer-member-initializer

2022-04-07 Thread Nathan James via cfe-commits

Author: Nathan James
Date: 2022-04-07T19:13:50+01:00
New Revision: d0fcbb37838a653c1c3f8d6ac83e64714c407b19

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

LOG: [clang-tidy] Fix invalid fix-it for 
cppcoreguidelines-prefer-member-initializer

Fixes https://github.com/llvm/llvm-project/issues/53515.

Reviewed By: LegalizeAdulthood

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

Added: 


Modified: 

clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
index 169b828a3c926..4ff362476a0c3 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
@@ -201,30 +201,42 @@ void PreferMemberInitializerCheck::check(
 diag(S->getBeginLoc(), "%0 should be initialized in an in-class"
" default member initializer")
 << Field;
-if (!InvalidFix) {
-  CharSourceRange StmtRange =
-  CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd);
-
-  SmallString<128> Insertion(
-  {UseAssignment ? " = " : "{",
-   Lexer::getSourceText(
-   CharSourceRange(InitValue->getSourceRange(), true),
-   *Result.SourceManager, getLangOpts()),
-   UseAssignment ? "" : "}"});
-
-  Diag << FixItHint::CreateInsertion(FieldEnd, Insertion)
-   << FixItHint::CreateRemoval(StmtRange);
-}
+if (InvalidFix)
+  continue;
+CharSourceRange StmtRange =
+CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd);
+
+SmallString<128> Insertion(
+{UseAssignment ? " = " : "{",
+ Lexer::getSourceText(
+ CharSourceRange(InitValue->getSourceRange(), true),
+ *Result.SourceManager, getLangOpts()),
+ UseAssignment ? "" : "}"});
+
+Diag << FixItHint::CreateInsertion(FieldEnd, Insertion)
+ << FixItHint::CreateRemoval(StmtRange);
+
   } else {
 StringRef InsertPrefix = "";
+bool HasInitAlready = false;
 SourceLocation InsertPos;
+SourceRange ReplaceRange;
 bool AddComma = false;
 bool InvalidFix = false;
 unsigned Index = Field->getFieldIndex();
 const CXXCtorInitializer *LastInListInit = nullptr;
 for (const CXXCtorInitializer *Init : Ctor->inits()) {
-  if (!Init->isWritten())
+  if (!Init->isWritten() || Init->isInClassMemberInitializer())
 continue;
+  if (Init->getMember() == Field) {
+HasInitAlready = true;
+if (isa(Init->getInit()))
+  InsertPos = Init->getRParenLoc();
+else {
+  ReplaceRange = Init->getInit()->getSourceRange();
+}
+break;
+  }
   if (Init->isMemberInitializer() &&
   Index < Init->getMember()->getFieldIndex()) {
 InsertPos = Init->getSourceLocation();
@@ -235,30 +247,38 @@ void PreferMemberInitializerCheck::check(
   }
   LastInListInit = Init;
 }
-if (InsertPos.isInvalid()) {
-  if (LastInListInit) {
-InsertPos = Lexer::getLocForEndOfToken(
-LastInListInit->getRParenLoc(), 0, *Result.SourceManager,
-getLangOpts());
-// Inserting after the last constructor initializer, so we need a
-// comma.
-InsertPrefix = ", ";
-  } else {
-InsertPos = Lexer::getLocForEndOfToken(
-Ctor->getTypeSourceInfo()
-->getTypeLoc()
-.getAs()
-.getLocalRangeEnd(),
-0, *Result.SourceManager, getLangOpts());
-
-// If this is first time in the loop, there are no initializers so
-// `:` declares member initialization list. If this is a subsequent
-// pass then we have already inserted a `:` so continue with a
-// comma.
-InsertPrefix = FirstToCtorInits ? " : " : ", ";
+if (HasInitAlready) {
+  if (InsertPos.isValid())
+InvalidFix |= InsertPos.isMacroID();
+  else
+InvalidFix |= ReplaceRange.getBegin().isMacroID() ||
+  

[PATCH] D118927: [clang-tidy] Fix invalid fix-it for cppcoreguidelines-prefer-member-initializer

2022-04-07 Thread Nathan James via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd0fcbb37838a: [clang-tidy] Fix invalid fix-it for 
cppcoreguidelines-prefer-member-initializer (authored by njames93).
Herald added a project: All.

Changed prior to commit:
  https://reviews.llvm.org/D118927?vs=410187=421292#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118927

Files:
  
clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines-prefer-member-initializer.cpp
@@ -526,14 +526,32 @@
   }
 };
 
-struct AlreadyHasInit {
+struct HasInClassInit {
   int m = 4;
-  AlreadyHasInit() {
+  HasInClassInit() {
 m = 3;
 // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: 'm' should be initialized in a member initializer of the constructor
   }
 };
 
+struct HasInitListInit {
+  int M;
+  // CHECK-MESSAGES: :[[@LINE+5]]:5: warning: 'M' should be initialized in a member initializer of the constructor
+  // CHECK-FIXES: HasInitListInit(const HasInitListInit ) : M(Other.M) {
+  // CHECK-FIXES-NEXT: {{^$}}
+  // CHECK-FIXES-NEXT: }
+  HasInitListInit(const HasInitListInit ) : M(4) {
+M = Other.M;
+  }
+  // CHECK-MESSAGES: :[[@LINE+5]]:5: warning: 'M' should be initialized in a member initializer of the constructor
+  // CHECK-FIXES: HasInitListInit(HasInitListInit &) : M(Other.M) {
+  // CHECK-FIXES-NEXT: {{^$}}
+  // CHECK-FIXES-NEXT: }
+  HasInitListInit(HasInitListInit &) : M() {
+M = Other.M;
+  }
+};
+
 #define ASSIGN_IN_MACRO(FIELD, VALUE) FIELD = (VALUE);
 
 struct MacroCantFix {
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -139,6 +139,12 @@
 
 - Fixed a crash in :doc:`bugprone-sizeof-expression ` when
   `sizeof(...)` is compared agains a `__int128_t`.
+  
+- Improved :doc:`cppcoreguidelines-prefer-member-initializer
+  ` check.
+
+  Fixed an issue when there was already an initializer in the constructor and
+  the check would try to create another initializer for the same member.
 
 Removed checks
 ^^
Index: clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
===
--- clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
+++ clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
@@ -201,30 +201,42 @@
 diag(S->getBeginLoc(), "%0 should be initialized in an in-class"
" default member initializer")
 << Field;
-if (!InvalidFix) {
-  CharSourceRange StmtRange =
-  CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd);
-
-  SmallString<128> Insertion(
-  {UseAssignment ? " = " : "{",
-   Lexer::getSourceText(
-   CharSourceRange(InitValue->getSourceRange(), true),
-   *Result.SourceManager, getLangOpts()),
-   UseAssignment ? "" : "}"});
-
-  Diag << FixItHint::CreateInsertion(FieldEnd, Insertion)
-   << FixItHint::CreateRemoval(StmtRange);
-}
+if (InvalidFix)
+  continue;
+CharSourceRange StmtRange =
+CharSourceRange::getCharRange(S->getBeginLoc(), SemiColonEnd);
+
+SmallString<128> Insertion(
+{UseAssignment ? " = " : "{",
+ Lexer::getSourceText(
+ CharSourceRange(InitValue->getSourceRange(), true),
+ *Result.SourceManager, getLangOpts()),
+ UseAssignment ? "" : "}"});
+
+Diag << FixItHint::CreateInsertion(FieldEnd, Insertion)
+ << FixItHint::CreateRemoval(StmtRange);
+
   } else {
 StringRef InsertPrefix = "";
+bool HasInitAlready = false;
 SourceLocation InsertPos;
+SourceRange ReplaceRange;
 bool AddComma = false;
 bool InvalidFix = false;
 unsigned Index = Field->getFieldIndex();
 const CXXCtorInitializer *LastInListInit = nullptr;
 for (const CXXCtorInitializer *Init : Ctor->inits()) {
-  if (!Init->isWritten())
+  if (!Init->isWritten() || Init->isInClassMemberInitializer())
 continue;
+  if (Init->getMember() == Field) {
+HasInitAlready = true;
+if 

[PATCH] D123295: [clang][extract-api] Use dedicated API to check for macro equality

2022-04-07 Thread Daniel Grumberg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG101559225189: [clang][extract-api][NFC] Use dedicated API to 
check for macro equality (authored by dang).

Changed prior to commit:
  https://reviews.llvm.org/D123295?vs=421147=421290#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123295

Files:
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp


Index: clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
===
--- clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
+++ clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
@@ -649,8 +649,9 @@
 
 class MacroCallback : public PPCallbacks {
 public:
-  MacroCallback(const SourceManager , LocationFileChecker , APISet )
-  : SM(SM), LCF(LCF), API(API) {}
+  MacroCallback(const SourceManager , LocationFileChecker , APISet ,
+Preprocessor )
+  : SM(SM), LCF(LCF), API(API), PP(PP) {}
 
   void MacroDefined(const Token ,
 const MacroDirective *MD) override {
@@ -677,9 +678,9 @@
 if (!Undef)
   return;
 
-llvm::erase_if(PendingMacros, [](const PendingMacro ) {
-  return MD.getMacroInfo()->getDefinitionLoc() ==
- PM.MD->getMacroInfo()->getDefinitionLoc();
+llvm::erase_if(PendingMacros, [, this](const PendingMacro ) {
+  return MD.getMacroInfo()->isIdenticalTo(*PM.MD->getMacroInfo(), PP,
+  /*Syntactically*/ false);
 });
   }
 
@@ -719,6 +720,7 @@
   const SourceManager 
   LocationFileChecker 
   APISet 
+  Preprocessor 
   llvm::SmallVector PendingMacros;
 };
 
@@ -741,9 +743,8 @@
   auto LCF = std::make_unique(CI.getSourceManager(),
KnownInputFiles);
 
-  // Register preprocessor callbacks that will add macro definitions to API.
-  CI.getPreprocessor().addPPCallbacks(
-  std::make_unique(CI.getSourceManager(), *LCF, *API));
+  CI.getPreprocessor().addPPCallbacks(std::make_unique(
+  CI.getSourceManager(), *LCF, *API, CI.getPreprocessor()));
 
   return std::make_unique(CI.getASTContext(),
   std::move(LCF), *API);


Index: clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
===
--- clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
+++ clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
@@ -649,8 +649,9 @@
 
 class MacroCallback : public PPCallbacks {
 public:
-  MacroCallback(const SourceManager , LocationFileChecker , APISet )
-  : SM(SM), LCF(LCF), API(API) {}
+  MacroCallback(const SourceManager , LocationFileChecker , APISet ,
+Preprocessor )
+  : SM(SM), LCF(LCF), API(API), PP(PP) {}
 
   void MacroDefined(const Token ,
 const MacroDirective *MD) override {
@@ -677,9 +678,9 @@
 if (!Undef)
   return;
 
-llvm::erase_if(PendingMacros, [](const PendingMacro ) {
-  return MD.getMacroInfo()->getDefinitionLoc() ==
- PM.MD->getMacroInfo()->getDefinitionLoc();
+llvm::erase_if(PendingMacros, [, this](const PendingMacro ) {
+  return MD.getMacroInfo()->isIdenticalTo(*PM.MD->getMacroInfo(), PP,
+  /*Syntactically*/ false);
 });
   }
 
@@ -719,6 +720,7 @@
   const SourceManager 
   LocationFileChecker 
   APISet 
+  Preprocessor 
   llvm::SmallVector PendingMacros;
 };
 
@@ -741,9 +743,8 @@
   auto LCF = std::make_unique(CI.getSourceManager(),
KnownInputFiles);
 
-  // Register preprocessor callbacks that will add macro definitions to API.
-  CI.getPreprocessor().addPPCallbacks(
-  std::make_unique(CI.getSourceManager(), *LCF, *API));
+  CI.getPreprocessor().addPPCallbacks(std::make_unique(
+  CI.getSourceManager(), *LCF, *API, CI.getPreprocessor()));
 
   return std::make_unique(CI.getASTContext(),
   std::move(LCF), *API);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1015592 - [clang][extract-api][NFC] Use dedicated API to check for macro equality

2022-04-07 Thread Daniel Grumberg via cfe-commits

Author: Daniel Grumberg
Date: 2022-04-07T19:08:17+01:00
New Revision: 101559225189e63b7f6236fb944501b1e6b74a87

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

LOG: [clang][extract-api][NFC] Use dedicated API to check for macro equality

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

Added: 


Modified: 
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp

Removed: 




diff  --git a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp 
b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
index 949413d7d2b1d..0757881862984 100644
--- a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
+++ b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
@@ -649,8 +649,9 @@ class ExtractAPIConsumer : public ASTConsumer {
 
 class MacroCallback : public PPCallbacks {
 public:
-  MacroCallback(const SourceManager , LocationFileChecker , APISet )
-  : SM(SM), LCF(LCF), API(API) {}
+  MacroCallback(const SourceManager , LocationFileChecker , APISet ,
+Preprocessor )
+  : SM(SM), LCF(LCF), API(API), PP(PP) {}
 
   void MacroDefined(const Token ,
 const MacroDirective *MD) override {
@@ -677,9 +678,9 @@ class MacroCallback : public PPCallbacks {
 if (!Undef)
   return;
 
-llvm::erase_if(PendingMacros, [](const PendingMacro ) {
-  return MD.getMacroInfo()->getDefinitionLoc() ==
- PM.MD->getMacroInfo()->getDefinitionLoc();
+llvm::erase_if(PendingMacros, [, this](const PendingMacro ) {
+  return MD.getMacroInfo()->isIdenticalTo(*PM.MD->getMacroInfo(), PP,
+  /*Syntactically*/ false);
 });
   }
 
@@ -719,6 +720,7 @@ class MacroCallback : public PPCallbacks {
   const SourceManager 
   LocationFileChecker 
   APISet 
+  Preprocessor 
   llvm::SmallVector PendingMacros;
 };
 
@@ -741,9 +743,8 @@ ExtractAPIAction::CreateASTConsumer(CompilerInstance , 
StringRef InFile) {
   auto LCF = std::make_unique(CI.getSourceManager(),
KnownInputFiles);
 
-  // Register preprocessor callbacks that will add macro definitions to API.
-  CI.getPreprocessor().addPPCallbacks(
-  std::make_unique(CI.getSourceManager(), *LCF, *API));
+  CI.getPreprocessor().addPPCallbacks(std::make_unique(
+  CI.getSourceManager(), *LCF, *API, CI.getPreprocessor()));
 
   return std::make_unique(CI.getASTContext(),
   std::move(LCF), *API);



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


[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

In D123297#3436867 , @mehdi_amini 
wrote:

> `-mmlir` is fine with me, but note that MLIR has much less global options 
> than LLVM: you will only get access to context and passmanager options and 
> not individual passes flags. That's not a criticism :)
> (that's what makes it not likely to have conflicts by the way: the set of 
> MLIR option is well identified)

Thanks for taking a look! All this should be fine - the main rationale for this 
patch is to enable MLIR options in `flang-new` so that tests using `tco` or 
`bbc` (and which use MLIR options) can be ported to use `flang-new`. We were 
discussing this recently in https://reviews.llvm.org/D121171.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123297

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


[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread Mehdi AMINI via Phabricator via cfe-commits
mehdi_amini added a comment.

`-mmlir` is fine with me, but note that MLIR has much less global options than 
LLVM: you will only get access to context and passmanager options and not 
individual passes flags. That's not a criticism :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123297

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


[PATCH] D123289: [clangd][SymbolCollector] Introduce a cache for SymbolID generation and some cleanups

2022-04-07 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Neat!

I think you've broken the FilesToTokenCache by moving it into the loop, so I'd 
expect further wins from fixing that.
(If you don't see any, something seems wrong: syntax::tokenize should be called 
a fair bit and should be pretty expensive!)




Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:589
+if (Opts.RefsInHeaders || FID == SM.getMainFileID()) {
+  // FIXME: It's better to use TokenBuffer by passing spelled tokens from
+  // the caller of SymbolCollector.

there's a big block of code here that's checking if the reference was spelled 
or not, pull out a function?



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:591
+  // the caller of SymbolCollector.
+  llvm::DenseMap> FilesToTokensCache;
+  if (!FilesToTokensCache.count(FID))

Um, is this cache meant to be a member? It's pretty well guaranteed to be empty 
on the next line :-)



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:710
 // FIXME: Populate container information for macro references.
-MacroRefs[ID].push_back({Loc, Roles, /*Container=*/nullptr});
+// FIXME: All macro references are marked as Spelled now, but this should 
be
+// checked.

What does a non-spelled macro reference look like?



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:810
   // At the end of the TU, add 1 to the refcount of all referenced symbols.
   auto IncRef = [this](const SymbolID ) {
 if (const auto *S = Symbols.find(ID)) {

no need for this to be a lambda anymore, a plain loop seems fine



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:814
   ++Inc.References;
   Symbols.insert(Inc);
 }

if you have timing set up, try making this 
`const_cast(S)->References++`.

Reinserting into a symbol slab is pretty expensive I think, and this is just an 
awkward gap in the API.
We could fix the API or live with const_cast if it matters.



Comment at: clang-tools-extra/clangd/index/SymbolCollector.cpp:964
+SymbolID SymbolCollector::getSymbolIDCached(const Decl *D) {
+  auto It = DeclToIDCache.try_emplace(D, SymbolID{});
+  if (It.second)

nit: just try_emplace(D). The rest of the arguments get forwarded to the V 
constructor, so you're calling an unneccesary move constructor here.

(Shouldn't matter here because SymbolID is trivial, but it can)



Comment at: clang-tools-extra/clangd/index/SymbolCollector.h:174
   // Symbols referenced from the current TU, flushed on finish().
-  llvm::DenseSet ReferencedDecls;
-  llvm::DenseSet ReferencedMacros;
-  llvm::DenseMap> DeclRefs;
-  llvm::DenseMap> MacroRefs;
+  llvm::DenseSet ReferencedSymbols;
   // Maps canonical declaration provided by clang to canonical declaration for

hash_code(SymbolID) is not defined in the header, but the hash function is 
trivial and could be inlined everywhere. Might be worth exposing.

(not really related to this patch, but you have some setup for benchmarking at 
the moment...)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123289

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


[PATCH] D121637: [PowerPC] Fix EmitPPCBuiltinExpr to emit arguments once

2022-04-07 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 421286.
quinnp added a comment.

Rebasing with main.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121637

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/PowerPC/builtins-ppc-fastmath.c
  clang/test/CodeGen/PowerPC/builtins-ppc-pair-mma-types.c
  clang/test/CodeGen/PowerPC/builtins-ppc-stmtexpr-argument.c
  clang/test/CodeGen/PowerPC/builtins-ppc-vsx.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cas.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-fetch.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-fp.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-math.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync.c
  clang/test/CodeGen/PowerPC/ppc-mma-types.c
  clang/test/Sema/ppc-pair-mma-types.c

Index: clang/test/Sema/ppc-pair-mma-types.c
===
--- clang/test/Sema/ppc-pair-mma-types.c
+++ clang/test/Sema/ppc-pair-mma-types.c
@@ -12,11 +12,6 @@
 
 // typedef
 typedef __vector_quad vq_t;
-void testVQTypedef(int *inp, int *outp) {
-  vq_t *vqin = (vq_t *)inp;
-  vq_t *vqout = (vq_t *)outp;
-  *vqout = *vqin;
-}
 
 // function argument
 void testVQArg1(__vector_quad vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
@@ -29,57 +24,22 @@
   *vqp = vq;
 }
 
-void testVQArg3(__vector_quad *vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
-void testVQArg4(const __vector_quad *const vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
-void testVQArg5(__vector_quad vqa[], int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = vqa[0];
-}
-
 void testVQArg6(const vq_t vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   *vqp = vq;
 }
 
-void testVQArg7(const vq_t *vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
 // function return
 __vector_quad testVQRet1(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   return *vqp; // expected-error {{invalid use of PPC MMA type}}
 }
 
-__vector_quad *testVQRet2(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
-const __vector_quad *testVQRet3(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
 const vq_t testVQRet4(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   return *vqp; // expected-error {{invalid use of PPC MMA type}}
 }
 
-const vq_t *testVQRet5(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
 // global
 __vector_quad globalvq;// expected-error {{invalid use of PPC MMA type}}
 const __vector_quad globalvq2; // expected-error {{invalid use of PPC MMA type}}
@@ -87,16 +47,6 @@
 const __vector_quad *const globalvqp2;
 vq_t globalvq_t; // expected-error {{invalid use of PPC MMA type}}
 
-// local
-void testVQLocal(int *ptr, vector unsigned char vc) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  __vector_quad vq1 = *vqp;
-  __vector_quad vq2;
-  __builtin_mma_xxsetaccz();
-  __vector_quad vq3;
-  __builtin_mma_xvi4ger8(, vc, vc);
-  *vqp = vq3;
-}
 
 // struct field
 struct TestVQStruct {
@@ -106,17 +56,6 @@
   __vector_quad *vq;
 };
 
-// sizeof / alignof
-int testVQSizeofAlignof(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  __vector_quad vq = *vqp;
-  unsigned sizet = sizeof(__vector_quad);
-  unsigned alignt = __alignof__(__vector_quad);
-  unsigned sizev = sizeof(vq);
-  unsigned alignv = __alignof__(vq);
-  return sizet + alignt + sizev + alignv;
-}
-
 // operators
 int testVQOperators1(int *ptr) {
   __vector_quad *vqp = (__vector_quad *)ptr;
@@ -168,11 +107,6 @@
 
 // typedef
 typedef __vector_pair vp_t;
-void testVPTypedef(int *inp, int *outp) {
-  vp_t *vpin = (vp_t *)inp;
-  vp_t *vpout = (vp_t *)outp;
-  *vpout = *vpin;
-}
 
 // function argument
 void testVPArg1(__vector_pair vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
@@ -185,57 +119,22 @@
   *vpp = vp;
 }
 
-void testVPArg3(__vector_pair *vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
-void testVPArg4(const __vector_pair *const vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
-void testVPArg5(__vector_pair vpa[], int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = vpa[0];
-}
-
 void testVPArg6(const vp_t vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_pair *vpp = (__vector_pair *)ptr;
   *vpp = vp;
 }
 
-void testVPArg7(const vp_t *vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
 // function return
 __vector_pair testVPRet1(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_pair 

[PATCH] D120989: Support debug info for alias variable

2022-04-07 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

This breaks tests on mac: 
https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket/8817534773179515649/+/u/package_clang/stdout?format=raw

  Script:
   --
   : 'RUN: at line 1';   
/opt/s/w/ir/cache/builder/src/third_party/llvm-bootstrap/bin/clang -cc1 
-internal-isystem 
/opt/s/w/ir/cache/builder/src/third_party/llvm-bootstrap/lib/clang/15.0.0/include
 -nostdsysteminc -emit-llvm -debug-info-kind=limited 
/opt/s/w/ir/cache/builder/src/third_party/llvm/clang/test/CodeGen/debug-info-alias.c
 -o - | /opt/s/w/ir/cache/builder/src/third_party/llvm-bootstrap/bin/FileCheck 
/opt/s/w/ir/cache/builder/src/third_party/llvm/clang/test/CodeGen/debug-info-alias.c
   --
   Exit Code: 2
   
   Command Output (stderr):
   --
   
/opt/s/w/ir/cache/builder/src/third_party/llvm/clang/test/CodeGen/debug-info-alias.c:10:27:
 error: aliases are not supported on darwin
   extern int __attribute__((alias("aliased_global"))) __global_alias;
 ^
   
/opt/s/w/ir/cache/builder/src/third_party/llvm/clang/test/CodeGen/debug-info-alias.c:14:27:
 error: aliases are not supported on darwin
   extern int __attribute__((alias("aliased_global_2"))) global_alias_2;
 ^
   
/opt/s/w/ir/cache/builder/src/third_party/llvm/clang/test/CodeGen/debug-info-alias.c:15:27:
 error: aliases are not supported on darwin
   extern int __attribute__((alias("global_alias_2"))) __global_alias_2_alias;
 ^
   3 errors generated.
   FileCheck error: '' is empty.
   FileCheck command line:  
/opt/s/w/ir/cache/builder/src/third_party/llvm-bootstrap/bin/FileCheck 
/opt/s/w/ir/cache/builder/src/third_party/llvm/clang/test/CodeGen/debug-info-alias.c
   
   --
   
   
   Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90.. 
   
   Failed Tests (1):
 Clang :: CodeGen/debug-info-alias.c

Probably easiest to pass an explicit triple?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120989

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


[PATCH] D123026: [clang][NFC] Extract EmitAssemblyHelper::shouldEmitRegularLTOSummary

2022-04-07 Thread Teresa Johnson via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb4ac84901e9b: [clang][NFC] Extract 
EmitAssemblyHelper::shouldEmitRegularLTOSummary (authored by psamolysov-intel, 
committed by tejohnson).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123026

Files:
  clang/lib/CodeGen/BackendUtil.cpp


Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -164,6 +164,16 @@
   std::unique_ptr ,
   std::unique_ptr );
 
+  /// Check whether we should emit a module summary for regular LTO.
+  /// The module summary should be emitted by default for regular LTO
+  /// except for ld64 targets.
+  ///
+  /// \return True if the module summary should be emitted.
+  bool shouldEmitRegularLTOSummary() const {
+return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
+   TargetTriple.getVendor() != llvm::Triple::Apple;
+  }
+
 public:
   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  const HeaderSearchOptions ,
@@ -1054,9 +1064,7 @@
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
-  bool EmitLTOSummary =
-  (CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
-   TargetTriple.getVendor() != llvm::Triple::Apple);
+  bool EmitLTOSummary = shouldEmitRegularLTOSummary();
   if (EmitLTOSummary) {
 if (!TheModule->getModuleFlag("ThinLTO"))
   TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
@@ -1064,7 +1072,6 @@
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-
   PerModulePasses.add(createBitcodeWriterPass(
   *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
 }
@@ -1470,9 +1477,7 @@
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
-  bool EmitLTOSummary =
-  (CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
-   TargetTriple.getVendor() != llvm::Triple::Apple);
+  bool EmitLTOSummary = shouldEmitRegularLTOSummary();
   if (EmitLTOSummary) {
 if (!TheModule->getModuleFlag("ThinLTO"))
   TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));


Index: clang/lib/CodeGen/BackendUtil.cpp
===
--- clang/lib/CodeGen/BackendUtil.cpp
+++ clang/lib/CodeGen/BackendUtil.cpp
@@ -164,6 +164,16 @@
   std::unique_ptr ,
   std::unique_ptr );
 
+  /// Check whether we should emit a module summary for regular LTO.
+  /// The module summary should be emitted by default for regular LTO
+  /// except for ld64 targets.
+  ///
+  /// \return True if the module summary should be emitted.
+  bool shouldEmitRegularLTOSummary() const {
+return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
+   TargetTriple.getVendor() != llvm::Triple::Apple;
+  }
+
 public:
   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  const HeaderSearchOptions ,
@@ -1054,9 +1064,7 @@
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
-  bool EmitLTOSummary =
-  (CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
-   TargetTriple.getVendor() != llvm::Triple::Apple);
+  bool EmitLTOSummary = shouldEmitRegularLTOSummary();
   if (EmitLTOSummary) {
 if (!TheModule->getModuleFlag("ThinLTO"))
   TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
@@ -1064,7 +1072,6 @@
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-
   PerModulePasses.add(createBitcodeWriterPass(
   *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
 }
@@ -1470,9 +1477,7 @@
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
-  bool EmitLTOSummary =
-  (CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
-   TargetTriple.getVendor() != llvm::Triple::Apple);
+  bool EmitLTOSummary = shouldEmitRegularLTOSummary();
   if (EmitLTOSummary) {
 if (!TheModule->getModuleFlag("ThinLTO"))
   TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] b4ac849 - [clang][NFC] Extract EmitAssemblyHelper::shouldEmitRegularLTOSummary

2022-04-07 Thread Teresa Johnson via cfe-commits

Author: Pavel Samolysov
Date: 2022-04-07T10:38:46-07:00
New Revision: b4ac84901e9b88429e5e51dc0b4a17b8d3e37708

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

LOG: [clang][NFC] Extract EmitAssemblyHelper::shouldEmitRegularLTOSummary

The code to check if the regular LTO summary should be emitted and to
add the corresponding module flags was duplicated in the
'EmitAssemblyHelper::EmitAssemblyWithLegacyPassManager' and
'EmitAssemblyHelper::RunOptimizationPipeline' methods.

In order to eliminate these code duplications, the
'EmitAssemblyHelper::shouldEmitRegularLTOSummary' method has been
extracted. The method returns a bool value, the value is 'true' if the
module summary should be emitted. The patch keeps the setting of the
module flags inline.

Reviewed By: tejohnson

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

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 36776d39b952a..c09afefb3cc9a 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -164,6 +164,16 @@ class EmitAssemblyHelper {
   std::unique_ptr ,
   std::unique_ptr );
 
+  /// Check whether we should emit a module summary for regular LTO.
+  /// The module summary should be emitted by default for regular LTO
+  /// except for ld64 targets.
+  ///
+  /// \return True if the module summary should be emitted.
+  bool shouldEmitRegularLTOSummary() const {
+return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
+   TargetTriple.getVendor() != llvm::Triple::Apple;
+  }
+
 public:
   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
  const HeaderSearchOptions ,
@@ -1054,9 +1064,7 @@ void 
EmitAssemblyHelper::EmitAssemblyWithLegacyPassManager(
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
-  bool EmitLTOSummary =
-  (CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
-   TargetTriple.getVendor() != llvm::Triple::Apple);
+  bool EmitLTOSummary = shouldEmitRegularLTOSummary();
   if (EmitLTOSummary) {
 if (!TheModule->getModuleFlag("ThinLTO"))
   TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
@@ -1064,7 +1072,6 @@ void 
EmitAssemblyHelper::EmitAssemblyWithLegacyPassManager(
   TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
uint32_t(1));
   }
-
   PerModulePasses.add(createBitcodeWriterPass(
   *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
 }
@@ -1470,9 +1477,7 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 } else {
   // Emit a module summary by default for Regular LTO except for ld64
   // targets
-  bool EmitLTOSummary =
-  (CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
-   TargetTriple.getVendor() != llvm::Triple::Apple);
+  bool EmitLTOSummary = shouldEmitRegularLTOSummary();
   if (EmitLTOSummary) {
 if (!TheModule->getModuleFlag("ThinLTO"))
   TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));



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


[PATCH] D121637: [PowerPC] Fix EmitPPCBuiltinExpr to emit arguments once

2022-04-07 Thread Quinn Pham via Phabricator via cfe-commits
quinnp added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:15627
+Value *Y =
+Builder.CreateAnd(EmitScalarExpr(E->getArg(1)), 
Builder.CreateNot(Op3));
 return Builder.CreateOr(X, Y);

nemanjai wrote:
> Nit: I understand that we only have one use of `E->getArg(1)`, but might as 
> well initialize `Op1` as above just for consistency.
I've fixed all the instances of this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121637

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


[PATCH] D121637: [PowerPC] Fix EmitPPCBuiltinExpr to emit arguments once

2022-04-07 Thread Quinn Pham via Phabricator via cfe-commits
quinnp updated this revision to Diff 421279.
quinnp marked an inline comment as done.
quinnp added a comment.

Fixing some testcases that broke due to re-ordering IR in my last update.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121637

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/PowerPC/builtins-ppc-fastmath.c
  clang/test/CodeGen/PowerPC/builtins-ppc-pair-mma-types.c
  clang/test/CodeGen/PowerPC/builtins-ppc-stmtexpr-argument.c
  clang/test/CodeGen/PowerPC/builtins-ppc-vsx.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-cas.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-fetch.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-fp.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-math.c
  clang/test/CodeGen/PowerPC/builtins-ppc-xlcompat-sync.c
  clang/test/CodeGen/PowerPC/ppc-mma-types.c
  clang/test/Sema/ppc-pair-mma-types.c

Index: clang/test/Sema/ppc-pair-mma-types.c
===
--- clang/test/Sema/ppc-pair-mma-types.c
+++ clang/test/Sema/ppc-pair-mma-types.c
@@ -12,11 +12,6 @@
 
 // typedef
 typedef __vector_quad vq_t;
-void testVQTypedef(int *inp, int *outp) {
-  vq_t *vqin = (vq_t *)inp;
-  vq_t *vqout = (vq_t *)outp;
-  *vqout = *vqin;
-}
 
 // function argument
 void testVQArg1(__vector_quad vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
@@ -29,57 +24,22 @@
   *vqp = vq;
 }
 
-void testVQArg3(__vector_quad *vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
-void testVQArg4(const __vector_quad *const vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
-void testVQArg5(__vector_quad vqa[], int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = vqa[0];
-}
-
 void testVQArg6(const vq_t vq, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   *vqp = vq;
 }
 
-void testVQArg7(const vq_t *vq, int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  *vqp = *vq;
-}
-
 // function return
 __vector_quad testVQRet1(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   return *vqp; // expected-error {{invalid use of PPC MMA type}}
 }
 
-__vector_quad *testVQRet2(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
-const __vector_quad *testVQRet3(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
 const vq_t testVQRet4(int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_quad *vqp = (__vector_quad *)ptr;
   return *vqp; // expected-error {{invalid use of PPC MMA type}}
 }
 
-const vq_t *testVQRet5(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  return vqp + 2;
-}
-
 // global
 __vector_quad globalvq;// expected-error {{invalid use of PPC MMA type}}
 const __vector_quad globalvq2; // expected-error {{invalid use of PPC MMA type}}
@@ -87,16 +47,6 @@
 const __vector_quad *const globalvqp2;
 vq_t globalvq_t; // expected-error {{invalid use of PPC MMA type}}
 
-// local
-void testVQLocal(int *ptr, vector unsigned char vc) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  __vector_quad vq1 = *vqp;
-  __vector_quad vq2;
-  __builtin_mma_xxsetaccz();
-  __vector_quad vq3;
-  __builtin_mma_xvi4ger8(, vc, vc);
-  *vqp = vq3;
-}
 
 // struct field
 struct TestVQStruct {
@@ -106,17 +56,6 @@
   __vector_quad *vq;
 };
 
-// sizeof / alignof
-int testVQSizeofAlignof(int *ptr) {
-  __vector_quad *vqp = (__vector_quad *)ptr;
-  __vector_quad vq = *vqp;
-  unsigned sizet = sizeof(__vector_quad);
-  unsigned alignt = __alignof__(__vector_quad);
-  unsigned sizev = sizeof(vq);
-  unsigned alignv = __alignof__(vq);
-  return sizet + alignt + sizev + alignv;
-}
-
 // operators
 int testVQOperators1(int *ptr) {
   __vector_quad *vqp = (__vector_quad *)ptr;
@@ -168,11 +107,6 @@
 
 // typedef
 typedef __vector_pair vp_t;
-void testVPTypedef(int *inp, int *outp) {
-  vp_t *vpin = (vp_t *)inp;
-  vp_t *vpout = (vp_t *)outp;
-  *vpout = *vpin;
-}
 
 // function argument
 void testVPArg1(__vector_pair vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
@@ -185,57 +119,22 @@
   *vpp = vp;
 }
 
-void testVPArg3(__vector_pair *vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
-void testVPArg4(const __vector_pair *const vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
-void testVPArg5(__vector_pair vpa[], int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = vpa[0];
-}
-
 void testVPArg6(const vp_t vp, int *ptr) { // expected-error {{invalid use of PPC MMA type}}
   __vector_pair *vpp = (__vector_pair *)ptr;
   *vpp = vp;
 }
 
-void testVPArg7(const vp_t *vp, int *ptr) {
-  __vector_pair *vpp = (__vector_pair *)ptr;
-  *vpp = *vp;
-}
-
 // function return
 

[PATCH] D123319: Change how we handle auto return types for lambda operator() to be consistent with gcc

2022-04-07 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.

> Are there cases where we emit debug info and we don't have the deduced type?

I don't think that would happen for a lambda.
https://dwarfstd.org/ShowIssue.php?issue=131217.1 specifically calls out method 
declarations without definitions, which makes sense to me.


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

https://reviews.llvm.org/D123319

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


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-07 Thread Thorsten via Phabricator via cfe-commits
tschuett added a comment.

In my example, they even promised that the flag will removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122008

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


[PATCH] D122008: [flang][driver] Add support for generating executables

2022-04-07 Thread Damian Rouson via Phabricator via cfe-commits
rouson added a comment.

I also very much like the second option.  I think it prevents a naive user from 
stumbling into treacherous territory.  Also, as someone who is funded to write 
tests for flang, making it easier to build executables would expand the options 
for testing. Currently, we're focused on semantics tests primarily because of 
the complications associated with generating executables.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122008

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-07 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 421270.
jhuber6 added a comment.

Make `-foffload-new-driver` imply GPU-RDC mode, it won't work otherwise. Also 
adjust tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

Files:
  clang/include/clang/Basic/Cuda.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/test/Driver/cuda-openmp-driver.cu

Index: clang/test/Driver/cuda-openmp-driver.cu
===
--- /dev/null
+++ clang/test/Driver/cuda-openmp-driver.cu
@@ -0,0 +1,18 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:-foffload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix BINDINGS %s
+
+// BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_35]]"], output: "[[CUBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_35]]", "[[PTX_SM_35]]"], output: "[[FATBIN_SM_35:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]"], output: "[[PTX_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_70:.+]]"], output: "[[CUBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_70]]", "[[PTX_SM_70:.+]]"], output: "[[FATBIN_SM_70:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT]]", "[[FATBIN_SM_35]]", "[[FATBIN_SM_70]]"], output: "[[HOST_OBJ:.+]]"
+// BINDINGS-NEXT: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN: %clang -### -nocudalib -foffload-new-driver %s 2>&1 | FileCheck -check-prefix RDC %s
+// RDC: ptxas{{.*}}-c
Index: clang/lib/Driver/ToolChains/HIPAMD.cpp
===
--- clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -188,7 +188,7 @@
 CC1Args.push_back("-fcuda-approx-transcendentals");
 
   if (!DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
-  false))
+  false) || DriverArgs.hasArg(options::OPT_foffload_new_driver))
 CC1Args.append({"-mllvm", "-amdgpu-internalize-symbols"});
 
   StringRef MaxThreadsPerBlock =
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -461,7 +461,8 @@
options::OPT_fnoopenmp_relocatable_target,
/*Default=*/true);
   else if (JA.isOffloading(Action::OFK_Cuda))
-Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
+Relocatable = Args.hasArg(options::OPT_foffload_new_driver) || 
+  Args.hasFlag(options::OPT_fgpu_rdc,
options::OPT_fno_gpu_rdc, /*Default=*/false);
 
   if (Relocatable)
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6248,6 +6248,8 @@
   if (IsCuda || IsHIP) {
 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
   CmdArgs.push_back("-fgpu-rdc");
+if (Args.hasArg(options::OPT_foffload_new_driver))
+  CmdArgs.push_back("-fgpu-rdc");
 if (Args.hasFlag(options::OPT_fgpu_defer_diag,
  options::OPT_fno_gpu_defer_diag, false))
   CmdArgs.push_back("-fgpu-defer-diag");
@@ -6930,6 +6932,8 @@
   CmdArgs.push_back(CudaDeviceInput->getFilename());
   if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
 CmdArgs.push_back("-fgpu-rdc");
+  if (Args.hasArg(options::OPT_foffload_new_driver))
+CmdArgs.push_back("-fgpu-rdc");
   }
 
   if (IsCuda) {
@@ -8250,14 +8254,17 @@
   ArgStringList CmdArgs;
 
   // Pass the CUDA path to the linker wrapper tool.
-  for (auto  : llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) {
-const ToolChain *TC = I.second;
-if (TC->getTriple().isNVPTX()) {
-  CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
-  if (CudaInstallation.isValid())
-CmdArgs.push_back(Args.MakeArgString(
-"--cuda-path=" + CudaInstallation.getInstallPath()));
-  break;
+  for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
+auto TCRange = C.getOffloadToolChains(Kind);
+for (auto  : llvm::make_range(TCRange.first, TCRange.second)) {
+ 

[PATCH] D123325: [Clang] Make enabling the new driver more generic

2022-04-07 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: JonChesterfield, jdoerfert, yaxunl, tra.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1, MaskRay.
Herald added a project: clang.

In preparation for allowing other offloading kinds to use the new driver
a new opt-in flag `-foffload-new-driver` is added. This is distinct from
the existing `-fopenmp-new-driver` because OpenMP will soon use the new
driver by default while the others should not.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D123325

Files:
  clang/include/clang/Driver/Compilation.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  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
@@ -4395,7 +4395,8 @@
  JA.isDeviceOffloading(Action::OFK_Host));
   bool IsHostOffloadingAction =
   JA.isHostOffloading(C.getActiveOffloadKinds()) &&
-  Args.hasArg(options::OPT_fopenmp_new_driver);
+  (Args.hasArg(options::OPT_fopenmp_new_driver) ||
+   Args.hasArg(options::OPT_foffload_new_driver));
   bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
   auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
 
@@ -4683,7 +4684,8 @@
 if (JA.getType() == types::TY_LLVM_BC)
   CmdArgs.push_back("-emit-llvm-uselists");
 
-if (IsUsingLTO && !Args.hasArg(options::OPT_fopenmp_new_driver)) {
+if (IsUsingLTO && !(Args.hasArg(options::OPT_fopenmp_new_driver) ||
+!Args.hasArg(options::OPT_foffload_new_driver))) {
   // Only AMDGPU supports device-side LTO.
   if (IsDeviceOffloadAction && !Triple.isAMDGPU()) {
 D.Diag(diag::err_drv_unsupported_opt_for_target)
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -3881,6 +3881,11 @@
   // Builder to be used to build offloading actions.
   OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
 
+  bool UseNewOffloadingDriver =
+  C.isOffloadingHostKind(C.getActiveOffloadKinds()) &&
+  (Args.hasArg(options::OPT_foffload_new_driver) ||
+   Args.hasArg(options::OPT_fopenmp_new_driver));
+
   // Construct the actions to perform.
   HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
   ExtractAPIJobAction *ExtractAPIAction = nullptr;
@@ -3902,14 +3907,14 @@
 
 // Use the current host action in any of the offloading actions, if
 // required.
-if (!Args.hasArg(options::OPT_fopenmp_new_driver))
+if (!UseNewOffloadingDriver)
   if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
 break;
 
 for (phases::ID Phase : PL) {
 
   // Add any offload action the host action depends on.
-  if (!Args.hasArg(options::OPT_fopenmp_new_driver))
+  if (!UseNewOffloadingDriver)
 Current = OffloadBuilder.addDeviceDependencesToHostAction(
 Current, InputArg, Phase, PL.back(), FullPL);
   if (!Current)
@@ -3952,7 +3957,7 @@
 
   // Try to build the offloading actions and add the result as a dependency
   // to the host.
-  if (Args.hasArg(options::OPT_fopenmp_new_driver))
+  if (UseNewOffloadingDriver)
 Current = BuildOffloadingActions(C, Args, I, Current);
 
   // FIXME: Should we include any prior module file outputs as inputs of
@@ -3974,7 +3979,7 @@
 
   // Use the current host action in any of the offloading actions, if
   // required.
-  if (!Args.hasArg(options::OPT_fopenmp_new_driver))
+  if (!UseNewOffloadingDriver)
 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
   break;
 
@@ -3987,7 +3992,7 @@
   Actions.push_back(Current);
 
 // Add any top level actions generated for offloading.
-if (!Args.hasArg(options::OPT_fopenmp_new_driver))
+if (!UseNewOffloadingDriver)
   OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
 else if (Current)
   Current->propagateHostOffloadInfo(C.getActiveOffloadKinds(),
@@ -4003,14 +4008,14 @@
   }
 
   if (!LinkerInputs.empty()) {
-if (!Args.hasArg(options::OPT_fopenmp_new_driver))
+if (!UseNewOffloadingDriver)
   if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
 LinkerInputs.push_back(Wrapper);
 Action *LA;
 // Check if this Linker Job should emit a static library.
 if (ShouldEmitStaticLibrary(Args)) {
   LA = C.MakeAction(LinkerInputs, types::TY_Image);
-} else if (Args.hasArg(options::OPT_fopenmp_new_driver) &&
+} else if (UseNewOffloadingDriver &&
C.getActiveOffloadKinds() != Action::OFK_None) {
   LA = C.MakeAction(LinkerInputs, types::TY_Image);
   

[PATCH] D122377: [PowerPC] Support 16-byte lock free atomics on pwr8 and up

2022-04-07 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast accepted this revision.
hubert.reinterpretcast added a comment.
This revision is now accepted and ready to land.

LGTM with minor comments.




Comment at: clang/test/CodeGen/PowerPC/atomic-alignment.c:1-12
 // RUN: %clang_cc1 -verify -triple powerpc-unknown-unknown -emit-llvm -o - %s 
| \
 // RUN:   FileCheck %s --check-prefixes=PPC,PPC32
 // RUN: %clang_cc1 -verify -triple powerpc64le-unknown-linux -emit-llvm -o - 
%s | \
 // RUN:   FileCheck %s --check-prefixes=PPC,PPC64
+// RUN: %clang_cc1 -verify -triple powerpc64le-unknown-linux -emit-llvm -o - 
%s \
+// RUN:   -target-cpu pwr8 | FileCheck %s --check-prefixes=PPC,PPC64
 // RUN: %clang_cc1 -verify -triple powerpc64-unknown-aix -emit-llvm -o - %s | \

Use `-Werror` in place of `-verify` with no diagnostics.



Comment at: clang/test/CodeGen/PowerPC/quadword-atomics.c:1-6
+// RUN: %clang_cc1 -verify -Wno-atomic-alignment -triple powerpc64le-linux-gnu 
\
+// RUN:   -target-cpu pwr8 -emit-llvm -o - %s | FileCheck %s 
--check-prefix=PPC64-PWR8
+// RUN: %clang_cc1 -verify -Wno-atomic-alignment -triple powerpc64le-linux-gnu 
\
+// RUN:   -emit-llvm -o - %s | FileCheck %s --check-prefix=PPC64
+// RUN: %clang_cc1 -verify -Wno-atomic-alignment -triple powerpc64-unknown-aix 
\
+// RUN:   -target-cpu pwr7 -emit-llvm -o - %s | FileCheck %s 
--check-prefix=PPC64

Same comment as for the other file.



Comment at: llvm/lib/Target/PowerPC/PPCISelLowering.cpp:18057
+bool PPCTargetLowering::shouldInlineQuadwordAtomics() const {
+  // TODO: 16-byte atomic type support for AIX is in progress, we should be 
able
+  // to inline 16-byte atomic ops on AIX too in the future.

Minor nit: Use semicolon.



Comment at: llvm/test/CodeGen/PowerPC/atomics-i128.ll:160
+; LE-PWR8-NEXT:adde r8, r5, r6
+; LE-PWR8-NEXT:stqcx. r8, 0, r3
+; LE-PWR8-NEXT:bne cr0, .LBB1_1

I have verified that the registers in the pairs are used correctly for this 
case. I've skimmed the other cases for the instructions applied to the loaded 
value (or, for non-inline cases, the functions called).

I did not check that the set-up for the calls, etc.

I also haven't looked into the memory barrier instruction usage (but that 
should be common with other widths).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122377

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


[PATCH] D123308: Handle a subtle hole in inline builtin handling

2022-04-07 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

Also, for the initial lines of commit messages, please try to make them less 
ambiguous about which parts of the project they touch.  For example 
`[Clang][Fortify] drop inline decls when redeclared` is more descriptive should 
this get bucketed with other commits in a buildbot failure. The online helps 
triagers quickly ascertain whether failures they observe look related to which 
change or not.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123308

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


[clang] 4048aad - [clang][ExtractAPI] Fix declaration fragments for ObjC methods

2022-04-07 Thread Zixu Wang via cfe-commits

Author: Zixu Wang
Date: 2022-04-07T10:22:41-07:00
New Revision: 4048aad85a843d2b15cb8e60b2ea37f148b7b770

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

LOG: [clang][ExtractAPI] Fix declaration fragments for ObjC methods

Objective-C methods selector parts should be considered as identifiers.

Depends on D123259

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

Added: 


Modified: 
clang/lib/ExtractAPI/DeclarationFragments.cpp
clang/test/ExtractAPI/objc_category.m
clang/test/ExtractAPI/objc_interface.m

Removed: 




diff  --git a/clang/lib/ExtractAPI/DeclarationFragments.cpp 
b/clang/lib/ExtractAPI/DeclarationFragments.cpp
index a569ff9168bc3..75d360a3ba167 100644
--- a/clang/lib/ExtractAPI/DeclarationFragments.cpp
+++ b/clang/lib/ExtractAPI/DeclarationFragments.cpp
@@ -593,20 +593,21 @@ DeclarationFragments 
DeclarationFragmentsBuilder::getFragmentsForObjCMethod(
 
   // For Objective-C methods that take arguments, build the selector slots.
   for (unsigned i = 0, end = Method->param_size(); i != end; ++i) {
-Fragments.appendSpace()
-.append(Selector.getNameForSlot(i),
-// The first slot is the name of the method, record as an
-// identifier, otherwise as exteranl parameters.
-i == 0 ? DeclarationFragments::FragmentKind::Identifier
-   : DeclarationFragments::FragmentKind::ExternalParam)
-.append(":", DeclarationFragments::FragmentKind::Text);
+// Objective-C method selector parts are considered as identifiers instead
+// of "external parameters" as in Swift. This is because Objective-C method
+// symbols are referenced with the entire selector, instead of just the
+// method name in Swift.
+SmallString<32> ParamID(Selector.getNameForSlot(i));
+ParamID.append(":");
+Fragments.appendSpace().append(
+ParamID, DeclarationFragments::FragmentKind::Identifier);
 
 // Build the internal parameter.
 const ParmVarDecl *Param = Method->getParamDecl(i);
 Fragments.append(getFragmentsForParam(Param));
   }
 
-  return Fragments;
+  return Fragments.append(";", DeclarationFragments::FragmentKind::Text);
 }
 
 DeclarationFragments DeclarationFragmentsBuilder::getFragmentsForObjCProperty(

diff  --git a/clang/test/ExtractAPI/objc_category.m 
b/clang/test/ExtractAPI/objc_category.m
index 2416e3049bd55..20eefdfbb00e5 100644
--- a/clang/test/ExtractAPI/objc_category.m
+++ b/clang/test/ExtractAPI/objc_category.m
@@ -136,6 +136,10 @@ + (void)ClassMethod;
 {
   "kind": "identifier",
   "spelling": "InstanceMethod"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {
@@ -190,6 +194,10 @@ + (void)ClassMethod;
 {
   "kind": "identifier",
   "spelling": "ClassMethod"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {

diff  --git a/clang/test/ExtractAPI/objc_interface.m 
b/clang/test/ExtractAPI/objc_interface.m
index a74a53c8db2cf..5ca6404683987 100644
--- a/clang/test/ExtractAPI/objc_interface.m
+++ b/clang/test/ExtractAPI/objc_interface.m
@@ -146,11 +146,7 @@ - (char)getIvar;
 },
 {
   "kind": "identifier",
-  "spelling": "getWithProperty"
-},
-{
-  "kind": "text",
-  "spelling": ":"
+  "spelling": "getWithProperty:"
 },
 {
   "kind": "text",
@@ -168,6 +164,10 @@ - (char)getIvar;
 {
   "kind": "internalParam",
   "spelling": "Property"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {
@@ -403,6 +403,10 @@ - (char)getIvar;
 {
   "kind": "identifier",
   "spelling": "getIvar"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {



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


[PATCH] D123261: [clang][ExtractAPI] Fix declaration fragments for ObjC methods

2022-04-07 Thread Zixu Wang 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 rG4048aad85a84: [clang][ExtractAPI] Fix declaration fragments 
for ObjC methods (authored by zixuw).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123261

Files:
  clang/lib/ExtractAPI/DeclarationFragments.cpp
  clang/test/ExtractAPI/objc_category.m
  clang/test/ExtractAPI/objc_interface.m


Index: clang/test/ExtractAPI/objc_interface.m
===
--- clang/test/ExtractAPI/objc_interface.m
+++ clang/test/ExtractAPI/objc_interface.m
@@ -146,11 +146,7 @@
 },
 {
   "kind": "identifier",
-  "spelling": "getWithProperty"
-},
-{
-  "kind": "text",
-  "spelling": ":"
+  "spelling": "getWithProperty:"
 },
 {
   "kind": "text",
@@ -168,6 +164,10 @@
 {
   "kind": "internalParam",
   "spelling": "Property"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {
@@ -403,6 +403,10 @@
 {
   "kind": "identifier",
   "spelling": "getIvar"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {
Index: clang/test/ExtractAPI/objc_category.m
===
--- clang/test/ExtractAPI/objc_category.m
+++ clang/test/ExtractAPI/objc_category.m
@@ -136,6 +136,10 @@
 {
   "kind": "identifier",
   "spelling": "InstanceMethod"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {
@@ -190,6 +194,10 @@
 {
   "kind": "identifier",
   "spelling": "ClassMethod"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {
Index: clang/lib/ExtractAPI/DeclarationFragments.cpp
===
--- clang/lib/ExtractAPI/DeclarationFragments.cpp
+++ clang/lib/ExtractAPI/DeclarationFragments.cpp
@@ -593,20 +593,21 @@
 
   // For Objective-C methods that take arguments, build the selector slots.
   for (unsigned i = 0, end = Method->param_size(); i != end; ++i) {
-Fragments.appendSpace()
-.append(Selector.getNameForSlot(i),
-// The first slot is the name of the method, record as an
-// identifier, otherwise as exteranl parameters.
-i == 0 ? DeclarationFragments::FragmentKind::Identifier
-   : DeclarationFragments::FragmentKind::ExternalParam)
-.append(":", DeclarationFragments::FragmentKind::Text);
+// Objective-C method selector parts are considered as identifiers instead
+// of "external parameters" as in Swift. This is because Objective-C method
+// symbols are referenced with the entire selector, instead of just the
+// method name in Swift.
+SmallString<32> ParamID(Selector.getNameForSlot(i));
+ParamID.append(":");
+Fragments.appendSpace().append(
+ParamID, DeclarationFragments::FragmentKind::Identifier);
 
 // Build the internal parameter.
 const ParmVarDecl *Param = Method->getParamDecl(i);
 Fragments.append(getFragmentsForParam(Param));
   }
 
-  return Fragments;
+  return Fragments.append(";", DeclarationFragments::FragmentKind::Text);
 }
 
 DeclarationFragments DeclarationFragmentsBuilder::getFragmentsForObjCProperty(


Index: clang/test/ExtractAPI/objc_interface.m
===
--- clang/test/ExtractAPI/objc_interface.m
+++ clang/test/ExtractAPI/objc_interface.m
@@ -146,11 +146,7 @@
 },
 {
   "kind": "identifier",
-  "spelling": "getWithProperty"
-},
-{
-  "kind": "text",
-  "spelling": ":"
+  "spelling": "getWithProperty:"
 },
 {
   "kind": "text",
@@ -168,6 +164,10 @@
 {
   "kind": "internalParam",
   "spelling": "Property"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {
@@ -403,6 +403,10 @@
 {
   "kind": "identifier",
   "spelling": "getIvar"
+},
+{
+  "kind": "text",
+  "spelling": ";"
 }
   ],
   "identifier": {
Index: clang/test/ExtractAPI/objc_category.m
===
--- clang/test/ExtractAPI/objc_category.m
+++ clang/test/ExtractAPI/objc_category.m
@@ -136,6 +136,10 @@
 {
   "kind": "identifier",
   "spelling": "InstanceMethod"
+},
+{
+  "kind": "text",

[PATCH] D123308: Handle a subtle hole in inline builtin handling

2022-04-07 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers accepted this revision.
nickdesaulniers added a comment.
This revision is now accepted and ready to land.

Thanks for the quick fix!




Comment at: clang/lib/CodeGen/CGExpr.cpp:4968-4969
 // name to make it clear it's not the actual builtin.
-if (FD->isInlineBuiltinDeclaration() &&
+if (OnlyHasInlineBuiltinDeclaration(FD) &&
 CGF.CurFn->getName() != FDInlineName) {
   llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);

If `OnlyHasInlineBuiltinDeclaration` returning `false` is unusual, can we get 
away with switching the order of the checks here, so that `CGF.CurFn->getName() 
!= FDInlineName` which might be more likely might short circuit the 
conditional? That might help us avoid walking the redecl list in 
`OnlyHasInlineBuiltinDeclaration` occasionally.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123308

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


[PATCH] D123319: Change how we handle auto return types for lambda operator() to be consistent with gcc

2022-04-07 Thread Adrian Prantl via Phabricator via cfe-commits
aprantl added a comment.

I think this is reasonable, but could you add a testcase?




Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:1684
+
+if (AT->isDeduced() && ThisPtr->getPointeeCXXRecordDecl()->isLambda())
+  Elts.push_back(getOrCreateType(AT->getDeducedType(),Unit));

Can you add a comment here, explaining why lambdas are special?


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

https://reviews.llvm.org/D123319

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-07 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/cuda-openmp-driver.cu:1
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target

clang-driver is unneeded. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-07 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/Driver/cuda-openmp-driver.cu:10
+// CHECK: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: 
"[[PTX_SM_35:.+]]"
+// CHECK: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: 
["[[PTX_SM_35]]"], output: "[[CUBIN_SM_35:.+]]"
+// CHECK: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_35]]", 
"[[PTX_SM_35]]"], output: "[[FATBIN_SM_35:.+]]"

Better to add -NEXT whenever applicable


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

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


[PATCH] D123319: Change how we handle auto return types for lambda operator() to be consistent with gcc

2022-04-07 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

I did some experiments where I did not restrict this to lambdas case and I 
could not come up with a test case where we emit debug info and do not have the 
deduced type.

Are there cases where we emit debug info and we don't have the deduced type?

If not what do we gain by using the auto return type?


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

https://reviews.llvm.org/D123319

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


[PATCH] D123148: [clang][extract-api] Process only APIs declared in inputs

2022-04-07 Thread Daniel Grumberg 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 rGaebe5fc6e7d8: [clang][extract-api] Process only APIs 
declared in inputs (authored by dang).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123148

Files:
  clang/include/clang/ExtractAPI/FrontendActions.h
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/test/ExtractAPI/known_files_only.c
  clang/test/ExtractAPI/known_files_only_hmap.c

Index: clang/test/ExtractAPI/known_files_only_hmap.c
===
--- /dev/null
+++ clang/test/ExtractAPI/known_files_only_hmap.c
@@ -0,0 +1,164 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%/t@g" %t/reference.output.json.in >> \
+// RUN: %t/reference.output.json
+// RUN: sed -e "s@INPUT_DIR@%/t@g" %t/known_files_only.hmap.json.in >> \
+// RUN: %t/known_files_only.hmap.json
+// RUN: %hmaptool write %t/known_files_only.hmap.json %t/known_files_only.hmap
+// RUN: %clang -extract-api --product-name=KnownFilesOnlyHmap -target arm64-apple-macosx \
+// RUN: -I%t/known_files_only.hmap -I%t/subdir %t/subdir/subdir1/input.h \
+// RUN: %t/subdir/subdir2/known_file.h -o %t/output.json | FileCheck -allow-empty %s
+
+// Generator version is not consistent across test runs, normalize it.
+// RUN: sed -e "s@\"generator\": \".*\"@\"generator\": \"?\"@g" \
+// RUN: %t/output.json >> %t/output-normalized.json
+// RUN: diff %t/reference.output.json %t/output-normalized.json
+
+// CHECK-NOT: error:
+// CHECK-NOT: warning:
+//--- known_files_only.hmap.json.in
+{
+  "mappings" :
+{
+ "subdir2/known_file.h" : "INPUT_DIR/subdir/subdir3/unknown.h"
+}
+}
+
+//--- subdir/subdir1/input.h
+int num;
+#include "subdir2/known_file.h"
+
+//--- subdir/subdir2/known_file.h
+int known_num;
+
+//--- subdir/subdir3/unknown.h
+// Ensure that these symbols are not emitted in the Symbol Graph.
+#ifndef INPUT4_H
+#define INPUT4_H
+
+#define HELLO 1
+char not_emitted;
+void foo(int);
+struct Foo { int a; };
+
+#endif
+
+//--- reference.output.json.in
+{
+  "metadata": {
+"formatVersion": {
+  "major": 0,
+  "minor": 5,
+  "patch": 3
+},
+"generator": "?"
+  },
+  "module": {
+"name": "KnownFilesOnlyHmap",
+"platform": {
+  "architecture": "arm64",
+  "operatingSystem": {
+"minimumVersion": {
+  "major": 11,
+  "minor": 0,
+  "patch": 0
+},
+"name": "macosx"
+  },
+  "vendor": "apple"
+}
+  },
+  "relationships": [],
+  "symbols": [
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "num"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:@num"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "c.var"
+  },
+  "location": {
+"position": {
+  "character": 5,
+  "line": 1
+},
+"uri": "file://INPUT_DIR/subdir/subdir1/input.h"
+  },
+  "names": {
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "num"
+  }
+],
+"title": "num"
+  },
+  "pathComponents": [
+"num"
+  ]
+},
+{
+  "accessLevel": "public",
+  "declarationFragments": [
+{
+  "kind": "typeIdentifier",
+  "preciseIdentifier": "c:I",
+  "spelling": "int"
+},
+{
+  "kind": "text",
+  "spelling": " "
+},
+{
+  "kind": "identifier",
+  "spelling": "known_num"
+}
+  ],
+  "identifier": {
+"interfaceLanguage": "c",
+"precise": "c:@known_num"
+  },
+  "kind": {
+"displayName": "Global Variable",
+"identifier": "c.var"
+  },
+  "location": {
+"position": {
+  "character": 5,
+  "line": 1
+},
+"uri": "file://INPUT_DIR/subdir/subdir2/known_file.h"
+  },
+  "names": {
+"subHeading": [
+  {
+"kind": "identifier",
+"spelling": "known_num"
+  }
+],
+"title": "known_num"
+  },
+  "pathComponents": [
+"known_num"
+  ]
+}
+  ]
+}
Index: clang/test/ExtractAPI/known_files_only.c
===
--- /dev/null
+++ clang/test/ExtractAPI/known_files_only.c
@@ -0,0 +1,100 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s@INPUT_DIR@%/t@g" 

[clang] aebe5fc - [clang][extract-api] Process only APIs declared in inputs

2022-04-07 Thread Daniel Grumberg via cfe-commits

Author: Daniel Grumberg
Date: 2022-04-07T17:49:05+01:00
New Revision: aebe5fc6e7d8ab99f3796067d430752552932d28

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

LOG: [clang][extract-api] Process only APIs declared in inputs

We should only process APIs declared in the command line inputs to avoid
drowning the ExtractAPI output with symbols the user doesn't care about.
This is achieved by keeping track of the provided input files and
checking that the associated Decl or Macro is declared in one of those files.

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

Added: 
clang/test/ExtractAPI/known_files_only.c
clang/test/ExtractAPI/known_files_only_hmap.c

Modified: 
clang/include/clang/ExtractAPI/FrontendActions.h
clang/lib/ExtractAPI/ExtractAPIConsumer.cpp

Removed: 




diff  --git a/clang/include/clang/ExtractAPI/FrontendActions.h 
b/clang/include/clang/ExtractAPI/FrontendActions.h
index 2bdb61dc6994d..dec3b5ca93d18 100644
--- a/clang/include/clang/ExtractAPI/FrontendActions.h
+++ b/clang/include/clang/ExtractAPI/FrontendActions.h
@@ -39,6 +39,9 @@ class ExtractAPIAction : public ASTFrontendAction {
   /// files.
   std::unique_ptr Buffer;
 
+  /// The input file originally provided on the command line.
+  std::vector KnownInputFiles;
+
   /// Prepare to execute the action on the given CompilerInstance.
   ///
   /// This is called before executing the action on any inputs. This generates 
a

diff  --git a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp 
b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
index 7c2914da7ea0c..949413d7d2b1d 100644
--- a/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
+++ b/clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
@@ -20,6 +20,8 @@
 #include "clang/AST/ParentMapContext.h"
 #include "clang/AST/RawCommentList.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/ExtractAPI/API.h"
 #include "clang/ExtractAPI/AvailabilityInfo.h"
@@ -31,11 +33,15 @@
 #include "clang/Frontend/FrontendOptions.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/PreprocessorOptions.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
+#include 
 
 using namespace clang;
 using namespace extractapi;
@@ -49,12 +55,44 @@ StringRef getTypedefName(const TagDecl *Decl) {
   return {};
 }
 
+struct LocationFileChecker {
+  bool isLocationInKnownFile(SourceLocation Loc) {
+// If the loc refers to a macro expansion we need to first get the file
+// location of the expansion.
+auto FileLoc = SM.getFileLoc(Loc);
+FileID FID = SM.getFileID(FileLoc);
+if (FID.isInvalid())
+  return false;
+
+const auto *File = SM.getFileEntryForID(FID);
+if (!File)
+  return false;
+
+if (KnownFileEntries.count(File))
+  return true;
+
+return false;
+  }
+
+  LocationFileChecker(const SourceManager ,
+  const std::vector )
+  : SM(SM) {
+for (const auto  : KnownFiles)
+  if (auto FileEntry = SM.getFileManager().getFile(KnownFilePath))
+KnownFileEntries.insert(*FileEntry);
+  }
+
+private:
+  const SourceManager 
+  llvm::DenseSet KnownFileEntries;
+};
+
 /// The RecursiveASTVisitor to traverse symbol declarations and collect API
 /// information.
 class ExtractAPIVisitor : public RecursiveASTVisitor {
 public:
-  ExtractAPIVisitor(ASTContext , APISet )
-  : Context(Context), API(API) {}
+  ExtractAPIVisitor(ASTContext , LocationFileChecker , APISet )
+  : Context(Context), API(API), LCF(LCF) {}
 
   const APISet () const { return API; }
 
@@ -76,6 +114,9 @@ class ExtractAPIVisitor : public 
RecursiveASTVisitor {
 Decl->getTemplateSpecializationKind() == TSK_Undeclared)
   return true;
 
+if (!LCF.isLocationInKnownFile(Decl->getLocation()))
+  return true;
+
 // Collect symbol information.
 StringRef Name = Decl->getName();
 StringRef USR = API.recordUSR(Decl);
@@ -133,6 +174,9 @@ class ExtractAPIVisitor : public 
RecursiveASTVisitor {
   return true;
 }
 
+if (!LCF.isLocationInKnownFile(Decl->getLocation()))
+  return true;
+
 // Collect symbol information.
 StringRef Name = Decl->getName();
 StringRef USR = API.recordUSR(Decl);
@@ -167,6 +211,9 @@ class ExtractAPIVisitor : public 
RecursiveASTVisitor {
 if (!Decl->isThisDeclarationADefinition())
   return true;
 
+if (!LCF.isLocationInKnownFile(Decl->getLocation()))
+  return true;
+
 // Collect symbol information.
 StringRef 

[PATCH] D120305: [Driver] Default CLANG_DEFAULT_PIE_ON_LINUX to ON

2022-04-07 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

The ScudoCUnitTest-mips64el-Test failure looks like a mips64el specific issue.

  FAILED: lib/scudo/standalone/tests/ScudoCUnitTest-mips64el-Test 
  cd 
/b/sanitizer-x86_64-linux-qemu/build/llvm_build2_debug_mips64el_qemu/lib/scudo/standalone/tests
 && /b/sanitizer-x86_64-linux-qemu/build/llvm_build0/bin/clang++ 
ScudoUnitTestsObjects.wrappers_c_test.cpp.mips64el.o 
ScudoUnitTestsObjects.scudo_unit_test_main.cpp.mips64el.o 
ScudoUnitTestsObjects.gtest-all.cc.mips64el.o 
/b/sanitizer-x86_64-linux-qemu/build/llvm_build2_debug_mips64el_qemu/lib/scudo/standalone/tests/libRTScudoCUnitTest.mips64el.a
 -o 
/b/sanitizer-x86_64-linux-qemu/build/llvm_build2_debug_mips64el_qemu/lib/scudo/standalone/tests/./ScudoCUnitTest-mips64el-Test
 -fuse-ld=lld --target=mips64el-linux-gnuabi64 -Wthread-safety 
-Wthread-safety-reference -Wthread-safety-beta -lstdc++ -pthread -latomic
  ld.lld: error: cannot preempt symbol: DW.ref.__gxx_personality_v0
  >>> defined in ScudoUnitTestsObjects.wrappers_c_test.cpp.mips64el.o
  >>> referenced by wrappers_c_test.cpp
  >>>   
ScudoUnitTestsObjects.wrappers_c_test.cpp.mips64el.o:(.eh_frame+0x1420B)



In D120305#3436154 , @thakis wrote:

> We're seeing the same problem here 
> https://bugs.chromium.org/p/chromium/issues/detail?id=1314297=linux_upload_clang=2
>
> Reverted in e22a60b1c898a760a73417fa225c2fbe0609a69f 
>  for now.

This was a different problem: on some old systems glibc crt1.o was not compiled 
with -fPIC and cannot be linked as `-pie`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120305

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


[PATCH] D116203: [clang] adds unary type transformations as compiler built-ins

2022-04-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D116203#3436572 , @cjdb wrote:

> Having `__remove_cv` do more than it's advertised to do doesn't sound like a 
> great idea to me. Both libc++ 
> 
>  and libstdc++ 
> 
>  define `std::remove_cv` without extensions, and I think it would be 
> surprising for `__remove_cv` to remove anything else.
>
> I'm not against adding `__remove_restrict`, `__remove_qualifiers` (although 
> "qualifier" could imply ref-qualifiers too?), etc.. I suppose that in the 
> rare case someone wants to remove `volatile restrict` and keep `const&`, it's 
> possible to do `__add_const(__remove_qualifiers(T)&)`.

Sorry, I was really unclear it seems. I was recommending we end up with:

`__remove_const`
`__remove_volatile`
`__remove_restrict`
`__remove_cv`  // Removes just `const` and `volatile`
`__remove_qualifiers` // Removes all qualifiers

and if we someday find a use for adding `__remove_cvr` we can add it (but I 
would be surprised if the need was that great).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116203

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


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

2022-04-07 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

Here are my remarks.




Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1415-1416
+
+  Range CoarseLHS = fillGaps(LHS);
+  Range CoarseRHS = fillGaps(RHS);
+

Avoid filling the gaps, because it's completely possible to compare all the 
ranges.
E.g. //LHS //`[1,2]U[8,9]`  and  //RHS //`[5,6]` are not equal.
And you don't need to fiil the gap in LHS, because it will lead you to a wrong 
answer, like `[1,9] != [5,6]` => **UNKNOWN** instead of **TRUE**.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1420-1421
+
+  auto ConvertedCoarseLHS = convert(CoarseLHS, ResultType);
+  auto ConvertedCoarseRHS = convert(CoarseRHS, ResultType);
+

The `ResultType` of `BO_NE` is `bool`. You don't need to convert your **integer 
**ranges to **boolean**. Otherwise, you'll lose the information to compare. 



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1430-1433
+  if ((ConvertedCoarseLHS->To() < ConvertedCoarseRHS->From()) ||
+  (ConvertedCoarseLHS->From() > ConvertedCoarseRHS->To())) {
+return getTrueRange(T);
+  }

You can simply check an intersection (`RangeSet::Factory::intersect`) between 
the ranges.
If the result range is //empty// then return TRUE.



Comment at: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp:1437-1441
+  if (ConvertedCoarseLHS->getConcreteValue() &&
+  ConvertedCoarseLHS->getConcreteValue() ==
+  ConvertedCoarseRHS->getConcreteValue()) {
+return getFalseRange(T);
+  }

This is OK but check `ConvertedCoarseRHS->getConcreteValue()` for `nullptr` 
before getting the value.




Comment at: clang/test/Analysis/constant-folding.c:339
+  }
+}

I'd like to see the cases with concrete integers as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112621

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


[PATCH] D123319: Change how we handle auto return types for lambda operator() to be consistent with gcc

2022-04-07 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik created this revision.
shafik added reviewers: aprantl, dblaikie, probinson.
Herald added a project: All.
shafik requested review of this revision.

D70524  added support for auto return types 
for C++ member functions. I was implementing support on the LLDB side for 
looking up the deduced type.

I ran into trouble with some cases with respect to lambdas. I looked into how 
gcc was handling these cases and it appears gcc emits the deduced return type 
for lambdas.

So I am changing out behavior to match that.


https://reviews.llvm.org/D123319

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp


Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1678,8 +1678,14 @@
   SmallVector Elts;
   // First element is always return type. For 'void' functions it is NULL.
   QualType temp = Func->getReturnType();
-  if (temp->getTypeClass() == Type::Auto && decl)
-Elts.push_back(CreateType(cast(temp)));
+  if (temp->getTypeClass() == Type::Auto && decl) {
+const AutoType *AT = cast(temp);
+
+if (AT->isDeduced() && ThisPtr->getPointeeCXXRecordDecl()->isLambda())
+  Elts.push_back(getOrCreateType(AT->getDeducedType(),Unit));
+else
+  Elts.push_back(CreateType(AT));
+  }
   else
 Elts.push_back(Args[0]);
 


Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1678,8 +1678,14 @@
   SmallVector Elts;
   // First element is always return type. For 'void' functions it is NULL.
   QualType temp = Func->getReturnType();
-  if (temp->getTypeClass() == Type::Auto && decl)
-Elts.push_back(CreateType(cast(temp)));
+  if (temp->getTypeClass() == Type::Auto && decl) {
+const AutoType *AT = cast(temp);
+
+if (AT->isDeduced() && ThisPtr->getPointeeCXXRecordDecl()->isLambda())
+  Elts.push_back(getOrCreateType(AT->getDeducedType(),Unit));
+else
+  Elts.push_back(CreateType(AT));
+  }
   else
 Elts.push_back(Args[0]);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D116203: [clang] adds unary type transformations as compiler built-ins

2022-04-07 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added a comment.

In D116203#3435729 , @aaron.ballman 
wrote:

> In D116203#3434761 , @rjmccall 
> wrote:
>
>> In D116203#3434515 , @cjdb wrote:
>>
>>> In D116203#3431612 , @rjmccall 
>>> wrote:
>>>
 In D116203#3430332 , 
 @aaron.ballman wrote:

> In D116203#3425512 , @cjdb 
> wrote:
>
>> I've noticed that libstdc++ has `using __remove_cv = typename 
>> remove_cv::type`, which causes Clang to chuck a wobbly. Changing from 
>> `KEYWORD` to `TYPE_TRAIT_1` didn't seem to fix anything.
>> Is there a way we can work around this, or should we just rename 
>> `__remove_cv` and friends to something else?
>
> You could work around it by taking note that you're in a libstdc++ system 
> header and do a special dance, but because these are in the 
> implementation's namespace, I think it's probably kinder for everyone to 
> just pick a different name.
>>>
>>> I was hoping we could do something similar to `struct __remove_cv` which 
>>> would issue a warning?
>>>
> If you wanted to be especially mean, you could go with `__remove_cvr`, 
> but I'd suggest `__remove_cv_qualifiers` instead. However, what about 
> `restrict` qualifiers? We support them in C++: 
> https://godbolt.org/z/11EPefhjf

 Along with a fair number of other vendor qualifiers, yeah.  I think you 
 have to make a policy decision about whether the intent of 
 `std::remove_cv` is really to just remove CV qualifiers or to produce an 
 unqualified type (at the outermost level).  The former is probably more 
 defensible, even if it makes the transform less useful in the presence of 
 extended qualifiers.
>>>
>>> I'm partial to `std::remove_cv` being faithful to its name, unless existing 
>>> implementations do something else already. I don't mind adding support for 
>>> the other stuff, but if there's more than just add/remove `restrict`, we're 
>>> going to have a combinatorial explosion for removes. Is there an alternate 
>>> way we can approach this?
>>> Possibly:
>>>
>>>   template
>>>   using remove_const_t = __remove_qualifiers(T, const);
>>>   
>>>   
>>>   template
>>>   using remove_reference_t = __remove_qualifiers(T, &, &&);
>>>   
>>>   template
>>>   using remove_rcvref_t = __remove_qualifiers(T, const, volatile, restrict, 
>>> &, &&); // rcv instead of cvr to prevent a typo with remove_cvref_t
>>
>> I don't think it's worth adding that parsing complexity for a builtin that 
>> we expect to only be used in system headers.  Let's just remove `const` and 
>> `volatile` and leave other qualifiers in place.
>
> I come down on the opposite side of the fence and think it should remove all 
> qualifiers (or that should be an interface we support in addition to removing 
> just cv qualifiers). WG14 adopted 
> https://www9.open-std.org/jtc1/sc22/wg14/www/docs/n2927.htm into C23 with a 
> `remove_quals` function which removes *all* qualifiers (including `_Atomic`), 
> as an example. But even in C++ mode, I fail to see why we wouldn't want 
>  interface for stripping `__restrict` the same as `const` or `volatile` 
> along with some interface for stripping all qualifiers period (I don't see a 
> huge need for a `__remove_cvr` if we have the ability to remove all 
> qualifiers, so I don't think we need the combinatorial explosion or a complex 
> interface). Basically -- if we have extensions like `__restrict` or _Atomic, 
> we should fully support them rather than halfway do it.

Having `__remove_cv` do more than it's advertised to do doesn't sound like a 
great idea to me. Both libc++ 

 and libstdc++ 

 define `std::remove_cv` without extensions, and I think it would be surprising 
for `__remove_cv` to remove anything else.

I'm not against adding `__remove_restrict`, `__remove_qualifiers` (although 
"qualifier" could imply ref-qualifiers too?), etc.. I suppose that in the rare 
case someone wants to remove `volatile restrict` and keep `const&`, it's 
possible to do `__add_const(__remove_qualifiers(T)&)`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D116203

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


[PATCH] D92956: Fix range-loop-analysis checks for trivial copyability

2022-04-07 Thread Anshil Gandhi via Phabricator via cfe-commits
gandhi21299 added a comment.

Perhaps, a description could be added to this patch before committing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92956

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


[PATCH] D123295: [clang][extract-api] Use dedicated API to check for macro equality

2022-04-07 Thread Zixu Wang via Phabricator via cfe-commits
zixuw accepted this revision.
zixuw 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/D123295/new/

https://reviews.llvm.org/D123295

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


[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added inline comments.



Comment at: flang/test/Driver/mllvm_vs_mmlir.f90:17
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM: --print-ir-after-all
+! MLLVM-NOT: --mlir-{{.*}}

rriddle wrote:
> awarzynski wrote:
> > awarzynski wrote:
> > > rovka wrote:
> > > > rovka wrote:
> > > > > Is this the most llvm-ish option we have? I'm concerned that MLIR 
> > > > > might also decide to add an option that sounds like this (and for 
> > > > > sure -print-ir-before-all is mentioned in the [[ 
> > > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> > > > > Is this the most llvm-ish option we have? I'm concerned that MLIR 
> > > > > might also decide to add an option that sounds like this (and for 
> > > > > sure -print-ir-before-all is mentioned in the [[ 
> > > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> > > > 
> > > > Right, I think that might be why the premerge tests are failing...
> > > > Is this the most llvm-ish option we have? 
> > > 
> > > Sadly, most LLVM options have rather generic names that could at some 
> > > point be added in MLIR. Perhaps you'll spot something more suitable:
> > > 
> > > ```lang=bash
> > > USAGE: flang (LLVM option parsing) [options]
> > > 
> > > OPTIONS:
> > > 
> > > Color Options:
> > > 
> > >   --color   - Use colors in 
> > > output (default=autodetect)
> > > 
> > > General options:
> > > 
> > >   --aarch64-neon-syntax= - Choose style of 
> > > NEON code to emit from AArch64 backend:
> > > =generic-   Emit generic NEON 
> > > assembly
> > > =apple  -   Emit Apple-style 
> > > NEON assembly
> > >   --aarch64-use-aa  - Enable the use of 
> > > AA during codegen.
> > >   --abort-on-max-devirt-iterations-reached  - Abort when the max 
> > > iterations for devirtualization CGSCC repeat pass is reached
> > >   --allow-ginsert-as-artifact   - Allow G_INSERT to 
> > > be considered an artifact. Hack around AMDGPU test infinite loops.
> > >   --always-execute-loop-body- force the body of a 
> > > loop to execute at least once
> > >   --array-constructor-initial-buffer-size=- set the incremental 
> > > array construction buffer size (default=32)
> > >   --cfg-hide-cold-paths=- Hide blocks with 
> > > relative frequency below the given value
> > >   --cfg-hide-deoptimize-paths   -
> > >   --cfg-hide-unreachable-paths  -
> > >   --cost-kind=   - Target cost kind
> > > =throughput -   Reciprocal 
> > > throughput
> > > =latency-   Instruction 
> > > latency
> > > =code-size  -   Code size
> > > =size-latency   -   Code size and 
> > > latency
> > >   --debugify-level=  - Kind of debug info 
> > > to add
> > > =locations  -   Locations only
> > > =location+variables -   Locations and 
> > > Variables
> > >   --debugify-quiet  - Suppress verbose 
> > > debugify output
> > >   --default-kinds= - string to set 
> > > default kind values
> > >   --disable-i2p-p2i-opt - Disables 
> > > inttoptr/ptrtoint roundtrip optimization
> > >   --dot-cfg-mssa= - file name for 
> > > generated dot file
> > >   --enable-cse-in-irtranslator  - Should enable CSE 
> > > in irtranslator
> > >   --enable-cse-in-legalizer - Should enable CSE 
> > > in Legalizer
> > >   --enable-gvn-memdep   -
> > >   --enable-load-in-loop-pre -
> > >   --enable-load-pre -
> > >   --enable-loop-simplifycfg-term-folding-
> > >   --enable-name-compression - Enable 
> > > name/filename string compression
> > >   --enable-split-backedge-in-load-pre   -
> > >   --experimental-debug-variable-locations   - Use experimental 
> > > new value-tracking variable locations
> > >   --fdebug-dump-pre-fir - dump the Pre-FIR 
> > > tree prior to FIR generation
> > >   --fs-profile-debug-bw-threshold=- Only show debug 
> > > message if the source branch weight is greater  than this value.
> > >   --fs-profile-debug-prob-diff-threshold= - Only show debug 
> > > message if the branch probility is greater than this value (in 
> > > percentage).
> > >   --gen-array-coor  - in lowering create 
> > > ArrayCoorOp instead of CoordinateOp
> > >   

[PATCH] D92956: Fix range-loop-analysis checks for trivial copyability

2022-04-07 Thread Anshil Gandhi via Phabricator via cfe-commits
gandhi21299 added a comment.
Herald added a project: All.

@Quuxplusone I can commit this patch on behalf of @fanfuqiang.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D92956

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


[PATCH] D123259: [clang][ExtractAPI] Fix appendSpace in DeclarationFragments

2022-04-07 Thread Zixu Wang 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 rGfe2c77a0065c: [clang][ExtractAPI] Fix appendSpace in 
DeclarationFragments (authored by zixuw).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123259

Files:
  clang/lib/ExtractAPI/DeclarationFragments.cpp
  clang/test/ExtractAPI/global_record.c
  clang/test/ExtractAPI/global_record_multifile.c
  clang/test/ExtractAPI/macro_undefined.c
  clang/test/ExtractAPI/objc_category.m
  clang/test/ExtractAPI/objc_interface.m

Index: clang/test/ExtractAPI/objc_interface.m
===
--- clang/test/ExtractAPI/objc_interface.m
+++ clang/test/ExtractAPI/objc_interface.m
@@ -142,7 +142,7 @@
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") "
 },
 {
   "kind": "identifier",
@@ -163,7 +163,7 @@
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") "
 },
 {
   "kind": "internalParam",
@@ -244,7 +244,7 @@
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") "
 },
 {
   "kind": "typeIdentifier",
@@ -398,7 +398,7 @@
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") "
 },
 {
   "kind": "identifier",
Index: clang/test/ExtractAPI/objc_category.m
===
--- clang/test/ExtractAPI/objc_category.m
+++ clang/test/ExtractAPI/objc_category.m
@@ -131,7 +131,7 @@
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") "
 },
 {
   "kind": "identifier",
@@ -185,7 +185,7 @@
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") "
 },
 {
   "kind": "identifier",
@@ -266,7 +266,7 @@
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") "
 },
 {
   "kind": "typeIdentifier",
Index: clang/test/ExtractAPI/macro_undefined.c
===
--- clang/test/ExtractAPI/macro_undefined.c
+++ clang/test/ExtractAPI/macro_undefined.c
@@ -142,7 +142,7 @@
 },
 {
   "kind": "text",
-  "spelling": " *"
+  "spelling": " * "
 },
 {
   "kind": "internalParam",
@@ -189,7 +189,7 @@
   },
   {
 "kind": "text",
-"spelling": " *"
+"spelling": " * "
   },
   {
 "kind": "internalParam",
Index: clang/test/ExtractAPI/global_record_multifile.c
===
--- clang/test/ExtractAPI/global_record_multifile.c
+++ clang/test/ExtractAPI/global_record_multifile.c
@@ -177,7 +177,7 @@
 },
 {
   "kind": "text",
-  "spelling": " *"
+  "spelling": " * "
 },
 {
   "kind": "internalParam",
@@ -333,7 +333,7 @@
   },
   {
 "kind": "text",
-"spelling": " *"
+"spelling": " * "
   },
   {
 "kind": "internalParam",
Index: clang/test/ExtractAPI/global_record.c
===
--- clang/test/ExtractAPI/global_record.c
+++ clang/test/ExtractAPI/global_record.c
@@ -175,7 +175,7 @@
 },
 {
   "kind": "text",
-  "spelling": " *"
+  "spelling": " * "
 },
 {
   "kind": "internalParam",
@@ -331,7 +331,7 @@
   },
   {
 "kind": "text",
-"spelling": " *"
+"spelling": " * "
   },
   {
 "kind": "internalParam",
Index: clang/lib/ExtractAPI/DeclarationFragments.cpp
===
--- clang/lib/ExtractAPI/DeclarationFragments.cpp
+++ clang/lib/ExtractAPI/DeclarationFragments.cpp
@@ -21,7 +21,7 @@
 
 DeclarationFragments ::appendSpace() {
   if (!Fragments.empty()) {
-Fragment Last = Fragments.back();
+Fragment  = Fragments.back();
 if (Last.Kind == FragmentKind::Text) {
   // Merge the extra space into the last fragment if the last fragment is
   // also text.
@@ -390,7 +390,7 @@
   if (Param->isObjCMethodParameter())
 Fragments.append("(", DeclarationFragments::FragmentKind::Text)
 .append(std::move(TypeFragments))
-.append(")", DeclarationFragments::FragmentKind::Text);
+

[clang] fe2c77a - [clang][ExtractAPI] Fix appendSpace in DeclarationFragments

2022-04-07 Thread Zixu Wang via cfe-commits

Author: Zixu Wang
Date: 2022-04-07T09:17:30-07:00
New Revision: fe2c77a0065cda43418d625f0162a974ce8ec1e5

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

LOG: [clang][ExtractAPI] Fix appendSpace in DeclarationFragments

There is a bug in `DeclarationFragments::appendSpace` where the space
character is added to a local copy of the last fragment.

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

Added: 


Modified: 
clang/lib/ExtractAPI/DeclarationFragments.cpp
clang/test/ExtractAPI/global_record.c
clang/test/ExtractAPI/global_record_multifile.c
clang/test/ExtractAPI/macro_undefined.c
clang/test/ExtractAPI/objc_category.m
clang/test/ExtractAPI/objc_interface.m

Removed: 




diff  --git a/clang/lib/ExtractAPI/DeclarationFragments.cpp 
b/clang/lib/ExtractAPI/DeclarationFragments.cpp
index fa28fad358db9..a569ff9168bc3 100644
--- a/clang/lib/ExtractAPI/DeclarationFragments.cpp
+++ b/clang/lib/ExtractAPI/DeclarationFragments.cpp
@@ -21,7 +21,7 @@ using namespace llvm;
 
 DeclarationFragments ::appendSpace() {
   if (!Fragments.empty()) {
-Fragment Last = Fragments.back();
+Fragment  = Fragments.back();
 if (Last.Kind == FragmentKind::Text) {
   // Merge the extra space into the last fragment if the last fragment is
   // also text.
@@ -390,7 +390,7 @@ DeclarationFragmentsBuilder::getFragmentsForParam(const 
ParmVarDecl *Param) {
   if (Param->isObjCMethodParameter())
 Fragments.append("(", DeclarationFragments::FragmentKind::Text)
 .append(std::move(TypeFragments))
-.append(")", DeclarationFragments::FragmentKind::Text);
+.append(") ", DeclarationFragments::FragmentKind::Text);
   else
 Fragments.append(std::move(TypeFragments)).appendSpace();
 

diff  --git a/clang/test/ExtractAPI/global_record.c 
b/clang/test/ExtractAPI/global_record.c
index 4c14cae2de877..dfe99c2f55f67 100644
--- a/clang/test/ExtractAPI/global_record.c
+++ b/clang/test/ExtractAPI/global_record.c
@@ -175,7 +175,7 @@ char unavailable __attribute__((unavailable));
 },
 {
   "kind": "text",
-  "spelling": " *"
+  "spelling": " * "
 },
 {
   "kind": "internalParam",
@@ -331,7 +331,7 @@ char unavailable __attribute__((unavailable));
   },
   {
 "kind": "text",
-"spelling": " *"
+"spelling": " * "
   },
   {
 "kind": "internalParam",

diff  --git a/clang/test/ExtractAPI/global_record_multifile.c 
b/clang/test/ExtractAPI/global_record_multifile.c
index 76e18811a53b4..577eb121cf922 100644
--- a/clang/test/ExtractAPI/global_record_multifile.c
+++ b/clang/test/ExtractAPI/global_record_multifile.c
@@ -177,7 +177,7 @@ char unavailable __attribute__((unavailable));
 },
 {
   "kind": "text",
-  "spelling": " *"
+  "spelling": " * "
 },
 {
   "kind": "internalParam",
@@ -333,7 +333,7 @@ char unavailable __attribute__((unavailable));
   },
   {
 "kind": "text",
-"spelling": " *"
+"spelling": " * "
   },
   {
 "kind": "internalParam",

diff  --git a/clang/test/ExtractAPI/macro_undefined.c 
b/clang/test/ExtractAPI/macro_undefined.c
index feb4b3f43637e..0ae04d02e1543 100644
--- a/clang/test/ExtractAPI/macro_undefined.c
+++ b/clang/test/ExtractAPI/macro_undefined.c
@@ -142,7 +142,7 @@ FUNC_GEN(bar, const int *, unsigned);
 },
 {
   "kind": "text",
-  "spelling": " *"
+  "spelling": " * "
 },
 {
   "kind": "internalParam",
@@ -189,7 +189,7 @@ FUNC_GEN(bar, const int *, unsigned);
   },
   {
 "kind": "text",
-"spelling": " *"
+"spelling": " * "
   },
   {
 "kind": "internalParam",

diff  --git a/clang/test/ExtractAPI/objc_category.m 
b/clang/test/ExtractAPI/objc_category.m
index bc572adfcd161..2416e3049bd55 100644
--- a/clang/test/ExtractAPI/objc_category.m
+++ b/clang/test/ExtractAPI/objc_category.m
@@ -131,7 +131,7 @@ + (void)ClassMethod;
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") "
 },
 {
   "kind": "identifier",
@@ -185,7 +185,7 @@ + (void)ClassMethod;
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") "
 },
 {
   "kind": "identifier",
@@ -266,7 +266,7 @@ + (void)ClassMethod;
 },
 {
   "kind": "text",
-  "spelling": ")"
+  "spelling": ") 

[PATCH] D122895: [C89/C2x] Improve diagnostics around strict prototypes in C

2022-04-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thanks @erichkeane!

@jyknight, @hubert.reinterpretcast, @eli.friedman -- I'll likely land this 
sometime tomorrow unless I hear from you. But if I land it and you still have 
comments, I'll be happy to address them post commit.


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

https://reviews.llvm.org/D122895

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


[PATCH] D111548: [Clang] Add the `annotate_type` attribute

2022-04-07 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added inline comments.



Comment at: clang/include/clang/Basic/AttrDocs.td:6387
+additional information specific to the annotation category. The optional
+arguments must be constant expressions of arbitrary type.
+

Do we want to mention that it is not actually part of the type system (i.e., 
annotated and unannotated types are considered the same)?



Comment at: clang/include/clang/Basic/AttrDocs.td:6393
+
+  int* [[clang::annotate("category1", "foo", 1)]] 
f(int[[clang::annotate("category2"]] *);
+

Missing closing paren for the second annotate. 



Comment at: clang/lib/AST/TypePrinter.cpp:1686
+  // would require retrieving the attribute arguments, which we don't have 
here.
+  if (T->getAttrKind() == attr::AnnotateType)
+return;

Would it make sense to print something without the arguments? I wonder which 
behavior would be less confusing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111548

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


[PATCH] D120272: [CUDA] Add driver support for compiling CUDA with the new driver

2022-04-07 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 421232.
jhuber6 added a comment.

Update with the more generic clang argument handling.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120272

Files:
  clang/include/clang/Basic/Cuda.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/cuda-openmp-driver.cu

Index: clang/test/Driver/cuda-openmp-driver.cu
===
--- /dev/null
+++ clang/test/Driver/cuda-openmp-driver.cu
@@ -0,0 +1,16 @@
+// REQUIRES: clang-driver
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+
+// RUN: %clang -### -target x86_64-linux-gnu -nocudalib -ccc-print-bindings -fgpu-rdc \
+// RUN:-foffload-new-driver --offload-arch=sm_35 --offload-arch=sm_70 %s 2>&1 \
+// RUN: | FileCheck -check-prefix CHECK %s
+
+// CHECK: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[PTX_SM_35:.+]]"
+// CHECK: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_35]]"], output: "[[CUBIN_SM_35:.+]]"
+// CHECK: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_35]]", "[[PTX_SM_35]]"], output: "[[FATBIN_SM_35:.+]]"
+// CHECK: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]"], output: "[[PTX_SM_70:.+]]"
+// CHECK: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[PTX_SM_70:.+]]"], output: "[[CUBIN_SM_70:.+]]"
+// CHECK: "nvptx64-nvidia-cuda" - "NVPTX::Linker", inputs: ["[[CUBIN_SM_70]]", "[[PTX_SM_70:.+]]"], output: "[[FATBIN_SM_70:.+]]"
+// CHECK: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT]]", "[[FATBIN_SM_35]]", "[[FATBIN_SM_70]]"], output: "[[HOST_OBJ:.+]]"
+// CHECK: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -8248,14 +8248,17 @@
   ArgStringList CmdArgs;
 
   // Pass the CUDA path to the linker wrapper tool.
-  for (auto  : llvm::make_range(OpenMPTCRange.first, OpenMPTCRange.second)) {
-const ToolChain *TC = I.second;
-if (TC->getTriple().isNVPTX()) {
-  CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
-  if (CudaInstallation.isValid())
-CmdArgs.push_back(Args.MakeArgString(
-"--cuda-path=" + CudaInstallation.getInstallPath()));
-  break;
+  for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
+auto TCRange = C.getOffloadToolChains(Kind);
+for (auto  : llvm::make_range(TCRange.first, TCRange.second)) {
+  const ToolChain *TC = I.second;
+  if (TC->getTriple().isNVPTX()) {
+CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
+if (CudaInstallation.isValid())
+  CmdArgs.push_back(Args.MakeArgString(
+  "--cuda-path=" + CudaInstallation.getInstallPath()));
+break;
+  }
 }
   }
 
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -4105,6 +4105,101 @@
   Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
 }
 
+/// Returns the canonical name for the offloading architecture when using HIP or
+/// CUDA.
+static StringRef getCanonicalArchString(Compilation ,
+llvm::opt::DerivedArgList ,
+StringRef ArchStr,
+Action::OffloadKind Kind) {
+  if (Kind == Action::OFK_Cuda) {
+CudaArch Arch = StringToCudaArch(ArchStr);
+if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) {
+  C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
+  return StringRef();
+}
+return Args.MakeArgStringRef(CudaArchToString(Arch));
+  } else if (Kind == Action::OFK_HIP) {
+llvm::StringMap Features;
+// getHIPOffloadTargetTriple() is known to return valid value as it has
+// been called successfully in the CreateOffloadingDeviceToolChains().
+auto Arch = parseTargetID(
+*getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), ArchStr,
+);
+if (!Arch) {
+  C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << ArchStr;
+  C.setContainsError();
+  return StringRef();
+}
+return Args.MakeArgStringRef(
+getCanonicalTargetID(Arch.getValue(), Features));
+  }
+  return StringRef();
+}
+
+/// Checks if the set offloading architectures does not conflict. Returns the
+/// incompatible pair if a conflict occurs.
+static llvm::Optional>
+getConflictOffloadArchCombination(const llvm::DenseSet ,
+  Action::OffloadKind Kind) {
+  if (Kind != Action::OFK_HIP)
+return 

[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-07 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/include/clang/AST/DeclCXX.h:1816-1821
+  void setLambdaIsDependent(bool IsDependent) {
+auto *DD = DefinitionData;
+assert(DD && DD->IsLambda && "setting lambda property of non-lambda 
class");
+auto  = static_cast(*DD);
+DL.DependencyKind = IsDependent ? LDK_AlwaysDependent : LDK_Unknown;
+  }

ChuanqiXu wrote:
> It looks like this one is not used, is it?
Thanks., you are right, i wrote that before realizing i did not need it.



Comment at: clang/include/clang/Sema/ScopeInfo.h:842
+
+  bool BeforeLambdaQualifiersScope = false;
+

ChuanqiXu wrote:
> I think the name `Before*` is a little bit confusing. From the context, it 
> would be set to true in `ActOnLambdaIntroducer`and be set to false in 
> `ActOnLambdaClosureQualifiers`. So it looks like something `IsInRangeOf...`. 
> The name before implies that it should be true by default and be false after 
> some point...
> 
> I am not sure if my point is clear...
I struggle to find a better name, but I added a comment. Does that help? 



Comment at: clang/include/clang/Sema/Sema.h:6848
+
+  // 1: Create the class
+  void ActOnLambdaIntroducer(LambdaIntroducer , Scope *CurContext);

ChuanqiXu wrote:
> The comment looks like a draft.
Thanks for noticing that, I added a longer comment



Comment at: clang/lib/Parse/ParseExprCXX.cpp:1439
+DeclEndLoc = RParenLoc = T.getCloseLocation();
+HasParameters = true;
+  }

ChuanqiXu wrote:
> It looks a little bit. It looks like if the code is `()` and `HasParameters` 
> would still be true. 
Which is what we want to track. But it was not clear, I renamed the variable to 
`HasParentheses`



Comment at: clang/lib/Sema/Scope.cpp:72
+  // Lambdas have an extra prototype scope that doesn't add any depth
+  if (flags & FunctionPrototypeScope && !(flags & LambdaScope))
+PrototypeDepth++;

ChuanqiXu wrote:
> ChuanqiXu wrote:
> > This looks like:
> This isn't addressed. I mean the flags would always be true if the last 
> clause get evaluated.
I'm not sure I understand your point. We are checking that it's a function 
scope that is not a lambda scope.
They are probably other ways to write that but they aren't clearer



Comment at: clang/lib/Sema/SemaLambda.cpp:358-360
+/// Start the definition of a lambda expression.
+/// In this overload, we do not know the type yet
+static QualType finishLambdaMethodType(Sema , clang::CXXRecordDecl *Class,

ChuanqiXu wrote:
> The comment says `Start` while the function name starts with `finish`. It 
> looks odd...
The comment appertain to the `startLambdaDefinition` below, i fixed it. 
I also renamed `finishLambdaMethodType` to buildTypeForLambdaCallOperator` 
which is clearer`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136

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


[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-07 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 421228.
cor3ntin added a comment.

Formatting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136

Files:
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Scope.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/Scope.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
  clang/test/SemaCXX/lambda-capture-type-deduction.cpp
  clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1356,7 +1356,7 @@
 
   Change scope of lambda trailing-return-type
   https://wg21.link/P2036R3;>P2036R3
-  No
+  Clang 15
 
 
   Multidimensional subscript operator
Index: clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
===
--- clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
+++ clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
@@ -95,7 +95,7 @@
 #ifdef AVOID
   auto l4 = [var = param] (int param) { ; }; // no warning
 #else
-  auto l4 = [var = param] (int param) { ; }; // expected-warning {{declaration shadows a local variable}}
+  auto l4 = [var = param](int param) { ; }; // expected-warning 2{{declaration shadows a local variable}}
 #endif
 
   // Make sure that inner lambdas work as well.
Index: clang/test/SemaCXX/lambda-capture-type-deduction.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lambda-capture-type-deduction.cpp
@@ -0,0 +1,132 @@
+// RUN: %clang_cc1 -std=c++2b -verify -fsyntax-only %s
+
+template 
+constexpr bool is_same = false;
+
+template 
+constexpr bool is_same = true;
+
+void f() {
+
+  int y;
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  auto ref = [ = y](
+ decltype([&](decltype(x)) { return 0; }) y) {
+return x;
+  };
+}
+
+void test_noexcept() {
+
+  int y;
+
+  static_assert(noexcept([x = 1] noexcept(is_same) {}()));
+  static_assert(noexcept([x = 1] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([y] noexcept(is_same) {}()));
+  static_assert(noexcept([y] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([=] noexcept(is_same) {}()));
+  static_assert(noexcept([=] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([&] noexcept(is_same) {}()));
+  static_assert(noexcept([&] mutable noexcept(is_same) {}()));
+
+  static_assert(noexcept([&] mutable noexcept(!is_same) {}())); //expected-error {{static_assert failed due}}
+}
+
+void test_requires() {
+
+  int x;
+
+  [x = 1]() requires is_same {}
+  ();
+  [x = 1]() mutable requires is_same {}
+  ();
+  [x]() requires is_same {}
+  ();
+  [x]() mutable requires is_same {}
+  ();
+  [=]() requires is_same {}
+  ();
+  [=]() mutable requires is_same {}
+  ();
+  [&]() requires is_same {}
+  ();
+  [&]() mutable requires is_same {}
+  ();
+  []() requires is_same {}
+  ();
+  []() mutable requires is_same {}
+  ();
+
+  [x = 1]() requires is_same {} (); //expected-error {{no matching function for call to object of type}} \
+   // expected-note {{candidate function not viable}} \
+   // expected-note {{'is_same' evaluated to false}}
+  [x = 1]() mutable requires is_same {} (); // expected-error {{no matching function for call to object of type}} \
+ // expected-note {{candidate function not viable}} \
+ // expected-note {{'is_same' evaluated to false}}
+}
+
+void err() {
+  int y, z;// expected-note 2{{declared here}}
+  auto implicit_tpl = [=]( // expected-note {{variable 'y' is captured here}}
+  decltype(
+  [&] { return 0; }) y) { //expected-error{{captured variable 'y' cannot appear}}
+return y;
+  };
+
+  auto init_tpl = [x = 1](  // expected-note{{explicitly captured here}}
+  decltype([&] { 

[PATCH] D119136: [clang] Implement Change scope of lambda trailing-return-type

2022-04-07 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 421227.
cor3ntin marked 4 inline comments as done.
cor3ntin added a comment.

Address ChuanqiXu's feedback


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119136

Files:
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Scope.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExprCXX.cpp
  clang/lib/Sema/Scope.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaCXXScopeSpec.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/TreeTransform.h
  clang/test/CXX/expr/expr.prim/expr.prim.lambda/p11-1y.cpp
  clang/test/SemaCXX/lambda-capture-type-deduction.cpp
  clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1356,7 +1356,7 @@
 
   Change scope of lambda trailing-return-type
   https://wg21.link/P2036R3;>P2036R3
-  No
+  Clang 15
 
 
   Multidimensional subscript operator
Index: clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
===
--- clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
+++ clang/test/SemaCXX/warn-shadow-in-lambdas.cpp
@@ -95,7 +95,7 @@
 #ifdef AVOID
   auto l4 = [var = param] (int param) { ; }; // no warning
 #else
-  auto l4 = [var = param] (int param) { ; }; // expected-warning {{declaration shadows a local variable}}
+  auto l4 = [var = param](int param) { ; }; // expected-warning 2{{declaration shadows a local variable}}
 #endif
 
   // Make sure that inner lambdas work as well.
Index: clang/test/SemaCXX/lambda-capture-type-deduction.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/lambda-capture-type-deduction.cpp
@@ -0,0 +1,132 @@
+// RUN: %clang_cc1 -std=c++2b -verify -fsyntax-only %s
+
+template 
+constexpr bool is_same = false;
+
+template 
+constexpr bool is_same = true;
+
+void f() {
+
+  int y;
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((x)) { return x; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  static_assert(is_same decltype((y)) { return y; }())>);
+
+  auto ref = [ = y](
+ decltype([&](decltype(x)) { return 0; }) y) {
+return x;
+  };
+}
+
+void test_noexcept() {
+
+  int y;
+
+  static_assert(noexcept([x = 1] noexcept(is_same) {}()));
+  static_assert(noexcept([x = 1] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([y] noexcept(is_same) {}()));
+  static_assert(noexcept([y] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([=] noexcept(is_same) {}()));
+  static_assert(noexcept([=] mutable noexcept(is_same) {}()));
+  static_assert(noexcept([&] noexcept(is_same) {}()));
+  static_assert(noexcept([&] mutable noexcept(is_same) {}()));
+
+  static_assert(noexcept([&] mutable noexcept(!is_same) {}())); //expected-error {{static_assert failed due}}
+}
+
+void test_requires() {
+
+  int x;
+
+  [x = 1]() requires is_same {}
+  ();
+  [x = 1]() mutable requires is_same {}
+  ();
+  [x]() requires is_same {}
+  ();
+  [x]() mutable requires is_same {}
+  ();
+  [=]() requires is_same {}
+  ();
+  [=]() mutable requires is_same {}
+  ();
+  [&]() requires is_same {}
+  ();
+  [&]() mutable requires is_same {}
+  ();
+  []() requires is_same {}
+  ();
+  []() mutable requires is_same {}
+  ();
+
+  [x = 1]() requires is_same {} (); //expected-error {{no matching function for call to object of type}} \
+   // expected-note {{candidate function not viable}} \
+   // expected-note {{'is_same' evaluated to false}}
+  [x = 1]() mutable requires is_same {} (); // expected-error {{no matching function for call to object of type}} \
+ // expected-note {{candidate function not viable}} \
+ // expected-note {{'is_same' evaluated to false}}
+}
+
+void err() {
+  int y, z;// expected-note 2{{declared here}}
+  auto implicit_tpl = [=]( // expected-note {{variable 'y' is captured here}}
+  decltype(
+  [&] { return 0; }) y) { //expected-error{{captured variable 'y' cannot appear}}
+return y;
+  };
+
+  auto init_tpl = [x = 1](  // 

[PATCH] D123297: [flang][driver] Add support for -mmlir

2022-04-07 Thread River Riddle via Phabricator via cfe-commits
rriddle added inline comments.



Comment at: flang/test/Driver/mllvm_vs_mmlir.f90:17
+! MLLVM: flang (LLVM option parsing) [options]
+! MLLVM: --print-ir-after-all
+! MLLVM-NOT: --mlir-{{.*}}

awarzynski wrote:
> awarzynski wrote:
> > rovka wrote:
> > > rovka wrote:
> > > > Is this the most llvm-ish option we have? I'm concerned that MLIR might 
> > > > also decide to add an option that sounds like this (and for sure 
> > > > -print-ir-before-all is mentioned in the [[ 
> > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> > > > Is this the most llvm-ish option we have? I'm concerned that MLIR might 
> > > > also decide to add an option that sounds like this (and for sure 
> > > > -print-ir-before-all is mentioned in the [[ 
> > > > https://mlir.llvm.org/getting_started/Debugging/ |  MLIR docs ]]).
> > > 
> > > Right, I think that might be why the premerge tests are failing...
> > > Is this the most llvm-ish option we have? 
> > 
> > Sadly, most LLVM options have rather generic names that could at some point 
> > be added in MLIR. Perhaps you'll spot something more suitable:
> > 
> > ```lang=bash
> > USAGE: flang (LLVM option parsing) [options]
> > 
> > OPTIONS:
> > 
> > Color Options:
> > 
> >   --color   - Use colors in output 
> > (default=autodetect)
> > 
> > General options:
> > 
> >   --aarch64-neon-syntax= - Choose style of NEON 
> > code to emit from AArch64 backend:
> > =generic-   Emit generic NEON 
> > assembly
> > =apple  -   Emit Apple-style 
> > NEON assembly
> >   --aarch64-use-aa  - Enable the use of AA 
> > during codegen.
> >   --abort-on-max-devirt-iterations-reached  - Abort when the max 
> > iterations for devirtualization CGSCC repeat pass is reached
> >   --allow-ginsert-as-artifact   - Allow G_INSERT to be 
> > considered an artifact. Hack around AMDGPU test infinite loops.
> >   --always-execute-loop-body- force the body of a 
> > loop to execute at least once
> >   --array-constructor-initial-buffer-size=- set the incremental 
> > array construction buffer size (default=32)
> >   --cfg-hide-cold-paths=- Hide blocks with 
> > relative frequency below the given value
> >   --cfg-hide-deoptimize-paths   -
> >   --cfg-hide-unreachable-paths  -
> >   --cost-kind=   - Target cost kind
> > =throughput -   Reciprocal 
> > throughput
> > =latency-   Instruction latency
> > =code-size  -   Code size
> > =size-latency   -   Code size and 
> > latency
> >   --debugify-level=  - Kind of debug info to 
> > add
> > =locations  -   Locations only
> > =location+variables -   Locations and 
> > Variables
> >   --debugify-quiet  - Suppress verbose 
> > debugify output
> >   --default-kinds= - string to set default 
> > kind values
> >   --disable-i2p-p2i-opt - Disables 
> > inttoptr/ptrtoint roundtrip optimization
> >   --dot-cfg-mssa= - file name for 
> > generated dot file
> >   --enable-cse-in-irtranslator  - Should enable CSE in 
> > irtranslator
> >   --enable-cse-in-legalizer - Should enable CSE in 
> > Legalizer
> >   --enable-gvn-memdep   -
> >   --enable-load-in-loop-pre -
> >   --enable-load-pre -
> >   --enable-loop-simplifycfg-term-folding-
> >   --enable-name-compression - Enable name/filename 
> > string compression
> >   --enable-split-backedge-in-load-pre   -
> >   --experimental-debug-variable-locations   - Use experimental new 
> > value-tracking variable locations
> >   --fdebug-dump-pre-fir - dump the Pre-FIR tree 
> > prior to FIR generation
> >   --fs-profile-debug-bw-threshold=- Only show debug 
> > message if the source branch weight is greater  than this value.
> >   --fs-profile-debug-prob-diff-threshold= - Only show debug 
> > message if the branch probility is greater than this value (in percentage).
> >   --gen-array-coor  - in lowering create 
> > ArrayCoorOp instead of CoordinateOp
> >   --generate-merged-base-profiles   - When generating 
> > nested context-sensitive profiles, always generate extra base profile for 
> > function with all its context profiles merged into it.
> >   --inline-all   

[PATCH] D123026: [clang][NFC] Extract EmitAssemblyHelper::shouldEmitRegularLTOSummary

2022-04-07 Thread Teresa Johnson via Phabricator via cfe-commits
tejohnson added a comment.

In D123026#3436323 , 
@psamolysov-intel wrote:

> Colleagues, could you help me with landing? @tejohnson has approved the patch 
> (if I applied the suggestion as it was expected, thank you @tejohnson!)

lgtm. I can commit for you today.


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

https://reviews.llvm.org/D123026

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


  1   2   >