[clang] 3b0dce5 - Use value_or (NFC)

2022-07-15 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2022-07-15T19:46:29-07:00
New Revision: 3b0dce5b8b1596c50360952a8fb031d52562ccf6

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

LOG: Use value_or (NFC)

Added: 


Modified: 
clang/include/clang/APINotes/Types.h
clang/lib/Frontend/InitPreprocessor.cpp
mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp

Removed: 




diff  --git a/clang/include/clang/APINotes/Types.h 
b/clang/include/clang/APINotes/Types.h
index 0e5b43080e4bb..f155d6a063274 100644
--- a/clang/include/clang/APINotes/Types.h
+++ b/clang/include/clang/APINotes/Types.h
@@ -77,7 +77,7 @@ class CommonEntityInfo {
 
   void setSwiftPrivate(llvm::Optional Private) {
 SwiftPrivateSpecified = Private.has_value();
-SwiftPrivate = Private ? *Private : 0;
+SwiftPrivate = Private.value_or(0);
   }
 
   friend bool operator==(const CommonEntityInfo &, const CommonEntityInfo &);

diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index d0360696ff9cb..655490ba06e5d 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -829,15 +829,8 @@ static void InitializePredefinedMacros(const TargetInfo 
,
 
 if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::ObjFW) {
   VersionTuple tuple = LangOpts.ObjCRuntime.getVersion();
-
-  unsigned minor = 0;
-  if (tuple.getMinor())
-minor = tuple.getMinor().value();
-
-  unsigned subminor = 0;
-  if (tuple.getSubminor())
-subminor = tuple.getSubminor().value();
-
+  unsigned minor = tuple.getMinor().value_or(0);
+  unsigned subminor = tuple.getSubminor().value_or(0);
   Builder.defineMacro("__OBJFW_RUNTIME_ABI__",
   Twine(tuple.getMajor() * 1 + minor * 100 +
 subminor));

diff  --git a/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp 
b/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp
index 146d9d0fc64ff..e4ae23e9bcde2 100644
--- a/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp
+++ b/mlir/lib/Dialect/Bufferization/Transforms/BufferUtils.cpp
@@ -160,9 +160,7 @@ bufferization::getGlobalFor(arith::ConstantOp constantOp, 
uint64_t alignment) {
   continue;
 if (!globalOp.getInitialValue().has_value())
   continue;
-uint64_t opAlignment = globalOp.getAlignment().has_value()
-   ? globalOp.getAlignment().value()
-   : 0;
+uint64_t opAlignment = globalOp.getAlignment().value_or(0);
 Attribute initialValue = globalOp.getInitialValue().value();
 if (opAlignment == alignment && initialValue == constantOp.getValue())
   return globalOp;



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


[PATCH] D127270: [clang-format] Add space in placement new expression

2022-07-15 Thread omar ahmed via Phabricator via cfe-commits
omarahmed updated this revision to Diff 445172.
omarahmed added a comment.

Change removes to remove


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127270

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

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -10130,6 +10130,42 @@
 "void delete(link p);\n",
 format("void new (link p);\n"
"void delete (link p);\n"));
+
+  FormatStyle AfterPlacementOperator = getLLVMStyle();
+  AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  EXPECT_EQ(
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave);
+  EXPECT_EQ("new (buf) int;", format("new (buf) int;", AfterPlacementOperator));
+  EXPECT_EQ("new(buf) int;", format("new(buf) int;", AfterPlacementOperator));
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Never;
+  verifyFormat("struct A {\n"
+   "  int *a;\n"
+   "  A(int *p) : a(new(p) int) {\n"
+   "new(p) int;\n"
+   "int *b = new(p) int;\n"
+   "int *c = new(p) int(3);\n"
+   "delete(b);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  verifyFormat("struct A {\n"
+   "  int *a;\n"
+   "  A(int *p) : a(new (p) int) {\n"
+   "new (p) int;\n"
+   "int *b = new (p) int;\n"
+   "int *c = new (p) int(3);\n"
+   "delete (b);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
@@ -20308,6 +20344,24 @@
   SpaceBeforeParens,
   FormatStyle::SBPO_ControlStatementsExceptControlMacros);
 
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  Style.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Never",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Never);
+
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Always",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Always);
+
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Leave",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave);
+
   Style.ColumnLimit = 123;
   FormatStyle BaseStyle = getLLVMStyle();
   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3393,6 +3393,18 @@
 if (Left.is(TT_IfMacro))
   return Style.SpaceBeforeParensOptions.AfterIfMacros ||
  spaceRequiredBeforeParens(Right);
+if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+Left.isOneOf(tok::kw_new, tok::kw_delete) &&
+Right.isNot(TT_OverloadedOperatorLParen) &&
+!(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
+  if (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+  FormatStyle::SpaceBeforeParensCustom::APO_Always ||
+  (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+   FormatStyle::SpaceBeforeParensCustom::APO_Leave &&
+   Right.hasWhitespaceBefore()))
+return true;
+  return false;
+}
 if (Line.Type == LT_ObjCDecl)
   return true;
 if (Left.is(tok::semi))
Index: clang/lib/Format/Format.cpp
===
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -936,6 +936,7 @@
Spacing.AfterFunctionDeclarationName);
 IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
 

[PATCH] D129466: [clang-format][NFC] Replace most of std::vector with SmallVector

2022-07-15 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/lib/Format/ContinuationIndenter.cpp:40
 static unsigned getLengthToMatchingParen(const FormatToken ,
- const std::vector ) 
{
+ const SmallVector ) 
{
   // Normally whether or not a break before T is possible is calculated and

curdeius wrote:
> owenpan wrote:
> > curdeius wrote:
> > > Sorry for a late comment. I think that in a parameter list, we should use 
> > > `SmallVectorBase` to avoid changing the type if the inplace element count 
> > > changes. That's not important now though.
> > Hmm. I can't find an example of `SmallVectorBase` in llvm-project sources, 
> > though.
> Typo, it's Impl: https://llvm.org/doxygen/classllvm_1_1SmallVectorImpl.html
Good catch, though `ArrayRef` is more appropriate in this case. See 
https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h. Fixed in 
a7789d6.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129466

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


[PATCH] D129912: [Tooling/DependencyScanning] Enable passing a `vfs::FileSystem` object to `DependencyScanningTool`

2022-07-15 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi created this revision.
Herald added a project: All.
akyrtzi requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Also include a unit test to validate that the `vfs::FileSystem` object is 
properly used.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129912

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningTool.h
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
  clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
  clang/unittests/Tooling/DependencyScannerTest.cpp

Index: clang/unittests/Tooling/DependencyScannerTest.cpp
===
--- clang/unittests/Tooling/DependencyScannerTest.cpp
+++ clang/unittests/Tooling/DependencyScannerTest.cpp
@@ -14,19 +14,21 @@
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Tooling/CompilationDatabase.h"
-#include "clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Testing/Support/Error.h"
 #include "gtest/gtest.h"
 #include 
 #include 
 
 using namespace clang;
 using namespace tooling;
+using namespace dependencies;
 
 namespace {
 
@@ -203,3 +205,33 @@
   EXPECT_EQ(convert_to_slash(Deps[4]), "/root/header.h");
   EXPECT_EQ(convert_to_slash(Deps[5]), "/root/symlink.h");
 }
+
+TEST(DependencyScanner, ScanDepsWithFS) {
+  std::vector CommandLine = {"clang", "-c", "test.cpp",
+  "-o"
+  "test.cpp.o"};
+  StringRef CWD = "/root";
+
+  auto VFS = new llvm::vfs::InMemoryFileSystem();
+  VFS->setCurrentWorkingDirectory(CWD);
+  auto Sept = llvm::sys::path::get_separator();
+  std::string HeaderPath =
+  std::string(llvm::formatv("{0}root{0}header.h", Sept));
+  std::string TestPath = std::string(llvm::formatv("{0}root{0}test.cpp", Sept));
+
+  VFS->addFile(HeaderPath, 0, llvm::MemoryBuffer::getMemBuffer("\n"));
+  VFS->addFile(TestPath, 0,
+   llvm::MemoryBuffer::getMemBuffer("#include \"header.h\"\n"));
+
+  DependencyScanningService Service(ScanningMode::DependencyDirectivesScan,
+ScanningOutputFormat::Make);
+  DependencyScanningTool ScanTool(Service, VFS);
+
+  std::string DepFile;
+  ASSERT_THAT_ERROR(
+  ScanTool.getDependencyFile(CommandLine, CWD).moveInto(DepFile),
+  llvm::Succeeded());
+  using llvm::sys::path::convert_to_slash;
+  EXPECT_EQ(convert_to_slash(DepFile),
+"test.cpp.o: /root/test.cpp /root/header.h\n");
+}
Index: clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -264,7 +264,8 @@
 } // end anonymous namespace
 
 DependencyScanningWorker::DependencyScanningWorker(
-DependencyScanningService )
+DependencyScanningService ,
+llvm::IntrusiveRefCntPtr FS)
 : Format(Service.getFormat()), OptimizeArgs(Service.canOptimizeArgs()) {
   PCHContainerOps = std::make_shared();
   PCHContainerOps->registerReader(
@@ -274,8 +275,8 @@
   PCHContainerOps->registerWriter(
   std::make_unique());
 
-  auto OverlayFS = llvm::makeIntrusiveRefCnt(
-  llvm::vfs::createPhysicalFileSystem());
+  auto OverlayFS =
+  llvm::makeIntrusiveRefCnt(std::move(FS));
   InMemoryFS = llvm::makeIntrusiveRefCnt();
   OverlayFS->pushOverlay(InMemoryFS);
   RealFS = OverlayFS;
Index: clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp
@@ -50,8 +50,9 @@
 }
 
 DependencyScanningTool::DependencyScanningTool(
-DependencyScanningService )
-: Worker(Service) {}
+DependencyScanningService ,
+llvm::IntrusiveRefCntPtr FS)
+: Worker(Service, std::move(FS)) {}
 
 llvm::Expected DependencyScanningTool::getDependencyFile(
 const std::vector , StringRef CWD,
Index: clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
===
--- clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
+++ clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h
@@ -52,7 +52,8 @@
 /// using the regular processing run.
 class 

[PATCH] D129883: [HLSL] Support cbuffer/tbuffer for hlsl.

2022-07-15 Thread Xiang Li via Phabricator via cfe-commits
python3kgae marked 2 inline comments as done.
python3kgae added inline comments.



Comment at: clang/test/SemaHLSL/cbuffer_tbuffer.hlsl:1
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -ast-dump -o 
- %s | FileCheck %s
+

beanz wrote:
> This looks like it should be an AST test, not SEMA.
> 
> We should also have parser tests for malformed parse cases:
> 
> ```
> cbuffer { ... };
> cbuffer missing_definition;
> int cbuffer; // using a keyword as a variable name
> cbuffer; // lots wrong here...
> cbuffer missing_semicolon { int woo; }
> ```
> 
> It looks like this patch doesn't handle making the buffer variables constant. 
> Having not looked at that I don't know how big of a change that is, so it 
> might be okay as a subsequent patch, but we'll need that support to handle 
> cases like:
> 
> ```
> cbuffer cb{
> int x;
> };
> 
> [numthreads(1,1,1)]
> void main(int GI : SV_GROUPINDEX) {
>   x = GI; // error: buffer content is const
> }
> ```
Marking constant variables const better be done when supporting global constant 
buffer. Will add it in another patch.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129883

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


[clang] a7789d6 - [clang-format][NFC] Replace SmallVector parameter with ArrayRef

2022-07-15 Thread via cfe-commits

Author: owenca
Date: 2022-07-15T17:26:22-07:00
New Revision: a7789d6315ff663fb5e21698264b7b77e89312fe

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

LOG: [clang-format][NFC] Replace SmallVector parameter with ArrayRef

Addresses https://reviews.llvm.org/D129466#3654410.

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 1cd28ab073da4..63214f0aa3d5a 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -37,7 +37,7 @@ static bool shouldIndentWrappedSelectorName(const FormatStyle 
,
 // Returns the length of everything up to the first possible line break after
 // the ), ], } or > matching \c Tok.
 static unsigned getLengthToMatchingParen(const FormatToken ,
- const SmallVector ) 
{
+ ArrayRef Stack) {
   // Normally whether or not a break before T is possible is calculated and
   // stored in T.CanBreakBefore. Braces, array initializers and text proto
   // messages like `key: < ... >` are an exception: a break is possible



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


[PATCH] D129883: [HLSL] Support cbuffer/tbuffer for hlsl.

2022-07-15 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 445162.
python3kgae added a comment.

Code cleanup and add test for error case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129883

Files:
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/TextNodeDumper.h
  clang/include/clang/Basic/DeclNodes.td
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Basic/IdentifierTable.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseHLSL.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/CMakeLists.txt
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaHLSL.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Serialization/ASTCommon.cpp
  clang/test/AST/HLSL/cbuffer_tbuffer.hlsl
  clang/test/SemaHLSL/cb_error.hlsl

Index: clang/test/SemaHLSL/cb_error.hlsl
===
--- /dev/null
+++ clang/test/SemaHLSL/cb_error.hlsl
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -o - -fsyntax-only %s -verify
+
+// expected-error@+2 {{expected identifier}}
+// expected-error@+1 {{expected unqualified-id}}
+cbuffer { ... };
+// expected-error@+1 {{expected '{'}}
+cbuffer missing_definition;
+// expected-error@+1 {{expected unqualified-id}}
+int cbuffer;
+// expected-error@+1 {{expected identifier}}
+cbuffer;
+
Index: clang/test/AST/HLSL/cbuffer_tbuffer.hlsl
===
--- /dev/null
+++ clang/test/AST/HLSL/cbuffer_tbuffer.hlsl
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -ast-dump -o - %s | FileCheck %s
+
+// CHECK:HLSLBufferDecl 0x[[CB:[0-9a-f]+]] {{.*}} line:5:9 cbuffer CB
+// CHECK-NEXT:VarDecl 0x[[A:[0-9a-f]+]] {{.*}} col:9 used a 'float'
+cbuffer CB {
+  float a;
+}
+
+// CHECK:HLSLBufferDecl 0x[[TB:[0-9a-f]+]] {{.*}} line:11:9 tbuffer TB
+// CHECK-NEXT:VarDecl 0x[[B:[0-9a-f]+]] {{.*}} col:9 used b 'float'
+tbuffer TB {
+  float b;
+}
+
+float foo() {
+// CHECK: BinaryOperator 0x{{[0-9a-f]+}}  'float' '+'
+// CHECK-NEXT: ImplicitCastExpr 0x{{[0-9a-f]+}}  'float' 
+// CHECK-NEXT: DeclRefExpr 0x{{[0-9a-f]+}}  'float' lvalue Var 0x[[A]] 'a' 'float'
+// CHECK-NEXT: ImplicitCastExpr 0x{{[0-9a-f]+}}  'float' 
+// CHECK-NEXT: DeclRefExpr 0x{{[0-9a-f]+}}  'float' lvalue Var 0x[[B]] 'b' 'float'
+  return a + b;
+}
Index: clang/lib/Serialization/ASTCommon.cpp
===
--- clang/lib/Serialization/ASTCommon.cpp
+++ clang/lib/Serialization/ASTCommon.cpp
@@ -433,6 +433,7 @@
   case Decl::LifetimeExtendedTemporary:
   case Decl::RequiresExprBody:
   case Decl::UnresolvedUsingIfExists:
+  case Decl::HLSLBuffer:
 return false;
 
   // These indirectly derive from Redeclarable but are not actually
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -873,6 +873,10 @@
   llvm_unreachable("Translation units cannot be instantiated");
 }
 
+Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
+  llvm_unreachable("HLSL buffer declarations cannot be instantiated");
+}
+
 Decl *
 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
   llvm_unreachable("pragma comment cannot be instantiated");
Index: clang/lib/Sema/SemaHLSL.cpp
===
--- /dev/null
+++ clang/lib/Sema/SemaHLSL.cpp
@@ -0,0 +1,37 @@
+//===- SemaHLSL.cpp - Semantic Analysis for HLSL constructs ---===//
+//
+// 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 implements Semantic Analysis for HLSL constructs.
+//===--===//
+
+#include "clang/Sema/Sema.h"
+
+using namespace clang;
+
+Decl *Sema::ActOnStartHLSLBuffer(Scope *BufferScope, bool CBuffer,
+ SourceLocation KwLoc, IdentifierInfo *Ident,
+ SourceLocation IdentLoc,
+ SourceLocation LBrace) {
+  // For anonymous namespace, take the location of the left brace.
+  DeclContext *LexicalParent = getCurLexicalContext();
+  HLSLBufferDecl *Result = HLSLBufferDecl::Create(
+  Context, LexicalParent, CBuffer, KwLoc, Ident, IdentLoc, LBrace);
+
+  

[PATCH] D129280: [analyzer] PlacementNewChecker, properly handle array overhead (cookie)

2022-07-15 Thread Domján Dániel via Phabricator via cfe-commits
isuckatcs added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/CheckPlacementNew.cpp:157
 "Storage provided to placement new is only {0} bytes, "
-"whereas the allocated array type requires more space for "
-"internal needs",
-SizeOfPlaceCI->getValue(), SizeOfTargetCI->getValue()));
+"whereas the allocated array type might require more space for "
+"allocation overhead",

martong wrote:
> NoQ wrote:
> > "might" is not very convincing, it may cause a reaction like "I've no idea 
> > what it's talking about and the compiler itself isn't sure, must be false 
> > positive". Can we do anything to point the user in the right direction? 
> > Say, if this is implementation-defined, are we looking at a portability 
> > issue?
> Okay, I see your point. Let's dissect the corresponding sections of the 
> standard:
> ```
> new(2, f) T[5] results in a call of operator new[](sizeof(T) * 5 + y, 2, f).
> 
> Here, ... and y are non-negative unspecified values representing array 
> allocation overhead;
> ```
> The array overhead is an **unspecified value**. What does it mean exactly? My 
> understanding is that this means it is implementation defined and the 
> implementation is not required to document or guarantee anything. I came to 
> this conclusion based on this [[ 
> https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior
>  | stackoverflow question ]]. 
> 
> My interpretation could be wrong, but that does not matter. I think, we 
> should just simply display the user what the standard says, and let them 
> digest themselves the meaning of "unspecified". I am updating the patch like 
> so.
I also looked into this overhead question. In this [[ 
https://stackoverflow.com/a/8721932 | stackoverflow answer]] someone links the 
same defect report that you did, and claims that since it's a defect report, it 
has been applied retroactively. 

Apparently [[ https://en.cppreference.com/w/cpp/language/new | cppreference ]] 
says the same. If you check the defect reports section on the bottom of the 
page you can see:
```
The following behavior-changing defect reports were applied retroactively to 
previously published C++ standards.

...
DR | Applied to | Behavior as published | Correct behavior
CWG 2382 | C++98 | non-allocating placement array new could require allocation 
overhead | such allocation overhead disallowed
```

So in my understanding you don't need to worry about this overhead at all. I 
hope this helps.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129280

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


[PATCH] D128401: [clang-tidy] Fixing a bug raising false alarms on static local variables in the Infinite Loop Checker

2022-07-15 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added a comment.

In D128401#3656559 , @NoQ wrote:

> Looks great, thanks!
>
> Yes, I think refactoring can be done in a follow-up patch.

Thank you, @NoQ!

Let me politely ping the rest of the commenters: @LegalizeAdulthood, 
@gribozavr2, @Eugene.Zelenko.  Is this patch looking good to you?


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

https://reviews.llvm.org/D128401

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


[clang] 46a6989 - [unittests/Tooling/DependencyScannerTest.cpp] Use `using namespace` instead of wrapping the `.cpp` file contents in namespaces, NFC

2022-07-15 Thread Argyrios Kyrtzidis via cfe-commits

Author: Argyrios Kyrtzidis
Date: 2022-07-15T16:10:36-07:00
New Revision: 46a69897364354c9ffcfb1f5f2341e675898d116

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

LOG: [unittests/Tooling/DependencyScannerTest.cpp] Use `using namespace` 
instead of wrapping the `.cpp` file contents in namespaces, NFC

This makes the file consistent with the coding style of the rest of LLVM.

Added: 


Modified: 
clang/unittests/Tooling/DependencyScannerTest.cpp

Removed: 




diff  --git a/clang/unittests/Tooling/DependencyScannerTest.cpp 
b/clang/unittests/Tooling/DependencyScannerTest.cpp
index a9d6e6e7fb6fd..6480ceacee963 100644
--- a/clang/unittests/Tooling/DependencyScannerTest.cpp
+++ b/clang/unittests/Tooling/DependencyScannerTest.cpp
@@ -25,8 +25,8 @@
 #include 
 #include 
 
-namespace clang {
-namespace tooling {
+using namespace clang;
+using namespace tooling;
 
 namespace {
 
@@ -203,6 +203,3 @@ TEST(DependencyScanner, ScanDepsReuseFilemanagerHasInclude) 
{
   EXPECT_EQ(convert_to_slash(Deps[4]), "/root/header.h");
   EXPECT_EQ(convert_to_slash(Deps[5]), "/root/symlink.h");
 }
-
-} // end namespace tooling
-} // end namespace clang



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


[PATCH] D128401: [clang-tidy] Fixing a bug raising false alarms on static local variables in the Infinite Loop Checker

2022-07-15 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ accepted this revision.
NoQ added a comment.

Looks great, thanks!

Yes, I think refactoring can be done in a follow-up patch.


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

https://reviews.llvm.org/D128401

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


[PATCH] D129885: [CUDA] Make the new driver properly ignore non-CUDA inputs

2022-07-15 Thread Joseph Huber 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 rGbb957a8d524c: [CUDA] Make the new driver properly ignore 
non-CUDA inputs (authored by jhuber6).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129885

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cuda-phases.cu

Index: clang/test/Driver/cuda-phases.cu
===
--- clang/test/Driver/cuda-phases.cu
+++ clang/test/Driver/cuda-phases.cu
@@ -221,48 +221,76 @@
 //
 // Test the phases generated when using the new offloading driver.
 //
-// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases --offload-new-driver -fgpu-rdc \
-// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW-DRIVER-RDC %s
-// NEW-DRIVER-RDC: 0: input, "[[INPUT:.+]]", cuda
-// NEW-DRIVER-RDC: 1: preprocessor, {0}, cuda-cpp-output
-// NEW-DRIVER-RDC: 2: compiler, {1}, ir
-// NEW-DRIVER-RDC: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 5: compiler, {4}, ir, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 6: backend, {5}, assembler, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 7: assembler, {6}, object, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
-// NEW-DRIVER-RDC: 9: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 10: preprocessor, {9}, cuda-cpp-output, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 11: compiler, {10}, ir, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 12: backend, {11}, assembler, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 13: assembler, {12}, object, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 14: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {13}, object
-// NEW-DRIVER-RDC: 15: clang-offload-packager, {8, 14}, image
-// NEW-DRIVER-RDC: 16: offload, " (powerpc64le-ibm-linux-gnu)" {2}, " (powerpc64le-ibm-linux-gnu)" {15}, ir
-// NEW-DRIVER-RDC: 17: backend, {16}, assembler, (host-cuda)
-// NEW-DRIVER-RDC: 18: assembler, {17}, object, (host-cuda)
-// NEW-DRIVER-RDC: 19: clang-linker-wrapper, {18}, image, (host-cuda)
+// RUN: %clang -### --target=powerpc64le-ibm-linux-gnu -ccc-print-phases --offload-new-driver -fgpu-rdc \
+// RUN:   --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW-DRIVER-RDC %s
+//  NEW-DRIVER-RDC: 0: input, "[[INPUT:.+]]", cuda
+// NEW-DRIVER-RDC-NEXT: 1: preprocessor, {0}, cuda-cpp-output
+// NEW-DRIVER-RDC-NEXT: 2: compiler, {1}, ir
+// NEW-DRIVER-RDC-NEXT: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 5: compiler, {4}, ir, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 6: backend, {5}, assembler, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 7: assembler, {6}, object, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
+// NEW-DRIVER-RDC-NEXT: 9: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 10: preprocessor, {9}, cuda-cpp-output, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 11: compiler, {10}, ir, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 12: backend, {11}, assembler, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 13: assembler, {12}, object, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 14: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {13}, object
+// NEW-DRIVER-RDC-NEXT: 15: clang-offload-packager, {8, 14}, image
+// NEW-DRIVER-RDC-NEXT: 16: offload, " (powerpc64le-ibm-linux-gnu)" {2}, " (powerpc64le-ibm-linux-gnu)" {15}, ir
+// NEW-DRIVER-RDC-NEXT: 17: backend, {16}, assembler, (host-cuda)
+// NEW-DRIVER-RDC-NEXT: 18: assembler, {17}, object, (host-cuda)
+// NEW-DRIVER-RDC-NEXT: 19: clang-linker-wrapper, {18}, image, (host-cuda)
 
 // RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases --offload-new-driver -fgpu-rdc \
-// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW-DRIVER %s
-// NEW-DRIVER: 0: input, "[[INPUT:.+]]", cuda
-// NEW-DRIVER: 1: preprocessor, {0}, cuda-cpp-output
-// NEW-DRIVER: 2: compiler, {1}, ir
-// NEW-DRIVER: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
-// NEW-DRIVER: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
-// NEW-DRIVER: 5: compiler, {4}, ir, (device-cuda, sm_52)
-// NEW-DRIVER: 6: backend, {5}, assembler, (device-cuda, sm_52)
-// NEW-DRIVER: 7: assembler, {6}, object, (device-cuda, sm_52)
-// NEW-DRIVER: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
-// NEW-DRIVER: 9: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
-// NEW-DRIVER: 10: preprocessor, {9}, cuda-cpp-output, (device-cuda, sm_70)
-// NEW-DRIVER: 11: compiler, {10}, ir, 

[clang] bb957a8 - [CUDA] Make the new driver properly ignore non-CUDA inputs

2022-07-15 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2022-07-15T17:38:34-04:00
New Revision: bb957a8d524cd38d6c5f7d547302258026049438

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

LOG: [CUDA] Make the new driver properly ignore non-CUDA inputs

The new driver generated offloadinga actions for each active toolchain.
However, for CUDA and HIP it is possible for the toolchain to be active
but one of the files is not a valid input. This can occur if the user
compiles both a CUDA and C source file in the same compiler invocation.
This patch adds some simple logic to quit if the input is not valid as
well.

Reviewed By: tra, MaskRay

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

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/test/Driver/cuda-phases.cu

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 3a8400a557416..bd2b9a5b39b39 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4432,6 +4432,11 @@ Action *Driver::BuildOffloadingActions(Compilation ,
 types::ID InputType = Input.first;
 const Arg *InputArg = Input.second;
 
+// The toolchain can be active for unsupported file types.
+if ((Kind == Action::OFK_Cuda && !types::isCuda(InputType)) ||
+(Kind == Action::OFK_HIP && !types::isHIP(InputType)))
+  continue;
+
 // Get the product of all bound architectures and toolchains.
 SmallVector> TCAndArchs;
 for (const ToolChain *TC : ToolChains)
@@ -4486,6 +4491,9 @@ Action *Driver::BuildOffloadingActions(Compilation ,
   if (offloadDeviceOnly())
 return C.MakeAction(DDeps, types::TY_Nothing);
 
+  if (OffloadActions.empty())
+return HostAction;
+
   OffloadAction::DeviceDependences DDep;
   if (C.isOffloadingHostKind(Action::OFK_Cuda) &&
   !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) {

diff  --git a/clang/test/Driver/cuda-phases.cu 
b/clang/test/Driver/cuda-phases.cu
index dc469f1bf168a..4e0c66aefab5b 100644
--- a/clang/test/Driver/cuda-phases.cu
+++ b/clang/test/Driver/cuda-phases.cu
@@ -221,48 +221,76 @@
 //
 // Test the phases generated when using the new offloading driver.
 //
-// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases 
--offload-new-driver -fgpu-rdc \
-// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck 
--check-prefix=NEW-DRIVER-RDC %s
-// NEW-DRIVER-RDC: 0: input, "[[INPUT:.+]]", cuda
-// NEW-DRIVER-RDC: 1: preprocessor, {0}, cuda-cpp-output
-// NEW-DRIVER-RDC: 2: compiler, {1}, ir
-// NEW-DRIVER-RDC: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 5: compiler, {4}, ir, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 6: backend, {5}, assembler, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 7: assembler, {6}, object, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, 
object
-// NEW-DRIVER-RDC: 9: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 10: preprocessor, {9}, cuda-cpp-output, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 11: compiler, {10}, ir, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 12: backend, {11}, assembler, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 13: assembler, {12}, object, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 14: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" 
{13}, object
-// NEW-DRIVER-RDC: 15: clang-offload-packager, {8, 14}, image
-// NEW-DRIVER-RDC: 16: offload, " (powerpc64le-ibm-linux-gnu)" {2}, " 
(powerpc64le-ibm-linux-gnu)" {15}, ir
-// NEW-DRIVER-RDC: 17: backend, {16}, assembler, (host-cuda)
-// NEW-DRIVER-RDC: 18: assembler, {17}, object, (host-cuda)
-// NEW-DRIVER-RDC: 19: clang-linker-wrapper, {18}, image, (host-cuda)
+// RUN: %clang -### --target=powerpc64le-ibm-linux-gnu -ccc-print-phases 
--offload-new-driver -fgpu-rdc \
+// RUN:   --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck 
--check-prefix=NEW-DRIVER-RDC %s
+//  NEW-DRIVER-RDC: 0: input, "[[INPUT:.+]]", cuda
+// NEW-DRIVER-RDC-NEXT: 1: preprocessor, {0}, cuda-cpp-output
+// NEW-DRIVER-RDC-NEXT: 2: compiler, {1}, ir
+// NEW-DRIVER-RDC-NEXT: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, 
sm_52)
+// NEW-DRIVER-RDC-NEXT: 5: compiler, {4}, ir, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 6: backend, {5}, assembler, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 7: assembler, {6}, object, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" 
{7}, object
+// NEW-DRIVER-RDC-NEXT: 9: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 10: preprocessor, {9}, cuda-cpp-output, 

[PATCH] D129504: [libclang][ObjC] Inherit availability attribute from containing decls or interface decls

2022-07-15 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir accepted this revision.
benlangmuir added a comment.
This revision is now accepted and ready to land.

LGTM, thanks


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129504

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


[PATCH] D129504: [libclang][ObjC] Inherit availability attribute from containing decls or interface decls

2022-07-15 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 445130.
ahatanak marked an inline comment as done.
ahatanak added a comment.

If a category decl doesn't have availability, inherit it from the class decl.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129504

Files:
  clang/test/Index/availability.mm
  clang/tools/libclang/CIndex.cpp

Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -8258,8 +8258,35 @@
   deprecated_message, always_unavailable, unavailable_message,
   AvailabilityAttrs);
 
-  if (AvailabilityAttrs.empty())
+  // If no availability attributes are found, inherit the attribute from the
+  // containing decl or the class or category interface decl.
+  if (AvailabilityAttrs.empty()) {
+const ObjCContainerDecl *CD = nullptr;
+const DeclContext *DC = D->getDeclContext();
+
+if (auto *IMD = dyn_cast(D))
+  CD = IMD->getClassInterface();
+else if (auto *CatD = dyn_cast(D))
+  CD = CatD->getClassInterface();
+else if (auto *IMD = dyn_cast(D))
+  CD = IMD->getCategoryDecl();
+else if (auto *ID = dyn_cast(DC))
+  CD = ID;
+else if (auto *CatD = dyn_cast(DC))
+  CD = CatD;
+else if (auto *IMD = dyn_cast(DC))
+  CD = IMD->getClassInterface();
+else if (auto *IMD = dyn_cast(DC))
+  CD = IMD->getCategoryDecl();
+else if (auto *PD = dyn_cast(DC))
+  CD = PD;
+
+if (CD)
+  getCursorPlatformAvailabilityForDecl(
+  CD, always_deprecated, deprecated_message, always_unavailable,
+  unavailable_message, AvailabilityAttrs);
 return;
+  }
 
   llvm::sort(
   AvailabilityAttrs, [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
Index: clang/test/Index/availability.mm
===
--- /dev/null
+++ clang/test/Index/availability.mm
@@ -0,0 +1,79 @@
+__attribute__((availability(macosx, introduced = 8.0)))
+@interface C {
+  int i0;
+  int i1 __attribute__((availability(macosx, introduced = 9.0)));
+}
+@property int p0;
+@property int p1 __attribute__((availability(macosx, introduced=9.0)));
+- (void)m0;
+- (void)m1 __attribute__((availability(macosx, introduced = 9.0)));
+@end
+
+@implementation C
+- (void)m0 {
+}
+- (void)m1 {
+}
+@end
+
+__attribute__((availability(macosx, introduced = 10.0)))
+@interface C(Cat)
+@property int p2;
+@property int p3 __attribute__((availability(macosx, introduced=11.0)));
+- (void)m2;
+- (void)m3 __attribute__((availability(macosx, introduced = 11.0)));
+@end
+
+@implementation C(Cat)
+- (void)m2 {
+}
+- (void)m3 {
+}
+@end
+
+__attribute__((availability(macosx, introduced = 10.0)))
+@protocol P
+@property int p4;
+@property int p5 __attribute__((availability(macosx, introduced=11.0)));
+- (void)m4;
+- (void)m5 __attribute__((availability(macosx, introduced = 11.0)));
+@end
+
+@interface C(Cat2)
+@end
+
+@implementation C(Cat2)
+@end
+
+// RUN: c-index-test -test-print-type --std=c++11 %s | FileCheck %s
+
+// CHECK: ObjCInterfaceDecl=C:2:12  (macos, introduced=8.0)
+// CHECK: ObjCIvarDecl=i0:3:7 (Definition)  (macos, introduced=8.0)
+// CHECK: ObjCIvarDecl=i1:4:7 (Definition)  (macos, introduced=9.0)
+// CHECK: ObjCPropertyDecl=p0:6:15  (macos, introduced=8.0)
+// CHECK: ObjCPropertyDecl=p1:7:15  (macos, introduced=9.0)
+// CHECK: ObjCInstanceMethodDecl=m0:8:9  (macos, introduced=8.0)
+// CHECK: ObjCInstanceMethodDecl=m1:9:9  (macos, introduced=9.0)
+
+// CHECK: ObjCImplementationDecl=C:12:17 (Definition)  (macos, introduced=8.0)
+// CHECK: ObjCInstanceMethodDecl=m0:13:9 (Definition)  (macos, introduced=8.0)
+// CHECK: ObjCInstanceMethodDecl=m1:15:9 (Definition)  (macos, introduced=9.0)
+
+// CHECK: ObjCCategoryDecl=Cat:20:12  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p2:21:15  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p3:22:15  (macos, introduced=11.0)
+// CHECK: ObjCInstanceMethodDecl=m2:23:9  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m3:24:9  (macos, introduced=11.0)
+
+// CHECK: ObjCCategoryImplDecl=Cat:27:17 (Definition)  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m2:28:9 (Definition)  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m3:30:9 (Definition)  (macos, introduced=11.0)
+
+// CHECK: ObjCProtocolDecl=P:35:11 (Definition)  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p4:36:15  (macos, introduced=10.0)
+// CHECK: ObjCPropertyDecl=p5:37:15  (macos, introduced=11.0)
+// CHECK: ObjCInstanceMethodDecl=m4:38:9  (macos, introduced=10.0)
+// CHECK: ObjCInstanceMethodDecl=m5:39:9  (macos, introduced=11.0)
+
+// CHECK: ObjCCategoryDecl=Cat2:42:12  (macos, introduced=8.0)
+// CHECK: ObjCCategoryImplDecl=Cat2:45:17 (Definition)  (macos, introduced=8.0)
___
cfe-commits mailing list

[PATCH] D129892: [clang-format] Fix aligning of trailing comments after comment at the end of a namespace

2022-07-15 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:17468-17470
+   "// Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+   "Nullam cursus nunc\n"
+   "// non",

Shouldn't this be aligned?



Comment at: clang/unittests/Format/FormatTest.cpp:17479
+   Style);
+  verifyFormat("namespace test {\n"
+   "class C;\n"

Why repeat this here with just a longer comment, or do I miss something?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129892

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


[PATCH] D129883: [HLSL] Support cbuffer/tbuffer for hlsl.

2022-07-15 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added inline comments.



Comment at: clang/include/clang/Parse/Parser.h:2820
   SourceLocation *EndLoc = nullptr);
+  Decl *ParseCTBuffer(SourceLocation ,
+  SourceLocation InlineLoc = SourceLocation());

nit: maybe `ParseHLSLBuffer`, I don't think `ParseCTBuffer` makes it apparent 
what this is doing, also everything else is `HLSLBuffer`



Comment at: clang/test/SemaHLSL/cbuffer_tbuffer.hlsl:1
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -ast-dump -o 
- %s | FileCheck %s
+

This looks like it should be an AST test, not SEMA.

We should also have parser tests for malformed parse cases:

```
cbuffer { ... };
cbuffer missing_definition;
int cbuffer; // using a keyword as a variable name
cbuffer; // lots wrong here...
cbuffer missing_semicolon { int woo; }
```

It looks like this patch doesn't handle making the buffer variables constant. 
Having not looked at that I don't know how big of a change that is, so it might 
be okay as a subsequent patch, but we'll need that support to handle cases like:

```
cbuffer cb{
int x;
};

[numthreads(1,1,1)]
void main(int GI : SV_GROUPINDEX) {
  x = GI; // error: buffer content is const
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129883

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


[PATCH] D129886: [clang] Add -fdiagnostics-format=sarif for SARIF diagnostics

2022-07-15 Thread Vaibhav Yenamandra via Phabricator via cfe-commits
vaibhav.y added a comment.

Might be worth hiding it from `--help`, despite the instability warning.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129886

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


[PATCH] D121141: [Clang] Add `-fexperimental-library` flag to enable unstable and experimental features: follow-up fixes

2022-07-15 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added subscribers: phosek, hans, thakis, rnk.
mstorsjo added a comment.

In D121141#3655323 , @ldionne wrote:

> The `experimental-library-flag` test is currently failing on Windows because 
> on Windows, `-stdlib=libc++` seems to be ignored and we don't add `-lc++` or 
> `-lc++experimental`. Does someone understand how things are supposed to work 
> when using libc++ on Windows? @mstorsjo maybe?

Clarification - I presume it would fail when targeting MSVC, not when targeting 
mingw.

Yes, I think `-stdlib=libc++` has no effect on MSVC targets currently, and you 
have to add the include directory and lib arguments when using it - I think 
@rnk, @hans or @thakis can confirm that.

@phosek has a patch to take the option into use there too, but it's essentially 
blocked by D103947  if I remember correctly. 
(The chain of dependencies that trigger that is a bit non-obvious, but I think 
it was the case that they build their Clang with 
`-DCLANG_DEFAULT_CXX_STDLIB=libc++`, and once that has an effect on the MSVC 
configs, a bunch of code in their build setup suddenly ends up using libc++ 
instead of MSVC STL, and there's a lot of code there that is built with 
`_HAS_EXCEPTIONS=0` - hence libc++ needing to work in that configuration.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121141

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


[PATCH] D129892: Fix aligning of trailing comments after comment at the end of a namespace

2022-07-15 Thread Danil Sidoruk via Phabricator via cfe-commits
eoanermine created this revision.
eoanermine added reviewers: owenpan, HazardyKnusperkeks, curdeius, 
MyDeveloperDay.
eoanermine added projects: clang, clang-format.
Herald added a project: All.
eoanermine requested review of this revision.
Herald added a subscriber: cfe-commits.

- Fix aligning of trailing comments after comment at the end of a namespace
- Add tests for aligning of trailing comments after comment that documents the 
closing of a namespace


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129892

Files:
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -17458,6 +17458,40 @@
Alignment);
 }
 
+TEST_F(FormatTest, AlignTrailingComments) {
+  FormatStyle Style = getLLVMStyle();
+  EXPECT_EQ(Style.AlignTrailingComments, true);
+
+  verifyFormat("namespace test {\n"
+   "class C;\n"
+   "} // namespace test\n"
+   "// Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+   "Nullam cursus nunc\n"
+   "// non",
+   Style);
+  verifyFormat("namespace test {\n"
+   "class C;\n"
+   "} // namespace test\n"
+   "// Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+   "Nullam cursus nunc\n"
+   "// non\n",
+   Style);
+  verifyFormat("namespace test {\n"
+   "class C;\n"
+   "} // namespace test\n"
+   "// Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+   "Nullam cursus nunc\n"
+   "// non other text",
+   Style);
+  verifyFormat("namespace test {\n"
+   "class C;\n"
+   "} // namespace test\n"
+   "// Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+   "Nullam cursus nunc\n"
+   "// non other text\n",
+   Style);
+}
+
 TEST_F(FormatTest, AlignConsecutiveBitFields) {
   FormatStyle Alignment = getLLVMStyle();
   Alignment.AlignConsecutiveBitFields.Enabled = true;
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -966,6 +966,10 @@
 
 unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
 Changes[j].OriginalWhitespaceRange.getEnd());
+// Handle files without newline before the end of file correct
+if (Changes[j].Tok->is(tok::eof))
+  NextColumn = 1;
+
 // The start of the next token was previously aligned with the
 // start of this comment.
 WasAlignedWithStartOfNextLine =


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -17458,6 +17458,40 @@
Alignment);
 }
 
+TEST_F(FormatTest, AlignTrailingComments) {
+  FormatStyle Style = getLLVMStyle();
+  EXPECT_EQ(Style.AlignTrailingComments, true);
+
+  verifyFormat("namespace test {\n"
+   "class C;\n"
+   "} // namespace test\n"
+   "// Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+   "Nullam cursus nunc\n"
+   "// non",
+   Style);
+  verifyFormat("namespace test {\n"
+   "class C;\n"
+   "} // namespace test\n"
+   "// Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+   "Nullam cursus nunc\n"
+   "// non\n",
+   Style);
+  verifyFormat("namespace test {\n"
+   "class C;\n"
+   "} // namespace test\n"
+   "// Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+   "Nullam cursus nunc\n"
+   "// non other text",
+   Style);
+  verifyFormat("namespace test {\n"
+   "class C;\n"
+   "} // namespace test\n"
+   "// Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
+   "Nullam cursus nunc\n"
+   "// non other text\n",
+   Style);
+}
+
 TEST_F(FormatTest, AlignConsecutiveBitFields) {
   FormatStyle Alignment = getLLVMStyle();
   Alignment.AlignConsecutiveBitFields.Enabled = true;
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -966,6 +966,10 @@
 
 unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
 Changes[j].OriginalWhitespaceRange.getEnd());
+// Handle files without newline before the 

[PATCH] D129891: [test-suite] Update the test suite for changes to -Wint-conversion

2022-07-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: fhahn, erichkeane, jroelofs.
Herald added subscribers: kristof.beyls, mgorny.
Herald added a project: All.
aaron.ballman requested review of this revision.

This updates the test suite to ignore `-Wint-conversion` warnings which have 
been upgraded to an error by https://reviews.llvm.org/D129881. Note, this 
warning already exists and is on by default, so landing this before D129881 
 is harmless even if that review is rejected.


Repository:
  rT test-suite

https://reviews.llvm.org/D129891

Files:
  MultiSource/Applications/Burg/CMakeLists.txt
  MultiSource/Applications/Burg/Makefile
  MultiSource/Benchmarks/Prolangs-C/assembler/CMakeLists.txt
  MultiSource/Benchmarks/Prolangs-C/assembler/Makefile
  MultiSource/Benchmarks/Prolangs-C/bison/CMakeLists.txt
  MultiSource/Benchmarks/Prolangs-C/bison/Makefile
  MultiSource/Benchmarks/Prolangs-C/football/CMakeLists.txt
  MultiSource/Benchmarks/Prolangs-C/football/Makefile
  MultiSource/Benchmarks/Prolangs-C/unix-smail/CMakeLists.txt
  MultiSource/Benchmarks/Prolangs-C/unix-smail/Makefile
  MultiSource/Benchmarks/TSVC/Recurrences-flt/CMakeLists.txt
  MultiSource/Benchmarks/TSVC/Recurrences-flt/Makefile
  MultiSource/Benchmarks/VersaBench/beamformer/CMakeLists.txt
  MultiSource/Benchmarks/VersaBench/beamformer/Makefile
  SingleSource/Regression/C/gcc-c-torture/execute/CMakeLists.txt

Index: SingleSource/Regression/C/gcc-c-torture/execute/CMakeLists.txt
===
--- SingleSource/Regression/C/gcc-c-torture/execute/CMakeLists.txt
+++ SingleSource/Regression/C/gcc-c-torture/execute/CMakeLists.txt
@@ -1,7 +1,7 @@
 add_subdirectory(ieee)
 
 # GCC C Torture Suite is conventionally run without warnings
-list(APPEND CFLAGS -Wno-implicit-int -Wno-implicit-function-declaration -w)
+list(APPEND CFLAGS -Wno-implicit-int -Wno-int-conversion -Wno-implicit-function-declaration -w)
 
 set(TestsToSkip)
 
Index: MultiSource/Benchmarks/VersaBench/beamformer/Makefile
===
--- MultiSource/Benchmarks/VersaBench/beamformer/Makefile
+++ MultiSource/Benchmarks/VersaBench/beamformer/Makefile
@@ -1,6 +1,6 @@
 LEVEL = ../../../..
 LDFLAGS += -lm
-CFLAGS += -DFP_ABSTOLERANCE=1e-5
+CFLAGS += -DFP_ABSTOLERANCE=1e-5 -Wno-int-conversion
 
 PROG = beamformer
 ifdef LARGE_PROBLEM_SIZE
Index: MultiSource/Benchmarks/VersaBench/beamformer/CMakeLists.txt
===
--- MultiSource/Benchmarks/VersaBench/beamformer/CMakeLists.txt
+++ MultiSource/Benchmarks/VersaBench/beamformer/CMakeLists.txt
@@ -1,3 +1,4 @@
+list(APPEND CFLAGS -Wno-int-conversion)
 list(APPEND LDFLAGS -lm)
 if(LARGE_PROBLEM_SIZE)
   set(RUN_OPTIONS -i 400)
Index: MultiSource/Benchmarks/TSVC/Recurrences-flt/Makefile
===
--- MultiSource/Benchmarks/TSVC/Recurrences-flt/Makefile
+++ MultiSource/Benchmarks/TSVC/Recurrences-flt/Makefile
@@ -2,7 +2,7 @@
 
 PROG = Recurrences-flt
 LDFLAGS  = -lm
-CFLAGS += -std=gnu99
+CFLAGS += -std=gnu99 -Wno-int-conversion
 RUN_OPTIONS = 2 5
 include $(LEVEL)/MultiSource/Makefile.multisrc
 
Index: MultiSource/Benchmarks/TSVC/Recurrences-flt/CMakeLists.txt
===
--- MultiSource/Benchmarks/TSVC/Recurrences-flt/CMakeLists.txt
+++ MultiSource/Benchmarks/TSVC/Recurrences-flt/CMakeLists.txt
@@ -1,4 +1,4 @@
 list(APPEND LDFLAGS -lm)
-list(APPEND CFLAGS -std=gnu99)
+list(APPEND CFLAGS -std=gnu99 -Wno-int-conversion)
 set(RUN_OPTIONS 2 5)
 llvm_multisource(Recurrences-flt)
Index: MultiSource/Benchmarks/Prolangs-C/unix-smail/Makefile
===
--- MultiSource/Benchmarks/Prolangs-C/unix-smail/Makefile
+++ MultiSource/Benchmarks/Prolangs-C/unix-smail/Makefile
@@ -1,6 +1,7 @@
 LEVEL = ../../../..
 
 PROG = unix-smail
+CFLAGS += -Wno-int-conversion
 RUN_OPTIONS = -v ALL
 STDIN_FILENAME = $(PROJ_SRC_DIR)/main.c
 
Index: MultiSource/Benchmarks/Prolangs-C/unix-smail/CMakeLists.txt
===
--- MultiSource/Benchmarks/Prolangs-C/unix-smail/CMakeLists.txt
+++ MultiSource/Benchmarks/Prolangs-C/unix-smail/CMakeLists.txt
@@ -1,3 +1,4 @@
+list(APPEND CFLAGS -Wno-int-conversion)
 set(RUN_OPTIONS -v ALL < main.c)
 llvm_multisource(unix-smail)
 llvm_test_data(unix-smail main.c)
Index: MultiSource/Benchmarks/Prolangs-C/football/Makefile
===
--- MultiSource/Benchmarks/Prolangs-C/football/Makefile
+++ MultiSource/Benchmarks/Prolangs-C/football/Makefile
@@ -1,5 +1,6 @@
 LEVEL = ../../../..
 
 PROG = football
+CFLAGS += -Wno-int-conversion
 include $(LEVEL)/MultiSource/Makefile.multisrc
 
Index: 

[clang] 5b8337c - [syntax] Some #includes cleanup, NFC.

2022-07-15 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-07-15T21:05:59+02:00
New Revision: 5b8337cf402b224c5ed310dc570aa471dcdbd116

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

LOG: [syntax] Some #includes cleanup, NFC.

Added: 


Modified: 
clang/include/clang/Tooling/Syntax/Nodes.h
clang/include/clang/Tooling/Syntax/Tokens.h
clang/include/clang/Tooling/Syntax/Tree.h
clang/lib/Tooling/Syntax/Nodes.cpp
clang/lib/Tooling/Syntax/Tree.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/Syntax/Nodes.h 
b/clang/include/clang/Tooling/Syntax/Nodes.h
index 293ae24e6e26a..c4f31900d0ce0 100644
--- a/clang/include/clang/Tooling/Syntax/Nodes.h
+++ b/clang/include/clang/Tooling/Syntax/Nodes.h
@@ -23,9 +23,6 @@
 
 #include "clang/Basic/LLVM.h"
 #include "clang/Tooling/Syntax/Tree.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/StringRef.h"
-#include "llvm/Support/raw_ostream.h"
 namespace clang {
 namespace syntax {
 

diff  --git a/clang/include/clang/Tooling/Syntax/Tokens.h 
b/clang/include/clang/Tooling/Syntax/Tokens.h
index 7fd7e2ef5649d..9adb2b12f1adb 100644
--- a/clang/include/clang/Tooling/Syntax/Tokens.h
+++ b/clang/include/clang/Tooling/Syntax/Tokens.h
@@ -27,13 +27,11 @@
 #ifndef LLVM_CLANG_TOOLING_SYNTAX_TOKENS_H
 #define LLVM_CLANG_TOOLING_SYNTAX_TOKENS_H
 
-#include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/Token.h"
-#include "clang/Tooling/Syntax/TokenManager.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/Optional.h"

diff  --git a/clang/include/clang/Tooling/Syntax/Tree.h 
b/clang/include/clang/Tooling/Syntax/Tree.h
index 5f09a5a7a205c..c9c957af0a289 100644
--- a/clang/include/clang/Tooling/Syntax/Tree.h
+++ b/clang/include/clang/Tooling/Syntax/Tree.h
@@ -23,12 +23,10 @@
 
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Tooling/Syntax/TokenManager.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/iterator.h"
 #include "llvm/Support/Allocator.h"
 #include 
-#include 
+#include 
 
 namespace clang {
 namespace syntax {

diff  --git a/clang/lib/Tooling/Syntax/Nodes.cpp 
b/clang/lib/Tooling/Syntax/Nodes.cpp
index fc6f8ef1a82cb..d0c1e9297cfa8 100644
--- a/clang/lib/Tooling/Syntax/Nodes.cpp
+++ b/clang/lib/Tooling/Syntax/Nodes.cpp
@@ -6,7 +6,7 @@
 //
 
//===--===//
 #include "clang/Tooling/Syntax/Nodes.h"
-#include "clang/Basic/TokenKinds.h"
+#include "llvm/Support/raw_ostream.h"
 
 using namespace clang;
 

diff  --git a/clang/lib/Tooling/Syntax/Tree.cpp 
b/clang/lib/Tooling/Syntax/Tree.cpp
index 576226f6e2cec..20f7bd087aa02 100644
--- a/clang/lib/Tooling/Syntax/Tree.cpp
+++ b/clang/lib/Tooling/Syntax/Tree.cpp
@@ -8,9 +8,8 @@
 #include "clang/Tooling/Syntax/Tree.h"
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Tooling/Syntax/Nodes.h"
-#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/BitVector.h"
-#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Casting.h"
 #include 
 



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


[PATCH] D129886: [clang] Add -fdiagnostics-format=sarif for SARIF diagnostics

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

Thanks for getting this started! To get this ready for submission, would you be 
able to add a test please?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129886

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


[PATCH] D129464: [Clang][CodeGen] Set FP options of builder at entry to compound statement

2022-07-15 Thread John McCall via Phabricator via cfe-commits
rjmccall added a comment.

This property adheres to a function definition, so it seems to me that an 
explicit *instantiation* ought to preserve it from the instantiated template 
definition, but an explicit *specialization* ought to be independent.

i.e.

  #pragma float_control(precise, on, push)
  template 
  float func2(Ty) {
float f1 = 1.0f, f2 = 3.0f;
return f1 + f2 * 2.0f;
  }
  #pragma float_control(pop)
  
  template float func2(int); // precise
  template <> float func2(long) { ... } // not precise


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129464

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


[PATCH] D129398: [ASTMatchers] Add a new matcher for callee declarations of Obj-C message expressions

2022-07-15 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 added a comment.

Thanks @aaron.ballman ,  I plan to commit this patch on Monday (18th July 2022).


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

https://reviews.llvm.org/D129398

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


[PATCH] D129885: [CUDA] Make the new driver properly ignore non-CUDA inputs

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

Adjusting tests


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129885

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cuda-phases.cu

Index: clang/test/Driver/cuda-phases.cu
===
--- clang/test/Driver/cuda-phases.cu
+++ clang/test/Driver/cuda-phases.cu
@@ -221,48 +221,76 @@
 //
 // Test the phases generated when using the new offloading driver.
 //
-// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases --offload-new-driver -fgpu-rdc \
-// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW-DRIVER-RDC %s
-// NEW-DRIVER-RDC: 0: input, "[[INPUT:.+]]", cuda
-// NEW-DRIVER-RDC: 1: preprocessor, {0}, cuda-cpp-output
-// NEW-DRIVER-RDC: 2: compiler, {1}, ir
-// NEW-DRIVER-RDC: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 5: compiler, {4}, ir, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 6: backend, {5}, assembler, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 7: assembler, {6}, object, (device-cuda, sm_52)
-// NEW-DRIVER-RDC: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
-// NEW-DRIVER-RDC: 9: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 10: preprocessor, {9}, cuda-cpp-output, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 11: compiler, {10}, ir, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 12: backend, {11}, assembler, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 13: assembler, {12}, object, (device-cuda, sm_70)
-// NEW-DRIVER-RDC: 14: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {13}, object
-// NEW-DRIVER-RDC: 15: clang-offload-packager, {8, 14}, image
-// NEW-DRIVER-RDC: 16: offload, " (powerpc64le-ibm-linux-gnu)" {2}, " (powerpc64le-ibm-linux-gnu)" {15}, ir
-// NEW-DRIVER-RDC: 17: backend, {16}, assembler, (host-cuda)
-// NEW-DRIVER-RDC: 18: assembler, {17}, object, (host-cuda)
-// NEW-DRIVER-RDC: 19: clang-linker-wrapper, {18}, image, (host-cuda)
+// RUN: %clang -### --target=powerpc64le-ibm-linux-gnu -ccc-print-phases --offload-new-driver -fgpu-rdc \
+// RUN:   --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW-DRIVER-RDC %s
+//  NEW-DRIVER-RDC: 0: input, "[[INPUT:.+]]", cuda
+// NEW-DRIVER-RDC-NEXT: 1: preprocessor, {0}, cuda-cpp-output
+// NEW-DRIVER-RDC-NEXT: 2: compiler, {1}, ir
+// NEW-DRIVER-RDC-NEXT: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 5: compiler, {4}, ir, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 6: backend, {5}, assembler, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 7: assembler, {6}, object, (device-cuda, sm_52)
+// NEW-DRIVER-RDC-NEXT: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
+// NEW-DRIVER-RDC-NEXT: 9: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 10: preprocessor, {9}, cuda-cpp-output, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 11: compiler, {10}, ir, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 12: backend, {11}, assembler, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 13: assembler, {12}, object, (device-cuda, sm_70)
+// NEW-DRIVER-RDC-NEXT: 14: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" {13}, object
+// NEW-DRIVER-RDC-NEXT: 15: clang-offload-packager, {8, 14}, image
+// NEW-DRIVER-RDC-NEXT: 16: offload, " (powerpc64le-ibm-linux-gnu)" {2}, " (powerpc64le-ibm-linux-gnu)" {15}, ir
+// NEW-DRIVER-RDC-NEXT: 17: backend, {16}, assembler, (host-cuda)
+// NEW-DRIVER-RDC-NEXT: 18: assembler, {17}, object, (host-cuda)
+// NEW-DRIVER-RDC-NEXT: 19: clang-linker-wrapper, {18}, image, (host-cuda)
 
 // RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases --offload-new-driver -fgpu-rdc \
-// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s 2>&1 | FileCheck --check-prefix=NEW-DRIVER %s
-// NEW-DRIVER: 0: input, "[[INPUT:.+]]", cuda
-// NEW-DRIVER: 1: preprocessor, {0}, cuda-cpp-output
-// NEW-DRIVER: 2: compiler, {1}, ir
-// NEW-DRIVER: 3: input, "[[INPUT]]", cuda, (device-cuda, sm_52)
-// NEW-DRIVER: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
-// NEW-DRIVER: 5: compiler, {4}, ir, (device-cuda, sm_52)
-// NEW-DRIVER: 6: backend, {5}, assembler, (device-cuda, sm_52)
-// NEW-DRIVER: 7: assembler, {6}, object, (device-cuda, sm_52)
-// NEW-DRIVER: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, object
-// NEW-DRIVER: 9: input, "[[INPUT]]", cuda, (device-cuda, sm_70)
-// NEW-DRIVER: 10: preprocessor, {9}, cuda-cpp-output, (device-cuda, sm_70)
-// NEW-DRIVER: 11: compiler, {10}, ir, (device-cuda, sm_70)
-// NEW-DRIVER: 12: backend, {11}, assembler, (device-cuda, sm_70)
-// NEW-DRIVER: 13: assembler, {12}, object, (device-cuda, sm_70)
-// 

[PATCH] D129881: [C] Strengthen -Wint-conversion to default to an error

2022-07-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaExprCXX.cpp:8483
+if ((SemaRef.getLangOpts().CPlusPlus && Trap.hasErrorOccurred()) ||
+Res.isInvalid())
   return ExprError();

aaron.ballman wrote:
> efriedma wrote:
> > I'd prefer not to introduce unnecessary differences in C vs. C++ handling 
> > like this...
> > 
> > This seems weird for two reasons:
> > 
> > - We don't use ext_typecheck_convert_pointer_int in C++, so there's not 
> > really any reason to mark it SFINAEFailure
> > - Whatever code is calling this probably doesn't want an SFINAE context.  
> > Is this coming from TransformToPotentiallyEvaluated?  We don't want SFINAE 
> > traps from there, in C or C++.
> > We don't use ext_typecheck_convert_pointer_int in C++, so there's not 
> > really any reason to mark it SFINAEFailure
> 
> The original changes came from: 
> https://github.com/llvm/llvm-project/issues/39709 but I see now that we used 
> to treat this as a warning in C++ rather than an error. So adding 
> SFINAEFailure made sense at that point, but I think you're right that it 
> should be removed now. I'll try that locally and see if anything explodes as 
> a result.
> 
> > Whatever code is calling this probably doesn't want an SFINAE context. Is 
> > this coming from TransformToPotentiallyEvaluated? We don't want SFINAE 
> > traps from there, in C or C++.
> 
> Typo correction went haywire. Specifically: 
> https://github.com/llvm/llvm-project/blob/main/clang/test/Sema/typo-correction-ambiguity.c#L13
> 
> We would typo correct `v_231` to be `v_2_0` here, and when deciding whether 
> that was valid or not, we'd hit the SFINAE trap in C code and that changed 
> the behavior of the test to add suggestions instead of silence them.
> 
> I think it's incredibly weird to ever use SFINAE in C, even by accident.
> I'll try that locally and see if anything explodes as a result.

All my local tests passed, so I've made the change and we'll see if precommit 
CI finds anything I didn't.


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

https://reviews.llvm.org/D129881

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


[PATCH] D129498: [analyzer] Add new function `clang_analyzer_value` to ExprInspectionChecker

2022-07-15 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov closed this revision.
ASDenysPetrov added a comment.

Closed with bc08c3cb7f8e797fee14e96eedd3dc358608ada3 





Comment at: clang/test/Analysis/print-ranges.cpp:1
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-analyzer-config eagerly-assume=false -verify %s
+// REQUIRES: no-z3

martong wrote:
> Don't forget to pin the target/triple.
Why does this specific test need it?



Comment at: clang/test/Analysis/print-ranges.cpp:1
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,debug.ExprInspection 
-analyzer-config eagerly-assume=false -verify %s
+

NoQ wrote:
> ASDenysPetrov wrote:
> > NoQ wrote:
> > > I suspect this test will crash when clang is built with Z3, because the 
> > > Z3 constraint manager doesn't implement your new function yet.
> > Agree. Is it enough `REQUIRES: no-z3` or to add `#ifdef ANALYZER_CM_Z3`?
> That should be good. My personal tradition in such cases is to double-check 
> that this doesn't disable the test entirely.
I added `REQUIRES: z3` it prints `Unsupported`, then added `REQUIRES: no-z3` 
and it passed.


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

https://reviews.llvm.org/D129498

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


[PATCH] D129881: [C] Strengthen -Wint-conversion to default to an error

2022-07-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 445086.
aaron.ballman added a comment.

Removed the SFINAEFailure and trap changes, added a release note.


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

https://reviews.llvm.org/D129881

Files:
  clang-tools-extra/test/clang-tidy/checkers/bugprone/no-escape.m
  clang-tools-extra/test/clang-tidy/checkers/performance/no-int-to-ptr.c
  clang/bindings/python/tests/cindex/test_diagnostics.py
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/test/Analysis/ObjCProperties.m
  clang/test/Analysis/bsd-string.c
  clang/test/Analysis/novoidtypecrash.c
  clang/test/Analysis/null-deref-ps.c
  clang/test/Analysis/number-object-conversion.c
  clang/test/Analysis/number-object-conversion.m
  clang/test/Analysis/pr22954.c
  clang/test/C/drs/dr0xx.c
  clang/test/C/drs/dr2xx.c
  clang/test/CodeGen/2008-03-05-syncPtr.c
  clang/test/CodeGen/2008-07-31-promotion-of-compound-pointer-arithmetic.c
  clang/test/CodeGen/aarch64-mops.c
  clang/test/CodeGen/address-space-cast.c
  clang/test/CodeGen/const-init.c
  clang/test/CodeGen/pointer-arithmetic.c
  clang/test/CodeGen/pointer-to-int.c
  clang/test/CodeGen/statements.c
  clang/test/CodeGen/struct-init.c
  clang/test/CodeGen/vla.c
  clang/test/CodeGenObjC/block-ptr-type-crash.m
  clang/test/CodeGenOpenCL/builtins-generic-amdgcn.cl
  clang/test/FixIt/dereference-addressof.c
  clang/test/FixIt/selector-fixit.m
  clang/test/Misc/serialized-diags.c
  clang/test/Misc/tabstop.c
  clang/test/Modules/config_macros.m
  clang/test/PCH/objc_exprs.m
  clang/test/Parser/implicit-casts.c
  clang/test/Sema/array-init.c
  clang/test/Sema/atomic-ops.c
  clang/test/Sema/block-return.c
  clang/test/Sema/builtin-alloca-with-align.c
  clang/test/Sema/builtin-assume-aligned.c
  clang/test/Sema/builtin-dump-struct.c
  clang/test/Sema/builtins-bpf.c
  clang/test/Sema/builtins.c
  clang/test/Sema/compound-literal.c
  clang/test/Sema/conditional-expr.c
  clang/test/Sema/enum.c
  clang/test/Sema/extern-redecl.c
  clang/test/Sema/format-strings.c
  clang/test/Sema/function-redecl.c
  clang/test/Sema/function.c
  clang/test/Sema/i-c-e.c
  clang/test/Sema/indirect-goto.c
  clang/test/Sema/matrix-type-builtins.c
  clang/test/Sema/nullability.c
  clang/test/SemaObjC/argument-checking.m
  clang/test/SemaObjC/comptypes-7.m
  clang/test/SemaObjC/ivar-lookup-resolution-builtin.m
  clang/test/SemaObjC/message.m
  clang/test/SemaObjC/method-lookup-5.m
  clang/test/SemaObjC/nullability.m
  clang/test/SemaObjC/objc-container-subscripting-3.m
  clang/test/SemaObjC/objc-literal-fixit.m
  clang/test/SemaObjC/signed-char-bool-conversion.m
  clang/test/SemaOpenCL/atomic-ops.cl
  clang/test/SemaOpenCL/builtins-amdgcn-error.cl
  clang/test/VFS/Inputs/external-names.h
  clang/test/VFS/external-names.c
  compiler-rt/test/dfsan/gep.c
  compiler-rt/test/dfsan/sigaction.c

Index: compiler-rt/test/dfsan/sigaction.c
===
--- compiler-rt/test/dfsan/sigaction.c
+++ compiler-rt/test/dfsan/sigaction.c
@@ -1,5 +1,5 @@
-// RUN: %clang_dfsan -DUSE_SIGNAL_ACTION %s -o %t && %run %t
-// RUN: %clang_dfsan %s -o %t && %run %t
+// RUN: %clang_dfsan -DUSE_SIGNAL_ACTION -Wno-error=int-conversion %s -o %t && %run %t
+// RUN: %clang_dfsan -Wno-error=int-conversion %s -o %t && %run %t
 //
 // REQUIRES: x86_64-target-arch
 
Index: compiler-rt/test/dfsan/gep.c
===
--- compiler-rt/test/dfsan/gep.c
+++ compiler-rt/test/dfsan/gep.c
@@ -1,5 +1,5 @@
-// RUN: %clang_dfsan %s -mllvm -dfsan-combine-offset-labels-on-gep=false -o %t && %run %t
-// RUN: %clang_dfsan %s -DPROP_OFFSET_LABELS -o %t && %run %t
+// RUN: %clang_dfsan %s -mllvm -dfsan-combine-offset-labels-on-gep=false -Wno-error=int-conversion -o %t && %run %t
+// RUN: %clang_dfsan %s -DPROP_OFFSET_LABELS -Wno-error=int-conversion -o %t && %run %t
 //
 // REQUIRES: x86_64-target-arch
 
Index: clang/test/VFS/external-names.c
===
--- clang/test/VFS/external-names.c
+++ clang/test/VFS/external-names.c
@@ -21,7 +21,7 @@
 // Diagnostics:
 
 // RUN: %clang_cc1 -I %t -ivfsoverlay %t.external.yaml -fsyntax-only %s 2>&1 | FileCheck -check-prefix=CHECK-DIAG-EXTERNAL %s
-// CHECK-DIAG-EXTERNAL: {{.*}}Inputs{{..?}}external-names.h:{{[0-9]*:[0-9]*}}: warning: incompatible pointer
+// CHECK-DIAG-EXTERNAL: {{.*}}Inputs{{..?}}external-names.h:{{[0-9]*:[0-9]*}}: warning: initializing 'const char **'
 
 // RUN: %clang_cc1 -I %t -ivfsoverlay %t.yaml -fsyntax-only %s 2>&1 | FileCheck -check-prefix=CHECK-DIAG %s
 // CHECK-DIAG-NOT: Inputs
Index: clang/test/VFS/Inputs/external-names.h
===
--- clang/test/VFS/Inputs/external-names.h
+++ clang/test/VFS/Inputs/external-names.h
@@ -1,4 +1,4 @@
 void foo(char **c) {
   *c = __FILE__;
-  int x = c; // produce a diagnostic
+  

[PATCH] D129885: [CUDA] Make the new driver properly ignore non-CUDA inputs

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



Comment at: clang/test/Driver/cuda-phases.cu:270
+
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases 
--offload-new-driver \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s %S/Inputs/empty.cpp 2>&1 
| FileCheck --check-prefix=NON-CUDA-INPUT %s

Use `--target=`. `-target ` is legacy.



Comment at: clang/test/Driver/cuda-phases.cu:271
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases 
--offload-new-driver \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s %S/Inputs/empty.cpp 2>&1 
| FileCheck --check-prefix=NON-CUDA-INPUT %s
+// NON-CUDA-INPUT: 0: input, "[[CUDA:.+]]", cuda, (host-cuda)

The continuation line is typically indented by 2 spaces



Comment at: clang/test/Driver/cuda-phases.cu:273
+// NON-CUDA-INPUT: 0: input, "[[CUDA:.+]]", cuda, (host-cuda)
+// NON-CUDA-INPUT: 1: preprocessor, {0}, cuda-cpp-output, (host-cuda)
+// NON-CUDA-INPUT: 2: compiler, {1}, ir, (host-cuda)

If `-NEXT` is applicable, add it



Comment at: clang/test/Driver/cuda-phases.cu:297
+// NON-CUDA-INPUT: 24: clang-linker-wrapper, {18, 23}, image, (host-cuda)
+

delete blank line


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129885

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


[PATCH] D129886: [clang] Add -fdiagnostics-format=sarif for SARIF diagnostics

2022-07-15 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd updated this revision to Diff 445077.
abrahamcd retitled this revision from "Adds `-fdiagnostics-format=sarif` flag 
option and warning." to "[clang] Add -fdiagnostics-format=sarif for SARIF 
diagnostics".
abrahamcd edited the summary of this revision.
abrahamcd added a comment.

Commit message edits did not go through


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129886

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/TextDiagnostic.cpp


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -815,6 +815,7 @@
 
   emitFilename(PLoc.getFilename(), Loc.getManager());
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
 if (DiagOpts->ShowLine)
   OS << ':' << LineNo;
@@ -837,6 +838,7 @@
   OS << ColNo;
 }
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
   case DiagnosticOptions::Vi:OS << ':';break;
   case DiagnosticOptions::MSVC:
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4006,6 +4006,9 @@
   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
 CmdArgs.push_back("-fdiagnostics-format");
 CmdArgs.push_back(A->getValue());
+if (std::string(A->getValue()) == "sarif") {
+  D.Diag(diag::warn_drv_sarif_format_unstable);
+}
   }
 
   if (const Arg *A = Args.getLastArg(
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -5574,8 +5574,8 @@
 
 def fdiagnostics_format : Separate<["-"], "fdiagnostics-format">,
   HelpText<"Change diagnostic formatting to match IDE and command line tools">,
-  Values<"clang,msvc,vi">,
-  NormalizedValuesScope<"DiagnosticOptions">, NormalizedValues<["Clang", 
"MSVC", "Vi"]>,
+  Values<"clang,msvc,vi,sarif">,
+  NormalizedValuesScope<"DiagnosticOptions">, NormalizedValues<["Clang", 
"MSVC", "Vi", "SARIF"]>,
   MarshallingInfoEnum, "Clang">;
 def fdiagnostics_show_category : Separate<["-"], "fdiagnostics-show-category">,
   HelpText<"Print diagnostic category">,
Index: clang/include/clang/Basic/DiagnosticOptions.h
===
--- clang/include/clang/Basic/DiagnosticOptions.h
+++ clang/include/clang/Basic/DiagnosticOptions.h
@@ -74,7 +74,7 @@
   friend class CompilerInvocation;
 
 public:
-  enum TextDiagnosticFormat { Clang, MSVC, Vi };
+  enum TextDiagnosticFormat { Clang, MSVC, Vi, SARIF };
 
   // Default values.
   enum {
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -678,4 +678,7 @@
 def err_drv_invalid_empty_dxil_validator_version : Error<
   "invalid validator version : %0\n"
   "If validator major version is 0, minor version must also be 0.">;
+
+def warn_drv_sarif_format_unstable : Warning<
+  "diagnostic formatting in SARIF mode is currently unstable">;
 }


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -815,6 +815,7 @@
 
   emitFilename(PLoc.getFilename(), Loc.getManager());
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
 if (DiagOpts->ShowLine)
   OS << ':' << LineNo;
@@ -837,6 +838,7 @@
   OS << ColNo;
 }
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
   case DiagnosticOptions::Vi:OS << ':';break;
   case DiagnosticOptions::MSVC:
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4006,6 +4006,9 @@
   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
 CmdArgs.push_back("-fdiagnostics-format");
 CmdArgs.push_back(A->getValue());
+if (std::string(A->getValue()) == "sarif") {
+  D.Diag(diag::warn_drv_sarif_format_unstable);
+}
   }
 
   if (const Arg *A = Args.getLastArg(
Index: clang/include/clang/Driver/Options.td
===
--- 

[PATCH] D129885: [CUDA] Make the new driver properly ignore non-CUDA inputs

2022-07-15 Thread Artem Belevich via Phabricator via cfe-commits
tra accepted this revision.
tra 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/D129885/new/

https://reviews.llvm.org/D129885

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


[PATCH] D129886: Adds `-fdiagnostics-format=sarif` flag option and warning.

2022-07-15 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd updated this revision to Diff 445073.
abrahamcd added a comment.

Edited commit message


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129886

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/TextDiagnostic.cpp


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -815,6 +815,7 @@
 
   emitFilename(PLoc.getFilename(), Loc.getManager());
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
 if (DiagOpts->ShowLine)
   OS << ':' << LineNo;
@@ -837,6 +838,7 @@
   OS << ColNo;
 }
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
   case DiagnosticOptions::Vi:OS << ':';break;
   case DiagnosticOptions::MSVC:
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4006,6 +4006,9 @@
   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
 CmdArgs.push_back("-fdiagnostics-format");
 CmdArgs.push_back(A->getValue());
+if (std::string(A->getValue()) == "sarif") {
+  D.Diag(diag::warn_drv_sarif_format_unstable);
+}
   }
 
   if (const Arg *A = Args.getLastArg(
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -5574,8 +5574,8 @@
 
 def fdiagnostics_format : Separate<["-"], "fdiagnostics-format">,
   HelpText<"Change diagnostic formatting to match IDE and command line tools">,
-  Values<"clang,msvc,vi">,
-  NormalizedValuesScope<"DiagnosticOptions">, NormalizedValues<["Clang", 
"MSVC", "Vi"]>,
+  Values<"clang,msvc,vi,sarif">,
+  NormalizedValuesScope<"DiagnosticOptions">, NormalizedValues<["Clang", 
"MSVC", "Vi", "SARIF"]>,
   MarshallingInfoEnum, "Clang">;
 def fdiagnostics_show_category : Separate<["-"], "fdiagnostics-show-category">,
   HelpText<"Print diagnostic category">,
Index: clang/include/clang/Basic/DiagnosticOptions.h
===
--- clang/include/clang/Basic/DiagnosticOptions.h
+++ clang/include/clang/Basic/DiagnosticOptions.h
@@ -74,7 +74,7 @@
   friend class CompilerInvocation;
 
 public:
-  enum TextDiagnosticFormat { Clang, MSVC, Vi };
+  enum TextDiagnosticFormat { Clang, MSVC, Vi, SARIF };
 
   // Default values.
   enum {
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -678,4 +678,7 @@
 def err_drv_invalid_empty_dxil_validator_version : Error<
   "invalid validator version : %0\n"
   "If validator major version is 0, minor version must also be 0.">;
+
+def warn_drv_sarif_format_unstable : Warning<
+  "diagnostic formatting in SARIF mode is currently unstable">;
 }


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -815,6 +815,7 @@
 
   emitFilename(PLoc.getFilename(), Loc.getManager());
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
 if (DiagOpts->ShowLine)
   OS << ':' << LineNo;
@@ -837,6 +838,7 @@
   OS << ColNo;
 }
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
   case DiagnosticOptions::Vi:OS << ':';break;
   case DiagnosticOptions::MSVC:
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4006,6 +4006,9 @@
   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
 CmdArgs.push_back("-fdiagnostics-format");
 CmdArgs.push_back(A->getValue());
+if (std::string(A->getValue()) == "sarif") {
+  D.Diag(diag::warn_drv_sarif_format_unstable);
+}
   }
 
   if (const Arg *A = Args.getLastArg(
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -5574,8 +5574,8 @@
 
 def fdiagnostics_format : Separate<["-"], "fdiagnostics-format">,
   HelpText<"Change diagnostic formatting to match IDE and 

[PATCH] D129881: [C] Strengthen -Wint-conversion to default to an error

2022-07-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaExprCXX.cpp:8483
+if ((SemaRef.getLangOpts().CPlusPlus && Trap.hasErrorOccurred()) ||
+Res.isInvalid())
   return ExprError();

efriedma wrote:
> I'd prefer not to introduce unnecessary differences in C vs. C++ handling 
> like this...
> 
> This seems weird for two reasons:
> 
> - We don't use ext_typecheck_convert_pointer_int in C++, so there's not 
> really any reason to mark it SFINAEFailure
> - Whatever code is calling this probably doesn't want an SFINAE context.  Is 
> this coming from TransformToPotentiallyEvaluated?  We don't want SFINAE traps 
> from there, in C or C++.
> We don't use ext_typecheck_convert_pointer_int in C++, so there's not really 
> any reason to mark it SFINAEFailure

The original changes came from: 
https://github.com/llvm/llvm-project/issues/39709 but I see now that we used to 
treat this as a warning in C++ rather than an error. So adding SFINAEFailure 
made sense at that point, but I think you're right that it should be removed 
now. I'll try that locally and see if anything explodes as a result.

> Whatever code is calling this probably doesn't want an SFINAE context. Is 
> this coming from TransformToPotentiallyEvaluated? We don't want SFINAE traps 
> from there, in C or C++.

Typo correction went haywire. Specifically: 
https://github.com/llvm/llvm-project/blob/main/clang/test/Sema/typo-correction-ambiguity.c#L13

We would typo correct `v_231` to be `v_2_0` here, and when deciding whether 
that was valid or not, we'd hit the SFINAE trap in C code and that changed the 
behavior of the test to add suggestions instead of silence them.

I think it's incredibly weird to ever use SFINAE in C, even by accident.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129881

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


[PATCH] D123878: [AMDGPU] Add remarks to output some resource usage

2022-07-15 Thread Vang Thao 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 rG67357739c6d3: [AMDGPU] Add remarks to output some resource 
usage (authored by vangthao).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123878

Files:
  clang/test/Frontend/amdgcn-machine-analysis-remarks.cl
  llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp
  llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.h
  llvm/lib/Target/AMDGPU/SIProgramInfo.h
  llvm/test/CodeGen/AMDGPU/resource-optimization-remarks.ll

Index: llvm/test/CodeGen/AMDGPU/resource-optimization-remarks.ll
===
--- /dev/null
+++ llvm/test/CodeGen/AMDGPU/resource-optimization-remarks.ll
@@ -0,0 +1,158 @@
+; RUN: llc -mtriple=amdgcn-amd-amdhsa -mcpu=gfx908 -pass-remarks-output=%t -pass-remarks-analysis=kernel-resource-usage -filetype=obj -o /dev/null %s 2>&1 | FileCheck -check-prefix=STDERR %s
+; RUN: FileCheck -check-prefix=REMARK %s < %t
+
+; STDERR: remark: foo.cl:27:0: Function Name: test_kernel
+; STDERR-NEXT: remark: foo.cl:27:0: SGPRs: 24
+; STDERR-NEXT: remark: foo.cl:27:0: VGPRs: 9
+; STDERR-NEXT: remark: foo.cl:27:0: AGPRs: 43
+; STDERR-NEXT: remark: foo.cl:27:0: ScratchSize [bytes/lane]: 0
+; STDERR-NEXT: remark: foo.cl:27:0: Occupancy [waves/SIMD]: 5
+; STDERR-NEXT: remark: foo.cl:27:0: SGPRs Spill: 0
+; STDERR-NEXT: remark: foo.cl:27:0: VGPRs Spill: 0
+; STDERR-NEXT: remark: foo.cl:27:0: LDS Size [bytes/block]: 512
+
+; REMARK-LABEL: --- !Analysis
+; REMARK: Pass:kernel-resource-usage
+; REMARK-NEXT: Name:FunctionName
+; REMARK-NEXT: DebugLoc:{ File: foo.cl, Line: 27, Column: 0 }
+; REMARK-NEXT: Function:test_kernel
+; REMARK-NEXT: Args:
+; REMARK-NEXT:   - String:  'Function Name: '
+; REMARK-NEXT:   - FunctionName:  test_kernel
+; REMARK-NEXT: ...
+; REMARK-NEXT: --- !Analysis
+; REMARK-NEXT: Pass:kernel-resource-usage
+; REMARK-NEXT: Name:NumSGPR
+; REMARK-NEXT: DebugLoc:{ File: foo.cl, Line: 27, Column: 0 }
+; REMARK-NEXT: Function:test_kernel
+; REMARK-NEXT: Args:
+; REMARK-NEXT:   - String:  'SGPRs: '
+; REMARK-NEXT:   - NumSGPR: '24'
+; REMARK-NEXT: ...
+; REMARK-NEXT: --- !Analysis
+; REMARK-NEXT: Pass:kernel-resource-usage
+; REMARK-NEXT: Name:NumVGPR
+; REMARK-NEXT: DebugLoc:{ File: foo.cl, Line: 27, Column: 0 }
+; REMARK-NEXT: Function:test_kernel
+; REMARK-NEXT: Args:
+; REMARK-NEXT:   - String:  'VGPRs: '
+; REMARK-NEXT:   - NumVGPR: '9'
+; REMARK-NEXT: ...
+; REMARK-NEXT: --- !Analysis
+; REMARK-NEXT: Pass:kernel-resource-usage
+; REMARK-NEXT: Name:NumAGPR
+; REMARK-NEXT: DebugLoc:{ File: foo.cl, Line: 27, Column: 0 }
+; REMARK-NEXT: Function:test_kernel
+; REMARK-NEXT: Args:
+; REMARK-NEXT:   - String:  'AGPRs: '
+; REMARK-NEXT:   - NumAGPR: '43'
+; REMARK-NEXT: ...
+; REMARK-NEXT: --- !Analysis
+; REMARK-NEXT: Pass:kernel-resource-usage
+; REMARK-NEXT: Name:ScratchSize
+; REMARK-NEXT: DebugLoc:{ File: foo.cl, Line: 27, Column: 0 }
+; REMARK-NEXT: Function:test_kernel
+; REMARK-NEXT: Args:
+; REMARK-NEXT:   - String:  'ScratchSize [bytes/lane]: '
+; REMARK-NEXT:   - ScratchSize: '0'
+; REMARK-NEXT: ...
+; REMARK-NEXT: --- !Analysis
+; REMARK-NEXT: Pass:kernel-resource-usage
+; REMARK-NEXT: Name:Occupancy
+; REMARK-NEXT: DebugLoc:{ File: foo.cl, Line: 27, Column: 0 }
+; REMARK-NEXT: Function:test_kernel
+; REMARK-NEXT: Args:
+; REMARK-NEXT:   - String:  'Occupancy [waves/SIMD]: '
+; REMARK-NEXT:   - Occupancy:   '5'
+; REMARK-NEXT: ...
+; REMARK-NEXT: --- !Analysis
+; REMARK-NEXT: Pass:kernel-resource-usage
+; REMARK-NEXT: Name:SGPRSpill
+; REMARK-NEXT: DebugLoc:{ File: foo.cl, Line: 27, Column: 0 }
+; REMARK-NEXT: Function:test_kernel
+; REMARK-NEXT: Args:
+; REMARK-NEXT:   - String:  'SGPRs Spill: '
+; REMARK-NEXT:   - SGPRSpill:   '0'
+; REMARK-NEXT: ...
+; REMARK-NEXT: --- !Analysis
+; REMARK-NEXT: Pass:kernel-resource-usage
+; REMARK-NEXT: Name:VGPRSpill
+; REMARK-NEXT: DebugLoc:{ File: foo.cl, Line: 27, Column: 0 }
+; REMARK-NEXT: Function:test_kernel
+; REMARK-NEXT: Args:
+; REMARK-NEXT:   - String:  'VGPRs Spill: '
+; REMARK-NEXT:   - VGPRSpill:   '0'
+; REMARK-NEXT: ...
+; REMARK-NEXT: --- !Analysis
+; REMARK-NEXT: Pass:kernel-resource-usage
+; REMARK-NEXT: Name:BytesLDS
+; REMARK-NEXT: DebugLoc:{ File: foo.cl, Line: 27, Column: 0 }
+; REMARK-NEXT: Function:test_kernel
+; REMARK-NEXT: Args:
+; REMARK-NEXT:  

[clang] 6735773 - [AMDGPU] Add remarks to output some resource usage

2022-07-15 Thread Vang Thao via cfe-commits

Author: Vang Thao
Date: 2022-07-15T11:01:53-07:00
New Revision: 67357739c6d36a61972c1fc0e829e35cb5375279

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

LOG: [AMDGPU] Add remarks to output some resource usage

Add analyis remarks to output kernel name, register usage, occupancy,
scratch usage, spills, and LDS information.

Reviewed By: arsenm

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

Added: 
clang/test/Frontend/amdgcn-machine-analysis-remarks.cl
llvm/test/CodeGen/AMDGPU/resource-optimization-remarks.ll

Modified: 
llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp
llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.h
llvm/lib/Target/AMDGPU/SIProgramInfo.h

Removed: 




diff  --git a/clang/test/Frontend/amdgcn-machine-analysis-remarks.cl 
b/clang/test/Frontend/amdgcn-machine-analysis-remarks.cl
new file mode 100644
index 0..cf0c15b6319f1
--- /dev/null
+++ b/clang/test/Frontend/amdgcn-machine-analysis-remarks.cl
@@ -0,0 +1,17 @@
+// REQUIRES: amdgpu-registered-target
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -target-cpu gfx908 
-Rpass-analysis=kernel-resource-usage -S -O0 -verify %s -o /dev/null
+
+// expected-remark@+9 {{Function Name: foo}}
+// expected-remark@+8 {{SGPRs: 9}}
+// expected-remark@+7 {{VGPRs: 10}}
+// expected-remark@+6 {{AGPRs: 12}}
+// expected-remark@+5 {{ScratchSize [bytes/lane]: 0}}
+// expected-remark@+4 {{Occupancy [waves/SIMD]: 10}}
+// expected-remark@+3 {{SGPRs Spill: 0}}
+// expected-remark@+2 {{VGPRs Spill: 0}}
+// expected-remark@+1 {{LDS Size [bytes/block]: 0}}
+__kernel void foo() {
+  __asm volatile ("; clobber s8" :::"s8");
+  __asm volatile ("; clobber v9" :::"v9");
+  __asm volatile ("; clobber a11" :::"a11");
+}

diff  --git a/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp
index 57a4660bc1ebc..f1cc40b3a69af 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp
@@ -27,8 +27,10 @@
 #include "SIMachineFunctionInfo.h"
 #include "TargetInfo/AMDGPUTargetInfo.h"
 #include "Utils/AMDGPUBaseInfo.h"
+#include "llvm/Analysis/OptimizationRemarkEmitter.h"
 #include "llvm/BinaryFormat/ELF.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
+#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
 #include "llvm/IR/DiagnosticInfo.h"
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCContext.h"
@@ -506,6 +508,9 @@ bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction 
) {
 
   emitFunctionBody();
 
+  emitResourceUsageRemarks(MF, CurrentProgramInfo, 
MFI->isModuleEntryFunction(),
+   STM.hasMAIInsts());
+
   if (isVerbose()) {
 MCSectionELF *CommentSection =
 Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
@@ -875,6 +880,9 @@ void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo 
,
 LDSAlignShift = 9;
   }
 
+  ProgInfo.SGPRSpill = MFI->getNumSpilledSGPRs();
+  ProgInfo.VGPRSpill = MFI->getNumSpilledVGPRs();
+
   ProgInfo.LDSSize = MFI->getLDSSize();
   ProgInfo.LDSBlocks =
   alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
@@ -1180,3 +1188,58 @@ void AMDGPUAsmPrinter::getAnalysisUsage(AnalysisUsage 
) const {
   AU.addPreserved();
   AsmPrinter::getAnalysisUsage(AU);
 }
+
+void AMDGPUAsmPrinter::emitResourceUsageRemarks(
+const MachineFunction , const SIProgramInfo ,
+bool isModuleEntryFunction, bool hasMAIInsts) {
+  if (!ORE)
+return;
+
+  const char *Name = "kernel-resource-usage";
+  const char *Indent = "";
+
+  // If the remark is not specifically enabled, do not output to yaml
+  LLVMContext  = MF.getFunction().getContext();
+  if (!Ctx.getDiagHandlerPtr()->isAnalysisRemarkEnabled(Name))
+return;
+
+  auto EmitResourceUsageRemark = [&](StringRef RemarkName,
+ StringRef RemarkLabel, auto Argument) {
+// Add an indent for every line besides the line with the kernel name. This
+// makes it easier to tell which resource usage go with which kernel since
+// the kernel name will always be displayed first.
+std::string LabelStr = RemarkLabel.str() + ": ";
+if (!RemarkName.equals("FunctionName"))
+  LabelStr = Indent + LabelStr;
+
+ORE->emit([&]() {
+  return MachineOptimizationRemarkAnalysis(Name, RemarkName,
+   
MF.getFunction().getSubprogram(),
+   ())
+ << LabelStr << ore::NV(RemarkName, Argument);
+});
+  };
+
+  // FIXME: Formatting here is pretty nasty because clang does not accept
+  // newlines from diagnostics. This forces us to emit multiple diagnostic
+  // remarks to simulate newlines. If and when clang does accept 

[PATCH] D129886: Adds `-fdiagnostics-format=sarif` flag option and warning.

2022-07-15 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd created this revision.
Herald added a project: All.
abrahamcd requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129886

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/DiagnosticOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Frontend/TextDiagnostic.cpp


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -815,6 +815,7 @@
 
   emitFilename(PLoc.getFilename(), Loc.getManager());
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
 if (DiagOpts->ShowLine)
   OS << ':' << LineNo;
@@ -837,6 +838,7 @@
   OS << ColNo;
 }
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
   case DiagnosticOptions::Vi:OS << ':';break;
   case DiagnosticOptions::MSVC:
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4006,6 +4006,9 @@
   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
 CmdArgs.push_back("-fdiagnostics-format");
 CmdArgs.push_back(A->getValue());
+if (std::string(A->getValue()) == "sarif") {
+  D.Diag(diag::warn_drv_sarif_format_unstable);
+}
   }
 
   if (const Arg *A = Args.getLastArg(
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -5574,8 +5574,8 @@
 
 def fdiagnostics_format : Separate<["-"], "fdiagnostics-format">,
   HelpText<"Change diagnostic formatting to match IDE and command line tools">,
-  Values<"clang,msvc,vi">,
-  NormalizedValuesScope<"DiagnosticOptions">, NormalizedValues<["Clang", 
"MSVC", "Vi"]>,
+  Values<"clang,msvc,vi,sarif">,
+  NormalizedValuesScope<"DiagnosticOptions">, NormalizedValues<["Clang", 
"MSVC", "Vi", "SARIF"]>,
   MarshallingInfoEnum, "Clang">;
 def fdiagnostics_show_category : Separate<["-"], "fdiagnostics-show-category">,
   HelpText<"Print diagnostic category">,
Index: clang/include/clang/Basic/DiagnosticOptions.h
===
--- clang/include/clang/Basic/DiagnosticOptions.h
+++ clang/include/clang/Basic/DiagnosticOptions.h
@@ -74,7 +74,7 @@
   friend class CompilerInvocation;
 
 public:
-  enum TextDiagnosticFormat { Clang, MSVC, Vi };
+  enum TextDiagnosticFormat { Clang, MSVC, Vi, SARIF };
 
   // Default values.
   enum {
Index: clang/include/clang/Basic/DiagnosticDriverKinds.td
===
--- clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -678,4 +678,7 @@
 def err_drv_invalid_empty_dxil_validator_version : Error<
   "invalid validator version : %0\n"
   "If validator major version is 0, minor version must also be 0.">;
+
+def warn_drv_sarif_format_unstable : Warning<
+  "diagnostic formatting in SARIF mode is currently unstable">;
 }


Index: clang/lib/Frontend/TextDiagnostic.cpp
===
--- clang/lib/Frontend/TextDiagnostic.cpp
+++ clang/lib/Frontend/TextDiagnostic.cpp
@@ -815,6 +815,7 @@
 
   emitFilename(PLoc.getFilename(), Loc.getManager());
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
 if (DiagOpts->ShowLine)
   OS << ':' << LineNo;
@@ -837,6 +838,7 @@
   OS << ColNo;
 }
   switch (DiagOpts->getFormat()) {
+  case DiagnosticOptions::SARIF:
   case DiagnosticOptions::Clang:
   case DiagnosticOptions::Vi:OS << ':';break;
   case DiagnosticOptions::MSVC:
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4006,6 +4006,9 @@
   if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
 CmdArgs.push_back("-fdiagnostics-format");
 CmdArgs.push_back(A->getValue());
+if (std::string(A->getValue()) == "sarif") {
+  D.Diag(diag::warn_drv_sarif_format_unstable);
+}
   }
 
   if (const Arg *A = Args.getLastArg(
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -5574,8 +5574,8 @@
 
 def fdiagnostics_format : Separate<["-"], "fdiagnostics-format">,
   HelpText<"Change diagnostic formatting to 

[PATCH] D129881: [C] Strengthen -Wint-conversion to default to an error

2022-07-15 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

Given this is an on-by-default warning already, I don't expect changing it to 
an error by default to have much impact in practice.  Changing it fine.




Comment at: clang/lib/Sema/SemaExprCXX.cpp:8483
+if ((SemaRef.getLangOpts().CPlusPlus && Trap.hasErrorOccurred()) ||
+Res.isInvalid())
   return ExprError();

I'd prefer not to introduce unnecessary differences in C vs. C++ handling like 
this...

This seems weird for two reasons:

- We don't use ext_typecheck_convert_pointer_int in C++, so there's not really 
any reason to mark it SFINAEFailure
- Whatever code is calling this probably doesn't want an SFINAE context.  Is 
this coming from TransformToPotentiallyEvaluated?  We don't want SFINAE traps 
from there, in C or C++.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129881

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


[PATCH] D129885: [CUDA] Make the new driver properly ignore non-CUDA inputs

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

The new driver generated offloadinga actions for each active toolchain.
However, for CUDA and HIP it is possible for the toolchain to be active
but one of the files is not a valid input. This can occur if the user
compiles both a CUDA and C source file in the same compiler invocation.
This patch adds some simple logic to quit if the input is not valid as
well.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129885

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cuda-phases.cu


Index: clang/test/Driver/cuda-phases.cu
===
--- clang/test/Driver/cuda-phases.cu
+++ clang/test/Driver/cuda-phases.cu
@@ -266,3 +266,32 @@
 // NEW-DRIVER: 17: backend, {16}, assembler, (host-cuda)
 // NEW-DRIVER: 18: assembler, {17}, object, (host-cuda)
 // NEW-DRIVER: 19: clang-linker-wrapper, {18}, image, (host-cuda)
+
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases 
--offload-new-driver \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s %S/Inputs/empty.cpp 2>&1 
| FileCheck --check-prefix=NON-CUDA-INPUT %s
+// NON-CUDA-INPUT: 0: input, "[[CUDA:.+]]", cuda, (host-cuda)
+// NON-CUDA-INPUT: 1: preprocessor, {0}, cuda-cpp-output, (host-cuda)
+// NON-CUDA-INPUT: 2: compiler, {1}, ir, (host-cuda)
+// NON-CUDA-INPUT: 3: input, "[[CUDA]]", cuda, (device-cuda, sm_52)
+// NON-CUDA-INPUT: 4: preprocessor, {3}, cuda-cpp-output, (device-cuda, sm_52)
+// NON-CUDA-INPUT: 5: compiler, {4}, ir, (device-cuda, sm_52)
+// NON-CUDA-INPUT: 6: backend, {5}, assembler, (device-cuda, sm_52)
+// NON-CUDA-INPUT: 7: assembler, {6}, object, (device-cuda, sm_52)
+// NON-CUDA-INPUT: 8: offload, "device-cuda (nvptx64-nvidia-cuda:sm_52)" {7}, 
object
+// NON-CUDA-INPUT: 9: input, "[[CUDA]]", cuda, (device-cuda, sm_70)
+// NON-CUDA-INPUT: 10: preprocessor, {9}, cuda-cpp-output, (device-cuda, sm_70)
+// NON-CUDA-INPUT: 11: compiler, {10}, ir, (device-cuda, sm_70)
+// NON-CUDA-INPUT: 12: backend, {11}, assembler, (device-cuda, sm_70)
+// NON-CUDA-INPUT: 13: assembler, {12}, object, (device-cuda, sm_70)
+// NON-CUDA-INPUT: 14: offload, "device-cuda (nvptx64-nvidia-cuda:sm_70)" 
{13}, object
+// NON-CUDA-INPUT: 15: linker, {8, 14}, cuda-fatbin, (device-cuda)
+// NON-CUDA-INPUT: 16: offload, "host-cuda (powerpc64le-ibm-linux-gnu)" {2}, 
"device-cuda (nvptx64-nvidia-cuda)" {15}, ir
+// NON-CUDA-INPUT: 17: backend, {16}, assembler, (host-cuda)
+// NON-CUDA-INPUT: 18: assembler, {17}, object, (host-cuda)
+// NON-CUDA-INPUT: 19: input, "[[CPP:.+]]", c++, (host-cuda)
+// NON-CUDA-INPUT: 20: preprocessor, {19}, c++-cpp-output, (host-cuda)
+// NON-CUDA-INPUT: 21: compiler, {20}, ir, (host-cuda)
+// NON-CUDA-INPUT: 22: backend, {21}, assembler, (host-cuda)
+// NON-CUDA-INPUT: 23: assembler, {22}, object, (host-cuda)
+// NON-CUDA-INPUT: 24: clang-linker-wrapper, {18, 23}, image, (host-cuda)
+
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -4432,6 +4432,11 @@
 types::ID InputType = Input.first;
 const Arg *InputArg = Input.second;
 
+// The toolchain can be active for unsupported file types.
+if ((Kind == Action::OFK_Cuda && !types::isCuda(InputType)) ||
+(Kind == Action::OFK_HIP && !types::isHIP(InputType)))
+  continue;
+
 // Get the product of all bound architectures and toolchains.
 SmallVector> TCAndArchs;
 for (const ToolChain *TC : ToolChains)
@@ -4486,6 +4491,9 @@
   if (offloadDeviceOnly())
 return C.MakeAction(DDeps, types::TY_Nothing);
 
+  if (OffloadActions.empty())
+return HostAction;
+
   OffloadAction::DeviceDependences DDep;
   if (C.isOffloadingHostKind(Action::OFK_Cuda) &&
   !Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) {


Index: clang/test/Driver/cuda-phases.cu
===
--- clang/test/Driver/cuda-phases.cu
+++ clang/test/Driver/cuda-phases.cu
@@ -266,3 +266,32 @@
 // NEW-DRIVER: 17: backend, {16}, assembler, (host-cuda)
 // NEW-DRIVER: 18: assembler, {17}, object, (host-cuda)
 // NEW-DRIVER: 19: clang-linker-wrapper, {18}, image, (host-cuda)
+
+// RUN: %clang -### -target powerpc64le-ibm-linux-gnu -ccc-print-phases --offload-new-driver \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 %s %S/Inputs/empty.cpp 2>&1 | FileCheck --check-prefix=NON-CUDA-INPUT %s
+// NON-CUDA-INPUT: 0: input, "[[CUDA:.+]]", cuda, (host-cuda)
+// NON-CUDA-INPUT: 1: preprocessor, {0}, cuda-cpp-output, (host-cuda)
+// NON-CUDA-INPUT: 2: compiler, {1}, ir, (host-cuda)
+// NON-CUDA-INPUT: 3: input, "[[CUDA]]", cuda, (device-cuda, 

[PATCH] D129881: [C] Strengthen -Wint-conversion to default to an error

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

This seems like a good idea despite the breaking change.  I dont see anything 
in the code to be concerned about, but I'm hoping others will comment as to 
whether this is completely acceptable.




Comment at: clang/lib/Sema/SemaExprCXX.cpp:8482
 ExprResult Res = TransformExpr(E);
-if (Trap.hasErrorOccurred() || Res.isInvalid())
+if ((SemaRef.getLangOpts().CPlusPlus && Trap.hasErrorOccurred()) ||
+Res.isInvalid())

This makes sense to me, I don't see why this hasn't bit us before, but SFINAE 
in C mode seems wrong?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129881

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


[PATCH] D129884: [clang][deps] Include canonical invocation in ContextHash

2022-07-15 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir created this revision.
benlangmuir added reviewers: jansvoboda11, Bigcheese, akyrtzi.
Herald added a project: All.
benlangmuir requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The "strict context hash" is insufficient to identify module
dependencies during scanning, leading to different module build commands
being produced for a single module, and non-deterministically choosing
between them. This commit switches to hashing the canonicalized
`CompilerInvocation` of the module. By hashing the invocation we are
converting these from correctness issues to performance issues, and we
can then incrementally improve our ability to canonicalize
command-lines.

This change can cause a regression in the number of modules needed. Of
the 4 projects I tested, 3 had no regression, but 1, which was
clang+llvm itself, had a 66% regression in number of modules (4%
regression in total invocations). This is almost entirely due to
differences between -W options across targets.  Of this, 25% of the
additional modules are system modules, which we could avoid if we
canonicalized -W options when -Wsystem-headers is not present --
unfortunately this is non-trivial due to some warnings being enabled in
system headers by default. The rest of the additional modules are mostly
real differences in potential warnings, reflecting incorrect behaviour
in the current scanner.

There were also a couple of differences due to `-DFOO`
`-fmodule-ignore-macro=FOO`, which I fixed here.

Since the output paths for the module depend on its context hash, we
hash the invocation before filling in outputs, and rely on the build
system to always return the same output paths for a given module.

Note: since the scanner itself uses an implicit modules build, there can
still be non-determinism, but it will now present as different
module+hashes rather than different command-lines for the same
module+hash.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129884

Files:
  clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/ClangScanDeps/modules-context-hash-ignore-macros.c
  clang/test/ClangScanDeps/modules-context-hash-module-map-path.c
  clang/test/ClangScanDeps/modules-context-hash-warnings.c

Index: clang/test/ClangScanDeps/modules-context-hash-warnings.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-context-hash-warnings.c
@@ -0,0 +1,74 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed "s|DIR|%/t|g" %t/cdb.json.template > %t/cdb.json
+
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -j 1 \
+// RUN:   -format experimental-full > %t/deps.json
+// RUN: cat %t/deps.json | sed 's:\?:/:g' | FileCheck -DPREFIX=%/t %s
+
+// CHECK:  {
+// CHECK-NEXT:   "modules": [
+// CHECK:  {
+// CHECK:"command-line": [
+// CHECK:  "-Wall"
+// CHECK:]
+// CHECK:"context-hash": "[[HASH1:.*]]"
+// CHECK:"name": "Mod"
+// CHECK-NEXT: }
+// CHECK-NEXT: {
+// CHECK:"command-line": [
+// CHECK-NOT:  "-Wall"
+// CHECK:]
+// CHECK:"context-hash": "[[HASH2:.*]]"
+// CHECK:"name": "Mod"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ]
+// CHECK-NEXT:   "translation-units": [
+// CHECK-NEXT: {
+// CHECK:"clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "[[HASH1]]"
+// CHECK-NEXT:"module-name": "Mod"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ]
+// CHECK-NEXT:   "command-line": [
+// CHECK:  "-Wall"
+// CHECK:]
+// CHECK:"input-file": "{{.*}}tu1.c"
+// CHECK-NEXT: }
+// CHECK-NEXT: {
+// CHECK:"clang-module-deps": [
+// CHECK-NEXT: {
+// CHECK-NEXT:   "context-hash": "[[HASH2]]"
+// CHECK-NEXT:"module-name": "Mod"
+// CHECK-NEXT: }
+// CHECK-NEXT:   ]
+// CHECK-NEXT:   "command-line": [
+// CHECK-NOT:  "-Wall"
+// CHECK:]
+// CHECK:"input-file": "{{.*}}tu2.c"
+
+//--- cdb.json.template
+[
+  {
+"directory": "DIR",
+"command": "clang -Wall -fsyntax-only DIR/tu1.c -fmodules -fimplicit-module-maps -fmodules-cache-path=DIR/cache",
+"file": "DIR/tu1.c"
+  },
+  {
+"directory": "DIR",
+"command": "clang -fsyntax-only DIR/tu2.c -fmodules -fimplicit-module-maps -fmodules-cache-path=DIR/cache",
+"file": "DIR/tu2.c"
+  },
+]
+
+//--- module.modulemap
+module Mod { header "Mod.h" }
+
+//--- Mod.h
+
+//--- tu1.c
+#include "Mod.h"
+
+//--- tu2.c
+#include "Mod.h"
Index: clang/test/ClangScanDeps/modules-context-hash-module-map-path.c
===
--- /dev/null
+++ 

[PATCH] D129883: [HLSL] Support cbuffer/tbuffer for hlsl.

2022-07-15 Thread Xiang Li via Phabricator via cfe-commits
python3kgae created this revision.
python3kgae added reviewers: svenvh, asavonic, beanz, pow2clk, Anastasia, 
aaron.ballman.
Herald added a subscriber: mgorny.
Herald added a project: All.
python3kgae requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is first part for support cbuffer/tbuffer.

The format for cbuffer/tbuffer is
BufferType [Name] [: register(b#)] { VariableDeclaration [: 
packoffset(c#.xyzw)]; ... };

More details at 
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-constants

New keyword 'cbuffer' and 'tbuffer' are added.
New AST node HLSLBufferDecl is added.
Build AST for simple cbuffer/tbuffer without attribute support.

The special thing is variables declared inside cbuffer is exposed into global 
scope.
So isTransparentContext should return true for HLSLBuffer.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129883

Files:
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/AST/TextNodeDumper.h
  clang/include/clang/Basic/DeclNodes.td
  clang/include/clang/Basic/TokenKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Basic/IdentifierTable.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseHLSL.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/CMakeLists.txt
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaHLSL.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Serialization/ASTCommon.cpp
  clang/test/SemaHLSL/cbuffer_tbuffer.hlsl

Index: clang/test/SemaHLSL/cbuffer_tbuffer.hlsl
===
--- /dev/null
+++ clang/test/SemaHLSL/cbuffer_tbuffer.hlsl
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -ast-dump -o - %s | FileCheck %s
+
+// CHECK:HLSLBufferDecl 0x[[CB:[0-9a-f]+]] {{.*}} line:5:9 cbuffer CB
+// CHECK-NEXT:VarDecl 0x[[A:[0-9a-f]+]] {{.*}} col:9 used a 'float'
+cbuffer CB {
+  float a;
+};
+
+// CHECK:HLSLBufferDecl 0x[[TB:[0-9a-f]+]] {{.*}} line:11:9 tbuffer TB
+// CHECK-NEXT:VarDecl 0x[[B:[0-9a-f]+]] {{.*}} col:9 used b 'float'
+tbuffer TB {
+  float b;
+};
+
+float foo() {
+// CHECK: BinaryOperator 0x{{[0-9a-f]+}}  'float' '+'
+// CHECK-NEXT: ImplicitCastExpr 0x{{[0-9a-f]+}}  'float' 
+// CHECK-NEXT: DeclRefExpr 0x{{[0-9a-f]+}}  'float' lvalue Var 0x[[A]] 'a' 'float'
+// CHECK-NEXT: ImplicitCastExpr 0x{{[0-9a-f]+}}  'float' 
+// CHECK-NEXT: DeclRefExpr 0x{{[0-9a-f]+}}  'float' lvalue Var 0x[[B]] 'b' 'float'
+  return a + b;
+}
Index: clang/lib/Serialization/ASTCommon.cpp
===
--- clang/lib/Serialization/ASTCommon.cpp
+++ clang/lib/Serialization/ASTCommon.cpp
@@ -433,6 +433,7 @@
   case Decl::LifetimeExtendedTemporary:
   case Decl::RequiresExprBody:
   case Decl::UnresolvedUsingIfExists:
+  case Decl::HLSLBuffer:
 return false;
 
   // These indirectly derive from Redeclarable but are not actually
Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -873,6 +873,10 @@
   llvm_unreachable("Translation units cannot be instantiated");
 }
 
+Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
+  llvm_unreachable("HLSL buffer declarations cannot be instantiated");
+}
+
 Decl *
 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
   llvm_unreachable("pragma comment cannot be instantiated");
Index: clang/lib/Sema/SemaHLSL.cpp
===
--- /dev/null
+++ clang/lib/Sema/SemaHLSL.cpp
@@ -0,0 +1,37 @@
+//===- SemaHLSL.cpp - Semantic Analysis for HLSL constructs ---===//
+//
+// 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 implements Semantic Analysis for HLSL constructs.
+//===--===//
+
+#include "clang/Sema/Sema.h"
+
+using namespace clang;
+
+Decl *Sema::ActOnStartHLSLBuffer(Scope *BufferScope, bool CBuffer,
+ SourceLocation KwLoc, IdentifierInfo *Ident,
+ SourceLocation IdentLoc,
+ SourceLocation LBrace) {
+  // For anonymous namespace, take the location of the left brace.
+  DeclContext *LexicalParent = getCurLexicalContext();
+  HLSLBufferDecl *Result = HLSLBufferDecl::Create(
+  Context, 

[PATCH] D128619: [Clang] Implement P0848 (Conditionally Trivial Special Member Functions)

2022-07-15 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson marked an inline comment as done.
royjacobson added inline comments.



Comment at: clang/test/AST/conditionally-trivial-smfs.cpp:39
+
+template struct DefaultConstructorCheck<2>;
+// CHECK: "kind": "ClassTemplateSpecializationDecl",

BRevzin wrote:
> royjacobson wrote:
> > BRevzin wrote:
> > > It's possible that I just don't understand what these tests actually mean 
> > > but... where is the test for `DefaultConstructorCheck<2>` having a 
> > > deleted default constructor, or `DefaultConstructorCheck<3>` having a 
> > > non-defaulted one?
> > > 
> > > It'd also be worthwhile to have at least one test with constaints that 
> > > subsume each other instead of being mutually exclusive. 
> > Should I check this? Except destructors, the other SMFs are found during 
> > overload resolution using the usual lookup that already takes into account 
> > delete/default/constraints etc.
> > 
> > This patch is about making sure that we set the triviality attributes 
> > correctly according to the eligible functions, so this is what I added 
> > tests for.
> > 
> > Most of this testing is done in the sema test, but I need this AST test as 
> > well to make sure we get the `canPassInRegisters` attribute correctly - 
> > we're doing some custom processing over the functions without the usual 
> > type attributes because there are some weird compatibility edge cases.
> > 
> One of the motivations for the paper is to ensure that like given:
> 
> ```
> template 
> struct optional {
> optional(optional const&) requires copyable && trivially_copyableT> = 
> default;
> optional(optional const&) requires copyable;
> };
> ```
> 
> `optional` is copyable (but not trivially copyable), `optional` 
> is trivially copyable, and `optional>` isn't copyable. I'm 
> not sure what in here checks if that works. 
That's more-or-less the check in `constrained-special-member-functions.cpp:50`, 
I think.

Didn't acknowledge it in my first response - but yeah, I need some more 
complicated subsumption test cases



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128619

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


[PATCH] D129832: [sanitizer] Add "mainfile" prefix to sanitizer special case list

2022-07-15 Thread Fangrui Song via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0d5a62faca59: [sanitizer] Add mainfile prefix to 
sanitizer special case list (authored by MaskRay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129832

Files:
  clang/docs/SanitizerSpecialCaseList.rst
  clang/include/clang/Basic/NoSanitizeList.h
  clang/lib/Basic/NoSanitizeList.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/sanitize-ignorelist-mainfile.c
  llvm/include/llvm/Support/SpecialCaseList.h

Index: llvm/include/llvm/Support/SpecialCaseList.h
===
--- llvm/include/llvm/Support/SpecialCaseList.h
+++ llvm/include/llvm/Support/SpecialCaseList.h
@@ -19,9 +19,9 @@
 //   prefix:wildcard_expression[=category]
 // If category is not specified, it is assumed to be empty string.
 // Definitions of "prefix" and "category" are sanitizer-specific. For example,
-// sanitizer exclusion support prefixes "src", "fun" and "global".
-// Wildcard expressions define, respectively, source files, functions or
-// globals which shouldn't be instrumented.
+// sanitizer exclusion support prefixes "src", "mainfile", "fun" and "global".
+// Wildcard expressions define, respectively, source files, main files,
+// functions or globals which shouldn't be instrumented.
 // Examples of categories:
 //   "functional": used in DFSan to list functions with pure functional
 // semantics.
@@ -37,6 +37,7 @@
 // type:*Namespace::ClassName*=init
 // src:file_with_tricky_code.cc
 // src:ignore-global-initializers-issues.cc=init
+// mainfile:main_file.cc
 //
 // [dataflow]
 // # Functions with pure functional semantics:
Index: clang/test/CodeGen/sanitize-ignorelist-mainfile.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-ignorelist-mainfile.c
@@ -0,0 +1,41 @@
+/// Test mainfile in a sanitizer special case list.
+// RUN: rm -rf %t && split-file %s %t && cd %t
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fsanitize=address,alignment a.c -o - | FileCheck %s --check-prefixes=CHECK,DEFAULT
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fsanitize=address,alignment -fsanitize-ignorelist=a.list a.c -o - | FileCheck %s --check-prefixes=CHECK,IGNORE
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fsanitize=address,alignment -fsanitize-ignorelist=b.list a.c -o - | FileCheck %s --check-prefixes=CHECK,IGNORE
+
+//--- a.list
+mainfile:*a.c
+
+//--- b.list
+[address]
+mainfile:*a.c
+
+[alignment]
+mainfile:*.c
+
+//--- a.h
+int global_h;
+
+static inline int load(int *x) {
+  return *x;
+}
+
+//--- a.c
+#include "a.h"
+
+int global_c;
+
+int foo(void *x) {
+  return load(x);
+}
+
+// DEFAULT: @___asan_gen_{{.*}} = {{.*}} c"global_h\00"
+// DEFAULT: @___asan_gen_{{.*}} = {{.*}} c"global_c\00"
+// IGNORE-NOT:  @___asan_gen_
+
+// CHECK-LABEL: define {{.*}}@load(
+// DEFAULT:   call void @__ubsan_handle_type_mismatch_v1_abort(
+// DEFAULT:   call void @__asan_report_load4(
+// IGNORE-NOT:call void @__ubsan_handle_type_mismatch_v1_abort(
+// IGNORE-NOT:call void @__asan_report_load4(
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -2780,16 +2780,18 @@
   // NoSanitize by function name.
   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
 return true;
-  // NoSanitize by location.
+  // NoSanitize by location. Check "mainfile" prefix.
+  auto  = Context.getSourceManager();
+  const FileEntry  = *SM.getFileEntryForID(SM.getMainFileID());
+  if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
+return true;
+
+  // Check "src" prefix.
   if (Loc.isValid())
 return NoSanitizeL.containsLocation(Kind, Loc);
   // If location is unknown, this may be a compiler-generated function. Assume
   // it's located in the main file.
-  auto  = Context.getSourceManager();
-  if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
-return NoSanitizeL.containsFile(Kind, MainFile->getName());
-  }
-  return false;
+  return NoSanitizeL.containsFile(Kind, MainFile.getName());
 }
 
 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
@@ -2799,8 +2801,13 @@
   const auto  = getContext().getNoSanitizeList();
   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
 return true;
+  auto  = Context.getSourceManager();
+  if (NoSanitizeL.containsMainFile(
+  Kind, SM.getFileEntryForID(SM.getMainFileID())->getName(), Category))
+return true;
   if (NoSanitizeL.containsLocation(Kind, Loc, Category))
 return true;
+
   // Check global type.
   if (!Ty.isNull()) {
 // Drill down the array types: if global variable of a fixed type is
Index: 

[clang] 0d5a62f - [sanitizer] Add "mainfile" prefix to sanitizer special case list

2022-07-15 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2022-07-15T10:39:26-07:00
New Revision: 0d5a62faca5924c5a197faa946b5b78b3d80a0b2

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

LOG: [sanitizer] Add "mainfile" prefix to sanitizer special case list

When an issue exists in the main file (caller) instead of an included file
(callee), using a `src` pattern applying to the included file may be
inappropriate if it's the caller's responsibility. Add `mainfile` prefix to 
check
the main filename.

For the example below, the issue may reside in a.c (foo should not be called
with a misaligned pointer or foo should switch to an unaligned load), but with
`src` we can only apply to the innocent callee a.h. With this patch we can use
the more appropriate `mainfile:a.c`.
```
//--- a.h
// internal linkage
static inline int load(int *x) { return *x; }

//--- a.c, -fsanitize=alignment
#include "a.h"
int foo(void *x) { return load(x); }
```

See the updated clang/docs/SanitizerSpecialCaseList.rst for a caveat due
to C++ vague linkage functions.

Reviewed By: #sanitizers, kstoimenov, vitalybuka

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

Added: 
clang/test/CodeGen/sanitize-ignorelist-mainfile.c

Modified: 
clang/docs/SanitizerSpecialCaseList.rst
clang/include/clang/Basic/NoSanitizeList.h
clang/lib/Basic/NoSanitizeList.cpp
clang/lib/CodeGen/CodeGenModule.cpp
llvm/include/llvm/Support/SpecialCaseList.h

Removed: 




diff  --git a/clang/docs/SanitizerSpecialCaseList.rst 
b/clang/docs/SanitizerSpecialCaseList.rst
index cbb00fde9bb7..15e19b9c129c 100644
--- a/clang/docs/SanitizerSpecialCaseList.rst
+++ b/clang/docs/SanitizerSpecialCaseList.rst
@@ -75,6 +75,9 @@ tool-specific docs.
 # Turn off checks for the source file (use absolute path or path relative
 # to the current working directory):
 src:/path/to/source/file.c
+# Turn off checks for this main file, including files included by it.
+# Useful when the main file instead of an included file should be ignored.
+mainfile:file.c
 # Turn off checks for a particular functions (use mangled names):
 fun:MyFooBar
 fun:_Z8MyFooBarv
@@ -93,3 +96,18 @@ tool-specific docs.
 [cfi-vcall|cfi-icall]
 fun:*BadCfiCall
 # Entries without sections are placed into [*] and apply to all sanitizers
+
+``mainfile`` is similar to applying ``-fno-sanitize=`` to a set of files but
+does not need plumbing into the build system. This works well for internal
+linkage functions but has a caveat for C++ vague linkage functions.
+
+C++ vague linkage functions (e.g. inline functions, template instantiations) 
are
+deduplicated at link time. A function (in an included file) ignored by a
+specific ``mainfile`` pattern may not be the prevailing copy picked by the
+linker. Therefore, using ``mainfile`` requires caution. It may still be useful,
+e.g. when patterns are picked in a way to ensure the prevailing one is ignored.
+(There is action-at-a-distance risk.)
+
+``mainfile`` can be useful enabling a ubsan check for a large code base when
+finding the direct stack frame triggering the failure for every failure is
+
diff icult.

diff  --git a/clang/include/clang/Basic/NoSanitizeList.h 
b/clang/include/clang/Basic/NoSanitizeList.h
index 3f80e0fdedda..43415859fcd5 100644
--- a/clang/include/clang/Basic/NoSanitizeList.h
+++ b/clang/include/clang/Basic/NoSanitizeList.h
@@ -41,6 +41,8 @@ class NoSanitizeList {
   bool containsFunction(SanitizerMask Mask, StringRef FunctionName) const;
   bool containsFile(SanitizerMask Mask, StringRef FileName,
 StringRef Category = StringRef()) const;
+  bool containsMainFile(SanitizerMask Mask, StringRef FileName,
+StringRef Category = StringRef()) const;
   bool containsLocation(SanitizerMask Mask, SourceLocation Loc,
 StringRef Category = StringRef()) const;
 };

diff  --git a/clang/lib/Basic/NoSanitizeList.cpp 
b/clang/lib/Basic/NoSanitizeList.cpp
index 3efd613b0d33..e7e63c1f419e 100644
--- a/clang/lib/Basic/NoSanitizeList.cpp
+++ b/clang/lib/Basic/NoSanitizeList.cpp
@@ -47,6 +47,11 @@ bool NoSanitizeList::containsFile(SanitizerMask Mask, 
StringRef FileName,
   return SSCL->inSection(Mask, "src", FileName, Category);
 }
 
+bool NoSanitizeList::containsMainFile(SanitizerMask Mask, StringRef FileName,
+  StringRef Category) const {
+  return SSCL->inSection(Mask, "mainfile", FileName, Category);
+}
+
 bool NoSanitizeList::containsLocation(SanitizerMask Mask, SourceLocation Loc,
   StringRef Category) const {
   return Loc.isValid() &&

diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 1e90b0914538..4daf4120e0ca 

[PATCH] D129881: [C] Strengthen -Wint-conversion to default to an error

2022-07-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman created this revision.
aaron.ballman added reviewers: efriedma, jyknight, erichkeane, 
clang-language-wg.
Herald added subscribers: steakhal, Enna1, kosarev, arphaman, jvesely.
Herald added a project: All.
aaron.ballman requested review of this revision.
Herald added projects: clang, Sanitizers, clang-tools-extra.
Herald added a subscriber: Sanitizers.

Clang has traditionally allowed C programs to implicitly convert integers to 
pointers and pointers to integers, despite it not being valid to do so except 
under special circumstances (like converting the integer 0, which is the null 
pointer constant, to a pointer). In C89, this would result in undefined 
behavior per 3.3.4, and in C99 this rule was strengthened to be a constraint 
violation instead. Constraint violations are most often handled as an error.

This patch changes the warning to default to an error in all C modes (it is 
already an error in C++). This gives us better security posture by calling out 
potential programmer mistakes in code but still allows users who need this 
behavior to use `-Wno-error=int-conversion` to retain the warning behavior, or 
`-Wno-int-conversion` to silence the diagnostic entirely.

When modifying the diagnostics, I observed that 
`ext_typecheck_convert_int_pointer` was already marked `SFINAEFailure` but 
`ext_typecheck_convert_pointer_int` was not. This appeared to be an oversight 
which I corrected. That resulted in needing a change to not perform SFINAE 
traps in C mode. If desired, I can split those changes into a separate review, 
but they felt related enough to this change to be reasonable to roll in here by 
virtue of changing the behavior of the diagnostic.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129881

Files:
  clang-tools-extra/test/clang-tidy/checkers/bugprone/no-escape.m
  clang-tools-extra/test/clang-tidy/checkers/performance/no-int-to-ptr.c
  clang/bindings/python/tests/cindex/test_diagnostics.py
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/Analysis/ObjCProperties.m
  clang/test/Analysis/bsd-string.c
  clang/test/Analysis/novoidtypecrash.c
  clang/test/Analysis/null-deref-ps.c
  clang/test/Analysis/number-object-conversion.c
  clang/test/Analysis/number-object-conversion.m
  clang/test/Analysis/pr22954.c
  clang/test/C/drs/dr0xx.c
  clang/test/C/drs/dr2xx.c
  clang/test/CodeGen/2008-03-05-syncPtr.c
  clang/test/CodeGen/2008-07-31-promotion-of-compound-pointer-arithmetic.c
  clang/test/CodeGen/aarch64-mops.c
  clang/test/CodeGen/address-space-cast.c
  clang/test/CodeGen/const-init.c
  clang/test/CodeGen/pointer-arithmetic.c
  clang/test/CodeGen/pointer-to-int.c
  clang/test/CodeGen/statements.c
  clang/test/CodeGen/struct-init.c
  clang/test/CodeGen/vla.c
  clang/test/CodeGenObjC/block-ptr-type-crash.m
  clang/test/CodeGenOpenCL/builtins-generic-amdgcn.cl
  clang/test/FixIt/dereference-addressof.c
  clang/test/FixIt/selector-fixit.m
  clang/test/Misc/serialized-diags.c
  clang/test/Misc/tabstop.c
  clang/test/Modules/config_macros.m
  clang/test/PCH/objc_exprs.m
  clang/test/Parser/implicit-casts.c
  clang/test/Sema/array-init.c
  clang/test/Sema/atomic-ops.c
  clang/test/Sema/block-return.c
  clang/test/Sema/builtin-alloca-with-align.c
  clang/test/Sema/builtin-assume-aligned.c
  clang/test/Sema/builtin-dump-struct.c
  clang/test/Sema/builtins-bpf.c
  clang/test/Sema/builtins.c
  clang/test/Sema/compound-literal.c
  clang/test/Sema/conditional-expr.c
  clang/test/Sema/enum.c
  clang/test/Sema/extern-redecl.c
  clang/test/Sema/format-strings.c
  clang/test/Sema/function-redecl.c
  clang/test/Sema/function.c
  clang/test/Sema/i-c-e.c
  clang/test/Sema/indirect-goto.c
  clang/test/Sema/matrix-type-builtins.c
  clang/test/Sema/nullability.c
  clang/test/SemaObjC/argument-checking.m
  clang/test/SemaObjC/comptypes-7.m
  clang/test/SemaObjC/ivar-lookup-resolution-builtin.m
  clang/test/SemaObjC/message.m
  clang/test/SemaObjC/method-lookup-5.m
  clang/test/SemaObjC/nullability.m
  clang/test/SemaObjC/objc-container-subscripting-3.m
  clang/test/SemaObjC/objc-literal-fixit.m
  clang/test/SemaObjC/signed-char-bool-conversion.m
  clang/test/SemaOpenCL/atomic-ops.cl
  clang/test/SemaOpenCL/builtins-amdgcn-error.cl
  clang/test/VFS/Inputs/external-names.h
  clang/test/VFS/external-names.c
  compiler-rt/test/dfsan/gep.c
  compiler-rt/test/dfsan/sigaction.c

Index: compiler-rt/test/dfsan/sigaction.c
===
--- compiler-rt/test/dfsan/sigaction.c
+++ compiler-rt/test/dfsan/sigaction.c
@@ -1,5 +1,5 @@
-// RUN: %clang_dfsan -DUSE_SIGNAL_ACTION %s -o %t && %run %t
-// RUN: %clang_dfsan %s -o %t && %run %t
+// RUN: %clang_dfsan -DUSE_SIGNAL_ACTION -Wno-error=int-conversion %s -o %t && %run %t
+// RUN: %clang_dfsan -Wno-error=int-conversion %s -o %t && %run %t
 //
 // REQUIRES: x86_64-target-arch
 
Index: compiler-rt/test/dfsan/gep.c

[PATCH] D129832: [sanitizer] Add "mainfile" prefix to sanitizer special case list

2022-07-15 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 445051.
MaskRay retitled this revision from "[sanitizer] Add "mainsrc" prefix to 
sanitizer special case list" to "[sanitizer] Add "mainfile" prefix to sanitizer 
special case list".
MaskRay edited the summary of this revision.
MaskRay added a comment.

mainsrc => mainfile

Clang names the file "main file". CC1 has options like -main-file-name.
Using "mainfile" instead of "mainsrc" avoids introducing new terminology.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129832

Files:
  clang/docs/SanitizerSpecialCaseList.rst
  clang/include/clang/Basic/NoSanitizeList.h
  clang/lib/Basic/NoSanitizeList.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/sanitize-ignorelist-mainfile.c
  llvm/include/llvm/Support/SpecialCaseList.h

Index: llvm/include/llvm/Support/SpecialCaseList.h
===
--- llvm/include/llvm/Support/SpecialCaseList.h
+++ llvm/include/llvm/Support/SpecialCaseList.h
@@ -19,9 +19,9 @@
 //   prefix:wildcard_expression[=category]
 // If category is not specified, it is assumed to be empty string.
 // Definitions of "prefix" and "category" are sanitizer-specific. For example,
-// sanitizer exclusion support prefixes "src", "fun" and "global".
-// Wildcard expressions define, respectively, source files, functions or
-// globals which shouldn't be instrumented.
+// sanitizer exclusion support prefixes "src", "mainfile", "fun" and "global".
+// Wildcard expressions define, respectively, source files, main files,
+// functions or globals which shouldn't be instrumented.
 // Examples of categories:
 //   "functional": used in DFSan to list functions with pure functional
 // semantics.
@@ -37,6 +37,7 @@
 // type:*Namespace::ClassName*=init
 // src:file_with_tricky_code.cc
 // src:ignore-global-initializers-issues.cc=init
+// mainfile:main_file.cc
 //
 // [dataflow]
 // # Functions with pure functional semantics:
Index: clang/test/CodeGen/sanitize-ignorelist-mainfile.c
===
--- /dev/null
+++ clang/test/CodeGen/sanitize-ignorelist-mainfile.c
@@ -0,0 +1,41 @@
+/// Test mainfile in a sanitizer special case list.
+// RUN: rm -rf %t && split-file %s %t && cd %t
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fsanitize=address,alignment a.c -o - | FileCheck %s --check-prefixes=CHECK,DEFAULT
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fsanitize=address,alignment -fsanitize-ignorelist=a.list a.c -o - | FileCheck %s --check-prefixes=CHECK,IGNORE
+// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fsanitize=address,alignment -fsanitize-ignorelist=b.list a.c -o - | FileCheck %s --check-prefixes=CHECK,IGNORE
+
+//--- a.list
+mainfile:*a.c
+
+//--- b.list
+[address]
+mainfile:*a.c
+
+[alignment]
+mainfile:*.c
+
+//--- a.h
+int global_h;
+
+static inline int load(int *x) {
+  return *x;
+}
+
+//--- a.c
+#include "a.h"
+
+int global_c;
+
+int foo(void *x) {
+  return load(x);
+}
+
+// DEFAULT: @___asan_gen_{{.*}} = {{.*}} c"global_h\00"
+// DEFAULT: @___asan_gen_{{.*}} = {{.*}} c"global_c\00"
+// IGNORE-NOT:  @___asan_gen_
+
+// CHECK-LABEL: define {{.*}}@load(
+// DEFAULT:   call void @__ubsan_handle_type_mismatch_v1_abort(
+// DEFAULT:   call void @__asan_report_load4(
+// IGNORE-NOT:call void @__ubsan_handle_type_mismatch_v1_abort(
+// IGNORE-NOT:call void @__asan_report_load4(
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -2780,16 +2780,18 @@
   // NoSanitize by function name.
   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
 return true;
-  // NoSanitize by location.
+  // NoSanitize by location. Check "mainfile" prefix.
+  auto  = Context.getSourceManager();
+  const FileEntry  = *SM.getFileEntryForID(SM.getMainFileID());
+  if (NoSanitizeL.containsMainFile(Kind, MainFile.getName()))
+return true;
+
+  // Check "src" prefix.
   if (Loc.isValid())
 return NoSanitizeL.containsLocation(Kind, Loc);
   // If location is unknown, this may be a compiler-generated function. Assume
   // it's located in the main file.
-  auto  = Context.getSourceManager();
-  if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
-return NoSanitizeL.containsFile(Kind, MainFile->getName());
-  }
-  return false;
+  return NoSanitizeL.containsFile(Kind, MainFile.getName());
 }
 
 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind,
@@ -2799,8 +2801,13 @@
   const auto  = getContext().getNoSanitizeList();
   if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category))
 return true;
+  auto  = Context.getSourceManager();
+  if (NoSanitizeL.containsMainFile(
+  Kind, SM.getFileEntryForID(SM.getMainFileID())->getName(), Category))
+return true;
   

[PATCH] D129832: [sanitizer] Add "mainsrc" prefix to sanitizer special case list

2022-07-15 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

"unit:" ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129832

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


[PATCH] D129832: [sanitizer] Add "mainsrc" prefix to sanitizer special case list

2022-07-15 Thread Vitaly Buka via Phabricator via cfe-commits
vitalybuka added a comment.

I guess Kirills' complain is about **main** part, not **src**.
But I have no idea what name could be better.
I guess thechnically it's preprocessed src? :)
To me as is name is fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129832

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


[PATCH] D128619: [Clang] Implement P0848 (Conditionally Trivial Special Member Functions)

2022-07-15 Thread Barry Revzin via Phabricator via cfe-commits
BRevzin added inline comments.



Comment at: clang/test/AST/conditionally-trivial-smfs.cpp:39
+
+template struct DefaultConstructorCheck<2>;
+// CHECK: "kind": "ClassTemplateSpecializationDecl",

royjacobson wrote:
> BRevzin wrote:
> > It's possible that I just don't understand what these tests actually mean 
> > but... where is the test for `DefaultConstructorCheck<2>` having a deleted 
> > default constructor, or `DefaultConstructorCheck<3>` having a non-defaulted 
> > one?
> > 
> > It'd also be worthwhile to have at least one test with constaints that 
> > subsume each other instead of being mutually exclusive. 
> Should I check this? Except destructors, the other SMFs are found during 
> overload resolution using the usual lookup that already takes into account 
> delete/default/constraints etc.
> 
> This patch is about making sure that we set the triviality attributes 
> correctly according to the eligible functions, so this is what I added tests 
> for.
> 
> Most of this testing is done in the sema test, but I need this AST test as 
> well to make sure we get the `canPassInRegisters` attribute correctly - we're 
> doing some custom processing over the functions without the usual type 
> attributes because there are some weird compatibility edge cases.
> 
One of the motivations for the paper is to ensure that like given:

```
template 
struct optional {
optional(optional const&) requires copyable && trivially_copyableT> = 
default;
optional(optional const&) requires copyable;
};
```

`optional` is copyable (but not trivially copyable), `optional` is 
trivially copyable, and `optional>` isn't copyable. I'm not 
sure what in here checks if that works. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128619

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


[PATCH] D129835: [clang] adds a discardable attribute

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

In D129835#3655548 , @cjdb wrote:

> In D129835#3655487 , @aaron.ballman 
> wrote:
>
>>> When we have a function that can have its value discarded, we can use 
>>> [[clang::discardable]] to indicate that the `[[nodiscard]]` attribute 
>>> should be ignored.
>>
>> Alternatively, you can scope the pragma and declarations appropriately and 
>> then we don't need to add a new attribute. Is there a reason that wouldn't 
>> work for you?
>
> A key problem here (IMO) is that this requires manually pushing and popping 
> the pragma as it is required.

That's a feature to me, not a bug. It means you have to actually think about 
what you're doing instead of being surprised. This is the same reason our 
community standards want you to keep anonymous namespaces as small as possible 
-- it's too easy to have absolutely no idea about the behavior when you're in 
the middle of a block of code and the relevant part is off-screen somewhere.

> With `[[discardable]]` one just needs to push/pop at the extremes of a file 
> (and if a future version of module maps supports global pragmas for a module, 
> there too, but that's a discussion that requires a design doc).

I understood that, I just don't think that's a good thing. This is basically an 
attribute that says "I know we said we wanted everything here to be nodiscard, 
but JUST KIDDING not this one!" which is not a very clean approach to writing 
headers.

> It's also good for documenting "hey you can discard this thing in my sea of 
> nodiscard interfaces" on the interface itself. That coupling is also good for 
> correctness because it means something can't accidentally slip in/out of the 
> pragma's scope.

I'd like to see some examples of that. In my experience, attributes are most 
often hidden behind macros which are sometimes then combined with other macros, 
etc, so whether the attribute is effective or not is already not always obvious 
from the interface; I don't see how this will move the needle.

>> (This attribute would be interesting to consider if we added a feature flag 
>> like `-fdiagnose-discarded-results` where the default is as-if everything 
>> was declared `nodiscard` and then you could mark the APIs with 
>> `[[clang::discardable]]` for the few whose results don't matter. However, 
>> that's also a much bigger feature because system headers are a challenge.)
>
> The primary reason for me wanting to add this attribute comes from my libc++ 
> days, where I wanted to mark whatever made sense as nodiscard. @ldionne was 
> in favour in principle, but against in practice; noting that nodiscard would 
> clutter the interface too much, and it'd be better if the situation were 
> reversed (which is what this patch does). I think adding this is still a good 
> step for getting us to a world where `-fdiagnose-discarded-results` can be a 
> real consideration, especially if libc++ and llvm-libc adopt it.

Yes, I wish the default were correct as well, but it's not and it won't ever be 
corrected for practicality reasons. I don't know what libc++'s goals are in 
terms of other compilers, but it seems like using a clang-specific pragma would 
be making it more difficult to use libc++ with any other compiler.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129835

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


[PATCH] D128619: [Clang] Implement P0848 (Conditionally Trivial Special Member Functions)

2022-07-15 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson marked 4 inline comments as done and an inline comment as not done.
royjacobson added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:17960-17961
+}
+if (AnotherMethodIsMoreConstrained)
+  break;
+  }

cor3ntin wrote:
> Is that codepath ever taken?
> I wonder if there is a way to do that that is not n^2. Maybe not.
It's not, I didn't mean to leave it there. Thanks for the catch :)


Generally finding a maximal set in a partial ordering is O(n^2) in the worst 
case which is when no two objects are comparable.

We could optimize this a bit for some cases: We can group the functions by 
their kind, and we can skip comparing functions if we already know that they 
are not maximal. But since the number of SMFs expected in a class is very (1-3) 
small, I didn't think those possible improvements are worth the extra 
complexity.

Another possible optimization is we could short-circuit this evaluation if we 
know that a type is not trivially [copyable], since that's the only outcome we 
really care about, but then the AST is left in a very awkward state.




Comment at: clang/test/AST/conditionally-trivial-smfs.cpp:39
+
+template struct DefaultConstructorCheck<2>;
+// CHECK: "kind": "ClassTemplateSpecializationDecl",

BRevzin wrote:
> It's possible that I just don't understand what these tests actually mean 
> but... where is the test for `DefaultConstructorCheck<2>` having a deleted 
> default constructor, or `DefaultConstructorCheck<3>` having a non-defaulted 
> one?
> 
> It'd also be worthwhile to have at least one test with constaints that 
> subsume each other instead of being mutually exclusive. 
Should I check this? Except destructors, the other SMFs are found during 
overload resolution using the usual lookup that already takes into account 
delete/default/constraints etc.

This patch is about making sure that we set the triviality attributes correctly 
according to the eligible functions, so this is what I added tests for.

Most of this testing is done in the sema test, but I need this AST test as well 
to make sure we get the `canPassInRegisters` attribute correctly - we're doing 
some custom processing over the functions without the usual type attributes 
because there are some weird compatibility edge cases.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128619

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


[PATCH] D128619: [Clang] Implement P0848 (Conditionally Trivial Special Member Functions)

2022-07-15 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson updated this revision to Diff 445044.
royjacobson edited the summary of this revision.
royjacobson added a comment.

Address Corentin's feedback.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128619

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/DeclCXX.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/AST/conditionally-trivial-smfs.cpp
  clang/test/Lexer/cxx-features.cpp
  clang/test/SemaCXX/constrained-special-member-functions.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -927,7 +927,7 @@
   

 https://wg21.link/p0848r3;>P0848R3
-No
+Clang 15
   
   
 https://wg21.link/p1616r1;>P1616R1
Index: clang/test/SemaCXX/constrained-special-member-functions.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/constrained-special-member-functions.cpp
@@ -0,0 +1,130 @@
+// RUN: %clang_cc1 -verify -std=c++20 %s
+// expected-no-diagnostics
+
+template 
+concept C0 = (N == 0);
+template 
+concept C1 = (N == 1);
+template 
+concept C2 = (N == 2);
+
+// Checks are indexed by:
+// Definition:
+//  1. Explicitly defaulted definition
+//  2. Deleted definition
+//  3. User provided definition
+// We have a less constrained user provided method that should not disable
+// the (copyable) triviality of the type.
+
+// Note that because Clang does not implement DRs 1496 and 1734, we say some
+// classes are trivial when the SMFs are deleted.
+
+template 
+struct DefaultConstructorChecker {
+DefaultConstructorChecker() requires C0 = default;
+DefaultConstructorChecker() requires C1 = delete;
+DefaultConstructorChecker() requires C2;
+DefaultConstructorChecker();
+};
+static_assert(__is_trivially_copyable(DefaultConstructorChecker<0>));
+static_assert(__is_trivially_copyable(DefaultConstructorChecker<1>));
+static_assert(__is_trivially_copyable(DefaultConstructorChecker<2>));
+static_assert(__is_trivially_copyable(DefaultConstructorChecker<3>));
+static_assert(__is_trivial(DefaultConstructorChecker<0>));
+// FIXME: DR1496
+static_assert(__is_trivial(DefaultConstructorChecker<1>));
+static_assert(!__is_trivial(DefaultConstructorChecker<2>));
+static_assert(!__is_trivial(DefaultConstructorChecker<3>));
+
+template 
+struct CopyConstructorChecker {
+CopyConstructorChecker(const CopyConstructorChecker&) requires C0 = default;
+CopyConstructorChecker(const CopyConstructorChecker&) requires C1 = delete;
+CopyConstructorChecker(const CopyConstructorChecker&) requires C2;
+CopyConstructorChecker(const CopyConstructorChecker&);
+};
+
+static_assert(__is_trivially_copyable(CopyConstructorChecker<0>));
+// FIXME: DR1734
+static_assert(__is_trivially_copyable(CopyConstructorChecker<1>));
+static_assert(!__is_trivially_copyable(CopyConstructorChecker<2>));
+static_assert(!__is_trivially_copyable(CopyConstructorChecker<3>));
+static_assert(!__is_trivial(CopyConstructorChecker<0>));
+static_assert(!__is_trivial(CopyConstructorChecker<1>));
+static_assert(!__is_trivial(CopyConstructorChecker<2>));
+static_assert(!__is_trivial(CopyConstructorChecker<3>));
+
+template 
+struct MoveConstructorChecker {
+MoveConstructorChecker(MoveConstructorChecker&&) requires C0 = default;
+MoveConstructorChecker(MoveConstructorChecker&&) requires C1 = delete;
+MoveConstructorChecker(MoveConstructorChecker&&) requires C2;
+MoveConstructorChecker(MoveConstructorChecker&&);
+};
+
+static_assert(__is_trivially_copyable(MoveConstructorChecker<0>));
+// FIXME: DR1734
+static_assert(__is_trivially_copyable(MoveConstructorChecker<1>));
+static_assert(!__is_trivially_copyable(MoveConstructorChecker<2>));
+static_assert(!__is_trivially_copyable(MoveConstructorChecker<3>));
+static_assert(!__is_trivial(MoveConstructorChecker<0>));
+static_assert(!__is_trivial(MoveConstructorChecker<1>));
+static_assert(!__is_trivial(MoveConstructorChecker<2>));
+static_assert(!__is_trivial(MoveConstructorChecker<3>));
+
+template 
+struct MoveAssignmentChecker {
+MoveAssignmentChecker& operator=(MoveAssignmentChecker&&) requires C0 = default;
+MoveAssignmentChecker& operator=(MoveAssignmentChecker&&) requires C1 = delete;
+MoveAssignmentChecker& operator=(MoveAssignmentChecker&&) requires C2;
+MoveAssignmentChecker& operator=(MoveAssignmentChecker&&);
+};
+
+static_assert(__is_trivially_copyable(MoveAssignmentChecker<0>));
+// FIXME: DR1734.
+static_assert(__is_trivially_copyable(MoveAssignmentChecker<1>));
+static_assert(!__is_trivially_copyable(MoveAssignmentChecker<2>));
+static_assert(!__is_trivially_copyable(MoveAssignmentChecker<3>));

[clang] bc08c3c - [analyzer] Add new function `clang_analyzer_value` to ExprInspectionChecker

2022-07-15 Thread Denys Petrov via cfe-commits

Author: Denys Petrov
Date: 2022-07-15T20:07:04+03:00
New Revision: bc08c3cb7f8e797fee14e96eedd3dc358608ada3

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

LOG: [analyzer] Add new function `clang_analyzer_value` to ExprInspectionChecker

Summary: Introduce a new function 'clang_analyzer_value'. It emits a report 
that in turn prints a RangeSet or APSInt associated with SVal. If there is no 
associated value, prints "n/a".

Added: 
clang/test/Analysis/print-ranges.cpp

Modified: 
clang/docs/analyzer/developer-docs/DebugChecks.rst
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
clang/lib/StaticAnalyzer/Core/SVals.cpp

Removed: 




diff  --git a/clang/docs/analyzer/developer-docs/DebugChecks.rst 
b/clang/docs/analyzer/developer-docs/DebugChecks.rst
index 7a837659576d9..d038cb5d7ccac 100644
--- a/clang/docs/analyzer/developer-docs/DebugChecks.rst
+++ b/clang/docs/analyzer/developer-docs/DebugChecks.rst
@@ -309,6 +309,33 @@ ExprInspection checks
   clang_analyzer_dumpExtent(a);   // expected-warning {{8 S64b}}
   clang_analyzer_dumpElementCount(a); // expected-warning {{2 S64b}}
 }
+
+- ``clang_analyzer_value(a single argument of integer or pointer type)``
+
+  Prints an associated value for the given argument.
+  Supported argument types are integers, enums and pointers.
+  The value can be represented either as a range set or as a concrete integer.
+  For the rest of the types function prints ``n/a`` (aka not available).
+  
+  **Note:** This function will print nothing for clang built with Z3 
constraint manager.
+  This may cause crashes of your tests. To manage this use one of the test 
constraining
+  techniques:
+  
+  * llvm-lit commands ``REQUIRES no-z3`` or ``UNSUPPORTED z3`` `See for 
details. `_
+  
+  * a preprocessor directive ``#ifndef ANALYZER_CM_Z3``
+  
+  * a clang command argument ``-analyzer-constraints=range``
+
+  Example usage::
+
+void print(char c, unsigned u) {
+  clang_analyzer_value(c); // expected-warning {{8s:{ [-128, 127] }}}
+  if(u != 42)
+ clang_analyzer_value(u); // expected-warning {{32u:{ [0, 41], [43, 
4294967295] }}}
+  else
+ clang_analyzer_value(u); // expected-warning {{32u:42}}
+}
 
 Statistics
 ==

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
index 22b405919bc17..ca6d7849d6210 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
@@ -119,6 +119,9 @@ class ConstraintManager {
  const char *NL, unsigned int Space,
  bool IsDot) const = 0;
 
+  virtual void printValue(raw_ostream , ProgramStateRef State,
+  SymbolRef Sym) {}
+
   /// Convenience method to query the state to see if a symbol is null or
   /// not null, or if neither assumption can be made.
   ConditionTruthVal isNull(ProgramStateRef State, SymbolRef Sym) {

diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
index 69f19f7d85655..c9c21fcf230ef 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/SVals.h
@@ -169,6 +169,11 @@ class SVal {
   /// should continue to the base regions if the region is not symbolic.
   SymbolRef getAsSymbol(bool IncludeBaseRegions = false) const;
 
+  /// If this SVal is loc::ConcreteInt or nonloc::ConcreteInt,
+  /// return a pointer to APSInt which is held in it.
+  /// Otherwise, return nullptr.
+  const llvm::APSInt *getAsInteger() const;
+
   const MemRegion *getAsRegion() const;
 
   /// printJson - Pretty-prints in JSON format.

diff  --git a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
index 1c33648b2b321..ec1b0a70d7d3b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ExprInspectionChecker.cpp
@@ -40,6 +40,7 @@ class ExprInspectionChecker
   void analyzerNumTimesReached(const CallExpr *CE, CheckerContext ) const;
   void analyzerCrash(const CallExpr *CE, CheckerContext ) const;
   void analyzerWarnOnDeadSymbol(const CallExpr *CE, CheckerContext ) const;
+  void analyzerValue(const 

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

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

@manas

I'm sorry but it seems like I brought you a new work :-) I've just loaded these 
two patches (D129678  and D129498 
) and now you have to rebase your changes. 
But there is a good news as well. You will be able to use 
`clang_analyzer_value` function for your tests if needed.

I appreciate your efforts but I should tell that I'm currently working on the 
thing that should resolve the issue you are trying to solve D103096 
.

> The coverage showing unreachability of `VisitBinaryOperator` for 
> concrete integer cases.

Maybe it's better to remove that unreachable part but leave the tests for 
concrete ints just to verify that all the cases are covered.

Also I expect to see test case for `short-ushort`, `char-uchar` pairs, because 
if it would turn out that the `int-uint` is only pair that we handle the patch 
would be disappointing, unfortunately.


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] D128372: [Clang-Tidy] Empty Check

2022-07-15 Thread Abraham Corea Diaz via Phabricator via cfe-commits
abrahamcd added a comment.

Gentle ping!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128372

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


[PATCH] D129748: [Modules] Disable preferred_name attribute in C++20 Modules

2022-07-15 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann added a comment.

I'm not following what the root problem is. You stated:

> When we write the attribute preferred_name(foo) in ASTWriter, the compiler 
> would try to write the type for the argument foo. Then when the compiler 
> write the type for foo, the compiler find the type for foo is a TypeDef type. 
> So the compiler would write the corresponding type foo_templ. The key 
> point here is that the AST for foo_templ is complete now. Since the AST 
> for foo_templ is constructed in Sema.

Are you saying that the act of writing the AST is triggering the 
instantiation/completion of `foo_templ`? Serialization should certainly 
not cause such side effects.

I'm likewise not following the concern with reading the AST:

> When we read the attribute preferred_name(foo), we would read the type for 
> the argument foo and then we would try to read the type foo_templ 
> later. However, the key problem here is that when we read foo_templ, 
> its AST is not constructed yet! So we get a different type with the writer 
> writes. So here is the ODR violation.

I wouldn't expect the same `Sema` instance to be used to both write and read 
the same AST.

The test case defines two modules (`A` and `Use`) that both have definitions of 
`foo_templ`, `foo`, and `foo_templ` in their global module fragments. It 
sounds to me like the issue here might be that these definitions are not 
getting merged (perhaps because of the issue you are trying to describe and 
address).

Can you try again to explain the root problem? Perhaps with references to 
relevant code?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129748

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


[PATCH] D129835: [clang] adds a discardable attribute

2022-07-15 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added a subscriber: ldionne.
cjdb added a comment.

In D129835#3655487 , @aaron.ballman 
wrote:

>> When we have a function that can have its value discarded, we can use 
>> [[clang::discardable]] to indicate that the `[[nodiscard]]` attribute should 
>> be ignored.
>
> Alternatively, you can scope the pragma and declarations appropriately and 
> then we don't need to add a new attribute. Is there a reason that wouldn't 
> work for you?

A key problem here (IMO) is that this requires manually pushing and popping the 
pragma as it is required. With `[[discardable]]` one just needs to push/pop at 
the extremes of a file (and if a future version of module maps supports global 
pragmas for a module, there too, but that's a discussion that requires a design 
doc).

It's also good for documenting "hey you can discard this thing in my sea of 
nodiscard interfaces" on the interface itself. That coupling is also good for 
correctness because it means something can't accidentally slip in/out of the 
pragma's scope.

> (This attribute would be interesting to consider if we added a feature flag 
> like `-fdiagnose-discarded-results` where the default is as-if everything was 
> declared `nodiscard` and then you could mark the APIs with 
> `[[clang::discardable]]` for the few whose results don't matter. However, 
> that's also a much bigger feature because system headers are a challenge.)

The primary reason for me wanting to add this attribute comes from my libc++ 
days, where I wanted to mark whatever made sense as nodiscard. @ldionne was in 
favour in principle, but against in practice; noting that nodiscard would 
clutter the interface too much, and it'd be better if the situation were 
reversed (which is what this patch does). I think adding this is still a good 
step for getting us to a world where `-fdiagnose-discarded-results` can be a 
real consideration, especially if libc++ and llvm-libc adopt it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129835

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


[PATCH] D129832: [sanitizer] Add "mainsrc" prefix to sanitizer special case list

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



In D129832#3654436 , @vitalybuka 
wrote:

> The patch is LGTM, but please consider to keep an ignorelist limited.

Thanks!

In D129832#3655393 , @kstoimenov 
wrote:

> I think the name 'mainsrc' is slightly misleading because of the association 
> with the 'main' function. Maybe something like primarysrc would be better to 
> avoid this confusion?

How   about `mainfile`? Clang resources to the file as the `main file`. I 
picked `src` suffix just to be similar to `src`...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129832

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


[PATCH] D129678: [analyzer][NFC] Tidy up handler-functions in SymbolicRangeInferrer

2022-07-15 Thread Denys Petrov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG82f76c04774f: [analyzer][NFC] Tidy up handler-functions in 
SymbolicRangeInferrer (authored by ASDenysPetrov).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129678

Files:
  clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp

Index: clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
===
--- clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -1213,13 +1213,21 @@
   }
 
   RangeSet VisitSymExpr(SymbolRef Sym) {
-// If we got to this function, the actual type of the symbolic
+if (Optional RS = getRangeForNegatedSym(Sym))
+  return *RS;
+// If we've reached this line, the actual type of the symbolic
 // expression is not supported for advanced inference.
 // In this case, we simply backoff to the default "let's simply
 // infer the range from the expression's type".
 return infer(Sym->getType());
   }
 
+  RangeSet VisitUnarySymExpr(const UnarySymExpr *USE) {
+if (Optional RS = getRangeForNegatedUnarySym(USE))
+  return *RS;
+return infer(USE->getType());
+  }
+
   RangeSet VisitSymIntExpr(const SymIntExpr *Sym) {
 return VisitBinaryOperator(Sym);
   }
@@ -1228,14 +1236,25 @@
 return VisitBinaryOperator(Sym);
   }
 
-  RangeSet VisitSymSymExpr(const SymSymExpr *Sym) {
+  RangeSet VisitSymSymExpr(const SymSymExpr *SSE) {
 return intersect(
 RangeFactory,
+// If Sym is a difference of symbols A - B, then maybe we have range
+// set stored for B - A.
+//
+// If we have range set stored for both A - B and B - A then
+// calculate the effective range set by intersecting the range set
+// for A - B and the negated range set of B - A.
+getRangeForNegatedSymSym(SSE),
+// If Sym is a comparison expression (except <=>),
+// find any other comparisons with the same operands.
+// See function description.
+getRangeForComparisonSymbol(SSE),
 // If Sym is (dis)equality, we might have some information
 // on that in our equality classes data structure.
-getRangeForEqualities(Sym),
+getRangeForEqualities(SSE),
 // And we should always check what we can get from the operands.
-VisitBinaryOperator(Sym));
+VisitBinaryOperator(SSE));
   }
 
 private:
@@ -1264,25 +1283,13 @@
   }
 
   RangeSet infer(SymbolRef Sym) {
-return intersect(
-RangeFactory,
-// Of course, we should take the constraint directly associated with
-// this symbol into consideration.
-getConstraint(State, Sym),
-// If Sym is a difference of symbols A - B, then maybe we have range
-// set stored for B - A.
-//
-// If we have range set stored for both A - B and B - A then
-// calculate the effective range set by intersecting the range set
-// for A - B and the negated range set of B - A.
-getRangeForNegatedSub(Sym),
-// If Sym is a comparison expression (except <=>),
-// find any other comparisons with the same operands.
-// See function description.
-getRangeForComparisonSymbol(Sym),
-// Apart from the Sym itself, we can infer quite a lot if we look
-// into subexpressions of Sym.
-Visit(Sym));
+return intersect(RangeFactory,
+ // Of course, we should take the constraint directly
+ // associated with this symbol into consideration.
+ getConstraint(State, Sym),
+ // Apart from the Sym itself, we can infer quite a lot if
+ // we look into subexpressions of Sym.
+ Visit(Sym));
   }
 
   RangeSet infer(EquivalenceClass Class) {
@@ -1443,38 +1450,53 @@
 return RangeFactory.deletePoint(Domain, IntType.getZeroValue());
   }
 
-  Optional getRangeForNegatedSub(SymbolRef Sym) {
+  template 
+  Optional getRangeForNegatedExpr(ProduceNegatedSymFunc F,
+QualType T) {
 // Do not negate if the type cannot be meaningfully negated.
-if (!Sym->getType()->isUnsignedIntegerOrEnumerationType() &&
-!Sym->getType()->isSignedIntegerOrEnumerationType())
+if (!T->isUnsignedIntegerOrEnumerationType() &&
+!T->isSignedIntegerOrEnumerationType())
   return llvm::None;
 
-const RangeSet *NegatedRange = nullptr;
-SymbolManager  = State->getSymbolManager();
-if (const auto *USE = dyn_cast(Sym)) {
-  if (USE->getOpcode() == UO_Minus) {
-// Just get the operand when we negate a symbol that is already negated.
-// -(-a) == a
-NegatedRange = getConstraint(State, USE->getOperand());
-  

[clang] 82f76c0 - [analyzer][NFC] Tidy up handler-functions in SymbolicRangeInferrer

2022-07-15 Thread Denys Petrov via cfe-commits

Author: Denys Petrov
Date: 2022-07-15T19:24:57+03:00
New Revision: 82f76c04774fbeb2313b84932afac478f010c8d0

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

LOG: [analyzer][NFC] Tidy up handler-functions in SymbolicRangeInferrer

Summary: Sorted some handler-functions into more appropriate visitor functions 
of the SymbolicRangeInferrer.
- Spread `getRangeForNegatedSub` body over several visitor functions: 
`VisitSymExpr`, `VisitSymIntExpr`, `VisitSymSymExpr`.
- Moved `getRangeForComparisonSymbol` from `infer` to `VisitSymSymExpr`.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp 
b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
index e788a7a608302..8f1e3aa039759 100644
--- a/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
+++ b/clang/lib/StaticAnalyzer/Core/RangeConstraintManager.cpp
@@ -1213,13 +1213,21 @@ class SymbolicRangeInferrer
   }
 
   RangeSet VisitSymExpr(SymbolRef Sym) {
-// If we got to this function, the actual type of the symbolic
+if (Optional RS = getRangeForNegatedSym(Sym))
+  return *RS;
+// If we've reached this line, the actual type of the symbolic
 // expression is not supported for advanced inference.
 // In this case, we simply backoff to the default "let's simply
 // infer the range from the expression's type".
 return infer(Sym->getType());
   }
 
+  RangeSet VisitUnarySymExpr(const UnarySymExpr *USE) {
+if (Optional RS = getRangeForNegatedUnarySym(USE))
+  return *RS;
+return infer(USE->getType());
+  }
+
   RangeSet VisitSymIntExpr(const SymIntExpr *Sym) {
 return VisitBinaryOperator(Sym);
   }
@@ -1228,14 +1236,25 @@ class SymbolicRangeInferrer
 return VisitBinaryOperator(Sym);
   }
 
-  RangeSet VisitSymSymExpr(const SymSymExpr *Sym) {
+  RangeSet VisitSymSymExpr(const SymSymExpr *SSE) {
 return intersect(
 RangeFactory,
+// If Sym is a 
diff erence of symbols A - B, then maybe we have range
+// set stored for B - A.
+//
+// If we have range set stored for both A - B and B - A then
+// calculate the effective range set by intersecting the range set
+// for A - B and the negated range set of B - A.
+getRangeForNegatedSymSym(SSE),
+// If Sym is a comparison expression (except <=>),
+// find any other comparisons with the same operands.
+// See function description.
+getRangeForComparisonSymbol(SSE),
 // If Sym is (dis)equality, we might have some information
 // on that in our equality classes data structure.
-getRangeForEqualities(Sym),
+getRangeForEqualities(SSE),
 // And we should always check what we can get from the operands.
-VisitBinaryOperator(Sym));
+VisitBinaryOperator(SSE));
   }
 
 private:
@@ -1264,25 +1283,13 @@ class SymbolicRangeInferrer
   }
 
   RangeSet infer(SymbolRef Sym) {
-return intersect(
-RangeFactory,
-// Of course, we should take the constraint directly associated with
-// this symbol into consideration.
-getConstraint(State, Sym),
-// If Sym is a 
diff erence of symbols A - B, then maybe we have range
-// set stored for B - A.
-//
-// If we have range set stored for both A - B and B - A then
-// calculate the effective range set by intersecting the range set
-// for A - B and the negated range set of B - A.
-getRangeForNegatedSub(Sym),
-// If Sym is a comparison expression (except <=>),
-// find any other comparisons with the same operands.
-// See function description.
-getRangeForComparisonSymbol(Sym),
-// Apart from the Sym itself, we can infer quite a lot if we look
-// into subexpressions of Sym.
-Visit(Sym));
+return intersect(RangeFactory,
+ // Of course, we should take the constraint directly
+ // associated with this symbol into consideration.
+ getConstraint(State, Sym),
+ // Apart from the Sym itself, we can infer quite a lot if
+ // we look into subexpressions of Sym.
+ Visit(Sym));
   }
 
   RangeSet infer(EquivalenceClass Class) {
@@ -1443,38 +1450,53 @@ class SymbolicRangeInferrer
 return RangeFactory.deletePoint(Domain, IntType.getZeroValue());
   }
 
-  Optional getRangeForNegatedSub(SymbolRef Sym) {
+  template 
+  Optional getRangeForNegatedExpr(ProduceNegatedSymFunc F,
+QualType T) {
 // 

[PATCH] D129835: [clang] adds a discardable attribute

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

> When we have a function that can have its value discarded, we can use 
> [[clang::discardable]] to indicate that the `[[nodiscard]]` attribute should 
> be ignored.

Alternatively, you can scope the pragma and declarations appropriately and then 
we don't need to add a new attribute. Is there a reason that wouldn't work for 
you?

(This attribute would be interesting to consider if we added a feature flag 
like `-fdiagnose-discarded-results` where the default is as-if everything was 
declared `nodiscard` and then you could mark the APIs with 
`[[clang::discardable]]` for the few whose results don't matter. However, 
that's also a much bigger feature because system headers are a challenge.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129835

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


[PATCH] D129305: [clang-offload-bundler][NFC] Library-ize ClangOffloadBundler (4/4)

2022-07-15 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j abandoned this revision.
lamb-j added a comment.

Abandoned in favor of combined patch: https://reviews.llvm.org/D129873


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129305

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


[PATCH] D129304: [clang-offload-bundler] Library-ize ClangOffloadBundler (3/4)

2022-07-15 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j abandoned this revision.
lamb-j added a comment.

Abandoned in favor of combined patch: https://reviews.llvm.org/D129873


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129304

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


[PATCH] D129303: [clang-offload-bundler] Library-ize ClangOffloadBundler (2/4)

2022-07-15 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j abandoned this revision.
lamb-j added a comment.

Abandoned in favor of combined patch: https://reviews.llvm.org/D129873


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129303

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


[PATCH] D129301: [clang-offload-bundler][NFC] Library-ize ClangOffloadBundler (1/4)

2022-07-15 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j abandoned this revision.
lamb-j added a comment.

Abandoned in favor of combined patch: https://reviews.llvm.org/D129873


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129301

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


[PATCH] D129873: [clang-offload-bundler] Library-ize ClangOffloadBundler

2022-07-15 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j created this revision.
Herald added a subscriber: mgorny.
Herald added a reviewer: alexander-shaposhnikov.
Herald added a project: All.
lamb-j requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1, MaskRay.
Herald added a reviewer: jdoerfert.
Herald added a project: clang.

Lifting the core functionalities of the clang-offload-bundler into a
user-facing library/API. This will allow online and JIT compilers to
bundle and unbundle files without spawning a new process.

This patch lifts the classes and functions used to implement 
the clang-offload-bundler into a separate OffloadBundler.cpp,
and defines three top-level API functions in OfflaodBundler.h.

  BundleFiles()
  UnbundleFiles()
  UnbundleArchives()

This patch also introduces a Config class that locally stores the
previously global cl::opt options and arrays to allow users to call
the APIs in a multi-threaded context, and introduces an
OffloadBundler class to encapsulate the top-level API functions.

We also  lift the BundlerExecutable variable, which is specific
to the clang-offload-bundler tool, from the API, and replace
its use with an ObjcopyPath variable. This variable must be set
in order to internally call llvm-objcopy.

Finally, we move the API files from
clang/tools/clang-offload-bundler into clang/lib/Driver and
clang/include/clang/Driver.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129873

Files:
  clang/include/clang/Driver/OffloadBundler.h
  clang/lib/Driver/CMakeLists.txt
  clang/lib/Driver/OffloadBundler.cpp
  clang/tools/clang-offload-bundler/CMakeLists.txt
  clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp

Index: clang/tools/clang-offload-bundler/CMakeLists.txt
===
--- clang/tools/clang-offload-bundler/CMakeLists.txt
+++ clang/tools/clang-offload-bundler/CMakeLists.txt
@@ -2,15 +2,16 @@
 
 add_clang_tool(clang-offload-bundler
   ClangOffloadBundler.cpp
-  
+
   DEPENDS
   intrinsics_gen
   )
 
 set(CLANG_OFFLOAD_BUNDLER_LIB_DEPS
   clangBasic
+  clangDriver
   )
-  
+
 add_dependencies(clang clang-offload-bundler)
 
 clang_target_link_libraries(clang-offload-bundler
Index: clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
===
--- clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
+++ clang/tools/clang-offload-bundler/ClangOffloadBundler.cpp
@@ -7,15 +7,14 @@
 //===--===//
 ///
 /// \file
-/// This file implements a clang-offload-bundler that bundles different
-/// files that relate with the same source code but different targets into a
-/// single one. Also the implements the opposite functionality, i.e. unbundle
-/// files previous created by this tool.
+/// This file implements a stand-alone clang-offload-bundler tool using the
+/// OffloadBundler API.
 ///
 //===--===//
 
 #include "clang/Basic/Cuda.h"
 #include "clang/Basic/Version.h"
+#include "clang/Driver/OffloadBundler.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
@@ -56,37 +55,43 @@
 using namespace llvm;
 using namespace llvm::object;
 
-static cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden);
+static void PrintVersion(raw_ostream ) {
+  OS << clang::getClangToolFullVersion("clang-offload-bundler") << '\n';
+}
+
+int main(int argc, const char **argv) {
+
+  cl::opt Help("h", cl::desc("Alias for -help"), cl::Hidden);
 
-// Mark all our options with this category, everything else (except for -version
-// and -help) will be hidden.
-static cl::OptionCategory
+  // Mark all our options with this category, everything else (except for
+  // -version and -help) will be hidden.
+  cl::OptionCategory
 ClangOffloadBundlerCategory("clang-offload-bundler options");
-static cl::list
-InputFileNames("input",
+  cl::list
+InputFileNames("input", cl::ZeroOrMore,
cl::desc("Input file."
 " Can be specified multiple times "
 "for multiple input files."),
cl::cat(ClangOffloadBundlerCategory));
-static cl::list
-InputFileNamesDeprecatedOpt("inputs", cl::CommaSeparated,
+  cl::list
+InputFileNamesDeprecatedOpt("inputs", cl::CommaSeparated, cl::ZeroOrMore,
 cl::desc("[,...] (deprecated)"),
 cl::cat(ClangOffloadBundlerCategory));
-static cl::list
-OutputFileNames("output",
+  cl::list
+OutputFileNames("output", cl::ZeroOrMore,
 cl::desc("Output file."
  " Can be specified multiple times "
  "for multiple output files."),
 cl::cat(ClangOffloadBundlerCategory));
-static cl::list
-

[PATCH] D129872: [clang][OpenMP] Fix runtime crash in the call to __kmp_alloc.

2022-07-15 Thread Jennifer Yu via Phabricator via cfe-commits
jyu2 created this revision.
jyu2 added reviewers: ddpagan, ABataev, mikerice.
jyu2 added projects: clang, OpenMP.
Herald added subscribers: guansong, yaxunl.
Herald added a project: All.
jyu2 requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: openmp-commits, cfe-commits, sstefan1.

The problem is that "alloctor" from omp_init_allocator gets truncated before 
passing to __kmp_alloc.

To fix this, when generate AllocrVal, call to IgnoreImpCasts to skip 'trunc'


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129872

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/test/OpenMP/omp_init_allocator.c
  openmp/runtime/test/api/omp_init_allocator.c

Index: openmp/runtime/test/api/omp_init_allocator.c
===
--- /dev/null
+++ openmp/runtime/test/api/omp_init_allocator.c
@@ -0,0 +1,20 @@
+// RUN: %libomp-compile-and-run
+
+#include 
+#include 
+
+void test_allocate_allocator() {
+  omp_alloctrait_t x_traits[1] = {{omp_atk_alignment, 64}};
+  omp_allocator_handle_t x_alloc =
+  omp_init_allocator(omp_default_mem_space, 1, x_traits);
+  {
+int x;
+#pragma omp allocate(x) allocator(x_alloc)
+  }
+  omp_destroy_allocator(x_alloc);
+}
+
+int main() {
+  test_allocate_allocator();
+  printf("passed\n");
+}
Index: clang/test/OpenMP/omp_init_allocator.c
===
--- /dev/null
+++ clang/test/OpenMP/omp_init_allocator.c
@@ -0,0 +1,61 @@
+// RUN: %clang_cc1 -isystem %S/Inputs -emit-llvm -o - -fopenmp \
+// RUN: -fopenmp-version=50 -triple x86_64-unknown-linux-gnu %s | FileCheck %s
+
+typedef enum {
+  omp_atk_sync_hint = 1,
+  omp_atk_alignment = 2
+} omp_alloctrait_key_t;
+typedef unsigned long int uintptr_t;
+typedef uintptr_t omp_uintptr_t;
+typedef struct {
+  omp_alloctrait_key_t key;
+  omp_uintptr_t value;
+} omp_alloctrait_t;
+typedef enum omp_allocator_handle_t {
+  omp_null_allocator = 0,
+  omp_default_mem_alloc = 1,
+  omp_large_cap_mem_alloc = 2,
+  omp_const_mem_alloc = 3,
+  omp_high_bw_mem_alloc = 4,
+  omp_low_lat_mem_alloc = 5,
+  omp_cgroup_mem_alloc = 6,
+  omp_pteam_mem_alloc = 7,
+  omp_thread_mem_alloc = 8,
+
+  omp_target_host_mem_alloc = 100,
+  omp_target_shared_mem_alloc = 101,
+  omp_target_device_mem_alloc = 102,
+  KMP_ALLOCATOR_MAX_HANDLE = (18446744073709551615UL)
+} omp_allocator_handle_t;
+typedef enum omp_memspace_handle_t {
+  omp_default_mem_space = 0,
+  omp_large_cap_mem_space = 1,
+  omp_const_mem_space = 2,
+  omp_high_bw_mem_space = 3,
+  omp_low_lat_mem_space = 4,
+
+  omp_target_host_mem_space = 100,
+  omp_target_shared_mem_space = 101,
+  omp_target_device_mem_space = 102,
+  KMP_MEMSPACE_MAX_HANDLE = (18446744073709551615UL)
+} omp_memspace_handle_t;
+
+extern omp_allocator_handle_t omp_init_allocator(omp_memspace_handle_t m,
+ int ntraits,
+ omp_alloctrait_t traits[]);
+//CHECK-LABEL: test_allocate_allocator
+void test_allocate_allocator() {
+  omp_alloctrait_t x_traits[1] = {{omp_atk_alignment, 64}};
+  omp_allocator_handle_t x_alloc =
+  omp_init_allocator(omp_default_mem_space, 1, x_traits);
+  {
+int x;
+// CHECK: [[RET:%.+]] = call i64 @omp_init_allocator
+// CHECK-NEXT: store i64 [[RET]], ptr [[X_ALLOC:%x_alloc]]
+// CHECK: [[TMP:%.+]] = load i64, ptr [[X_ALLOC]]
+// CHECK-NEXT: [[CONV:%conv]] = inttoptr i64 [[TMP]] to ptr
+// CHECK-NEXT: call ptr @__kmpc_alloc(i32 %0, i64 4, ptr [[CONV]])
+// CHECK-NOT: trunc
+#pragma omp allocate(x) allocator(x_alloc)
+  }
+}
Index: clang/lib/CodeGen/CGOpenMPRuntime.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -12114,7 +12114,7 @@
 const Expr *Allocator) {
   llvm::Value *AllocVal;
   if (Allocator) {
-AllocVal = CGF.EmitScalarExpr(Allocator);
+AllocVal = CGF.EmitScalarExpr(Allocator->IgnoreImpCasts());
 // According to the standard, the original allocator type is a enum
 // (integer). Convert to pointer type, if required.
 AllocVal = CGF.EmitScalarConversion(AllocVal, Allocator->getType(),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129832: [sanitizer] Add "mainsrc" prefix to sanitizer special case list

2022-07-15 Thread Kirill Stoimenov via Phabricator via cfe-commits
kstoimenov accepted this revision.
kstoimenov added a comment.

I think the name 'mainsrc' is slightly misleading because of the association 
with the 'main' function. Maybe something like primarysrc would be better to 
avoid this confusion?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129832

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


[PATCH] D128048: Add a new clang option "-ftime-trace="

2022-07-15 Thread dongjunduo via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf5d9de8cc330: [Clang] Add a new clang option 
-ftime-trace=value (authored by dongjunduo).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128048

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/check-time-trace.cpp
  clang/tools/driver/cc1_main.cpp


Index: clang/tools/driver/cc1_main.cpp
===
--- clang/tools/driver/cc1_main.cpp
+++ clang/tools/driver/cc1_main.cpp
@@ -212,7 +212,9 @@
   bool Success = CompilerInvocation::CreateFromArgs(Clang->getInvocation(),
 Argv, Diags, Argv0);
 
-  if (Clang->getFrontendOpts().TimeTrace) {
+  if (Clang->getFrontendOpts().TimeTrace ||
+  !Clang->getFrontendOpts().TimeTracePath.empty()) {
+Clang->getFrontendOpts().TimeTrace = 1;
 llvm::timeTraceProfilerInitialize(
 Clang->getFrontendOpts().TimeTraceGranularity, Argv0);
   }
@@ -256,6 +258,13 @@
   if (llvm::timeTraceProfilerEnabled()) {
 SmallString<128> Path(Clang->getFrontendOpts().OutputFile);
 llvm::sys::path::replace_extension(Path, "json");
+if (!Clang->getFrontendOpts().TimeTracePath.empty()) {
+  // replace the suffix to '.json' directly
+  SmallString<128> TracePath(Clang->getFrontendOpts().TimeTracePath);
+  if (llvm::sys::fs::is_directory(TracePath))
+llvm::sys::path::append(TracePath, llvm::sys::path::filename(Path));
+  Path.assign(TracePath);
+}
 if (auto profilerOutput = Clang->createOutputFile(
 Path.str(), /*Binary=*/false, /*RemoveFileOnSignal=*/false,
 /*useTemporary=*/false)) {
Index: clang/test/Driver/check-time-trace.cpp
===
--- clang/test/Driver/check-time-trace.cpp
+++ clang/test/Driver/check-time-trace.cpp
@@ -2,6 +2,20 @@
 // RUN: cat %T/check-time-trace.json \
 // RUN:   | %python -c 'import json, sys; 
json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
 // RUN:   | FileCheck %s
+// RUN: %clangxx -S -ftime-trace=%T/new-name.json -ftime-trace-granularity=0 
-o %T/check-time-trace %s
+// RUN: cat %T/new-name.json \
+// RUN:   | %python -c 'import json, sys; 
json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
+// RUN:   | FileCheck %s
+// RUN: rm -rf %T/output1 && mkdir %T/output1
+// RUN: %clangxx -S -ftime-trace=%T/output1 -ftime-trace-granularity=0 -o 
%T/check-time-trace %s
+// RUN: cat %T/output1/check-time-trace.json \
+// RUN:   | %python -c 'import json, sys; 
json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
+// RUN:   | FileCheck %s
+// RUN: rm -rf %T/output2 && mkdir %T/output2
+// RUN: %clangxx -S -ftime-trace=%T/output2/ -ftime-trace-granularity=0 -o 
%T/check-time-trace %s
+// RUN: cat %T/output2/check-time-trace.json \
+// RUN:   | %python -c 'import json, sys; 
json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
+// RUN:   | FileCheck %s
 
 // CHECK:  "beginningOfTime": {{[0-9]{16},}}
 // CHECK-NEXT: "traceEvents": [
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6230,6 +6230,7 @@
   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
+  Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_EQ);
   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
Index: clang/include/clang/Frontend/FrontendOptions.h
===
--- clang/include/clang/Frontend/FrontendOptions.h
+++ clang/include/clang/Frontend/FrontendOptions.h
@@ -499,6 +499,9 @@
   /// Minimum time granularity (in microseconds) traced by time profiler.
   unsigned TimeTraceGranularity;
 
+  /// Path which stores the output files for -ftime-trace
+  std::string TimeTracePath;
+
 public:
   FrontendOptions()
   : DisableFree(false), RelocatablePCH(false), ShowHelp(false),
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2857,6 +2857,15 @@
   HelpText<"Minimum time granularity (in microseconds) traced by time 
profiler">,
   Flags<[CC1Option, CoreOption]>,
   MarshallingInfoInt, "500u">;
+def ftime_trace_EQ : Joined<["-"], "ftime-trace=">, Group,
+  HelpText<"Turn on time 

[clang] f5d9de8 - [Clang] Add a new clang option "-ftime-trace="

2022-07-15 Thread Junduo Dong via cfe-commits

Author: dongjunduo
Date: 2022-07-15T08:55:17-07:00
New Revision: f5d9de8cc33014923fbd1c5682758557887e85ba

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

LOG: [Clang] Add a new clang option "-ftime-trace="

The time profiler traces the stages during the clang compile
process. Each compiling stage of a single source file
corresponds to a separately .json file which holds its
time tracing data. However, the .json files are stored in the
same path/directory as its corresponding stage's '-o' option.
For example, if we compile the "demo.cc" to "demo.o" with option
"-o /tmp/demo.o", the time trace data file path is "/tmp/demo.json".

A typical c++ project can contain multiple source files in different
path, but all the json files' paths can be a mess.

The option "-ftime-trace=" allows you to specify where the json
files should be stored. This allows the users to place the time trace
data files of interest in the desired location for further data analysis.

Usage:
- clang/clang++ -ftime-trace ...
- clang/clang++ -ftime-trace=the-directory-you-want ...
- clang/clang++ -ftime-trace=the-directory-you-want/ ...
- clang/clang++ -ftime-trace=the-full-file-path-you-want ...

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

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/include/clang/Frontend/FrontendOptions.h
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/check-time-trace.cpp
clang/tools/driver/cc1_main.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 404effb4e1de4..6d0736c02bdda 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2857,6 +2857,15 @@ def ftime_trace_granularity_EQ : Joined<["-"], 
"ftime-trace-granularity=">, Grou
   HelpText<"Minimum time granularity (in microseconds) traced by time 
profiler">,
   Flags<[CC1Option, CoreOption]>,
   MarshallingInfoInt, "500u">;
+def ftime_trace_EQ : Joined<["-"], "ftime-trace=">, Group,
+  HelpText<"Turn on time profiler. Generates JSON file based on output 
filename. "
+   "Specify the path which stores the tracing output file.">,
+  DocBrief<[{
+  Turn on time profiler. Generates JSON file based on output filename. Results
+  can be analyzed with chrome://tracing or `Speedscope App
+  `_ for flamegraph visualization.}]>,
+  Flags<[CC1Option, CoreOption]>,
+  MarshallingInfoString>;
 def fproc_stat_report : Joined<["-"], "fproc-stat-report">, Group,
   HelpText<"Print subprocess statistics">;
 def fproc_stat_report_EQ : Joined<["-"], "fproc-stat-report=">, Group,

diff  --git a/clang/include/clang/Frontend/FrontendOptions.h 
b/clang/include/clang/Frontend/FrontendOptions.h
index ff5a9c5c77f4d..b0e719ffcacf5 100644
--- a/clang/include/clang/Frontend/FrontendOptions.h
+++ b/clang/include/clang/Frontend/FrontendOptions.h
@@ -499,6 +499,9 @@ class FrontendOptions {
   /// Minimum time granularity (in microseconds) traced by time profiler.
   unsigned TimeTraceGranularity;
 
+  /// Path which stores the output files for -ftime-trace
+  std::string TimeTracePath;
+
 public:
   FrontendOptions()
   : DisableFree(false), RelocatablePCH(false), ShowHelp(false),

diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 3e36d4def2f33..72a1250f89568 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6230,6 +6230,7 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
   Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
   Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
+  Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_EQ);
   Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
   Args.AddLastArg(CmdArgs, options::OPT_malign_double);
   Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);

diff  --git a/clang/test/Driver/check-time-trace.cpp 
b/clang/test/Driver/check-time-trace.cpp
index 1d80748a52331..52b3e71394fba 100644
--- a/clang/test/Driver/check-time-trace.cpp
+++ b/clang/test/Driver/check-time-trace.cpp
@@ -2,6 +2,20 @@
 // RUN: cat %T/check-time-trace.json \
 // RUN:   | %python -c 'import json, sys; 
json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
 // RUN:   | FileCheck %s
+// RUN: %clangxx -S -ftime-trace=%T/new-name.json -ftime-trace-granularity=0 
-o %T/check-time-trace %s
+// RUN: cat %T/new-name.json \
+// RUN:   | %python -c 'import json, sys; 
json.dump(json.loads(sys.stdin.read()), sys.stdout, sort_keys=True, indent=2)' \
+// RUN:   | FileCheck %s
+// RUN: rm -rf %T/output1 && mkdir %T/output1
+// RUN: 

[PATCH] D121141: [Clang] Add `-fexperimental-library` flag to enable unstable and experimental features: follow-up fixes

2022-07-15 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a subscriber: mstorsjo.
ldionne added a comment.

The `experimental-library-flag` test is currently failing on Windows because on 
Windows, `-stdlib=libc++` seems to be ignored and we don't add `-lc++` or 
`-lc++experimental`. Does someone understand how things are supposed to work 
when using libc++ on Windows? @mstorsjo maybe?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121141

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


[PATCH] D129648: Use pseudo parser for folding ranges

2022-07-15 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 445002.
usaxena95 added a comment.

Removed unused headers and fix spellings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129648

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/SemanticSelection.cpp
  clang-tools-extra/clangd/SemanticSelection.h
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/Token.h
  clang-tools-extra/pseudo/lib/CMakeLists.txt
  clang-tools-extra/pseudo/lib/Lex.cpp
  clang-tools-extra/pseudo/unittests/TokenTest.cpp

Index: clang-tools-extra/pseudo/unittests/TokenTest.cpp
===
--- clang-tools-extra/pseudo/unittests/TokenTest.cpp
+++ clang-tools-extra/pseudo/unittests/TokenTest.cpp
@@ -31,6 +31,10 @@
   return arg.Line == (unsigned)Line && arg.Indent == (unsigned)Indent;
 }
 
+MATCHER_P(originalIndex, index, "") {
+  return arg.OriginalIndex == (Token::Index)index;
+}
+
 TEST(TokenTest, Lex) {
   LangOptions Opts;
   std::string Code = R"cpp(
@@ -105,20 +109,23 @@
   Raw.tokens(),
   ElementsAre(AllOf(token("one_\\\ntoken", tok::raw_identifier),
 hasFlag(LexFlags::StartsPPLine),
-hasFlag(LexFlags::NeedsCleaning), lineIndent(1, 0)),
+hasFlag(LexFlags::NeedsCleaning), lineIndent(1, 0),
+originalIndex(0)),
   AllOf(token("two", tok::raw_identifier),
 hasFlag(LexFlags::StartsPPLine),
-Not(hasFlag(LexFlags::NeedsCleaning))),
+Not(hasFlag(LexFlags::NeedsCleaning)),
+originalIndex(1)),
   AllOf(token("\\\ntokens", tok::raw_identifier),
 Not(hasFlag(LexFlags::StartsPPLine)),
-hasFlag(LexFlags::NeedsCleaning;
+hasFlag(LexFlags::NeedsCleaning), originalIndex(2;
 
   TokenStream Cooked = cook(Raw, Opts);
   EXPECT_THAT(
   Cooked.tokens(),
-  ElementsAre(AllOf(token("one_token", tok::identifier), lineIndent(1, 0)),
-  token("two", tok::identifier),
-  token("tokens", tok::identifier)));
+  ElementsAre(AllOf(token("one_token", tok::identifier), lineIndent(1, 0),
+originalIndex(0)),
+  AllOf(token("two", tok::identifier), originalIndex(1)),
+  AllOf(token("tokens", tok::identifier), originalIndex(2;
 }
 
 TEST(TokenTest, EncodedCharacters) {
@@ -182,13 +189,14 @@
 )cpp";
   TokenStream Cook = cook(lex(Code, Opts), Opts);
   TokenStream Split = stripComments(Cook);
-  EXPECT_THAT(Split.tokens(), ElementsAreArray({
-  token(">", tok::greater),
-  token(">", tok::greater),
-  token(">", tok::greater),
-  token(">", tok::greater),
-  token(">>=", tok::greatergreaterequal),
-  }));
+  EXPECT_THAT(Split.tokens(),
+  ElementsAre(AllOf(token(">", tok::greater), originalIndex(0)),
+  AllOf(token(">", tok::greater), originalIndex(0)),
+  // Token 1 and 2 are comments.
+  AllOf(token(">", tok::greater), originalIndex(3)),
+  AllOf(token(">", tok::greater), originalIndex(3)),
+  AllOf(token(">>=", tok::greatergreaterequal),
+originalIndex(4;
 }
 
 TEST(TokenTest, DropComments) {
@@ -199,13 +207,16 @@
 )cpp";
   TokenStream Raw = cook(lex(Code, Opts), Opts);
   TokenStream Stripped = stripComments(Raw);
-  EXPECT_THAT(Raw.tokens(),
-  ElementsAreArray(
-  {token("// comment", tok::comment), token("int", tok::kw_int),
-   token("/*abc*/", tok::comment), token(";", tok::semi)}));
-
-  EXPECT_THAT(Stripped.tokens(), ElementsAreArray({token("int", tok::kw_int),
-   token(";", tok::semi)}));
+  EXPECT_THAT(
+  Raw.tokens(),
+  ElementsAre(AllOf(token("// comment", tok::comment), originalIndex(0)),
+  AllOf(token("int", tok::kw_int), originalIndex(1)),
+  AllOf(token("/*abc*/", tok::comment), originalIndex(2)),
+  AllOf(token(";", tok::semi), originalIndex(3;
+
+  EXPECT_THAT(Stripped.tokens(),
+  ElementsAre(AllOf(token("int", tok::kw_int), originalIndex(1)),
+  AllOf(token(";", tok::semi), originalIndex(3;
 }
 
 } // namespace
Index: clang-tools-extra/pseudo/lib/Lex.cpp
===
--- clang-tools-extra/pseudo/lib/Lex.cpp
+++ 

[PATCH] D121141: [Clang] Add `-funstable` flag to enable unstable and experimental features: follow-up fixes

2022-07-15 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1186
 
-defm unstable : BoolFOption<"unstable",
-  LangOpts<"Unstable">, DefaultFalse,
-  PosFlag,
+defm experimental_library : BoolFOption<"experimental-library",
+  LangOpts<"ExperimentalLibrary">, DefaultFalse,

MaskRay wrote:
> This can be simplified with `OptInCC1FFlag` (both driver/CC1 for the pos 
> form, but driver-only for the neg form).
> You'll need to set CoreOption to make the option available to clang-cl.
I was looking for documentation on `OptInCC1FFlag`, and I found:

```
// A boolean option which is opt-in in CC1. The positive option exists in CC1 
and
// Args.hasArg(OPT_ffoo) can be used to check that the flag is enabled.
// This is useful if the option is usually disabled.
// Use this only when the option cannot be declared via BoolFOption.
multiclass OptInCC1FFlag There may be an archive ordering problem. 
I'm not sure I follow -- what problem are you concerned about?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121141

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


[PATCH] D129864: [Flang] Generate documentation for compiler flags

2022-07-15 Thread Dylan Fleming via Phabricator via cfe-commits
DylanFleming-arm created this revision.
Herald added subscribers: arphaman, mgorny.
Herald added a reviewer: sscalpone.
Herald added projects: Flang, All.
DylanFleming-arm requested review of this revision.
Herald added subscribers: cfe-commits, jdoerfert.
Herald added a project: clang.

This patch aims to create a webpage to document
Flang's command line options on https://flang.llvm.org/docs/
in a similar way to Clang's
https://clang.llvm.org/docs/ClangCommandLineReference.html

This is done by using clang tablegen to generate an .rst
file from options.td (which is current shared with clang)
For this to work, ClangOptionDocEmitter.cpp was updated
to allow specific flang flags to be included,
rather than bulk excluding clang flags.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129864

Files:
  clang/utils/TableGen/ClangOptionDocEmitter.cpp
  flang/docs/CMakeLists.txt
  flang/docs/index.md
  flang/include/flang/FlangOptionsDocs.td

Index: flang/include/flang/FlangOptionsDocs.td
===
--- /dev/null
+++ flang/include/flang/FlangOptionsDocs.td
@@ -0,0 +1,35 @@
+//==--- FlangOptionDocs.td - Option documentation -===//
+//
+// 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
+//
+//===--===//
+
+def GlobalDocumentation {
+  code Intro =[{..
+  ---
+  NOTE: This file is automatically generated by running clang-tblgen
+  -gen-opt-docs. Do not edit this file by hand!!
+  ---
+
+=
+Flang command line argument reference
+=
+.. contents::
+   :local:
+
+Introduction
+
+
+}];
+
+  string Program = "flang";
+
+  list ExcludedFlags = [""];
+  list IncludedFlags = ["FlangOption"];
+
+}
+
+
+include "../../../clang/include/clang/Driver/Options.td"
Index: flang/docs/index.md
===
--- flang/docs/index.md
+++ flang/docs/index.md
@@ -45,6 +45,7 @@
DoConcurrent
Extensions
FIRLangRef
+   FlangCommandLineReference
FlangDriver
FortranIR
FortranLLVMTestSuite
Index: flang/docs/CMakeLists.txt
===
--- flang/docs/CMakeLists.txt
+++ flang/docs/CMakeLists.txt
@@ -91,6 +91,16 @@
 endif()
 endif()
 
+function (gen_rst_file_from_td output_file td_option source docs_target)
+  if (NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${source}")
+message(FATAL_ERROR "Cannot find source file: ${source} in ${CMAKE_CURRENT_SOURCE_DIR}")
+  endif()
+  get_filename_component(TABLEGEN_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${source}" DIRECTORY)
+  list(APPEND LLVM_TABLEGEN_FLAGS "-I${TABLEGEN_INCLUDE_DIR}")
+  clang_tablegen(Source/${output_file} ${td_option} SOURCE ${source} TARGET "gen-${output_file}")
+  add_dependencies(${docs_target} "gen-${output_file}")
+endfunction()
+
 if (LLVM_ENABLE_SPHINX)
   include(AddSphinxTarget)
   if (SPHINX_FOUND)
@@ -114,6 +124,7 @@
   COMMAND "${Python3_EXECUTABLE}"
   ARGS ${CMAKE_CURRENT_BINARY_DIR}/Source/FIR/CreateFIRLangRef.py)
 
+  gen_rst_file_from_td(FlangCommandLineReference.rst -gen-opt-docs ../include/flang/FlangOptionsDocs.td docs-flang-html)
 endif()
 if (${SPHINX_OUTPUT_MAN})
   add_sphinx_target(man flang)
Index: clang/utils/TableGen/ClangOptionDocEmitter.cpp
===
--- clang/utils/TableGen/ClangOptionDocEmitter.cpp
+++ clang/utils/TableGen/ClangOptionDocEmitter.cpp
@@ -168,6 +168,30 @@
   return false;
 }
 
+bool isIncluded(const Record *OptionOrGroup, const Record *DocInfo) {
+  if (!DocInfo->getValue("IncludedFlags"))
+return true;
+  for (StringRef Inclusion : DocInfo->getValueAsListOfStrings("IncludedFlags"))
+if (hasFlag(OptionOrGroup, Inclusion))
+  return true;
+  return false;
+}
+
+bool isGroupIncluded(const DocumentedGroup , const Record *DocInfo) {
+  if (isIncluded(Group.Group, DocInfo))
+return true;
+  for (auto  : Group.Options)
+if (isIncluded(O.Option, DocInfo))
+  return true;
+  for (auto  : Group.Groups) {
+if (isIncluded(G.Group, DocInfo))
+  return true;
+if (isGroupIncluded(G, DocInfo))
+  return true;
+  }
+  return false;
+}
+
 bool isExcluded(const Record *OptionOrGroup, const Record *DocInfo) {
   // FIXME: Provide a flag to specify the set of exclusions.
   for (StringRef Exclusion : DocInfo->getValueAsListOfStrings("ExcludedFlags"))
@@ -302,7 +326,7 @@
 
 void emitOption(const DocumentedOption , const Record *DocInfo,
 raw_ostream ) {
-  if 

[PATCH] D121141: [Clang] Add `-funstable` flag to enable unstable and experimental features: follow-up fixes

2022-07-15 Thread Mark de Wever via Phabricator via cfe-commits
Mordante accepted this revision.
Mordante added a comment.

LGTM, but please update the name of the flag in the title before landing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121141

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


[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-07-15 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 444989.
iains added a comment.

rebased, fixed the interaction with clang module map modules.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126189

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/Basic/Module.h
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGDeclCXX.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/Parse/ParseAST.cpp
  clang/lib/Sema/SemaModule.cpp
  clang/test/CodeGen/module-intializer-pmf.cpp
  clang/test/CodeGen/module-intializer.cpp

Index: clang/test/CodeGen/module-intializer.cpp
===
--- /dev/null
+++ clang/test/CodeGen/module-intializer.cpp
@@ -0,0 +1,186 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: cd %t
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 N.cpp \
+// RUN:-emit-module-interface -o N.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 N.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-N
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 O.cpp \
+// RUN:-emit-module-interface -o O.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 O.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-O
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M-part.cpp \
+// RUN:-emit-module-interface -o M-part.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M-part.pcm -S \
+// RUN: -emit-llvm -o - | FileCheck %s --check-prefix=CHECK-P
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M.cpp \
+// RUN: -fmodule-file=N.pcm -fmodule-file=O.pcm -fmodule-file=M-part.pcm \
+// RUN:-emit-module-interface -o M.pcm
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M.pcm -S -emit-llvm \
+// RUN:  -o - | FileCheck %s --check-prefix=CHECK-M
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 useM.cpp \
+// RUN: -fmodule-file=M.pcm -S -emit-llvm  -o - \
+// RUN: | FileCheck %s --check-prefix=CHECK-USE
+
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++20 M-impl.cpp \
+// RUN: -fmodule-file=M.pcm -S -emit-llvm  -o - \
+// RUN: | FileCheck %s --check-prefix=CHECK-IMPL
+
+//--- N-h.h
+
+struct Oink {
+  Oink(){};
+};
+
+Oink Hog;
+
+//--- N.cpp
+
+module;
+#include "N-h.h"
+
+export module N;
+
+export struct Quack {
+  Quack(){};
+};
+
+export Quack Duck;
+
+// CHECK-N: define internal void @__cxx_global_var_init
+// CHECK-N: call {{.*}} @_ZN4OinkC1Ev
+// CHECK-N: define internal void @__cxx_global_var_init
+// CHECK-N: call {{.*}} @_ZNW1N5QuackC1Ev
+// CHECK-N: define void @_ZGIW1N
+// CHECK-N: store i8 1, ptr @_ZGIW1N__in_chrg
+// CHECK-N: call void @__cxx_global_var_init
+// CHECK-N: call void @__cxx_global_var_init
+
+//--- O-h.h
+
+struct Meow {
+  Meow(){};
+};
+
+Meow Cat;
+
+//--- O.cpp
+
+module;
+#include "O-h.h"
+
+export module O;
+
+export struct Bark {
+  Bark(){};
+};
+
+export Bark Dog;
+
+// CHECK-O: define internal void @__cxx_global_var_init
+// CHECK-O: call {{.*}} @_ZN4MeowC2Ev
+// CHECK-O: define internal void @__cxx_global_var_init
+// CHECK-O: call {{.*}} @_ZNW1O4BarkC1Ev
+// CHECK-O: define void @_ZGIW1O
+// CHECK-O: store i8 1, ptr @_ZGIW1O__in_chrg
+// CHECK-O: call void @__cxx_global_var_init
+// CHECK-O: call void @__cxx_global_var_init
+
+//--- P-h.h
+
+struct Croak {
+  Croak(){};
+};
+
+Croak Frog;
+
+//--- M-part.cpp
+
+module;
+#include "P-h.h"
+
+module M:Part;
+
+struct Squawk {
+  Squawk(){};
+};
+
+Squawk parrot;
+
+// CHECK-P: define internal void @__cxx_global_var_init
+// CHECK-P: call {{.*}} @_ZN5CroakC1Ev
+// CHECK-P: define internal void @__cxx_global_var_init
+// CHECK-P: call {{.*}} @_ZNW1M6SquawkC1Ev
+// CHECK-P: define void @_ZGIW1MWP4Part
+// CHECK-P: store i8 1, ptr @_ZGIW1MWP4Part__in_chrg
+// CHECK-P: call void @__cxx_global_var_init
+// CHECK-P: call void @__cxx_global_var_init
+
+//--- M-h.h
+
+struct Moo {
+  Moo(){};
+};
+
+Moo Cow;
+
+//--- M.cpp
+
+module;
+#include "M-h.h"
+
+export module M;
+import N;
+export import O;
+import :Part;
+
+export struct Baa {
+  int x;
+  Baa(){};
+  Baa(int x) : x(x) {}
+  int getX() { return x; }
+};
+
+export Baa Sheep(10);
+
+// CHECK-M: define internal void @__cxx_global_var_init
+// CHECK-M: call {{.*}} @_ZN3MooC1Ev
+// CHECK-M: define internal void @__cxx_global_var_init
+// CHECK-M: call {{.*}} @_ZNW1M3BaaC1Ei
+// CHECK-M: declare void @_ZGIW1O()
+// CHECK-M: declare void @_ZGIW1N()
+// CHECK-M: declare void @_ZGIW1MWP4Part()
+// CHECK-M: define void @_ZGIW1M
+// CHECK-M: store i8 1, ptr @_ZGIW1M__in_chrg
+// CHECK-M: call void @_ZGIW1O()
+// CHECK-M: call void @_ZGIW1N()
+// CHECK-M: call void @_ZGIW1MWP4Part()
+// CHECK-M: call void @__cxx_global_var_init
+// CHECK-M: call void @__cxx_global_var_init
+
+//--- useM.cpp
+
+import M;
+
+int main() {
+  return Sheep.getX();
+}
+
+// 

[PATCH] D126189: [C++20][Modules] Build module static initializers per P1874R1.

2022-07-15 Thread Iain Sandoe via Phabricator via cfe-commits
iains reopened this revision.
iains added a comment.
This revision is now accepted and ready to land.

reopening to post the patch I intend to land.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D126189

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


[PATCH] D128745: [c++] implements DR692, DR1395 and tentatively DR1432, about partial ordering of variadic template partial specialization or function template

2022-07-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM!




Comment at: clang/lib/Sema/SemaTemplateDeduction.cpp:5444
+  if (Better1 && Better2) {
+bool ClangABICompat14 = S.Context.getLangOpts().getClangABICompat() <=
+LangOptions::ClangABI::Ver14;

ychen wrote:
> aaron.ballman wrote:
> > Can you add CodeGen test coverage for both ABI modes (new RUN line with 
> > `-fclang-abi-compat=14`)
> Some test cases could reach the CodeGen phase *with* 
> `-fclang-abi-compat=14`(i.e without this patch), some test cases could reach 
> the CodeGen phase *without* `-fclang-abi-compat=14`(i.e with this patch). 
> Please let me know if the added CodeGen tests are what you expected.
Yes, that test is what I was looking for, thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128745

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


[PATCH] D129222: [pseudo] Implement a guard to determine function declarator.

2022-07-15 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 444976.
hokein added a comment.

rebase and address the main comment -- encoding the function-declarator into 
the grammar.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129222

Files:
  clang-tools-extra/pseudo/lib/cxx/CXX.cpp
  clang-tools-extra/pseudo/lib/cxx/cxx.bnf
  clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
  clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
  clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
  clang-tools-extra/pseudo/test/glr.cpp

Index: clang-tools-extra/pseudo/test/glr.cpp
===
--- clang-tools-extra/pseudo/test/glr.cpp
+++ clang-tools-extra/pseudo/test/glr.cpp
@@ -1,4 +1,4 @@
-// RUN: clang-pseudo -grammar=%cxx-bnf-file -source=%s --print-forest -print-statistics | FileCheck %s
+// RUN: clang-pseudo -grammar=cxx -source=%s --print-forest -print-statistics | FileCheck %s
 
 void foo() {
   T* a; // a multiply expression or a pointer declaration?
Index: clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
===
--- clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
+++ clang-tools-extra/pseudo/test/cxx/recovery-init-list.cpp
@@ -3,7 +3,7 @@
 // CHECK:  translation-unit~simple-declaration
 // CHECK-NEXT: ├─decl-specifier-seq~AUTO := tok[0]
 // CHECK-NEXT: ├─init-declarator-list~init-declarator
-// CHECK-NEXT: │ ├─declarator~IDENTIFIER := tok[1]
+// CHECK-NEXT: │ ├─non-function-declarator~IDENTIFIER := tok[1]
 // CHECK-NEXT: │ └─initializer~brace-or-equal-initializer
 // CHECK-NEXT: │   ├─= := tok[2]
 // CHECK-NEXT: │   └─initializer-clause~braced-init-list
Index: clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
===
--- clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
+++ clang-tools-extra/pseudo/test/cxx/declarator-var.cpp
@@ -1,11 +1,9 @@
 // The standard grammar allows an function-body to use any declarator, including
 // a non-function declarator. This creates an ambiguity where a
 // simple-declaration is misparsed as a function-definition.
-// FIXME: eliminate this false parse.
-// XFAIL: *
 
 // RUN: clang-pseudo -grammar=cxx -source=%s --print-forest | FileCheck %s
 void (*s)(){};
 // CHECK-NOT:  function-definition
-// CHECK:  init-declarator := declarator initializer
+// CHECK:  init-declarator := non-function-declarator initializer
 // CHECK-NOT:  function-definition
Index: clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
===
--- clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
+++ clang-tools-extra/pseudo/test/cxx/declarator-function.cpp
@@ -1,11 +1,28 @@
 // The standard grammar allows an init-list with any declarator, including
 // a function declarator. This creates an ambiguity where a function-definition
 // is misparsed as a simple-declaration.
-// FIXME: eliminate this false parse.
-// XFAIL: *
 
 // RUN: clang-pseudo -grammar=cxx -source=%s --print-forest | FileCheck %s
-void s(){};
-// CHECK-NOT:  simple-declaration
-// CHECK:  function-definition := decl-specifier-seq declarator
-// function-body CHECK-NOT:  simple-declaration
+void s() {};
+// CHECK:  ├─declaration-seq~function-definition := decl-specifier-seq function-declarator function-body
+// CHECK-NEXT: │ ├─decl-specifier-seq~VOID := tok[0]
+// CHECK-NEXT: │ ├─function-declarator~noptr-declarator := noptr-declarator parameters-and-qualifiers
+// CHECK-NEXT: │ │ ├─noptr-declarator~IDENTIFIER := tok[1]
+// CHECK-NEXT: │ │ └─parameters-and-qualifiers := ( )
+// CHECK-NEXT: │ │   ├─( := tok[2]
+// CHECK-NEXT: │ │   └─) := tok[3]
+// CHECK-NEXT: │ └─function-body~compound-statement := { }
+// CHECK-NEXT: │   ├─{ := tok[4]
+// CHECK-NEXT: │   └─} := tok[5]
+// CHECK-NEXT: └─declaration~; := tok[6]
+
+// Should not parse as a function-definition.
+int s2 {};
+// CHECK-NEXT:  declaration~simple-declaration := decl-specifier-seq init-declarator-list ;
+// CHECK-NEXT:  ├─decl-specifier-seq~INT := tok[7]
+// CHECK-NEXT:  ├─init-declarator-list~init-declarator := non-function-declarator initializer
+// CHECK-NEXT:  │ ├─non-function-declarator~IDENTIFIER := tok[8]
+// CHECK-NEXT:  │ └─initializer~braced-init-list := { }
+// CHECK-NEXT:  │   ├─{ := tok[9]
+// CHECK-NEXT:  │   └─} := tok[10]
+// CHECK-NEXT:  └─; := tok[11]
Index: clang-tools-extra/pseudo/lib/cxx/cxx.bnf
===
--- clang-tools-extra/pseudo/lib/cxx/cxx.bnf
+++ clang-tools-extra/pseudo/lib/cxx/cxx.bnf
@@ -402,8 +402,10 @@
 placeholder-type-specifier := type-constraint_opt 

[PATCH] D129648: Use pseudo parser for folding ranges

2022-07-15 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 added inline comments.



Comment at: clang-tools-extra/clangd/SemanticSelection.cpp:185
+if (auto *Paired = Tok.pair()) {
+  if (Tok.Line < Paired->Line) {
+Position Start = offsetToPosition(

hokein wrote:
> The `if` logic seems tricky, it is doing two different things:
> 
> 1) avoid creating duplicate `FoldingRange` for a pair bracket
> 2) avoid creating a FoldingRange if the pair bracket is on the same line.
> 
> Are both intended?
Yes. Both of these are intentional. Added a comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129648

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


[PATCH] D129648: Use pseudo parser for folding ranges

2022-07-15 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 444975.
usaxena95 marked 15 inline comments as done.
usaxena95 added a comment.

Addressed comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129648

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/SemanticSelection.cpp
  clang-tools-extra/clangd/SemanticSelection.h
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/Token.h
  clang-tools-extra/pseudo/lib/CMakeLists.txt
  clang-tools-extra/pseudo/lib/Lex.cpp
  clang-tools-extra/pseudo/unittests/TokenTest.cpp

Index: clang-tools-extra/pseudo/unittests/TokenTest.cpp
===
--- clang-tools-extra/pseudo/unittests/TokenTest.cpp
+++ clang-tools-extra/pseudo/unittests/TokenTest.cpp
@@ -31,6 +31,10 @@
   return arg.Line == (unsigned)Line && arg.Indent == (unsigned)Indent;
 }
 
+MATCHER_P(originalIndex, index, "") {
+  return arg.OriginalIndex == (Token::Index)index;
+}
+
 TEST(TokenTest, Lex) {
   LangOptions Opts;
   std::string Code = R"cpp(
@@ -105,20 +109,23 @@
   Raw.tokens(),
   ElementsAre(AllOf(token("one_\\\ntoken", tok::raw_identifier),
 hasFlag(LexFlags::StartsPPLine),
-hasFlag(LexFlags::NeedsCleaning), lineIndent(1, 0)),
+hasFlag(LexFlags::NeedsCleaning), lineIndent(1, 0),
+originalIndex(0)),
   AllOf(token("two", tok::raw_identifier),
 hasFlag(LexFlags::StartsPPLine),
-Not(hasFlag(LexFlags::NeedsCleaning))),
+Not(hasFlag(LexFlags::NeedsCleaning)),
+originalIndex(1)),
   AllOf(token("\\\ntokens", tok::raw_identifier),
 Not(hasFlag(LexFlags::StartsPPLine)),
-hasFlag(LexFlags::NeedsCleaning;
+hasFlag(LexFlags::NeedsCleaning), originalIndex(2;
 
   TokenStream Cooked = cook(Raw, Opts);
   EXPECT_THAT(
   Cooked.tokens(),
-  ElementsAre(AllOf(token("one_token", tok::identifier), lineIndent(1, 0)),
-  token("two", tok::identifier),
-  token("tokens", tok::identifier)));
+  ElementsAre(AllOf(token("one_token", tok::identifier), lineIndent(1, 0),
+originalIndex(0)),
+  AllOf(token("two", tok::identifier), originalIndex(1)),
+  AllOf(token("tokens", tok::identifier), originalIndex(2;
 }
 
 TEST(TokenTest, EncodedCharacters) {
@@ -182,13 +189,14 @@
 )cpp";
   TokenStream Cook = cook(lex(Code, Opts), Opts);
   TokenStream Split = stripComments(Cook);
-  EXPECT_THAT(Split.tokens(), ElementsAreArray({
-  token(">", tok::greater),
-  token(">", tok::greater),
-  token(">", tok::greater),
-  token(">", tok::greater),
-  token(">>=", tok::greatergreaterequal),
-  }));
+  EXPECT_THAT(Split.tokens(),
+  ElementsAre(AllOf(token(">", tok::greater), originalIndex(0)),
+  AllOf(token(">", tok::greater), originalIndex(0)),
+  // Token and 1 and 2 are comments.
+  AllOf(token(">", tok::greater), originalIndex(3)),
+  AllOf(token(">", tok::greater), originalIndex(3)),
+  AllOf(token(">>=", tok::greatergreaterequal),
+originalIndex(4;
 }
 
 TEST(TokenTest, DropComments) {
@@ -199,13 +207,16 @@
 )cpp";
   TokenStream Raw = cook(lex(Code, Opts), Opts);
   TokenStream Stripped = stripComments(Raw);
-  EXPECT_THAT(Raw.tokens(),
-  ElementsAreArray(
-  {token("// comment", tok::comment), token("int", tok::kw_int),
-   token("/*abc*/", tok::comment), token(";", tok::semi)}));
-
-  EXPECT_THAT(Stripped.tokens(), ElementsAreArray({token("int", tok::kw_int),
-   token(";", tok::semi)}));
+  EXPECT_THAT(
+  Raw.tokens(),
+  ElementsAre(AllOf(token("// comment", tok::comment), originalIndex(0)),
+  AllOf(token("int", tok::kw_int), originalIndex(1)),
+  AllOf(token("/*abc*/", tok::comment), originalIndex(2)),
+  AllOf(token(";", tok::semi), originalIndex(3;
+
+  EXPECT_THAT(Stripped.tokens(),
+  ElementsAre(AllOf(token("int", tok::kw_int), originalIndex(1)),
+  AllOf(token(";", tok::semi), originalIndex(3;
 }
 
 } // namespace
Index: clang-tools-extra/pseudo/lib/Lex.cpp
===
--- 

[PATCH] D112374: [clang] Implement ElaboratedType sugaring for types written bare

2022-07-15 Thread Chris Hamilton via Phabricator via cfe-commits
chrish_ericsson_atx added a comment.

In D112374#3653967 , @JDevlieghere 
wrote:

> I don't. I think reverting your change was well within the guidelines 
> outlined by LLVM's patch reversion policy: 
> https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy
>
> Additionally, I think you could've given me a little bit more time to catch 
> up on the discussion here. The code review policy and practices 
> (https://llvm.org/docs/CodeReview.html#code-reviews-speed-and-reciprocity) 
> recommend pinging every few days to once per week depending on how urgent the 
> patch is.
>
> By relanding, you broke the bots again 
> (https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/45354/#showFailuresLink)
>  and I'm forced to revert this change a second time. Please refrain from 
> landing this again until we've settled on a way forward.

I agree with @JDevlieghere here. In general, it's reasonable that the patch was 
reverted when it was found to break other things in the LLVM project, and 
reasonable to expect the original author's cooperation in resolving that 
breakage before the patch gets reapplied--especially when the patch is as large 
and far-reaching as this one is.

As an aside, this also patch breaks one of our internal tidy checkers. Likely 
the fix we'll need for that checker is simple, but it'll take a bit of research 
for me to understand what needs to happen in our internal code. Thanks for your 
patience and willingness to help your colleagues understand and adapt to the 
change you've authored.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112374

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


[PATCH] D129855: [clang][PowerPC] Set lld as clang's default linker for PowerPC Linux

2022-07-15 Thread Quinn Pham via Phabricator via cfe-commits
quinnp created this revision.
Herald added subscribers: steven.zhang, shchenz, kbarton, nemanjai.
Herald added a project: All.
quinnp requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

This patch changes the default linker for `clang` on PowerPC Linux to `lld`.
Here is a summary of the expected behaviour before and after this patch:

To use `lld` as the linker before this patch:

- build with `lld` in `LLVM_ENABLE_PROJECTS`
- build with `-DCLANG_DEFAULT_LINKER=lld`

To use `lld` as the linker after this patch:

- build with `lld` in `LLVM_ENABLE_PROJECTS`

To use `ld` as the linker before this patch:

- default behaviour

To use `ld` as the linker after this patch:

- build with `-DCLANG_DEFAULT_LINKER=`

Note: After this patch, if you build `clang` for PowerPC Linux and `lld` is not
included in `LLVM_ENABLE_PROJECTS`, the built compiler will report an error
during linking on PowerPC Linux. Therefore, anyone using the default behaviour
before this patch will need to modify their build configuration to either:

- include `-DCLANG_DEFAULT_LINKER=` to continue using `ld` or
- `lld` in `LLVM_ENABLE_PROJECTS` to switch to `lld`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D129855

Files:
  clang/lib/Driver/ToolChains/PPCLinux.h


Index: clang/lib/Driver/ToolChains/PPCLinux.h
===
--- clang/lib/Driver/ToolChains/PPCLinux.h
+++ clang/lib/Driver/ToolChains/PPCLinux.h
@@ -24,6 +24,8 @@
   AddClangSystemIncludeArgs(const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ) const override;
 
+  const char *getDefaultLinker() const override { return "ld.lld"; }
+
 private:
   bool SupportIEEEFloat128(const Driver , const llvm::Triple ,
const llvm::opt::ArgList ) const;


Index: clang/lib/Driver/ToolChains/PPCLinux.h
===
--- clang/lib/Driver/ToolChains/PPCLinux.h
+++ clang/lib/Driver/ToolChains/PPCLinux.h
@@ -24,6 +24,8 @@
   AddClangSystemIncludeArgs(const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ) const override;
 
+  const char *getDefaultLinker() const override { return "ld.lld"; }
+
 private:
   bool SupportIEEEFloat128(const Driver , const llvm::Triple ,
const llvm::opt::ArgList ) const;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129359: [pseudo] Generate an enum type for identifying grammar rules.

2022-07-15 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/pseudo/lib/grammar/Grammar.cpp:48
 
+std::string Grammar::mangleSymbol(SymbolID SID) const {
+  static const char *const TokNames[] = {

hokein wrote:
> sammccall wrote:
> > I'm not sure exposing these from `Grammar` is an improvement, i think even 
> > in principle we'd only want to use these for codegen.
> > 
> > The need for testing is real, but i guess you can add a test that uses the 
> > CXX generated grammar, assert the elements of Rule::whatever, and the name 
> > of Symbol::whatever?
> Yeah, these functions are only used in the codegen. I'm inlined to the put it 
> into the `Grammar`(it also has a `symbolName` definition, I'd prefer to have 
> all naming functions in a single place). 
That's exactly my point though: that symbolname is general purpose and should 
be used everywhere, which is why it belongs on grammar.

Vs the mangled name that literally nobody should be using for anything.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129359

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


[PATCH] D128619: [Clang] Implement P0848 (Conditionally Trivial Special Member Functions)

2022-07-15 Thread Barry Revzin via Phabricator via cfe-commits
BRevzin added inline comments.



Comment at: clang/test/AST/conditionally-trivial-smfs.cpp:39
+
+template struct DefaultConstructorCheck<2>;
+// CHECK: "kind": "ClassTemplateSpecializationDecl",

It's possible that I just don't understand what these tests actually mean 
but... where is the test for `DefaultConstructorCheck<2>` having a deleted 
default constructor, or `DefaultConstructorCheck<3>` having a non-defaulted one?

It'd also be worthwhile to have at least one test with constaints that subsume 
each other instead of being mutually exclusive. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D128619

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


[PATCH] D129802: [DRAFT] Implementing new atomic orderings in LLVM and generate barriers for legacy __sync builtins. Support corresponding memory model in outline atomics as well.

2022-07-15 Thread Wilco Dijkstra via Phabricator via cfe-commits
Wilco1 added a comment.

The general requirement is that inline and outline atomics have identical 
behaviour, and that GCC and LLVM emit the same sequences. I agree __sync is 
badly documented, so it's hard to figure whether an extra DMB barrier could 
actually make a difference, but it's best to be conservative with atomics. Also 
it was trivial to add (GCC just adds an extra flag for __sync which then emits 
the extra barrier if the flag is set, so you don't need to introduce new atomic 
models).

However if __sync primitives are hardly used in the real world then perhaps it 
is about time to deprecate them with annoying warnings, and completely remove 
support next year. Does that sound reasonable?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129802

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


[PATCH] D129045: [C++20][Modules] Update handling of implicit inlines [P1779R3]

2022-07-15 Thread Iain Sandoe via Phabricator via cfe-commits
iains updated this revision to Diff 444965.
iains added a comment.

rebased, fixed interaction with clang modules.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129045

Files:
  clang/lib/AST/TextNodeDumper.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/test/AST/ast-dump-constant-expr.cpp
  clang/test/AST/ast-dump-lambda.cpp
  clang/test/CXX/class/class.friend/p7-cxx20.cpp
  clang/test/CXX/class/class.mfct/p1-cxx20.cpp

Index: clang/test/CXX/class/class.mfct/p1-cxx20.cpp
===
--- /dev/null
+++ clang/test/CXX/class/class.mfct/p1-cxx20.cpp
@@ -0,0 +1,57 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+// RUN: cd %t
+//
+// RUN: %clang_cc1 -std=c++20 no-modules.cpp -fsyntax-only -ast-dump | \
+// RUN: FileCheck --match-full-lines --check-prefix=CHECK-NM %s
+// RUN: %clang_cc1 -std=c++20 -xc++-user-header header-unit.h -ast-dump | \
+// RUN: FileCheck --match-full-lines --check-prefix=CHECK-HU %s
+// RUN: %clang_cc1 -std=c++20 module.cpp -ast-dump | \
+// RUN: FileCheck --match-full-lines --check-prefix=CHECK-MOD %s
+
+//--- no-modules.cpp
+
+class X {
+  void x(){};
+};
+
+// CHECK-NM: `-CXXRecordDecl {{.*}}  line:2:7 class X definition
+// CHECK-NM:   |-CXXRecordDecl {{.*}}  col:7 implicit class X
+// CHECK-NM-NEXT: `-CXXMethodDecl {{.*}}  col:8 x 'void ()' implicit-inline
+
+// A header unit header
+//--- header-unit.h
+
+class Y {
+  void y(){};
+};
+
+// CHECK-HU: `-CXXRecordDecl {{.*}} <./header-unit.h:2:1, line:4:1> line:2:7 class Y definition
+// CHECK-HU: |-CXXRecordDecl {{.*}}  col:7 implicit class Y
+// CHECK-HU-NEXT: `-CXXMethodDecl {{.*}}  col:8 y 'void ()' implicit-inline
+
+// A textually-included header
+//--- header.h
+
+class A {
+  void a(){};
+};
+
+//--- module.cpp
+module;
+#include "header.h"
+
+export module M;
+
+class Z {
+  void z(){};
+};
+
+// CHECK-MOD: |-CXXRecordDecl {{.*}} <./header.h:2:1, line:4:1> line:2:7 in M. hidden class A definition
+// CHECK-MOD: | |-CXXRecordDecl {{.*}}  col:7 in M. hidden implicit class A
+// CHECK-MOD-NEXT: | `-CXXMethodDecl {{.*}}  col:8 in M. hidden a 'void ()' implicit-inline
+
+// CHECK-MOD: `-CXXRecordDecl {{.*}}  line:6:7 in M hidden class Z{{( ReachableWhenImported)?}} definition
+// CHECK-MOD: |-CXXRecordDecl {{.*}}  col:7 in M hidden implicit class Z{{( ReachableWhenImported)?}}
+// CHECK-MOD-NEXT: `-CXXMethodDecl {{.*}}  col:8 in M hidden z 'void ()'{{( ReachableWhenImported)?}}
Index: clang/test/CXX/class/class.friend/p7-cxx20.cpp
===
--- /dev/null
+++ clang/test/CXX/class/class.friend/p7-cxx20.cpp
@@ -0,0 +1,59 @@
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+// RUN: cd %t
+//
+// RUN: %clang_cc1 -std=c++20 no-modules.cpp -fsyntax-only -ast-dump | \
+// RUN: FileCheck --match-full-lines --check-prefix=CHECK-NM %s
+// RUN: %clang_cc1 -std=c++20 -xc++-user-header header-unit.h -ast-dump | \
+// RUN: FileCheck --match-full-lines --check-prefix=CHECK-HU %s
+// RUN: %clang_cc1 -std=c++20 module.cpp -ast-dump | \
+// RUN: FileCheck --match-full-lines --check-prefix=CHECK-MOD %s
+
+//--- no-modules.cpp
+
+class X {
+  friend void x(){};
+};
+
+// CHECK-NM: `-CXXRecordDecl {{.*}}  line:2:7 class X definition
+// CHECK-NM:   |-CXXRecordDecl {{.*}}  col:7 implicit class X
+// CHECK-NM-NEXT: `-FriendDecl {{.*}}  col:15
+// CHECK-NM-NEXT: `-FunctionDecl {{.*}} parent {{.*}}  col:15 x 'void ()' implicit-inline
+
+//--- header-unit.h
+
+class Y {
+  friend void y(){};
+};
+
+// CHECK-HU: `-CXXRecordDecl {{.*}} <./header-unit.h:2:1, line:4:1> line:2:7 class Y definition
+// CHECK-HU: |-CXXRecordDecl {{.*}}  col:7 implicit class Y
+// CHECK-HU-NEXT: `-FriendDecl {{.*}}  col:15
+// CHECK-HU-NEXT: `-FunctionDecl {{.*}} parent {{.*}}  col:15 y 'void ()' implicit-inline
+
+// A textually-included header
+//--- header.h
+
+class A {
+  friend void a(){};
+};
+
+//--- module.cpp
+module;
+#include "header.h"
+
+export module M;
+
+class Z {
+  friend void z(){};
+};
+// CHECK-MOD: |-CXXRecordDecl {{.*}} <./header.h:2:1, line:4:1> line:2:7 in M. hidden class A definition
+// CHECK-MOD: | |-CXXRecordDecl {{.*}}  col:7 in M. hidden implicit class A
+// CHECK-MOD-NEXT: | `-FriendDecl {{.*}}  col:15 in M.
+// CHECK-MOD-NEXT: |   `-FunctionDecl {{.*}} parent {{.*}}  col:15 in M. hidden a 'void ()' implicit-inline
+
+// CHECK-MOD: `-CXXRecordDecl {{.*}}  line:6:7 in M hidden class Z{{( ReachableWhenImported)?}} definition
+// CHECK-MOD: |-CXXRecordDecl {{.*}}  col:7 in M hidden implicit class Z{{( ReachableWhenImported)?}}
+// CHECK-MOD-NEXT: `-FriendDecl {{.*}}  col:15 in M{{( ReachableWhenImported)?}}
+// CHECK-MOD-NEXT: `-FunctionDecl {{.*}} parent {{.*}}  col:15 in M hidden z 'void ()'{{( ReachableWhenImported)?}}
Index: clang/test/AST/ast-dump-lambda.cpp

[PATCH] D129045: [C++20][Modules] Update handling of implicit inlines [P1779R3]

2022-07-15 Thread Iain Sandoe via Phabricator via cfe-commits
iains reopened this revision.
iains added a comment.
This revision is now accepted and ready to land.

reopening to post the patch I plan to  re-land.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129045

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


[PATCH] D109701: [clang] Emit SARIF Diagnostics: Create `clang::SarifDocumentWriter` interface

2022-07-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM assuming precommit CI comes back happy with it, thank you! I'll land it 
once I see things are green.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109701

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


[PATCH] D129280: [analyzer] PlacementNewChecker, properly handle array overhead (cookie)

2022-07-15 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129280

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


[PATCH] D129748: [Modules] Disable preferred_name attribute in C++20 Modules

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

In D129748#3654909 , @erichkeane 
wrote:

> I think there _IS_ perhaps an acceptability to ignoring this attribute when 
> it would cause a problem.  However, I think doing it as you're doing it now 
> is wrong.  IF we are going to solve the symptom here, I think we should use a 
> much more precise cut, and make either ASTReader not emit the attribute, or 
> ASTWriter just 'ignore' it when reading.  WDYT?  @aaron.ballman as well...

I'm less convinced that's reasonable, because that root cause seems like it 
will impact several other attributes as well. For example, I would be 
`IBOutletCollection`, `OwnerAttr`, `PointerAttr`, and `TypeTagForDatatypeAttr` 
all behave the same way as they all take a type argument. I don't think we want 
to selectively disable so many attributes (for example, disallowing owner and 
pointer attributes means we lose out on C++ Core Guideline features that people 
will likely expect to be able to use with modules. However, I agree that being 
able to modularize the STL is an important use case.

I'd like to understand better what the root cause is. The attribute requires a 
resolved type name, which means we must have seen the type before the attribute 
when writing the AST out. When reading the AST back in, why is the type not 
visible before the attribute? That sounds like we're writing the AST out in the 
wrong order somehow, or something odd like that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129748

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


[PATCH] D129748: [Modules] Disable preferred_name attribute in C++20 Modules

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

In D129748#3653897 , @ChuanqiXu wrote:

> In D129748#3651771 , @erichkeane 
> wrote:
>
>> I guess I don't have a good idea why this attribute would cause ODR issues?  
>> It would seem that if it appeared in 2 different TUs that we could just 
>> 'pick' whichever we wanted, right?
>
> If the compiler finds it appeared in 2 different TUs with different 
> definition (although the judgement is wrong), the compiler would emit an 
> error. So it would block the uses of C++20 Modules with `preferred_name`.
>
>> The description in the bug report of the problem isn't clear to me what the 
>> actual issue is.
>
> Sorry. My bad. Let me try to clarify it. When we write the attribute 
> `preferred_name(foo)` in ASTWriter, the compiler would try to write the type 
> for the argument `foo`. Then when the compiler write the type for `foo`, the 
> compiler find the type for `foo` is a TypeDef type. So the compiler would 
> write the corresponding type `foo_templ`. The key point here is that 
> the AST for `foo_templ` is complete now. Since the AST for 
> `foo_templ` is constructed in Sema.
>
> But problem comes when we read it. When we read the attribute 
> `preferred_name(foo)`, we would read the type for the argument `foo` and then 
> we would try to read the type `foo_templ` later. However, the key 
> problem here is that when we read `foo_templ`, its AST is not 
> constructed yet! So we get a different type with the writer writes. So here 
> is the ODR violation.
>
> The problem is fundamental and I've spent 2 weeks on it. But I don't find any 
> fixes for it. Then I found that, once I disabled `preferred_name`, we could 
> go much further. So I am wondering if it would be an option to skip 
> `preferred_name` if C++ modules is enabled. The idea may not be good in 
> general. But I feel it might be an option in this specific case given it is 
> hard to solve and `preferred_name` is primarily for printers.

Hmm... interesting.  I wish I had a better understanding of the ASTWriter to 
help with this, but given:

1- Getting modules compiled is important
2- this attribute is 'ignore-able', and is for diagnostics only
3- the ASTWriter/ASTReader seems to be messing this up.

I think there _IS_ perhaps an acceptability to ignoring this attribute when it 
would cause a problem.  However, I think doing it as you're doing it now is 
wrong.  IF we are going to solve the symptom here, I think we should use a much 
more precise cut, and make either ASTReader not emit the attribute, or 
ASTWriter just 'ignore' it when reading.  WDYT?  @aaron.ballman as well...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129748

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


[PATCH] D125311: [pseudo] Share the underly payload when stripping comments for a token stream

2022-07-15 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG76910d4a56c8: [pseudo] Share the underly payload when 
stripping comments for a token stream (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125311

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/Token.h
  clang-tools-extra/pseudo/lib/Lex.cpp
  clang-tools-extra/pseudo/lib/Token.cpp


Index: clang-tools-extra/pseudo/lib/Token.cpp
===
--- clang-tools-extra/pseudo/lib/Token.cpp
+++ clang-tools-extra/pseudo/lib/Token.cpp
@@ -116,7 +116,7 @@
 }
 
 TokenStream stripComments(const TokenStream ) {
-  TokenStream Out;
+  TokenStream Out(Input.getPayload());
   for (const Token  : Input.tokens()) {
 if (T.Kind == tok::comment)
   continue;
Index: clang-tools-extra/pseudo/lib/Lex.cpp
===
--- clang-tools-extra/pseudo/lib/Lex.cpp
+++ clang-tools-extra/pseudo/lib/Lex.cpp
@@ -77,7 +77,7 @@
   auto CleanedStorage = std::make_shared();
   clang::IdentifierTable Identifiers(LangOpts);
   TokenStream Result(CleanedStorage);
-
+  Result.addPayload(Code.getPayload());
   for (auto Tok : Code.tokens()) {
 if (Tok.flag(LexFlags::NeedsCleaning)) {
   // Remove escaped newlines and trigraphs.
Index: clang-tools-extra/pseudo/include/clang-pseudo/Token.h
===
--- clang-tools-extra/pseudo/include/clang-pseudo/Token.h
+++ clang-tools-extra/pseudo/include/clang-pseudo/Token.h
@@ -170,6 +170,18 @@
 return Storage[1];
   }
 
+  /// Returns the shared payload.
+  std::shared_ptr getPayload() const { return Payload; }
+  /// Adds the given payload to the stream.
+  void addPayload(std::shared_ptr P) {
+if (!Payload)
+  Payload = std::move(P);
+else
+  Payload = std::make_shared<
+  std::pair, std::shared_ptr>>(
+  std::move(P), std::move(Payload));
+  }
+
   /// Print the tokens in this stream to the output stream.
   ///
   /// The presence of newlines/spaces is preserved, but not the quantity.


Index: clang-tools-extra/pseudo/lib/Token.cpp
===
--- clang-tools-extra/pseudo/lib/Token.cpp
+++ clang-tools-extra/pseudo/lib/Token.cpp
@@ -116,7 +116,7 @@
 }
 
 TokenStream stripComments(const TokenStream ) {
-  TokenStream Out;
+  TokenStream Out(Input.getPayload());
   for (const Token  : Input.tokens()) {
 if (T.Kind == tok::comment)
   continue;
Index: clang-tools-extra/pseudo/lib/Lex.cpp
===
--- clang-tools-extra/pseudo/lib/Lex.cpp
+++ clang-tools-extra/pseudo/lib/Lex.cpp
@@ -77,7 +77,7 @@
   auto CleanedStorage = std::make_shared();
   clang::IdentifierTable Identifiers(LangOpts);
   TokenStream Result(CleanedStorage);
-
+  Result.addPayload(Code.getPayload());
   for (auto Tok : Code.tokens()) {
 if (Tok.flag(LexFlags::NeedsCleaning)) {
   // Remove escaped newlines and trigraphs.
Index: clang-tools-extra/pseudo/include/clang-pseudo/Token.h
===
--- clang-tools-extra/pseudo/include/clang-pseudo/Token.h
+++ clang-tools-extra/pseudo/include/clang-pseudo/Token.h
@@ -170,6 +170,18 @@
 return Storage[1];
   }
 
+  /// Returns the shared payload.
+  std::shared_ptr getPayload() const { return Payload; }
+  /// Adds the given payload to the stream.
+  void addPayload(std::shared_ptr P) {
+if (!Payload)
+  Payload = std::move(P);
+else
+  Payload = std::make_shared<
+  std::pair, std::shared_ptr>>(
+  std::move(P), std::move(Payload));
+  }
+
   /// Print the tokens in this stream to the output stream.
   ///
   /// The presence of newlines/spaces is preserved, but not the quantity.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 76910d4 - [pseudo] Share the underly payload when stripping comments for a token stream

2022-07-15 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-07-15T15:20:48+02:00
New Revision: 76910d4a56c8dba000f198bba13e71cf0492c8cb

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

LOG: [pseudo] Share the underly payload when stripping comments for a token 
stream

`stripComments(cook(...))` is a common pattern being written.
Without this patch, this has a use-after-free issue (cook returns a temporary
TokenStream object which has its own payload, but the payload is not
shared with the one returned by stripComments).

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/pseudo/include/clang-pseudo/Token.h
clang-tools-extra/pseudo/lib/Lex.cpp
clang-tools-extra/pseudo/lib/Token.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/Token.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/Token.h
index b558891f0a86..36e5221a0d30 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/Token.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/Token.h
@@ -170,6 +170,18 @@ class TokenStream {
 return Storage[1];
   }
 
+  /// Returns the shared payload.
+  std::shared_ptr getPayload() const { return Payload; }
+  /// Adds the given payload to the stream.
+  void addPayload(std::shared_ptr P) {
+if (!Payload)
+  Payload = std::move(P);
+else
+  Payload = std::make_shared<
+  std::pair, std::shared_ptr>>(
+  std::move(P), std::move(Payload));
+  }
+
   /// Print the tokens in this stream to the output stream.
   ///
   /// The presence of newlines/spaces is preserved, but not the quantity.

diff  --git a/clang-tools-extra/pseudo/lib/Lex.cpp 
b/clang-tools-extra/pseudo/lib/Lex.cpp
index 6a5a10f1b979..c96e2f27cba9 100644
--- a/clang-tools-extra/pseudo/lib/Lex.cpp
+++ b/clang-tools-extra/pseudo/lib/Lex.cpp
@@ -77,7 +77,7 @@ TokenStream cook(const TokenStream , const LangOptions 
) {
   auto CleanedStorage = std::make_shared();
   clang::IdentifierTable Identifiers(LangOpts);
   TokenStream Result(CleanedStorage);
-
+  Result.addPayload(Code.getPayload());
   for (auto Tok : Code.tokens()) {
 if (Tok.flag(LexFlags::NeedsCleaning)) {
   // Remove escaped newlines and trigraphs.

diff  --git a/clang-tools-extra/pseudo/lib/Token.cpp 
b/clang-tools-extra/pseudo/lib/Token.cpp
index b58c8e4a862e..5b07a62f37fb 100644
--- a/clang-tools-extra/pseudo/lib/Token.cpp
+++ b/clang-tools-extra/pseudo/lib/Token.cpp
@@ -116,7 +116,7 @@ clang::LangOptions genericLangOpts(clang::Language Lang,
 }
 
 TokenStream stripComments(const TokenStream ) {
-  TokenStream Out;
+  TokenStream Out(Input.getPayload());
   for (const Token  : Input.tokens()) {
 if (T.Kind == tok::comment)
   continue;



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


[PATCH] D109701: [clang] Emit SARIF Diagnostics: Create `clang::SarifDocumentWriter` interface

2022-07-15 Thread Vaibhav Yenamandra via Phabricator via cfe-commits
vaibhav.y updated this revision to Diff 444960.
vaibhav.y added a comment.

Undo test case renames


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D109701

Files:
  clang/include/clang/Basic/Sarif.h
  clang/lib/Basic/CMakeLists.txt
  clang/lib/Basic/Sarif.cpp
  clang/unittests/Basic/CMakeLists.txt
  clang/unittests/Basic/SarifTest.cpp

Index: clang/unittests/Basic/SarifTest.cpp
===
--- /dev/null
+++ clang/unittests/Basic/SarifTest.cpp
@@ -0,0 +1,325 @@
+//===- unittests/Basic/SarifTest.cpp - Test writing SARIF documents ---===//
+//
+// 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 "clang/Basic/Sarif.h"
+#include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/FileSystemOptions.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/JSON.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VirtualFileSystem.h"
+#include "llvm/Support/raw_ostream.h"
+#include "gmock/gmock-matchers.h"
+#include "gtest/gtest-death-test.h"
+#include "gtest/gtest-matchers.h"
+#include "gtest/gtest.h"
+
+#include 
+
+using namespace clang;
+
+namespace {
+
+using LineCol = std::pair;
+
+static std::string serializeSarifDocument(llvm::json::Object &) {
+  std::string Output;
+  llvm::json::Value value(std::move(Doc));
+  llvm::raw_string_ostream OS{Output};
+  OS << llvm::formatv("{0}", value);
+  OS.flush();
+  return Output;
+}
+
+class SarifDocumentWriterTest : public ::testing::Test {
+protected:
+  SarifDocumentWriterTest()
+  : InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem),
+FileMgr(FileSystemOptions(), InMemoryFileSystem),
+DiagID(new DiagnosticIDs()), DiagOpts(new DiagnosticOptions()),
+Diags(DiagID, DiagOpts.get(), new IgnoringDiagConsumer()),
+SourceMgr(Diags, FileMgr) {}
+
+  IntrusiveRefCntPtr InMemoryFileSystem;
+  FileManager FileMgr;
+  IntrusiveRefCntPtr DiagID;
+  IntrusiveRefCntPtr DiagOpts;
+  DiagnosticsEngine Diags;
+  SourceManager SourceMgr;
+  LangOptions LangOpts;
+
+  FileID registerSource(llvm::StringRef Name, const char *SourceText,
+bool IsMainFile = false) {
+std::unique_ptr SourceBuf =
+llvm::MemoryBuffer::getMemBuffer(SourceText);
+const FileEntry *SourceFile =
+FileMgr.getVirtualFile(Name, SourceBuf->getBufferSize(), 0);
+SourceMgr.overrideFileContents(SourceFile, std::move(SourceBuf));
+FileID FID = SourceMgr.getOrCreateFileID(SourceFile, SrcMgr::C_User);
+if (IsMainFile)
+  SourceMgr.setMainFileID(FID);
+return FID;
+  }
+
+  CharSourceRange getFakeCharSourceRange(FileID FID, LineCol Begin,
+ LineCol End) {
+auto BeginLoc = SourceMgr.translateLineCol(FID, Begin.first, Begin.second);
+auto EndLoc = SourceMgr.translateLineCol(FID, End.first, End.second);
+return CharSourceRange{SourceRange{BeginLoc, EndLoc}, /* ITR = */ false};
+  }
+};
+
+TEST_F(SarifDocumentWriterTest, canCreateEmptyDocument) {
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+
+  // WHEN:
+  const llvm::json::Object  = Writer.createDocument();
+  std::vector Keys(EmptyDoc.size());
+  std::transform(EmptyDoc.begin(), EmptyDoc.end(), Keys.begin(),
+ [](auto item) { return item.getFirst(); });
+
+  // THEN:
+  ASSERT_THAT(Keys, testing::UnorderedElementsAre("$schema", "version"));
+}
+
+// Test that a newly inserted run will associate correct tool names
+TEST_F(SarifDocumentWriterTest, canCreateDocumentWithOneRun) {
+  // GIVEN:
+  SarifDocumentWriter Writer{SourceMgr};
+  const char *ShortName = "sariftest";
+  const char *LongName = "sarif writer test";
+
+  // WHEN:
+  Writer.createRun(ShortName, LongName);
+  Writer.endRun();
+  const llvm::json::Object  = Writer.createDocument();
+  const llvm::json::Array *Runs = Doc.getArray("runs");
+
+  // THEN:
+  // A run was created
+  ASSERT_THAT(Runs, testing::NotNull());
+
+  // It is the only run
+  ASSERT_EQ(Runs->size(), 1UL);
+
+  // The tool associated with the run was the tool
+  const llvm::json::Object *driver =
+  Runs->begin()->getAsObject()->getObject("tool")->getObject("driver");
+  ASSERT_THAT(driver, testing::NotNull());
+
+  ASSERT_TRUE(driver->getString("name").hasValue());
+  ASSERT_TRUE(driver->getString("fullName").hasValue());
+  ASSERT_TRUE(driver->getString("language").hasValue());
+
+  

[PATCH] D129359: [pseudo] Generate an enum type for identifying grammar rules.

2022-07-15 Thread Haojian Wu 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 rG231535890655: [pseudo] Generate an enum type for identifying 
grammar rules. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129359

Files:
  clang-tools-extra/pseudo/gen/Main.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
  clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
  clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -114,6 +114,21 @@
   EXPECT_NE(G.lookupRule(ruleFor("x")).Guard, G.lookupRule(ruleFor("y")).Guard);
 }
 
+TEST_F(GrammarTest, MangleName) {
+  build(R"bnf(
+_ := declaration
+
+declaration := ptr-declarator ;
+ptr-declarator := * IDENTIFIER
+
+  )bnf");
+  ASSERT_TRUE(Diags.empty());
+  EXPECT_EQ(G.mangleRule(ruleFor("declaration")),
+"declaration_0ptr_declarator_1semi");
+  EXPECT_EQ(G.mangleRule(ruleFor("ptr-declarator")),
+"ptr_declarator_0star_1identifier");
+}
+
 TEST_F(GrammarTest, Diagnostics) {
   build(R"cpp(
 _ := ,_opt
Index: clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
===
--- clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
+++ clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
@@ -45,6 +45,28 @@
   return T->Nonterminals[SID].Name;
 }
 
+std::string Grammar::mangleSymbol(SymbolID SID) const {
+  static const char *const TokNames[] = {
+#define TOK(X) #X,
+#define KEYWORD(X, Y) #X,
+#include "clang/Basic/TokenKinds.def"
+  nullptr};
+  if (clang::pseudo::isToken(SID))
+return TokNames[clang::pseudo::symbolToToken(SID)];
+  std::string Name = symbolName(SID).str();
+  // translation-unit -> translation_unit
+  std::replace(Name.begin(), Name.end(), '-', '_');
+  return Name;
+}
+
+std::string Grammar::mangleRule(RuleID RID) const {
+  const auto  = lookupRule(RID);
+  std::string MangleName = mangleSymbol(R.Target);
+  for (size_t I = 0; I < R.seq().size(); ++I)
+MangleName += llvm::formatv("_{0}{1}", I, mangleSymbol(R.seq()[I]));
+  return MangleName;
+}
+
 llvm::Optional Grammar::findNonterminal(llvm::StringRef Name) const {
   auto It = llvm::partition_point(
   T->Nonterminals,
Index: clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
===
--- clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
+++ clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
@@ -165,6 +165,21 @@
   // Terminals have names like "," (kw_comma) or "OPERATOR" (kw_operator).
   llvm::StringRef symbolName(SymbolID) const;
 
+  // Gets the mangled name for a terminal/nonterminal.
+  // Compared to names in the grammar,
+  //   nonterminals `ptr-declartor` becomes `ptr_declarator`;
+  //   terminal `,` becomes `comma`;
+  //   terminal `IDENTIFIER` becomes `identifier`;
+  //   terminal `INT` becomes `int`;
+  // NOTE: for nonterminals, the mangled name is the same as the cxx::Symbol
+  // enum class; for terminals, we deliberately stripped the `kw_` prefix in
+  // favor of the simplicity.
+  std::string mangleSymbol(SymbolID) const;
+  // Gets the mangled name for the rule.
+  // E.g. for the grammar rule `ptr-declarator := ptr-operator ptr-declarator`,
+  // it is `ptr_declarator_0ptr_operator_1ptr_declarator`.
+  std::string mangleRule(RuleID) const;
+
   // Lookup the SymbolID of the nonterminal symbol by Name.
   llvm::Optional findNonterminal(llvm::StringRef Name) const;
 
Index: clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
===
--- clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
+++ clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
@@ -37,6 +37,12 @@
 #undef NONTERMINAL
 };
 
+enum class Rule : RuleID {
+#define RULE(X, Y) X = Y,
+#include "CXXSymbols.inc"
+#undef RULE
+};
+
 enum class Extension : ExtensionID {
 #define EXTENSION(X, Y) X = Y,
 #include "CXXSymbols.inc"
Index: clang-tools-extra/pseudo/gen/Main.cpp
===
--- clang-tools-extra/pseudo/gen/Main.cpp
+++ clang-tools-extra/pseudo/gen/Main.cpp
@@ -83,17 +83,19 @@
 #ifndef NONTERMINAL
 #define NONTERMINAL(X, Y)
 #endif
+#ifndef RULE
+#define RULE(X, Y)
+#endif
 #ifndef EXTENSION
 #define EXTENSION(X, Y)
 #endif
-)cpp";
+)cpp";
 for (clang::pseudo::SymbolID ID = 0; ID < G.table().Nonterminals.size();
- ++ID) {
-  std::string Name = G.symbolName(ID).str();
-  // translation-unit -> 

[clang-tools-extra] 2315358 - [pseudo] Generate an enum type for identifying grammar rules.

2022-07-15 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-07-15T15:09:31+02:00
New Revision: 2315358906078cd35e2eb64bdcb711b2ec35

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

LOG: [pseudo] Generate an enum type for identifying grammar rules.

The Rule enum type enables us to identify a grammar rule within C++'s
type system.

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

Added: 


Modified: 
clang-tools-extra/pseudo/gen/Main.cpp
clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Removed: 




diff  --git a/clang-tools-extra/pseudo/gen/Main.cpp 
b/clang-tools-extra/pseudo/gen/Main.cpp
index b74f3d46c3560..27857ca4b3e86 100644
--- a/clang-tools-extra/pseudo/gen/Main.cpp
+++ b/clang-tools-extra/pseudo/gen/Main.cpp
@@ -83,17 +83,19 @@ int main(int argc, char *argv[]) {
 #ifndef NONTERMINAL
 #define NONTERMINAL(X, Y)
 #endif
+#ifndef RULE
+#define RULE(X, Y)
+#endif
 #ifndef EXTENSION
 #define EXTENSION(X, Y)
 #endif
-)cpp";
+)cpp";
 for (clang::pseudo::SymbolID ID = 0; ID < G.table().Nonterminals.size();
- ++ID) {
-  std::string Name = G.symbolName(ID).str();
-  // translation-unit -> translation_unit
-  std::replace(Name.begin(), Name.end(), '-', '_');
-  Out.os() << llvm::formatv("NONTERMINAL({0}, {1})\n", Name, ID);
-}
+ ++ID)
+  Out.os() << llvm::formatv("NONTERMINAL({0}, {1})\n", G.mangleSymbol(ID),
+ID);
+for (clang::pseudo::RuleID RID = 0; RID < G.table().Rules.size(); ++RID)
+  Out.os() << llvm::formatv("RULE({0}, {1})\n", G.mangleRule(RID), RID);
 for (clang::pseudo::ExtensionID EID = 1 /*skip the sentinel 0 value*/;
  EID < G.table().AttributeValues.size(); ++EID) {
   llvm::StringRef Name = G.table().AttributeValues[EID];
@@ -102,8 +104,9 @@ int main(int argc, char *argv[]) {
 }
 Out.os() << R"cpp(
 #undef NONTERMINAL
+#undef RULE
 #undef EXTENSION
-)cpp";
+)cpp";
 break;
   case EmitGrammarContent:
 for (llvm::StringRef Line : llvm::split(GrammarText, '\n')) {

diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
index d2509927337ed..a1426722262e1 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
@@ -37,6 +37,12 @@ enum class Symbol : SymbolID {
 #undef NONTERMINAL
 };
 
+enum class Rule : RuleID {
+#define RULE(X, Y) X = Y,
+#include "CXXSymbols.inc"
+#undef RULE
+};
+
 enum class Extension : ExtensionID {
 #define EXTENSION(X, Y) X = Y,
 #include "CXXSymbols.inc"

diff  --git a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h 
b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
index ab11a84ebf295..ef22f71d801c0 100644
--- a/clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
+++ b/clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
@@ -165,6 +165,21 @@ class Grammar {
   // Terminals have names like "," (kw_comma) or "OPERATOR" (kw_operator).
   llvm::StringRef symbolName(SymbolID) const;
 
+  // Gets the mangled name for a terminal/nonterminal.
+  // Compared to names in the grammar,
+  //   nonterminals `ptr-declartor` becomes `ptr_declarator`;
+  //   terminal `,` becomes `comma`;
+  //   terminal `IDENTIFIER` becomes `identifier`;
+  //   terminal `INT` becomes `int`;
+  // NOTE: for nonterminals, the mangled name is the same as the cxx::Symbol
+  // enum class; for terminals, we deliberately stripped the `kw_` prefix in
+  // favor of the simplicity.
+  std::string mangleSymbol(SymbolID) const;
+  // Gets the mangled name for the rule.
+  // E.g. for the grammar rule `ptr-declarator := ptr-operator ptr-declarator`,
+  // it is `ptr_declarator_0ptr_operator_1ptr_declarator`.
+  std::string mangleRule(RuleID) const;
+
   // Lookup the SymbolID of the nonterminal symbol by Name.
   llvm::Optional findNonterminal(llvm::StringRef Name) const;
 

diff  --git a/clang-tools-extra/pseudo/lib/grammar/Grammar.cpp 
b/clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
index 149d97f28a778..da4e2dfd7a542 100644
--- a/clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
+++ b/clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
@@ -45,6 +45,28 @@ llvm::StringRef Grammar::symbolName(SymbolID SID) const {
   return T->Nonterminals[SID].Name;
 }
 
+std::string Grammar::mangleSymbol(SymbolID SID) const {
+  static const char *const TokNames[] = {
+#define TOK(X) #X,
+#define KEYWORD(X, Y) #X,
+#include "clang/Basic/TokenKinds.def"
+  nullptr};
+  if (clang::pseudo::isToken(SID))
+

[PATCH] D129359: [pseudo] Generate an enum type for identifying grammar rules.

2022-07-15 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h:172
+  //   terminal `,` becomes `comma`;
+  //   terminal `INT` becomes `int`;
+  std::string mangleSymbol(SymbolID) const;

sammccall wrote:
> I hope you mean kw_int? I'd like this to compile :-)
> 
> Can you also give the example for IDENTIFIER?
As discussed offline, we stick to the current version without `kw_` prefix. 
Added some comments for this decision.



Comment at: clang-tools-extra/pseudo/lib/grammar/Grammar.cpp:48
 
+std::string Grammar::mangleSymbol(SymbolID SID) const {
+  static const char *const TokNames[] = {

sammccall wrote:
> I'm not sure exposing these from `Grammar` is an improvement, i think even in 
> principle we'd only want to use these for codegen.
> 
> The need for testing is real, but i guess you can add a test that uses the 
> CXX generated grammar, assert the elements of Rule::whatever, and the name of 
> Symbol::whatever?
Yeah, these functions are only used in the codegen. I'm inlined to the put it 
into the `Grammar`(it also has a `symbolName` definition, I'd prefer to have 
all naming functions in a single place). 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129359

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


[PATCH] D129359: [pseudo] Generate an enum type for identifying grammar rules.

2022-07-15 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 444956.
hokein marked 2 inline comments as done.
hokein added a comment.

update.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129359

Files:
  clang-tools-extra/pseudo/gen/Main.cpp
  clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
  clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
  clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
  clang-tools-extra/pseudo/unittests/GrammarTest.cpp

Index: clang-tools-extra/pseudo/unittests/GrammarTest.cpp
===
--- clang-tools-extra/pseudo/unittests/GrammarTest.cpp
+++ clang-tools-extra/pseudo/unittests/GrammarTest.cpp
@@ -114,6 +114,21 @@
   EXPECT_NE(G.lookupRule(ruleFor("x")).Guard, G.lookupRule(ruleFor("y")).Guard);
 }
 
+TEST_F(GrammarTest, MangleName) {
+  build(R"bnf(
+_ := declaration
+
+declaration := ptr-declarator ;
+ptr-declarator := * IDENTIFIER
+
+  )bnf");
+  ASSERT_TRUE(Diags.empty());
+  EXPECT_EQ(G.mangleRule(ruleFor("declaration")),
+"declaration_0ptr_declarator_1semi");
+  EXPECT_EQ(G.mangleRule(ruleFor("ptr-declarator")),
+"ptr_declarator_0star_1identifier");
+}
+
 TEST_F(GrammarTest, Diagnostics) {
   build(R"cpp(
 _ := ,_opt
Index: clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
===
--- clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
+++ clang-tools-extra/pseudo/lib/grammar/Grammar.cpp
@@ -45,6 +45,28 @@
   return T->Nonterminals[SID].Name;
 }
 
+std::string Grammar::mangleSymbol(SymbolID SID) const {
+  static const char *const TokNames[] = {
+#define TOK(X) #X,
+#define KEYWORD(X, Y) #X,
+#include "clang/Basic/TokenKinds.def"
+  nullptr};
+  if (clang::pseudo::isToken(SID))
+return TokNames[clang::pseudo::symbolToToken(SID)];
+  std::string Name = symbolName(SID).str();
+  // translation-unit -> translation_unit
+  std::replace(Name.begin(), Name.end(), '-', '_');
+  return Name;
+}
+
+std::string Grammar::mangleRule(RuleID RID) const {
+  const auto  = lookupRule(RID);
+  std::string MangleName = mangleSymbol(R.Target);
+  for (size_t I = 0; I < R.seq().size(); ++I)
+MangleName += llvm::formatv("_{0}{1}", I, mangleSymbol(R.seq()[I]));
+  return MangleName;
+}
+
 llvm::Optional Grammar::findNonterminal(llvm::StringRef Name) const {
   auto It = llvm::partition_point(
   T->Nonterminals,
Index: clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
===
--- clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
+++ clang-tools-extra/pseudo/include/clang-pseudo/grammar/Grammar.h
@@ -165,6 +165,21 @@
   // Terminals have names like "," (kw_comma) or "OPERATOR" (kw_operator).
   llvm::StringRef symbolName(SymbolID) const;
 
+  // Gets the mangled name for a terminal/nonterminal.
+  // Compared to names in the grammar,
+  //   nonterminals `ptr-declartor` becomes `ptr_declarator`;
+  //   terminal `,` becomes `comma`;
+  //   terminal `IDENTIFIER` becomes `identifier`;
+  //   terminal `INT` becomes `int`;
+  // NOTE: for nonterminals, the mangled name is the same as the cxx::Symbol
+  // enum class; for terminals, we deliberately stripped the `kw_` prefix in
+  // favor of the simplicity.
+  std::string mangleSymbol(SymbolID) const;
+  // Gets the mangled name for the rule.
+  // E.g. for the grammar rule `ptr-declarator := ptr-operator ptr-declarator`,
+  // it is `ptr_declarator_0ptr_operator_1ptr_declarator`.
+  std::string mangleRule(RuleID) const;
+
   // Lookup the SymbolID of the nonterminal symbol by Name.
   llvm::Optional findNonterminal(llvm::StringRef Name) const;
 
Index: clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
===
--- clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
+++ clang-tools-extra/pseudo/include/clang-pseudo/cxx/CXX.h
@@ -37,6 +37,12 @@
 #undef NONTERMINAL
 };
 
+enum class Rule : RuleID {
+#define RULE(X, Y) X = Y,
+#include "CXXSymbols.inc"
+#undef RULE
+};
+
 enum class Extension : ExtensionID {
 #define EXTENSION(X, Y) X = Y,
 #include "CXXSymbols.inc"
Index: clang-tools-extra/pseudo/gen/Main.cpp
===
--- clang-tools-extra/pseudo/gen/Main.cpp
+++ clang-tools-extra/pseudo/gen/Main.cpp
@@ -83,17 +83,19 @@
 #ifndef NONTERMINAL
 #define NONTERMINAL(X, Y)
 #endif
+#ifndef RULE
+#define RULE(X, Y)
+#endif
 #ifndef EXTENSION
 #define EXTENSION(X, Y)
 #endif
-)cpp";
+)cpp";
 for (clang::pseudo::SymbolID ID = 0; ID < G.table().Nonterminals.size();
- ++ID) {
-  std::string Name = G.symbolName(ID).str();
-  // translation-unit -> translation_unit
-  std::replace(Name.begin(), Name.end(), '-', '_');
-  Out.os() << llvm::formatv("NONTERMINAL({0}, 

  1   2   >