[PATCH] D125037: [pseudo] Add fuzzer for the pseudoparser.

2022-05-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added a comment.
This revision is now accepted and ready to land.

Nice!




Comment at: clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp:81
+  bool PrintForest = false;
+  unsigned O = 1;
+  for (int I = 1; I < *Argc; ++I) {

nit: I'd suggest using another name -- `O` looks similar to the number literal 
`0`.  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125037

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


[PATCH] D125064: [clang-format][NFC] Make all TokenAnnotator member functions const

2022-05-05 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius 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/D125064/new/

https://reviews.llvm.org/D125064

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


[PATCH] D125026: [clang-tidy][NFC] Reimplement most of SimplifyBooleanExpr with RecursiveASTVisitors

2022-05-05 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 427529.
njames93 added a comment.

Remove unnecessary tests in ReadabilityTidyModule now that the 
SimplifyBooleanExprMatchers header has been removed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
  clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp

Index: clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
===
--- clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
+++ clang-tools-extra/unittests/clang-tidy/ReadabilityModuleTest.cpp
@@ -2,8 +2,6 @@
 #include "ClangTidyTest.h"
 #include "readability/BracesAroundStatementsCheck.h"
 #include "readability/NamespaceCommentCheck.h"
-#include "readability/SimplifyBooleanExprMatchers.h"
-#include "clang/ASTMatchers/ASTMatchers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
@@ -14,91 +12,6 @@
 using readability::NamespaceCommentCheck;
 using namespace ast_matchers;
 
-TEST_P(ASTMatchersTest, HasCaseSubstatement) {
-  EXPECT_TRUE(matches(
-  "void f() { switch (1) { case 1: return; break; default: break; } }",
-  traverse(TK_AsIs, caseStmt(hasSubstatement(returnStmt());
-}
-
-TEST_P(ASTMatchersTest, HasDefaultSubstatement) {
-  EXPECT_TRUE(matches(
-  "void f() { switch (1) { case 1: return; break; default: break; } }",
-  traverse(TK_AsIs, defaultStmt(hasSubstatement(breakStmt());
-}
-
-TEST_P(ASTMatchersTest, HasLabelSubstatement) {
-  EXPECT_TRUE(
-  matches("void f() { while (1) { bar: break; foo: return; } }",
-  traverse(TK_AsIs, labelStmt(hasSubstatement(breakStmt());
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceSimple) {
-  const char *Text = "int f() { int x = 5; if (x < 0) return 1; return 0; }";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), labelStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(returnStmt(), ifStmt();
-  EXPECT_FALSE(matches(
-  Text, compoundStmt(hasSubstatementSequence(switchStmt(), labelStmt();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceAlmost) {
-  const char *Text = R"code(
-int f() {
-  int x = 5;
-  if (x < 10)
-;
-  if (x < 0)
-return 1;
-  return 0;
-}
-)code";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_TRUE(
-  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), ifStmt();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceComplex) {
-  const char *Text = R"code(
-int f() {
-  int x = 5;
-  if (x < 10)
-x -= 10;
-  if (x < 0)
-return 1;
-  return 0;
-}
-)code";
-  EXPECT_TRUE(matches(
-  Text, compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt();
-  EXPECT_FALSE(
-  matches(Text, compoundStmt(hasSubstatementSequence(ifStmt(), expr();
-}
-
-TEST_P(ASTMatchersTest, HasSubstatementSequenceExpression) {
-  const char *Text = R"code(
-int f() {
-  return ({ int x = 5;
-  int result;
-  if (x < 10)
-x -= 10;
-  if (x < 0)
-result = 1;
-  else
-result = 0;
-  result;
-});
-  }
-)code";
-  EXPECT_TRUE(
-  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), expr();
-  EXPECT_FALSE(
-  matches(Text, stmtExpr(hasSubstatementSequence(ifStmt(), returnStmt();
-}
-
 // Copied from ASTMatchersTests
 static std::vector allTestClangConfigs() {
   std::vector all_configs;
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
+++ /dev/null
@@ -1,68 +0,0 @@
-//===-- SimplifyBooleanExprMatchers.h - clang-tidy ===//
-//
-// 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/ASTMatchers/ASTMatchersInternal.h"
-#include "clang/ASTMatchers/ASTMatchersMacros.h"
-
-namespace clang {
-namespace ast_matchers {
-
-/// Matches the substatement associated with a case, default or label statement.
-///
-/// Given
-/// \code
-///   switch (1) { case 1: break; case 2: return; break; default: return; break;
-///   }
-///   foo: return;
-///   bar: break;
-/// \endcode
-///
-/// caseStmt(hasSubstatement(returnStmt()))
-///   matches 

[PATCH] D125059: [Lex] Don't assert when decoding invalid UCNs.

2022-05-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/pseudo/test/crash/bad-ucn.c:4
+// RUN: clang-pseudo -source=%s
+A\U

nit: this test seems duplicated with the one in unicode.c, I'd just remove it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125059

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


[PATCH] D104975: Implement P1949

2022-05-05 Thread Ade Durcov via Phabricator via cfe-commits
intractabilis added a comment.

In D104975#3493992 , @tahonermann 
wrote:

> Please refrain from such unhelpful comments.

Absolutely, no problem. It's great that my other comments were helpful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104975

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


[PATCH] D125061: [clang] A more robust way to attach comments

2022-05-05 Thread Argyrios Kyrtzidis via Phabricator via cfe-commits
akyrtzi added a comment.

Since the issue is specific to enumerators I would recommend against increasing 
the size of `DeclBase`, which would increase the size of every single `Decl` in 
the AST.

There are multiple ways to approach this:

- Consider whether bringing back the comma check just for enumerators would 
work.
- Check the enumerators from the parent `EnumDecl`. The number of enumerators 
inside an `EnumDecl` is usually relatively small, you can do measurements to 
see how the performance looks with actual code.
- If there is noticable performance regression:
  - Either add "previous enumerator" pointer in `EnumConstantDecl` (increases 
size of every `EnumConstantDecl` in the AST)
  - Or add "out-of-AST-decl" tracking via adding some `DenseMap` in 
`ASTContext` that is only populated when comments for enumerators of an 
`EnumDecl` are requested. There is much precedent for this, for example see 
these examples:

  /// A cache mapping from CXXRecordDecls to key functions.
  llvm::DenseMap KeyFunctions;
  
  /// Mapping from ObjCContainers to their ObjCImplementations.
  llvm::DenseMap ObjCImpls;
  
  /// Mapping from ObjCMethod to its duplicate declaration in the same
  /// interface.
  llvm::DenseMap 
ObjCMethodRedecls;
  
  /// Mapping from __block VarDecls to BlockVarCopyInit.
  llvm::DenseMap BlockVarCopyInits;
  

The benefit of a separate map is that it only takes additional memory when a 
particular functionality is requested.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125061

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


[PATCH] D121733: Clean pathnames in FileManager.

2022-05-05 Thread Paul Pluzhnikov via Phabricator via cfe-commits
ppluzhnikov updated this revision to Diff 427526.
ppluzhnikov added a comment.

Fix more UNIX and Winx64 failures.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121733

Files:
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
  clang-tools-extra/test/clang-apply-replacements/conflict.cpp
  clang-tools-extra/test/clang-apply-replacements/order-dependent.cpp
  clang-tools-extra/test/clang-tidy/checkers/abseil-no-internal-dependencies.cpp
  clang-tools-extra/test/clang-tidy/checkers/abseil-no-namespace.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability-identifier-naming-multiple-styles.cpp
  clang-tools-extra/test/modularize/ProblemsMissingHeader.modularize
  clang/bindings/python/tests/cindex/test_translation_unit.py
  clang/lib/Basic/FileManager.cpp
  clang/test/ClangScanDeps/header-search-pruning-transitive.c
  clang/test/Frontend/dependency-gen.c
  clang/test/Index/skip-parsed-bodies/compile_commands.json
  clang/test/Modules/cxx20-hu-04.cpp
  clang/test/Modules/cxx20-hu-05.cpp
  clang/test/Modules/cxx20-hu-06.cpp
  clang/test/Modules/filename.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp
  clang/unittests/Tooling/Syntax/TokensTest.cpp
  clang/unittests/Tooling/TransformerTest.cpp

Index: clang/unittests/Tooling/TransformerTest.cpp
===
--- clang/unittests/Tooling/TransformerTest.cpp
+++ clang/unittests/Tooling/TransformerTest.cpp
@@ -1622,21 +1622,22 @@
   return L.getFilePath() < R.getFilePath();
 });
 
-  ASSERT_EQ(Changes[0].getFilePath(), "./input.h");
-  EXPECT_THAT(Changes[0].getInsertedHeaders(), IsEmpty());
-  EXPECT_THAT(Changes[0].getRemovedHeaders(), IsEmpty());
+  const auto _h = Changes[1];
+  ASSERT_EQ(change_h.getFilePath(), "input.h");
+  EXPECT_THAT(change_h.getInsertedHeaders(), IsEmpty());
+  EXPECT_THAT(change_h.getRemovedHeaders(), IsEmpty());
   llvm::Expected UpdatedCode =
-  clang::tooling::applyAllReplacements(Header,
-   Changes[0].getReplacements());
+  clang::tooling::applyAllReplacements(Header, change_h.getReplacements());
   ASSERT_TRUE(static_cast(UpdatedCode))
   << "Could not update code: " << llvm::toString(UpdatedCode.takeError());
   EXPECT_EQ(format(*UpdatedCode), "");
 
-  ASSERT_EQ(Changes[1].getFilePath(), "input.cc");
-  EXPECT_THAT(Changes[1].getInsertedHeaders(), IsEmpty());
-  EXPECT_THAT(Changes[1].getRemovedHeaders(), IsEmpty());
-  UpdatedCode = clang::tooling::applyAllReplacements(
-  Source, Changes[1].getReplacements());
+  const auto _cc = Changes[0];
+  ASSERT_EQ(change_cc.getFilePath(), "input.cc");
+  EXPECT_THAT(change_cc.getInsertedHeaders(), IsEmpty());
+  EXPECT_THAT(change_cc.getRemovedHeaders(), IsEmpty());
+  UpdatedCode =
+  clang::tooling::applyAllReplacements(Source, change_cc.getReplacements());
   ASSERT_TRUE(static_cast(UpdatedCode))
   << "Could not update code: " << llvm::toString(UpdatedCode.takeError());
   EXPECT_EQ(format(*UpdatedCode), format("#include \"input.h\"\n"));
@@ -1659,7 +1660,7 @@
   {{"input.h", Header}}));
 
   ASSERT_EQ(Changes.size(), 1U);
-  ASSERT_EQ(Changes[0].getFilePath(), "./input.h");
+  ASSERT_EQ(Changes[0].getFilePath(), "input.h");
   EXPECT_THAT(Changes[0].getInsertedHeaders(), ElementsAre("header.h"));
   EXPECT_THAT(Changes[0].getRemovedHeaders(), IsEmpty());
   llvm::Expected UpdatedCode =
@@ -1708,7 +1709,7 @@
   ResultOf([](const AtomicChange ) { return C.getFilePath(); },
"input.cc"),
   ResultOf([](const AtomicChange ) { return C.getFilePath(); },
-   "./input.h";
+   "input.h";
 }
 
 TEST_F(TransformerTest, GeneratesMetadata) {
Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -292,7 +292,7 @@
   {"int main() {}",
R"(expanded tokens:
   int main ( ) { }
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 int main ( ) { }
   no mappings.
@@ -301,7 +301,7 @@
   {"\t\n  int\t\n  main\t\n  (\t\n  )\t\n{\t\n  }\t\n",
R"(expanded tokens:
   int main ( ) { }
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 int main ( ) { }
   no mappings.
@@ -313,7 +313,7 @@
   )cpp",
R"(expanded tokens:
   
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 # pragma GCC visibility push ( public ) # pragma GCC visibility pop
   mappings:
@@ -322,7 +322,7 @@
   // Empty files should not crash.
   {R"cpp()cpp", R"(expanded tokens:
   
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 
   no mappings.
@@ -336,7 +336,7 @@
 )cpp",
   R"(expanded tokens:
   a
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 

[PATCH] D123200: [compiler-rt][builtins] Add several helper functions for AVR

2022-05-05 Thread Ben Shi via Phabricator via cfe-commits
benshi001 added a comment.

In D123200#3495356 , @aykevl wrote:

> @benshi001 I have been looking through the GCC code and I think avr-gcc also 
> has a special calling convention for many other functions, including 
> `__mulqi3` and `__mulhi3`.
>
> Source:
>
> 1. I think this is where the ABI is specified in the compiler: 
> https://github.com/gcc-mirror/gcc/blob/releases/gcc-5.4.0/gcc/config/avr/avr.md#L1543-L1549
>  You can see that it multiplies R24 with R22 and stores the result in R24, 
> and clobbers R22 in the process. But no other registers.
> 2. In this code sample , avr-gcc doesn't 
> save `char c` (`r20`) across the `__mulqi3` and `__mulhi3` calls, which is 
> normally call-clobbered.
>
> Therefore, I think we need to be a bit more careful with defining these AVR 
> builtins and check the ABI in avr-gcc first.
> Also, we can make use of this and optimize the AVR backend more (you can see 
> that the Clang generated code is much worse than avr-gcc in the above 
> examples).

Let us discuss that at https://github.com/llvm/llvm-project/issues/55279


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123200

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


[PATCH] D124285: [clang][NFC] In parts of Objective-C Sema use Obj-C-specific types instead of `Decl`.

2022-05-05 Thread Volodymyr Sapsai via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG3b762b3ab8d2: [clang][NFC] In parts of Objective-C Sema use 
Obj-C-specific types instead of… (authored by vsapsai).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124285

Files:
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseObjc.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclObjC.cpp

Index: clang/lib/Sema/SemaDeclObjC.cpp
===
--- clang/lib/Sema/SemaDeclObjC.cpp
+++ clang/lib/Sema/SemaDeclObjC.cpp
@@ -971,7 +971,7 @@
   return false;
 }
 
-Decl *Sema::ActOnStartClassInterface(
+ObjCInterfaceDecl *Sema::ActOnStartClassInterface(
 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
 IdentifierInfo *SuperName, SourceLocation SuperLoc,
@@ -1100,7 +1100,8 @@
   }
 
   CheckObjCDeclScope(IDecl);
-  return ActOnObjCContainerStartDefinition(IDecl);
+  ActOnObjCContainerStartDefinition(IDecl);
+  return IDecl;
 }
 
 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
@@ -1208,7 +1209,7 @@
   return res;
 }
 
-Decl *Sema::ActOnStartProtocolInterface(
+ObjCProtocolDecl *Sema::ActOnStartProtocolInterface(
 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
@@ -1272,7 +1273,8 @@
   }
 
   CheckObjCDeclScope(PDecl);
-  return ActOnObjCContainerStartDefinition(PDecl);
+  ActOnObjCContainerStartDefinition(PDecl);
+  return PDecl;
 }
 
 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
@@ -1799,7 +1801,7 @@
   return BuildDeclaratorGroup(DeclsInGroup);
 }
 
-Decl *Sema::ActOnStartCategoryInterface(
+ObjCCategoryDecl *Sema::ActOnStartCategoryInterface(
 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
@@ -1826,7 +1828,8 @@
 
 if (!IDecl)
   Diag(ClassLoc, diag::err_undef_interface) << ClassName;
-return ActOnObjCContainerStartDefinition(CDecl);
+ActOnObjCContainerStartDefinition(CDecl);
+return CDecl;
   }
 
   if (!CategoryName && IDecl->getImplementation()) {
@@ -1889,17 +1892,17 @@
   }
 
   CheckObjCDeclScope(CDecl);
-  return ActOnObjCContainerStartDefinition(CDecl);
+  ActOnObjCContainerStartDefinition(CDecl);
+  return CDecl;
 }
 
 /// ActOnStartCategoryImplementation - Perform semantic checks on the
 /// category implementation declaration and build an ObjCCategoryImplDecl
 /// object.
-Decl *Sema::ActOnStartCategoryImplementation(
-  SourceLocation AtCatImplLoc,
-  IdentifierInfo *ClassName, SourceLocation ClassLoc,
-  IdentifierInfo *CatName, SourceLocation CatLoc,
-  const ParsedAttributesView ) {
+ObjCCategoryImplDecl *Sema::ActOnStartCategoryImplementation(
+SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
+SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
+const ParsedAttributesView ) {
   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
   ObjCCategoryDecl *CatIDecl = nullptr;
   if (IDecl && IDecl->hasDefinition()) {
@@ -1958,15 +1961,14 @@
   }
 
   CheckObjCDeclScope(CDecl);
-  return ActOnObjCContainerStartDefinition(CDecl);
+  ActOnObjCContainerStartDefinition(CDecl);
+  return CDecl;
 }
 
-Decl *Sema::ActOnStartClassImplementation(
-  SourceLocation AtClassImplLoc,
-  IdentifierInfo *ClassName, SourceLocation ClassLoc,
-  IdentifierInfo *SuperClassname,
-  SourceLocation SuperClassLoc,
-  const ParsedAttributesView ) {
+ObjCImplementationDecl *Sema::ActOnStartClassImplementation(
+SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
+SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
+SourceLocation SuperClassLoc, const ParsedAttributesView ) {
   ObjCInterfaceDecl *IDecl = nullptr;
   // Check for another declaration kind with the same name.
   NamedDecl *PrevDecl
@@ -2063,8 +2065,10 @@
   ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
   AddPragmaAttributes(TUScope, IMPDecl);
 
-  if (CheckObjCDeclScope(IMPDecl))
-return ActOnObjCContainerStartDefinition(IMPDecl);
+  if (CheckObjCDeclScope(IMPDecl)) {
+ActOnObjCContainerStartDefinition(IMPDecl);
+return IMPDecl;
+  }
 
   // Check that there is no duplicate implementation of this class.
   if (IDecl->getImplementation()) {
@@ -2090,7 +2094,8 @@
   << 

[clang] 3b762b3 - [clang][NFC] In parts of Objective-C Sema use Obj-C-specific types instead of `Decl`.

2022-05-05 Thread Volodymyr Sapsai via cfe-commits

Author: Volodymyr Sapsai
Date: 2022-05-05T19:19:41-07:00
New Revision: 3b762b3ab8d205cd6a7d42c96d39d5f4f701f2ab

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

LOG: [clang][NFC] In parts of Objective-C Sema use Obj-C-specific types instead 
of `Decl`.

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

Added: 


Modified: 
clang/include/clang/Parse/Parser.h
clang/include/clang/Sema/Sema.h
clang/lib/Parse/ParseObjc.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclObjC.cpp

Removed: 




diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 8f28eb30ad1dc..99fe375f9145f 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -447,7 +447,9 @@ class Parser : public CodeCompletionHandler {
 return Actions.incrementMSManglingNumber();
   }
 
-  Decl  *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
+  ObjCContainerDecl *getObjCDeclContext() const {
+return Actions.getObjCDeclContext();
+  }
 
   // Type forwarding.  All of these are statically 'void*', but they may all be
   // 
diff erent actual classes based on the actions in place.
@@ -1001,18 +1003,18 @@ class Parser : public CodeCompletionHandler {
   /// back.
   class ObjCDeclContextSwitch {
 Parser 
-Decl *DC;
+ObjCContainerDecl *DC;
 SaveAndRestore WithinObjCContainer;
   public:
 explicit ObjCDeclContextSwitch(Parser )
   : P(p), DC(p.getObjCDeclContext()),
 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) {
   if (DC)
-
P.Actions.ActOnObjCTemporaryExitContainerContext(cast(DC));
+P.Actions.ActOnObjCTemporaryExitContainerContext(DC);
 }
 ~ObjCDeclContextSwitch() {
   if (DC)
-P.Actions.ActOnObjCReenterContainerContext(cast(DC));
+P.Actions.ActOnObjCReenterContainerContext(DC);
 }
   };
 
@@ -1614,11 +1616,12 @@ class Parser : public CodeCompletionHandler {
   SmallVectorImpl ,
   SourceLocation , bool mayBeProtocolList = true);
 
-  void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation 
atLoc,
+  void HelperActionsForIvarDeclarations(ObjCContainerDecl *interfaceDecl,
+SourceLocation atLoc,
 BalancedDelimiterTracker ,
 SmallVectorImpl ,
 bool RBraceMissing);
-  void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
+  void ParseObjCClassInstanceVariables(ObjCContainerDecl *interfaceDecl,
tok::ObjCKeywordKind visibility,
SourceLocation atLoc);
   bool ParseObjCProtocolReferences(SmallVectorImpl ,

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 44fbffdda3900..27603f0b891f3 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3285,7 +3285,7 @@ class Sema final {
   /// Invoked when we enter a tag definition that we're skipping.
   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
 
-  Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
+  void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl);
 
   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
   /// C++ record definition's base-specifiers clause and are starting its
@@ -3309,8 +3309,8 @@ class Sema final {
   /// scope for parsing/looking-up C constructs.
   ///
   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
-  void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
-  void ActOnObjCReenterContainerContext(DeclContext *DC);
+  void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx);
+  void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx);
 
   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
   /// error parsing the definition of a tag.
@@ -9738,7 +9738,7 @@ class Sema final {
 SourceLocation rAngleLoc);
   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
 
-  Decl *ActOnStartClassInterface(
+  ObjCInterfaceDecl *ActOnStartClassInterface(
   Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
   SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
   IdentifierInfo *SuperName, SourceLocation SuperLoc,
@@ -9772,13 +9772,13 @@ class Sema final {
 SourceLocation , SourceLocation PrevLoc,
 const ObjCList );
 
-  Decl *ActOnStartProtocolInterface(
+  ObjCProtocolDecl *ActOnStartProtocolInterface(
   SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,

[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Jez Ng via Phabricator via cfe-commits
int3 marked 3 inline comments as done.
int3 added inline comments.



Comment at: clang/lib/CodeGen/BackendUtil.cpp:456
   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
+  Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;

int3 wrote:
> smeenai wrote:
> > smeenai wrote:
> > > int3 wrote:
> > > > smeenai wrote:
> > > > > int3 wrote:
> > > > > > this code doesn't execute if clang is passed an assembly file 
> > > > > > instead of a .c file, so this option doesn't have the desired 
> > > > > > effect on assembly inputs. I'm not sure what's the right way to 
> > > > > > tackle this, or if this behavior inconsistency is acceptable
> > > > > > 
> > > > > > 
> > > > > It seems unfortunate to have that inconsistency. From what I can 
> > > > > tell, clang/tools/driver/cc1as_main.cpp looks like it might be the 
> > > > > rough equivalent of this for the integrated assembler?
> > > > that's what I'd thought too, but I set a breakpoint on `cc1as_main` & 
> > > > `ExecuteAssemblerImpl` and then ran `clang -c foo.s`; neither 
> > > > breakpoint triggered
> > > Hmm, interesting. If you run with `-###`, is `-cc1as` being invoked 
> > > in-process or out of process? Idk if the in-process cc1as has a different 
> > > entry point.
> > Nah, looks like in-process cc1as should be calling `cc1as_main` as well: 
> > https://github.com/llvm/llvm-project/blob/98616cfc02613d98964588fac6494ec7583c495f/clang/tools/driver/driver.cpp#L319
> > 
> > (If it's out of process you'd need to debug the cc1as process and not the 
> > driver process, of course, but I'd be surprised if you end up with an out 
> > of process cc1as)
> ah yeah I guess that's it. I'd enabled `settings set 
> target.process.follow-fork-mode child` but that doesn't seem to have the 
> desired effect; but modifying cc1as_main itself shows that it is indeed being 
> called.
alright this works now, thanks for the pointers!



Comment at: clang/tools/driver/cc1as_main.cpp:323
 
+  if (auto *A = Args.getLastArg(OPT_femit_dwarf_unwind_EQ)) {
+Opts.EmitDwarfUnwind =

this is a bit of code duplication, but the same approach is used to have 
`OPT_fembed_bitcode_EQ` accepted by both the integrated assembler as will as 
the CompilerInvocation.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

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


[PATCH] D125061: [clang] A more robust way to attach comments

2022-05-05 Thread Zixu Wang via Phabricator via cfe-commits
zixuw added a comment.

Well, apparently there are still some corner-case bugs in the logic. ExtractAPI 
and a few other tests failed. Will look into it tomorrow.

And if folks have concerns or opinions of the performance/space cost of adding 
the extra pointer to `DeclBase`, I can try to keep the original logic and just 
special-case enum constants to find the previous enum constant decl in the 
parent enum. Not sure if there are existing ways to get preceding enum 
constants efficiently, otherwise it'd be an O(n^2) operation for an enum.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125061

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


[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Jez Ng via Phabricator via cfe-commits
int3 updated this revision to Diff 427509.
int3 added a comment.

make things work under cc1as too


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/femit-dwarf-unwind.c
  clang/test/Driver/femit-dwarf-unwind.s
  clang/tools/driver/cc1as_main.cpp
  llvm/include/llvm/MC/MCContext.h
  llvm/include/llvm/MC/MCTargetOptions.h
  llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h
  llvm/lib/CodeGen/LLVMTargetMachine.cpp
  llvm/lib/CodeGen/MachineModuleInfo.cpp
  llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp
  llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp
  llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp
  llvm/lib/MC/MCContext.cpp
  llvm/lib/MC/MCDwarf.cpp
  llvm/lib/MC/MCObjectFileInfo.cpp
  llvm/lib/MC/MCTargetOptions.cpp
  llvm/lib/MC/MCTargetOptionsCommandFlags.cpp
  llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
  llvm/test/MC/MachO/force-dwarf-unwind.s
  llvm/test/MC/X86/compact-unwind-mode-dwarf.s

Index: llvm/test/MC/X86/compact-unwind-mode-dwarf.s
===
--- /dev/null
+++ llvm/test/MC/X86/compact-unwind-mode-dwarf.s
@@ -0,0 +1,50 @@
+// RUN: llvm-mc -triple x86_64-apple-macos10.6 -filetype=obj %s -o %t.o
+// RUN: llvm-objdump --macho --unwind-info --dwarf=frames %t.o | FileCheck %s
+
+/// For functions whose unwind info cannot be encoded with compact unwind, make
+/// sure that we encode them using DWARF unwind, and make sure we emit a compact
+/// unwind entry that indicates that a DWARF encoding is being used.
+
+_f:
+  .cfi_startproc
+  ## This encodes DW_CFA_GNU_args_size which cannot be expressed using compact
+  ## unwind, so we must use DWARF unwind instead.
+  .cfi_escape 0x2e, 0x10
+  ret
+  .cfi_endproc
+
+_g:
+  .cfi_startproc
+  ## This encodes DW_CFA_GNU_args_size which cannot be expressed using compact
+  ## unwind, so we must use DWARF unwind instead.
+  .cfi_escape 0x2e, 0x10
+  ret
+  .cfi_endproc
+
+// CHECK: Contents of __compact_unwind section:
+// CHECK:   Entry at offset 0x0:
+// CHECK: start:0x[[#%x,F:]] _f
+// CHECK: length:   0x1
+// CHECK: compact encoding: 0x0400
+// CHECK:   Entry at offset 0x20:
+// CHECK: start:0x[[#%x,G:]] _g
+// CHECK: length:   0x1
+// CHECK: compact encoding: 0x0400
+
+// CHECK: .eh_frame contents:
+// CHECK:  0014  CIE
+// CHECK:   Format:DWARF32
+// CHECK:   Version:   1
+// CHECK:   Augmentation:  "zR"
+// CHECK:   Code alignment factor: 1
+// CHECK:   Data alignment factor: -8
+// CHECK:   Return address column: 16
+// CHECK:   Augmentation data: 10
+
+// CHECK: FDE cie= pc=[[#%.8x,F]]...
+// CHECK:   Format:   DWARF32
+// CHECK:   DW_CFA_GNU_args_size: +16
+
+// CHECK: FDE cie= pc=[[#%.8x,G]]...
+// CHECK:   Format:   DWARF32
+// CHECK:   DW_CFA_GNU_args_size: +16
Index: llvm/test/MC/MachO/force-dwarf-unwind.s
===
--- /dev/null
+++ llvm/test/MC/MachO/force-dwarf-unwind.s
@@ -0,0 +1,33 @@
+// RUN: rm -rf %t; mkdir %t
+// RUN: llvm-mc -triple x86_64-apple-macos11.0 %s -filetype=obj -o %t/x86_64.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/x86_64.o | FileCheck %s --check-prefix TWO-FDES
+// RUN: llvm-mc -triple arm64-apple-macos11.0 %s -filetype=obj -o %t/arm64.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/arm64.o | FileCheck %s --check-prefix ONE-FDE
+// RUN: llvm-mc -triple x86_64-apple-macos11.0 %s -filetype=obj --emit-dwarf-unwind no-compact-unwind -o %t/x86_64-no-dwarf.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/x86_64-no-dwarf.o | FileCheck %s --check-prefix ONE-FDE
+// RUN: llvm-mc -triple arm64-apple-macos11.0 %s -filetype=obj --emit-dwarf-unwind always -o %t/arm64-dwarf.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/arm64-dwarf.o | FileCheck %s --check-prefix TWO-FDES
+
+// TWO-FDES: FDE
+// TWO-FDES: FDE
+
+// ONE-FDE-NOT: FDE
+// ONE-FDE: FDE
+// ONE-FDE-NOT: FDE
+
+_main:
+  .cfi_startproc
+  .cfi_def_cfa_offset 16
+  ret
+  .cfi_endproc
+
+_foo:
+  .cfi_startproc
+  .cfi_def_cfa_offset 16
+  /// This encodes DW_CFA_GNU_args_size which cannot be expressed using compact
+  /// unwind, so we must use DWARf unwind for this function.
+  .cfi_escape 0x2e, 0x10
+  ret
+  .cfi_endproc
+
+.subsections_via_symbols
Index: llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
===
--- llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
+++ llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
@@ -1377,7 +1377,7 @@
   default:
 // Any other CFI directives indicate a frame 

[PATCH] D125064: [clang-format][NFC] Make all TokenAnnotator member functions const

2022-05-05 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: curdeius, HazardyKnusperkeks, MyDeveloperDay.
owenpan added a project: clang-format.
Herald added a project: All.
owenpan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125064

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/TokenAnnotator.h

Index: clang/lib/Format/TokenAnnotator.h
===
--- clang/lib/Format/TokenAnnotator.h
+++ clang/lib/Format/TokenAnnotator.h
@@ -161,43 +161,46 @@
   /// Adapts the indent levels of comment lines to the indent of the
   /// subsequent line.
   // FIXME: Can/should this be done in the UnwrappedLineParser?
-  void setCommentLineLevels(SmallVectorImpl );
+  void setCommentLineLevels(SmallVectorImpl ) const;
 
-  void annotate(AnnotatedLine );
-  void calculateFormattingInformation(AnnotatedLine );
+  void annotate(AnnotatedLine ) const;
+  void calculateFormattingInformation(AnnotatedLine ) const;
 
 private:
   /// Calculate the penalty for splitting before \c Tok.
   unsigned splitPenalty(const AnnotatedLine , const FormatToken ,
-bool InFunctionDecl);
+bool InFunctionDecl) const;
 
   bool spaceRequiredBeforeParens(const FormatToken ) const;
 
   bool spaceRequiredBetween(const AnnotatedLine , const FormatToken ,
-const FormatToken );
+const FormatToken ) const;
 
-  bool spaceRequiredBefore(const AnnotatedLine , const FormatToken );
+  bool spaceRequiredBefore(const AnnotatedLine ,
+   const FormatToken ) const;
 
-  bool mustBreakBefore(const AnnotatedLine , const FormatToken );
+  bool mustBreakBefore(const AnnotatedLine ,
+   const FormatToken ) const;
 
-  bool canBreakBefore(const AnnotatedLine , const FormatToken );
+  bool canBreakBefore(const AnnotatedLine ,
+  const FormatToken ) const;
 
   bool mustBreakForReturnType(const AnnotatedLine ) const;
 
-  void printDebugInfo(const AnnotatedLine );
+  void printDebugInfo(const AnnotatedLine ) const;
 
-  void calculateUnbreakableTailLengths(AnnotatedLine );
+  void calculateUnbreakableTailLengths(AnnotatedLine ) const;
 
-  void calculateArrayInitializerColumnList(AnnotatedLine );
+  void calculateArrayInitializerColumnList(AnnotatedLine ) const;
 
   FormatToken *calculateInitializerColumnList(AnnotatedLine ,
   FormatToken *CurrentToken,
-  unsigned Depth);
+  unsigned Depth) const;
   FormatStyle::PointerAlignmentStyle
-  getTokenReferenceAlignment(const FormatToken );
+  getTokenReferenceAlignment(const FormatToken ) const;
 
-  FormatStyle::PointerAlignmentStyle
-  getTokenPointerOrReferenceAlignment(const FormatToken );
+  FormatStyle::PointerAlignmentStyle getTokenPointerOrReferenceAlignment(
+  const FormatToken ) const;
 
   const FormatStyle 
 
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -2523,7 +2523,7 @@
 } // end anonymous namespace
 
 void TokenAnnotator::setCommentLineLevels(
-SmallVectorImpl ) {
+SmallVectorImpl ) const {
   const AnnotatedLine *NextNonCommentLine = nullptr;
   for (AnnotatedLine *Line : llvm::reverse(Lines)) {
 assert(Line->First);
@@ -2558,7 +2558,7 @@
   return Result;
 }
 
-void TokenAnnotator::annotate(AnnotatedLine ) {
+void TokenAnnotator::annotate(AnnotatedLine ) const {
   for (auto  : Line.Children)
 annotate(*Child);
 
@@ -2725,7 +2725,7 @@
   return false;
 }
 
-void TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) {
+void TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
   for (AnnotatedLine *ChildLine : Line.Children)
 calculateFormattingInformation(*ChildLine);
 
@@ -2845,7 +2845,8 @@
   LLVM_DEBUG({ printDebugInfo(Line); });
 }
 
-void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine ) {
+void TokenAnnotator::calculateUnbreakableTailLengths(
+AnnotatedLine ) const {
   unsigned UnbreakableTailLength = 0;
   FormatToken *Current = Line.Last;
   while (Current) {
@@ -2861,7 +2862,8 @@
   }
 }
 
-void TokenAnnotator::calculateArrayInitializerColumnList(AnnotatedLine ) {
+void TokenAnnotator::calculateArrayInitializerColumnList(
+AnnotatedLine ) const {
   if (Line.First == Line.Last)
 return;
   auto *CurrentToken = Line.First;
@@ -2881,7 +2883,7 @@
 }
 
 FormatToken *TokenAnnotator::calculateInitializerColumnList(
-AnnotatedLine , FormatToken *CurrentToken, unsigned Depth) {
+AnnotatedLine , FormatToken *CurrentToken, unsigned Depth) const {
   while (CurrentToken != nullptr && 

[PATCH] D118355: Add -mmanual-endbr switch to allow manual selection of control-flow protection

2022-05-05 Thread Xiang Zhang via Phabricator via cfe-commits
xiangzhangllvm added inline comments.



Comment at: llvm/lib/Target/X86/X86IndirectBranchTracking.cpp:156-161
   if (needsPrologueENDBR(MF, M)) {
-auto MBB = MF.begin();
-Changed |= addENDBR(*MBB, MBB->begin());
+if (!ManualENDBR || MF.getFunction().doesCfCheck()) {
+  auto MBB = MF.begin();
+  Changed |= addENDBR(*MBB, MBB->begin());
+} else {
+  // When -mmanual-endbr is in effect, the compiler does not

I am a little puzzle here. Let me copy your patch description here:

```
>When -mmanual-endbr is set, llvm refrains from automatically adding
>ENDBR instructions to functions' prologues, which would have been
>automatically added by -fcf-protection=branch. Although this works
>correctly, missing ENDBR instructions where they are actually needed
>could lead to broken binaries, which would fail only in running time.
```
I think the purpose of "-mmanual-endbr" should be "Supplementary Way" for the 
cases which the CET can't correctly insert endbr in automatic way.
Here (in if (needsPrologueENDBR(MF, M)) ) the automatic way will insert the 
endbr. So I think the job for "-mmanual-endbr" should be done in parallel with 
the old condition. Some like:
```
if (ManualENDBR ){
  do something
}else { // automatic
  if (needsPrologueENDBR(MF, M)) {insert endbr}
 }
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118355

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


[PATCH] D125061: [clang] A more robust way to attach comments

2022-05-05 Thread Zixu Wang via Phabricator via cfe-commits
zixuw created this revision.
Herald added a subscriber: arphaman.
Herald added a reviewer: dang.
Herald added a project: All.
zixuw requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The current implementation in `getRawCommentForDeclNoCacheImpl` to check
if a leading comment is attached to a given `Decl *D` is to see if there
is any of `";{}#@"` between the comment and the source location of `D`,
which indicates that there's other declarations or preprocessor
directives that the comment is meant for. However, this does not work
for enum constants, which are separated by commas.
Comma was originally included in the filter characters list, but removed
in b534d3a0ef69 because macros, attributes and other decorators might
also introduce commas before a declaration. And there's no good way to
reliably and efficiently check if all the commas are from other
declarations.
This patch added a forward pointer in `DeclBase` pointing to the
previous declaration inside the lexical `DeclContext`, similar to the
existing `NextInContextAndBits`. This constructs a doubly linked list so
we can easily query the lexically preceding declaration of the current
decl `D`, to check if any decl falls between the comment and `D`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125061

Files:
  clang/include/clang/AST/DeclBase.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/DeclBase.cpp
  clang/test/Index/annotate-comments-enum-constant.c
  clang/test/Index/annotate-comments.cpp

Index: clang/test/Index/annotate-comments.cpp
===
--- clang/test/Index/annotate-comments.cpp
+++ clang/test/Index/annotate-comments.cpp
@@ -254,6 +254,14 @@
 MYMAC(0,0)
 void isdoxy54(int);
 
+/// IS_DOXYGEN_SINGLE
+struct isdoxy55 {
+  int notdoxy48;
+  /// IS_DOXYGEN_SINGLE
+  int isdoxy56;
+};
+bool notdoxy49;
+
 #endif
 
 // RUN: rm -rf %t
@@ -337,3 +345,6 @@
 // CHECK: annotate-comments.cpp:241:6: FunctionDecl=isdoxy52:{{.*}} BriefComment=[Aaa. IS_DOXYGEN_START Bbb.]
 // CHECK: annotate-comments.cpp:248:6: FunctionDecl=isdoxy53:{{.*}} BriefComment=[Aaa. IS_DOXYGEN_START IS_DOXYGEN_END]
 // CHECK: annotate-comments.cpp:255:6: FunctionDecl=isdoxy54:{{.*}} BriefComment=[Aaa. IS_DOXYGEN_START IS_DOXYGEN_END]
+
+// CHECK: annotate-comments.cpp:258:8: StructDecl=isdoxy55:{{.*}} IS_DOXYGEN_SINGLE
+// CHECK: annotate-comments.cpp:261:7: FieldDecl=isdoxy56:{{.*}} IS_DOXYGEN_SINGLE
Index: clang/test/Index/annotate-comments-enum-constant.c
===
--- /dev/null
+++ clang/test/Index/annotate-comments-enum-constant.c
@@ -0,0 +1,16 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng %s > %t/out
+// RUN: FileCheck %s --dump-input always < %t/out
+
+enum {
+  /// Documentation for Foo
+  Foo,
+  Bar, // No documentation for Bar
+  /// Documentation for Baz
+  Baz,
+};
+// CHECK: EnumConstantDecl=Foo:[[@LINE-5]]:3 (Definition) {{.*}} BriefComment=[Documentation for Foo] FullCommentAsHTML=[ Documentation for Foo] FullCommentAsXML=[Fooc:@Ea@Foo@FooFoo Documentation for Foo]
+// CHECK: EnumConstantDecl=Bar:[[@LINE-5]]:3 (Definition)
+// CHECK-NOT: BriefComment=[Documentation for Foo]
+// CHECK: EnumConstantDecl=Baz:[[@LINE-5]]:3 (Definition) {{.*}} BriefComment=[Documentation for Baz] FullCommentAsHTML=[ Documentation for Baz] FullCommentAsXML=[Bazc:@Ea@Foo@BazBaz Documentation for Baz]
Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -1344,6 +1344,7 @@
 else
   FirstNewDecl = D;
 
+D->PreviousInContext = PrevDecl;
 PrevDecl = D;
   }
 
@@ -1392,6 +1393,8 @@
   std::tie(ExternalFirst, ExternalLast) =
   BuildDeclChain(Decls, FieldsAlreadyLoaded);
   ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
+  if (FirstDecl)
+FirstDecl->PreviousInContext = ExternalLast;
   FirstDecl = ExternalFirst;
   if (!LastDecl)
 LastDecl = ExternalLast;
@@ -1498,25 +1501,26 @@
   assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
  "decl is not in decls list");
 
-  // Remove D from the decl chain.  This is O(n) but hopefully rare.
+  // Remove D from the decl chain.
   if (D == FirstDecl) {
 if (D == LastDecl)
   FirstDecl = LastDecl = nullptr;
 else
   FirstDecl = D->NextInContextAndBits.getPointer();
-  } else {
-for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
-  assert(I && "decl not found in linked list");
-  if (I->NextInContextAndBits.getPointer() == D) {
-I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
-if (D == LastDecl) LastDecl = I;
-break;
-  }
-}
+  }
+
+  if (auto *Next = 

[PATCH] D125050: [OpenMP] Try to Infer target triples using the offloading architecture

2022-05-05 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 marked 3 inline comments as done.
jhuber6 added inline comments.



Comment at: clang/lib/Driver/Driver.cpp:788-789
+   options::OPT_fno_openmp, false) &&
+  (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ) ||
+   C.getInputArgs().hasArg(options::OPT_offload_arch_EQ));
+  if (IsOpenMP) {

tra wrote:
> So, specifying just `-fopenmp` will result in `IsOpenMP=false`? This seems 
> odd.
> Perhaps the variable should be called `IsOpenMPOffload` ? 
Will do.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125050

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


[PATCH] D125050: [OpenMP] Try to Infer target triples using the offloading architecture

2022-05-05 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 427496.
jhuber6 added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125050

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/openmp-offload-infer.c

Index: clang/test/Driver/openmp-offload-infer.c
===
--- /dev/null
+++ clang/test/Driver/openmp-offload-infer.c
@@ -0,0 +1,44 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp \
+// RUN:  --offload-arch=sm_52 --offload-arch=gfx803 \
+// RUN:  --libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib/libomptarget-amdgpu-gfx803.bc \
+// RUN:  --libomptarget-nvptx-bc-path=%S/Inputs/libomptarget/libomptarget-nvptx-test.bc %s 2>&1 \
+// RUN:   | FileCheck %s
+
+// verify the tools invocations
+// CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-llvm-bc"{{.*}}"-x" "c"
+// CHECK: "-cc1" "-triple" "amdgcn-amd-amdhsa" "-aux-triple" "x86_64-unknown-linux-gnu"{{.*}}"-target-cpu" "gfx803"
+// CHECK: "-cc1" "-triple" "nvptx64-nvidia-cuda" "-aux-triple" "x86_64-unknown-linux-gnu"{{.*}}"-target-cpu" "sm_52"
+// CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-obj"
+// CHECK: clang-linker-wrapper{{.*}}"--"{{.*}} "-o" "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: --offload-arch=sm_70 --offload-arch=gfx908:sramecc+:xnack- \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-NVIDIA-AMDGPU
+
+// CHECK-NVIDIA-AMDGPU: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[HOST_BC:.+]]"
+// CHECK-NVIDIA-AMDGPU: "amdgcn-amd-amdhsa" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[AMD_BC:.+]]"
+// CHECK-NVIDIA-AMDGPU: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[NVIDIA_PTX:.+]]"
+// CHECK-NVIDIA-AMDGPU: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[NVIDIA_PTX]]"], output: "[[NVIDIA_CUBIN:.+]]"
+// CHECK-NVIDIA-AMDGPU: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[HOST_BC]]", "[[AMD_BC]]", "[[NVIDIA_CUBIN]]"], output: "[[HOST_OBJ:.+]]"
+// CHECK-NVIDIA-AMDGPU: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-ARCH-BINDINGS
+
+// CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.*]]"], output: "[[HOST_BC:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[DEVICE_BC_SM_52:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_BC_SM_52]]"], output: "[[DEVICE_OBJ_SM_52:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[DEVICE_BC_SM_70:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_BC_SM_70]]"], output: "[[DEVICE_OBJ_SM_70:.*]]"
+// CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[HOST_BC]]", "[[DEVICE_OBJ_SM_52]]", "[[DEVICE_OBJ_SM_70]]"], output: "[[HOST_OBJ:.*]]"
+// CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: --offload-arch=sm_70 --offload-arch=gfx908 --offload-arch=native \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-FAILED
+
+// CHECK-FAILED: error: failed to deduce triple for target architecture 'native'; specify the triple using '-fopenmp-targets' and '-Xopenmp-target' instead.
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7003,20 +7003,13 @@
   // For all the host OpenMP offloading compile jobs we need to pass the targets
   // information using -fopenmp-targets= option.
   if (JA.isHostOffloading(Action::OFK_OpenMP)) {
-SmallString<128> TargetInfo("-fopenmp-targets=");
-
-Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
-assert(Tgts && Tgts->getNumValues() &&
-   "OpenMP offloading has to have targets specified.");
-for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
-  if (i)
-TargetInfo += ',';
-  // We need to get the string from the triple because it may be not exactly
-  // the same as the one we get 

[PATCH] D125059: [Lex] Don't assert when decoding invalid UCNs.

2022-05-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

With this and D125049 , I no longer get any 
low-hanging fuzzer crashes.

(Though we're probably mostly fuzzing the lexer. Providing a list of tokens as 
a dictionaly may help)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125059

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


[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-05 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp:313
+  if (BoundArch.empty())
+checkSystemForAMDGPU(Args, *this, Arch);
   DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), Arch);

tra wrote:
> I'd change `checkSystemForAMDGPU` to return the Arch or empty string.
> 
> I'd also simplify the code to something like this:
> ```
> std::string Arch = DAL->getLastArgValue(options::OPT_march_EQ).str();
> if (Arch.empty()) {
>   Arch = !BoundArch.empty() ? BoundArch :  checkSystemForAMDGPU(Args, *this);
>   DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), Arch);
> }
> ```
Having `checkSystemForAMDGPU` cause errors when trying to test this was a pain. 
It'll take a bit more plumbing to address that so I think I'll leave this as-is 
for this patch and address it in a follow-up.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[PATCH] D125059: [Lex] Don't assert when decoding invalid UCNs.

2022-05-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added a project: All.
sammccall requested review of this revision.
Herald added projects: clang, clang-tools-extra.
Herald added a subscriber: cfe-commits.

Currently if a lexically-valid UCN encodes an invalid codepoint, then we
diagnose that, and then hit an assertion while trying to decode it.

Since there isn't anything preventing us reaching this state, remove the
assertion. expandUCNs("X\UY") will produce "XY".


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125059

Files:
  clang-tools-extra/pseudo/test/crash/bad-ucn.c
  clang/lib/Lex/LiteralSupport.cpp
  clang/test/Lexer/unicode.c


Index: clang/test/Lexer/unicode.c
===
--- clang/test/Lexer/unicode.c
+++ clang/test/Lexer/unicode.c
@@ -28,6 +28,9 @@
 
 int _;
 
+extern int X\U; // expected-error {{not allowed in an identifier}}
+int Y = '\U'; // expected-error {{invalid universal character}}
+
 #ifdef __cplusplus
 
 extern int ༀ;
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -320,10 +320,8 @@
 llvm::SmallVectorImpl ) {
   char ResultBuf[4];
   char *ResultPtr = ResultBuf;
-  bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
-  (void)Res;
-  assert(Res && "Unexpected conversion failure");
-  Str.append(ResultBuf, ResultPtr);
+  if (llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr))
+Str.append(ResultBuf, ResultPtr);
 }
 
 void clang::expandUCNs(SmallVectorImpl , StringRef Input) {
Index: clang-tools-extra/pseudo/test/crash/bad-ucn.c
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/crash/bad-ucn.c
@@ -0,0 +1,4 @@
+// This UCN doesn't encode a valid codepoint.
+// We used to assert while trying to expand UCNs in the token.
+// RUN: clang-pseudo -source=%s
+A\U


Index: clang/test/Lexer/unicode.c
===
--- clang/test/Lexer/unicode.c
+++ clang/test/Lexer/unicode.c
@@ -28,6 +28,9 @@
 
 int _;
 
+extern int X\U; // expected-error {{not allowed in an identifier}}
+int Y = '\U'; // expected-error {{invalid universal character}}
+
 #ifdef __cplusplus
 
 extern int ༀ;
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -320,10 +320,8 @@
 llvm::SmallVectorImpl ) {
   char ResultBuf[4];
   char *ResultPtr = ResultBuf;
-  bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
-  (void)Res;
-  assert(Res && "Unexpected conversion failure");
-  Str.append(ResultBuf, ResultPtr);
+  if (llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr))
+Str.append(ResultBuf, ResultPtr);
 }
 
 void clang::expandUCNs(SmallVectorImpl , StringRef Input) {
Index: clang-tools-extra/pseudo/test/crash/bad-ucn.c
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/crash/bad-ucn.c
@@ -0,0 +1,4 @@
+// This UCN doesn't encode a valid codepoint.
+// We used to assert while trying to expand UCNs in the token.
+// RUN: clang-pseudo -source=%s
+A\U
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D125049: [pseudo] Only expand UCNs for raw_identifiers

2022-05-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 427490.
sammccall added a comment.

oops, forgot testcase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125049

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/Token.h
  clang-tools-extra/pseudo/lib/Lex.cpp
  clang-tools-extra/pseudo/test/crash/backslashes.c
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp


Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -17,6 +17,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Signals.h"
 
 using clang::pseudo::Grammar;
 using llvm::cl::desc;
@@ -52,6 +53,7 @@
 
 int main(int argc, char *argv[]) {
   llvm::cl::ParseCommandLineOptions(argc, argv, "");
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
   clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
   std::string SourceText;
Index: clang-tools-extra/pseudo/test/crash/backslashes.c
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/crash/backslashes.c
@@ -0,0 +1,4 @@
+// We used to try to interpret these backslashes as UCNs.
+// RUN: clang-pseudo -source=%s
+\
+\ x
Index: clang-tools-extra/pseudo/lib/Lex.cpp
===
--- clang-tools-extra/pseudo/lib/Lex.cpp
+++ clang-tools-extra/pseudo/lib/Lex.cpp
@@ -90,12 +90,23 @@
 assert(CharSize != 0 && "no progress!");
 Pos += CharSize;
   }
-  // Remove universal character names (UCN).
+  llvm::StringRef Text = CleanBuffer;
   llvm::SmallString<64> UCNBuffer;
-  clang::expandUCNs(UCNBuffer, CleanBuffer);
+  // A surface reading of the standard suggests UCNs might appear anywhere.
+  // But we need only decode them in raw_identifiers.
+  //  - they cannot appear in punctuation/keyword tokens, because UCNs
+  //cannot encode basic characters outside of literals [lex.charset]
+  //  - they can appear in literals, but we need not unescape them now.
+  //We treat them as escape sequences when evaluating the literal.
+  //  - comments are handled similarly to literals
+  // This is good fortune, because expandUCNs requires its input to be a
+  // reasonably valid identifier (e.g. without stray backslashes).
+  if (Tok.Kind == tok::raw_identifier) {
+clang::expandUCNs(UCNBuffer, CleanBuffer);
+Text = UCNBuffer;
+  }
 
-  llvm::StringRef Text = llvm::StringRef(UCNBuffer).copy(*CleanedStorage);
-  Tok.Data = Text.data();
+  Tok.Data = Text.copy(*CleanedStorage).data();
   Tok.Length = Text.size();
   Tok.Flags &= ~static_cast(LexFlags::NeedsCleaning);
 }
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
@@ -199,12 +199,15 @@
 clang::Language = clang::Language::CXX,
 clang::LangStandard::Kind = clang::LangStandard::lang_unspecified);
 
-/// Derives a token stream by decoding escapes, interpreting raw_identifiers 
and
-/// splitting the greatergreater token.
+/// Decoding raw tokens written in the source code, returning a derived stream.
 ///
-/// Tokens containing UCNs, escaped newlines, trigraphs etc are decoded and
-/// their backing data is owned by the returned stream.
-/// raw_identifier tokens are assigned specific types (identifier, keyword 
etc).
+/// - escaped newlines within tokens are removed
+/// - trigraphs are replaced with the characters they encode
+/// - UCNs within raw_identifiers are replaced by the characters they encode
+///   (UCNs within strings, comments etc are not translated)
+/// - raw_identifier tokens are assigned their correct keyword type
+/// - the >> token is split into separate > > tokens
+///   (we use a modified grammar where >> is a nonterminal, not a token)
 ///
 /// The StartsPPLine flag is preserved.
 ///


Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -17,6 +17,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Signals.h"
 
 using clang::pseudo::Grammar;
 using llvm::cl::desc;
@@ -52,6 +53,7 @@
 
 int main(int argc, char *argv[]) {
   llvm::cl::ParseCommandLineOptions(argc, argv, "");
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
   clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
   

[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

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



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:84
+  if (!BlockToOutputState ||
+  BlockToOutputState->size() <= Context->getCFG().getExit().getBlockID())
+return;

ymandel wrote:
> xazax.hun wrote:
> > xazax.hun wrote:
> > > ymandel wrote:
> > > > xazax.hun wrote:
> > > > > xazax.hun wrote:
> > > > > > Could the size of the vector ever be wrong? Should this be an 
> > > > > > assert instead?
> > > > > Whoops, after the update this comment is out of place, now it 
> > > > > supposed to be on line 60. 
> > > > Based on my reading, it is a rare, but possible condition. Basically, 
> > > > we need code where the exit block is unreachable, which I believe can 
> > > > happen in weird cases like:
> > > > 
> > > > ```
> > > > while(true) {...}
> > > > ```
> > > > https://godbolt.org/z/rfEnfaWTv -- notice the lack of predecessors for 
> > > > the exit block.
> > > > 
> > > > See the code here, which follows the ordering of the blocks and doesn't 
> > > > force blocks to be processed:
> > > > 
> > > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp#L337-L364
> > > Interesting. Since we already have optionals in the vector, I assumed we 
> > > will always have matching size. I think we might want to change this so 
> > > there is only one way for the analysis to not provide a state for a basic 
> > > block to make this a bit less confusing, 
> > Actually, in the linked code I see ` 
> > BlockStates.resize(CFCtx.getCFG().size(), llvm::None);`. So I would expect 
> > the size to be always right with possibly some `None`s for the nodes that 
> > were not processed.
> > Actually, in the linked code I see ` 
> > BlockStates.resize(CFCtx.getCFG().size(), llvm::None);`. So I would expect 
> > the size to be always right with possibly some `None`s for the nodes that 
> > were not processed.
> Ah, my mistake! I thought `resize` only allocated the space. #TIL
> 
> Changed to an assert. Thanks.
> 
But this discussion shed light on an interesting detail. If the exit block is 
unreachable, we will not diagnose the unsafe accesses. I wonder if this worth a 
FIXME. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D125050: [OpenMP] Try to Infer target triples using the offloading architecture

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

Just a drive-by style review. I didn't look at the functionality of the changes 
much.




Comment at: clang/lib/Driver/Driver.cpp:788-789
+   options::OPT_fno_openmp, false) &&
+  (C.getInputArgs().hasArg(options::OPT_fopenmp_targets_EQ) ||
+   C.getInputArgs().hasArg(options::OPT_offload_arch_EQ));
+  if (IsOpenMP) {

So, specifying just `-fopenmp` will result in `IsOpenMP=false`? This seems odd.
Perhaps the variable should be called `IsOpenMPOffload` ? 



Comment at: clang/lib/Driver/Driver.cpp:821-822
+  HostTC->getTriple());
+  if (!AMDTriple || !NVPTXTriple) {
+Diag(clang::diag::err_drv_failed_to_deduce_targets);
+return;

This seems a bit too restrictive as it would fail if we've failed to get either 
of those triples. We may be able to proceed with only one of them in many cases.
I'd remove this check and would make the loop below more forgiving. 



Comment at: clang/lib/Driver/Driver.cpp:831
+  for (StringRef Arch : Archs) {
+if (IsNVIDIAGpuArch(StringToCudaArch(
+getProcessorFromTargetID(*NVPTXTriple, Arch {

```
if (NvidiaTriple && IsNVIDIAGpuArch(...))
...
else if (AMDTriple && IsAMDGpuArch(...))
...
else {
   Diag(); 
   return;
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125050

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


[clang] f6c7493 - [docs] Fix uses of `foo` that should be ``foo`` throughout release notes.

2022-05-05 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2022-05-05T16:04:19-07:00
New Revision: f6c74932b59619aa1a680caa7c4b78d4d29c2877

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

LOG: [docs] Fix uses of `foo` that should be ``foo`` throughout release notes.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b77bd8445a70..9e9990fa4a9b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -77,17 +77,19 @@ Bug Fixes
   This fixes `Issue 53742 
`_.
 - We now ignore full expressions when traversing cast subexpressions. This
   fixes `Issue 53044 `_.
-- Allow `-Wno-gnu` to silence GNU extension diagnostics for pointer arithmetic
-  diagnostics. Fixes `Issue 5 
`_.
-- Placeholder constraints, as in `Concept auto x = f();`, were not checked 
when modifiers
-  like ``auto&`` or ``auto**`` were added. These constraints are now checked.
+- Allow ``-Wno-gnu`` to silence GNU extension diagnostics for pointer
+  arithmetic diagnostics. Fixes `Issue 5
+  `_.
+- Placeholder constraints, as in ``Concept auto x = f();``, were not checked
+  when modifiers like ``auto&`` or ``auto**`` were added. These constraints are
+  now checked.
   This fixes  `Issue 53911 
`_
   and  `Issue 54443 `_.
 - Previously invalid member variables with template parameters would crash 
clang.
   Now fixed by setting identifiers for them.
   This fixes `Issue 28475 (PR28101) 
`_.
-- Now allow the `restrict` and `_Atomic` qualifiers to be used in conjunction
-  with `__auto_type` to match the behavior in GCC. This fixes
+- Now allow the ``restrict`` and ``_Atomic`` qualifiers to be used in
+  conjunction with ``__auto_type`` to match the behavior in GCC. This fixes
   `Issue 53652 `_.
 - No longer crash when specifying a variably-modified parameter type in a
   function with the ``naked`` attribute. This fixes
@@ -101,7 +103,7 @@ Bug Fixes
   `Issue 48742 `_.
 - Improved the diagnostic when accessing a member of an atomic structure or
   union object in C; was previously an unhelpful error, but now issues a
-  `-Watomic-access` warning which defaults to an error. Fixes
+  ``-Watomic-access`` warning which defaults to an error. Fixes
   `Issue 54563 `_.
 - Unevaluated lambdas in dependant contexts no longer result in clang crashing.
   This fixes Issues `50376 
`_,
@@ -254,7 +256,7 @@ New Pragmas in Clang
 Attribute Changes in Clang
 --
 
-- Added support for parameter pack expansion in `clang::annotate`.
+- Added support for parameter pack expansion in ``clang::annotate``.
 
 - The ``overloadable`` attribute can now be written in all of the syntactic
   locations a declaration attribute may appear.
@@ -293,7 +295,7 @@ C2x Feature Support
 - Implemented `WG14 N2935 Make false and true first-class language features 
`_.
 - Implemented `WG14 N2763 Adding a fundamental type for N-bit integers 
`_.
 - Implemented `WG14 N2775 Literal suffixes for bit-precise integers 
`_.
-- Implemented the `*_WIDTH` macros to complete support for
+- Implemented the ``*_WIDTH`` macros to complete support for
   `WG14 N2412 Two's complement sign representation for C2x 
`_.
 - Implemented `WG14 N2418 Adding the u8 character prefix 
`_.
 - Removed support for implicit function declarations. This was a C89 feature
@@ -322,7 +324,8 @@ C++20 Feature Support
   it is called through a template instantiation. This fixes
   `Issue 54578 `_.
 
-- Implemented `__builtin_source_location()` which enables library support for 
std::source_location.
+- Implemented ``__builtin_source_location()``, which enables library support
+  for ``std::source_location``.
 
 - The mangling scheme for C++20 modules has incompatibly changed. The
   initial mangling was discovered not to be reversible, and the weak
@@ -377,11 +380,11 @@ Floating Point 

[PATCH] D123200: [compiler-rt][builtins] Add several helper functions for AVR

2022-05-05 Thread Ayke via Phabricator via cfe-commits
aykevl added a comment.

@benshi001 I have been looking through the GCC code and I think avr-gcc also 
has a special calling convention for many other functions, including `__mulqi3` 
and `__mulhi3`.

Source:

1. I think this is where the ABI is specified in the compiler: 
https://github.com/gcc-mirror/gcc/blob/releases/gcc-5.4.0/gcc/config/avr/avr.md#L1543-L1549
 You can see that it multiplies R24 with R22 and stores the result in R24, and 
clobbers R22 in the process. But no other registers.
2. In this code sample , avr-gcc doesn't save 
`char c` (`r20`) across the `__mulqi3` and `__mulhi3` calls.

Therefore, I think we need to be a bit more careful with defining these AVR 
builtins and check the ABI in avr-gcc first.
Also, we can make use of this and optimize the AVR backend more (you can see 
that the Clang generated code is much worse than avr-gcc in the above examples).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123200

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


[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

2022-05-05 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui added a comment.

@aaron.ballman

I could suppress the strange warnings by using `isWrittenInBuiltinFile` and 
`isWrittenInCommandLineFile`. Thank you!
Could you please review this patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

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


[clang] c2572d8 - [docs] Add blank lines to help Sphinx parse nested bullets.

2022-05-05 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2022-05-05T15:58:26-07:00
New Revision: c2572d8b1fccffcc5dd7b900cf3c4cfa07df3b50

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

LOG: [docs] Add blank lines to help Sphinx parse nested bullets.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 119d6eb95f45..b77bd8445a70 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -205,9 +205,12 @@ Improvements to Clang's diagnostics
 
 Non-comprehensive list of changes in this release
 -
+
 - Improve __builtin_dump_struct:
+
   - Support bitfields in struct and union.
-  - Improve the dump format, dump both bitwidth(if its a bitfield) and field 
value.
+  - Improve the dump format, dump both bitwidth(if its a bitfield) and field
+value.
   - Remove anonymous tag locations and flatten anonymous struct members.
   - Beautify dump format, add indent for struct members.
   - Support passing additional arguments to the formatting function, allowing
@@ -217,6 +220,7 @@ Non-comprehensive list of changes in this release
   - Support formatting of base classes in C++.
   - Support calling a formatting function template in C++, which can provide
 custom formatting for non-aggregate types.
+
 - Previously disabled sanitizer options now enabled by default:
   - ASAN_OPTIONS=detect_stack_use_after_return=1 (only on Linux).
   - MSAN_OPTIONS=poison_in_dtor=1.



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


[PATCH] D124534: [clang] Add a diagnostic for line directive of a gnu extension

2022-05-05 Thread Ken Matsui via Phabricator via cfe-commits
ken-matsui updated this revision to Diff 427482.
ken-matsui added a comment.

Update codes as reviewed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124534

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticLexKinds.td
  clang/lib/Lex/PPDirectives.cpp
  clang/test/Preprocessor/line-directive.c
  clang/test/SemaCXX/constexpr-string.cpp

Index: clang/test/SemaCXX/constexpr-string.cpp
===
--- clang/test/SemaCXX/constexpr-string.cpp
+++ clang/test/SemaCXX/constexpr-string.cpp
@@ -7,7 +7,7 @@
 // RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only -verify -pedantic -Wno-vla-extension -fno-signed-char
 // RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only -verify -pedantic -Wno-vla-extension -fno-wchar -DNO_PREDEFINED_WCHAR_T
 
-# 9 "/usr/include/string.h" 1 3 4
+# 9 "/usr/include/string.h" 1 3 4  // expected-warning {{this style of line directive is a GNU extension}}
 extern "C" {
   typedef decltype(sizeof(int)) size_t;
 
@@ -29,7 +29,7 @@
 }
 # 25 "SemaCXX/constexpr-string.cpp" 2
 
-# 27 "/usr/include/wchar.h" 1 3 4
+# 27 "/usr/include/wchar.h" 1 3 4  // expected-warning {{this style of line directive is a GNU extension}}
 extern "C" {
 #if NO_PREDEFINED_WCHAR_T
   typedef decltype(L'0') wchar_t;
Index: clang/test/Preprocessor/line-directive.c
===
--- clang/test/Preprocessor/line-directive.c
+++ clang/test/Preprocessor/line-directive.c
@@ -9,8 +9,8 @@
 # 20 "" 2
 
 // a push/pop before any other line control
-# 10 "enter-0" 1
-# 11 "" 2 // pop to main file
+# 10 "enter-0" 1 // expected-warning {{this style of line directive is a GNU extension}}
+# 11 "" 2 // pop to main file: expected-warning {{this style of line directive is a GNU extension}}
 #error MAIN7
 // expected-error@-1{{MAIN7}}
 
@@ -27,13 +27,13 @@
 #define A 42 "foo"
 #line A
 
-# 42
-# 42 "foo"
+# 42 // expected-warning {{this style of line directive is a GNU extension}}
+# 42 "foo" // expected-warning {{this style of line directive is a GNU extension}}
 # 42 "foo" 2 // expected-error {{invalid line marker flag '2': cannot pop empty include stack}}
 # 42 "foo" 1 3  // enter
 # 42 "foo" 2 3  // exit
 # 42 "foo" 2 3 4 // expected-error {{invalid line marker flag '2': cannot pop empty include stack}}
-# 42 "foo" 3 4
+# 42 "foo" 3 4 // expected-warning {{this style of line directive is a GNU extension}}
 
 # 'a'// expected-error {{invalid preprocessing directive}}
 # 42 'f' // expected-error {{invalid filename for line marker directive}}
@@ -54,7 +54,7 @@
 
 // Verify that linemarker diddling of the system header flag works.
 
-# 192 "glomp.h" // not a system header.
+# 192 "glomp.h" // not a system header.: expected-warning {{this style of line directive is a GNU extension}}
 typedef int x;  // expected-note {{previous definition is here}}
 typedef int x;  // expected-warning {{redefinition of typedef 'x' is a C11 feature}}
 
@@ -97,7 +97,7 @@
 #line 010  // expected-warning {{#line directive interprets number as decimal, not octal}}
 extern int array[__LINE__ == 10 ? 1:-1];
 
-# 020  // expected-warning {{GNU line marker directive interprets number as decimal, not octal}}
+# 020  // expected-warning {{GNU line marker directive interprets number as decimal, not octal}} expected-warning {{this style of line directive is a GNU extension}}
 extern int array_gnuline[__LINE__ == 20 ? 1:-1];
 
 /* PR3917 */
@@ -106,7 +106,7 @@
 _\
 _LINE__ == 42 ? 1: -1];  /* line marker is location of first _ */
 
-# 51
+# 51 // expected-warning {{this style of line directive is a GNU extension}}
 extern char array2_gnuline[\
 _\
 _LINE__ == 52 ? 1: -1];  /* line marker is location of first _ */
@@ -115,12 +115,12 @@
 #line 0 "line-directive.c" // expected-warning {{#line directive with zero argument is a GNU extension}}
 undefined t; // expected-error {{unknown type name 'undefined'}}
 
-# 115 "main"
-# 116 "enter-1" 1
-# 117 "enter-2" 1
-# 118 "" 2 // pop to enter-1
+# 115 "main" // expected-warning {{this style of line directive is a GNU extension}}
+# 116 "enter-1" 1 // expected-warning {{this style of line directive is a GNU extension}}
+# 117 "enter-2" 1 // expected-warning {{this style of line directive is a GNU extension}}
+# 118 "" 2 // pop to enter-1: expected-warning {{this style of line directive is a GNU extension}}
 #error ENTER1
 // expected-error@-1{{ENTER1}}
-# 121 "" 2 // pop to "main"
+# 121 "" 2 // pop to "main": expected-warning {{this style of line directive is a GNU extension}}
 #error MAIN2
 // expected-error@-1{{MAIN2}}
Index: clang/lib/Lex/PPDirectives.cpp
===
--- clang/lib/Lex/PPDirectives.cpp
+++ clang/lib/Lex/PPDirectives.cpp
@@ -1431,6 +1431,7 @@
   // 

[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-05 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 in general.




Comment at: clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp:313
+  if (BoundArch.empty())
+checkSystemForAMDGPU(Args, *this, Arch);
   DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), Arch);

I'd change `checkSystemForAMDGPU` to return the Arch or empty string.

I'd also simplify the code to something like this:
```
std::string Arch = DAL->getLastArgValue(options::OPT_march_EQ).str();
if (Arch.empty()) {
  Arch = !BoundArch.empty() ? BoundArch :  checkSystemForAMDGPU(Args, *this);
  DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), Arch);
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[clang] 1c50909 - Revert "Pedantically warn about // comments in gnu89 mode"

2022-05-05 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-05T18:39:13-04:00
New Revision: 1c50909f6f8ac183b82e973457522439a8856e96

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

LOG: Revert "Pedantically warn about // comments in gnu89 mode"

This reverts commit f6dff93641b2259623e686eb13a1884b8b9f4a00.

This diagnostic is also in the -Wcomment group, which is in the -Wall
group, so the diagnostic is enabled in a wider context than GCC does.
That turns out to be disruptive for the Linux kernel builds still using
-std=gnu89 because the kernel requires C source files to start with //
comments: 
https://kernel.org/doc/html/v5.18-rc5/process/license-rules.html#license-identifier-syntax

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/LangStandards.def
clang/test/Lexer/c90.c
clang/test/Sema/gnu89.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 47abde0747d6f..119d6eb95f454 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -147,9 +147,6 @@ Bug Fixes
   because there is no way to fully qualify the enumerator name, so this
   "extension" was unintentional and useless. This fixes
   `Issue 42372 `_.
-- Now correctly diagnose use of ``//`` comments in ``gnu89`` mode (which
-  matches the behavior of GCC) in addition to ``c89`` mode. This fixes
-  `Issue 18427 `_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/include/clang/Basic/LangStandards.def 
b/clang/include/clang/Basic/LangStandards.def
index d4e42b4cd6d86..323032f41da02 100644
--- a/clang/include/clang/Basic/LangStandards.def
+++ b/clang/include/clang/Basic/LangStandards.def
@@ -46,7 +46,7 @@ LANGSTANDARD(c94, "iso9899:199409",
 
 LANGSTANDARD(gnu89, "gnu89",
  C, "ISO C 1990 with GNU extensions",
- Digraphs | GNUMode)
+ LineComment | Digraphs | GNUMode)
 LANGSTANDARD_ALIAS(gnu89, "gnu90")
 
 // C99-ish modes

diff  --git a/clang/test/Lexer/c90.c b/clang/test/Lexer/c90.c
index 39ffdc170b108..8752404c1c199 100644
--- a/clang/test/Lexer/c90.c
+++ b/clang/test/Lexer/c90.c
@@ -1,7 +1,5 @@
 /* RUN: %clang_cc1 -std=c90 -fsyntax-only %s -verify -pedantic-errors
  */
-/* RUN: %clang_cc1 -std=gnu89 -fsyntax-only %s -verify -pedantic-errors
- */
 
 enum { cast_hex = (long) (
   0x0p-1   /* expected-error {{hexadecimal floating constants are a C99 
feature}} */

diff  --git a/clang/test/Sema/gnu89.c b/clang/test/Sema/gnu89.c
index d96d3536fbfff..1be717f54260e 100644
--- a/clang/test/Sema/gnu89.c
+++ b/clang/test/Sema/gnu89.c
@@ -1,6 +1,5 @@
-/* RUN: %clang_cc1 %s -std=gnu89 -pedantic -fsyntax-only -verify
- */
+// RUN: %clang_cc1 %s -std=gnu89 -pedantic -fsyntax-only -verify
 
 int f(int restrict);
 
-void main(void) {} /* expected-warning {{return type of 'main' is not 'int'}} 
expected-note {{change return type to 'int'}} */
+void main(void) {} // expected-warning {{return type of 'main' is not 'int'}} 
expected-note {{change return type to 'int'}}



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


[PATCH] D125052: [HLSL] Enable vector types for hlsl.

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

Vector types in hlsl is using clang ext_vector_type.
Declaration of vector types is in builtin header hlsl.h.
hlsl.h will be included by default for hlsl shader.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125052

Files:
  clang/lib/Basic/LangOptions.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Headers/CMakeLists.txt
  clang/lib/Headers/hlsl.h
  clang/lib/Headers/hlsl/hlsl_basic_types.h
  clang/test/CodeGenHLSL/basic_types.hlsl

Index: clang/test/CodeGenHLSL/basic_types.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/basic_types.hlsl
@@ -0,0 +1,76 @@
+// RUN: %clang_dxc  -Tlib_6_7 -Fo - %s | FileCheck %s
+
+// FIXME: check 16bit types once enable-16bit-types is ready.
+
+// CHECK:@uint_Val = global i32 0, align 4
+// CHECK:@uint64_t_Val = global i64 0, align 8
+// CHECK:@int64_t_Val = global i64 0, align 8
+// CHECK:@int2_Val = global <2 x i32> zeroinitializer, align 8
+// CHECK:@int3_Val = global <3 x i32> zeroinitializer, align 16
+// CHECK:@int4_Val = global <4 x i32> zeroinitializer, align 16
+// CHECK:@uint2_Val = global <2 x i32> zeroinitializer, align 8
+// CHECK:@uint3_Val = global <3 x i32> zeroinitializer, align 16
+// CHECK:@uint4_Val = global <4 x i32> zeroinitializer, align 16
+// CHECK:@int64_t2_Val = global <2 x i64> zeroinitializer, align 16
+// CHECK:@int64_t3_Val = global <3 x i64> zeroinitializer, align 32
+// CHECK:@int64_t4_Val = global <4 x i64> zeroinitializer, align 32
+// CHECK:@uint64_t2_Val = global <2 x i64> zeroinitializer, align 16
+// CHECK:@uint64_t3_Val = global <3 x i64> zeroinitializer, align 32
+// CHECK:@uint64_t4_Val = global <4 x i64> zeroinitializer, align 32
+// CHECK:@float2_Val = global <2 x float> zeroinitializer, align 8
+// CHECK:@float3_Val = global <3 x float> zeroinitializer, align 16
+// CHECK:@float4_Val = global <4 x float> zeroinitializer, align 16
+// CHECK:@double2_Val = global <2 x double> zeroinitializer, align 16
+// CHECK:@double3_Val = global <3 x double> zeroinitializer, align 32
+// CHECK:@double4_Val = global <4 x double> zeroinitializer, align 32
+
+#define TYPE_DECL(T)  T T##_Val
+
+#ifdef __HLSL_ENABLE_16_BIT
+TYPE_DECL(uint16_t);
+TYPE_DECL(int16_t);
+#endif
+
+// unsigned 32-bit integer.
+TYPE_DECL(uint);
+
+// 64-bit integer.
+TYPE_DECL(uint64_t);
+TYPE_DECL(int64_t);
+
+// built-in vector data types:
+
+#ifdef __HLSL_ENABLE_16_BIT
+TYPE_DECL(int16_t2   );
+TYPE_DECL(int16_t3   );
+TYPE_DECL(int16_t4   );
+TYPE_DECL( uint16_t2 );
+TYPE_DECL( uint16_t3 );
+TYPE_DECL( uint16_t4 );
+#endif
+
+TYPE_DECL( int2  );
+TYPE_DECL( int3  );
+TYPE_DECL( int4  );
+TYPE_DECL( uint2 );
+TYPE_DECL( uint3 );
+TYPE_DECL( uint4 );
+TYPE_DECL( int64_t2  );
+TYPE_DECL( int64_t3  );
+TYPE_DECL( int64_t4  );
+TYPE_DECL( uint64_t2 );
+TYPE_DECL( uint64_t3 );
+TYPE_DECL( uint64_t4 );
+
+#ifdef __HLSL_ENABLE_16_BIT
+TYPE_DECL(half2 );
+TYPE_DECL(half3 );
+TYPE_DECL(half4 );
+#endif
+
+TYPE_DECL( float2  );
+TYPE_DECL( float3  );
+TYPE_DECL( float4  );
+TYPE_DECL( double2 );
+TYPE_DECL( double3 );
+TYPE_DECL( double4 );
Index: clang/lib/Headers/hlsl/hlsl_basic_types.h
===
--- /dev/null
+++ clang/lib/Headers/hlsl/hlsl_basic_types.h
@@ -0,0 +1,64 @@
+//===- hlsl_basic_types.h - HLSL definitions for basic types --===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _HLSL_HLSL_BASIC_TYPES_H_
+#define _HLSL_HLSL_BASIC_TYPES_H_
+
+// built-in scalar data types:
+
+#ifdef __HLSL_ENABLE_16_BIT
+// 16-bit integer.
+typedef unsigned short uint16_t;
+typedef short int16_t;
+#endif
+
+// unsigned 32-bit integer.
+typedef unsigned int uint;
+
+// 64-bit integer.
+typedef unsigned long uint64_t;
+typedef long int64_t;
+
+// built-in vector data types:
+
+#ifdef __HLSL_ENABLE_16_BIT
+typedef int16_t int16_t2 __attribute__((ext_vector_type(2)));
+typedef int16_t int16_t3 __attribute__((ext_vector_type(3)));
+typedef int16_t int16_t4 __attribute__((ext_vector_type(4)));
+typedef uint16_t uint16_t2 __attribute__((ext_vector_type(2)));
+typedef uint16_t uint16_t3 __attribute__((ext_vector_type(3)));
+typedef uint16_t uint16_t4 __attribute__((ext_vector_type(4)));
+#endif
+
+typedef int int2 __attribute__((ext_vector_type(2)));
+typedef int int3 __attribute__((ext_vector_type(3)));
+typedef int int4 

[PATCH] D124721: [OpenMP] Allow compiling multiple target architectures with OpenMP

2022-05-05 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124721

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


[PATCH] D125049: [pseudo] Only expand UCNs for raw_identifiers

2022-05-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall updated this revision to Diff 427475.
sammccall added a comment.

rename testcase to be more descriptive, add comment


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125049

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


Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -17,6 +17,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Signals.h"
 
 using clang::pseudo::Grammar;
 using llvm::cl::desc;
@@ -52,6 +53,7 @@
 
 int main(int argc, char *argv[]) {
   llvm::cl::ParseCommandLineOptions(argc, argv, "");
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
   clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
   std::string SourceText;
Index: clang-tools-extra/pseudo/lib/Lex.cpp
===
--- clang-tools-extra/pseudo/lib/Lex.cpp
+++ clang-tools-extra/pseudo/lib/Lex.cpp
@@ -90,12 +90,23 @@
 assert(CharSize != 0 && "no progress!");
 Pos += CharSize;
   }
-  // Remove universal character names (UCN).
+  llvm::StringRef Text = CleanBuffer;
   llvm::SmallString<64> UCNBuffer;
-  clang::expandUCNs(UCNBuffer, CleanBuffer);
+  // A surface reading of the standard suggests UCNs might appear anywhere.
+  // But we need only decode them in raw_identifiers.
+  //  - they cannot appear in punctuation/keyword tokens, because UCNs
+  //cannot encode basic characters outside of literals [lex.charset]
+  //  - they can appear in literals, but we need not unescape them now.
+  //We treat them as escape sequences when evaluating the literal.
+  //  - comments are handled similarly to literals
+  // This is good fortune, because expandUCNs requires its input to be a
+  // reasonably valid identifier (e.g. without stray backslashes).
+  if (Tok.Kind == tok::raw_identifier) {
+clang::expandUCNs(UCNBuffer, CleanBuffer);
+Text = UCNBuffer;
+  }
 
-  llvm::StringRef Text = llvm::StringRef(UCNBuffer).copy(*CleanedStorage);
-  Tok.Data = Text.data();
+  Tok.Data = Text.copy(*CleanedStorage).data();
   Tok.Length = Text.size();
   Tok.Flags &= ~static_cast(LexFlags::NeedsCleaning);
 }
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
@@ -199,12 +199,15 @@
 clang::Language = clang::Language::CXX,
 clang::LangStandard::Kind = clang::LangStandard::lang_unspecified);
 
-/// Derives a token stream by decoding escapes, interpreting raw_identifiers 
and
-/// splitting the greatergreater token.
+/// Decoding raw tokens written in the source code, returning a derived stream.
 ///
-/// Tokens containing UCNs, escaped newlines, trigraphs etc are decoded and
-/// their backing data is owned by the returned stream.
-/// raw_identifier tokens are assigned specific types (identifier, keyword 
etc).
+/// - escaped newlines within tokens are removed
+/// - trigraphs are replaced with the characters they encode
+/// - UCNs within raw_identifiers are replaced by the characters they encode
+///   (UCNs within strings, comments etc are not translated)
+/// - raw_identifier tokens are assigned their correct keyword type
+/// - the >> token is split into separate > > tokens
+///   (we use a modified grammar where >> is a nonterminal, not a token)
 ///
 /// The StartsPPLine flag is preserved.
 ///


Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -17,6 +17,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Signals.h"
 
 using clang::pseudo::Grammar;
 using llvm::cl::desc;
@@ -52,6 +53,7 @@
 
 int main(int argc, char *argv[]) {
   llvm::cl::ParseCommandLineOptions(argc, argv, "");
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
   clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
   std::string SourceText;
Index: clang-tools-extra/pseudo/lib/Lex.cpp
===
--- clang-tools-extra/pseudo/lib/Lex.cpp
+++ clang-tools-extra/pseudo/lib/Lex.cpp
@@ -90,12 +90,23 @@
 assert(CharSize != 0 && "no progress!");
 Pos += CharSize;
   }
-  

[PATCH] D125050: [OpenMP] Try to Infer target triples using the offloading architecture

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

Currently we require the `-fopenmp-targets=` option to specify the
triple to use for the offloading toolchains, and the `-Xopenmp-target=`
option to specify architectures to a specific toolchain. The changes
made in D124721  allowed us to use 
`--offload-arch=` to specify multiple
target architectures. However, this can become combersome with many
different architectures. This patch introduces functinality that
attempts to deduce the target triple and architectures from the
offloading action. Currently we will deduce known GPU architectures when
only `-fopenmp` is specified.

This required a bit of a hack to cache the deduced architectures,
without this we would've just thrown an error when we tried to look up
the architecture again when generating the job. Normally we require the
user to manually specify the toolchain arguments, but here they would
confict unless we overrode them.

Depends on: D124721 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125050

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/openmp-offload-infer.c

Index: clang/test/Driver/openmp-offload-infer.c
===
--- /dev/null
+++ clang/test/Driver/openmp-offload-infer.c
@@ -0,0 +1,44 @@
+// REQUIRES: x86-registered-target
+// REQUIRES: nvptx-registered-target
+// REQUIRES: amdgpu-registered-target
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp \
+// RUN:  --offload-arch=sm_52 --offload-arch=gfx803 \
+// RUN:  --libomptarget-amdgpu-bc-path=%S/Inputs/hip_dev_lib/libomptarget-amdgpu-gfx803.bc \
+// RUN:  --libomptarget-nvptx-bc-path=%S/Inputs/libomptarget/libomptarget-nvptx-test.bc %s 2>&1 \
+// RUN:   | FileCheck %s
+
+// verify the tools invocations
+// CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-llvm-bc"{{.*}}"-x" "c"
+// CHECK: "-cc1" "-triple" "amdgcn-amd-amdhsa" "-aux-triple" "x86_64-unknown-linux-gnu"{{.*}}"-target-cpu" "gfx803"
+// CHECK: "-cc1" "-triple" "nvptx64-nvidia-cuda" "-aux-triple" "x86_64-unknown-linux-gnu"{{.*}}"-target-cpu" "sm_52"
+// CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-obj"
+// CHECK: clang-linker-wrapper{{.*}}"--"{{.*}} "-o" "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: --offload-arch=sm_70 --offload-arch=gfx908:sramecc+:xnack- \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-NVIDIA-AMDGPU
+
+// CHECK-NVIDIA-AMDGPU: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.+]]"], output: "[[HOST_BC:.+]]"
+// CHECK-NVIDIA-AMDGPU: "amdgcn-amd-amdhsa" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[AMD_BC:.+]]"
+// CHECK-NVIDIA-AMDGPU: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[NVIDIA_PTX:.+]]"
+// CHECK-NVIDIA-AMDGPU: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[NVIDIA_PTX]]"], output: "[[NVIDIA_CUBIN:.+]]"
+// CHECK-NVIDIA-AMDGPU: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[HOST_BC]]", "[[AMD_BC]]", "[[NVIDIA_CUBIN]]"], output: "[[HOST_OBJ:.+]]"
+// CHECK-NVIDIA-AMDGPU: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: --offload-arch=sm_52 --offload-arch=sm_70 -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-ARCH-BINDINGS
+
+// CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[INPUT:.*]]"], output: "[[HOST_BC:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[DEVICE_BC_SM_52:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_BC_SM_52]]"], output: "[[DEVICE_OBJ_SM_52:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "clang", inputs: ["[[INPUT]]", "[[HOST_BC]]"], output: "[[DEVICE_BC_SM_70:.*]]"
+// CHECK-ARCH-BINDINGS: "nvptx64-nvidia-cuda" - "NVPTX::Assembler", inputs: ["[[DEVICE_BC_SM_70]]"], output: "[[DEVICE_OBJ_SM_70:.*]]"
+// CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "clang", inputs: ["[[HOST_BC]]", "[[DEVICE_OBJ_SM_52]]", "[[DEVICE_OBJ_SM_70]]"], output: "[[HOST_OBJ:.*]]"
+// CHECK-ARCH-BINDINGS: "x86_64-unknown-linux-gnu" - "Offload::Linker", inputs: ["[[HOST_OBJ]]"], output: "a.out"
+
+// RUN:   %clang -### --target=x86_64-unknown-linux-gnu -ccc-print-bindings -fopenmp \
+// RUN: 

[PATCH] D125049: [pseudo] Only expand UCNs for raw_identifiers

2022-05-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, alextsao1999.
Herald added a project: clang-tools-extra.

It turns out clang::expandUCNs only works on tokens that contain valid UCNs
and no other random escapes, and clang only uses it on raw_identifiers.

Currently we can hit an assertion by creating tokens with stray non-valid-UCN
backslashes in them.

Fortunately, expanding UCNs in raw_identifiers is actually all we need.
Most tokens (keywords, punctuation) can't have them. UCNs in literals can be
treated as escape sequences like \n even this isn't the standard's
interpretation. This more or less matches how clang works.
(See https://isocpp.org/files/papers/P2194R0.pdf which points out that the
standard's description of how UCNs work is misaligned with real implementations)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125049

Files:
  clang-tools-extra/pseudo/include/clang-pseudo/Token.h
  clang-tools-extra/pseudo/lib/Lex.cpp
  clang-tools-extra/pseudo/test/crash/crash.c
  clang-tools-extra/pseudo/tool/ClangPseudo.cpp


Index: clang-tools-extra/pseudo/tool/ClangPseudo.cpp
===
--- clang-tools-extra/pseudo/tool/ClangPseudo.cpp
+++ clang-tools-extra/pseudo/tool/ClangPseudo.cpp
@@ -17,6 +17,7 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Signals.h"
 
 using clang::pseudo::Grammar;
 using llvm::cl::desc;
@@ -52,6 +53,7 @@
 
 int main(int argc, char *argv[]) {
   llvm::cl::ParseCommandLineOptions(argc, argv, "");
+  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
 
   clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
   std::string SourceText;
Index: clang-tools-extra/pseudo/test/crash/crash.c
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/crash/crash.c
@@ -0,0 +1,3 @@
+// RUN: clang-pseudo -source=%s
+\
+\ x
Index: clang-tools-extra/pseudo/lib/Lex.cpp
===
--- clang-tools-extra/pseudo/lib/Lex.cpp
+++ clang-tools-extra/pseudo/lib/Lex.cpp
@@ -90,12 +90,23 @@
 assert(CharSize != 0 && "no progress!");
 Pos += CharSize;
   }
-  // Remove universal character names (UCN).
+  llvm::StringRef Text = CleanBuffer;
   llvm::SmallString<64> UCNBuffer;
-  clang::expandUCNs(UCNBuffer, CleanBuffer);
+  // A surface reading of the standard suggests UCNs might appear anywhere.
+  // But we need only decode them in raw_identifiers.
+  //  - they cannot appear in punctuation/keyword tokens, because UCNs
+  //cannot encode basic characters outside of literals [lex.charset]
+  //  - they can appear in literals, but we need not unescape them now.
+  //We treat them as escape sequences when evaluating the literal.
+  //  - comments are handled similarly to literals
+  // This is good fortune, because expandUCNs requires its input to be a
+  // reasonably valid identifier (e.g. without stray backslashes).
+  if (Tok.Kind == tok::raw_identifier) {
+clang::expandUCNs(UCNBuffer, CleanBuffer);
+Text = UCNBuffer;
+  }
 
-  llvm::StringRef Text = llvm::StringRef(UCNBuffer).copy(*CleanedStorage);
-  Tok.Data = Text.data();
+  Tok.Data = Text.copy(*CleanedStorage).data();
   Tok.Length = Text.size();
   Tok.Flags &= ~static_cast(LexFlags::NeedsCleaning);
 }
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
@@ -199,12 +199,15 @@
 clang::Language = clang::Language::CXX,
 clang::LangStandard::Kind = clang::LangStandard::lang_unspecified);
 
-/// Derives a token stream by decoding escapes, interpreting raw_identifiers 
and
-/// splitting the greatergreater token.
+/// Decoding raw tokens written in the source code, returning a derived stream.
 ///
-/// Tokens containing UCNs, escaped newlines, trigraphs etc are decoded and
-/// their backing data is owned by the returned stream.
-/// raw_identifier tokens are assigned specific types (identifier, keyword 
etc).
+/// - escaped newlines within tokens are removed
+/// - trigraphs are replaced with the characters they encode
+/// - UCNs within raw_identifiers are replaced by the characters they encode
+///   (UCNs within strings, comments etc are not translated)
+/// - raw_identifier tokens are assigned their correct keyword type
+/// - the >> token is split into separate > > tokens
+///   (we use a modified grammar where >> is a nonterminal, not a token)
 ///
 /// The StartsPPLine flag is preserved.
 ///


Index: 

[clang] e7aed73 - [clang-format][NFC] Add a few regression tests

2022-05-05 Thread via cfe-commits

Author: owenca
Date: 2022-05-05T15:12:24-07:00
New Revision: e7aed737eb2d8fb2150f38e48d1c3e0108931999

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

LOG: [clang-format][NFC] Add a few regression tests

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 40e2cb054b242..d7d69f950a323 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1573,6 +1573,17 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
"  f();\n"
"}");
 
+  AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
+  FormatStyle::SBS_Empty;
+  AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
+  FormatStyle::SIS_WithoutElse;
+  verifyFormat("if (true) {}", AllowSimpleBracedStatements);
+  verifyFormat("if (i) break;", AllowSimpleBracedStatements);
+  verifyFormat("if (i > 0) {\n"
+   "  return i;\n"
+   "}",
+   AllowSimpleBracedStatements);
+
   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
   // Where line-lengths matter, a 2-letter synonym that maintains line length.
   // Not IF to avoid any confusion that IF is somehow special.
@@ -1580,11 +1591,7 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
   AllowSimpleBracedStatements.ColumnLimit = 40;
   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
   FormatStyle::SBS_Always;
-
-  AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
-  FormatStyle::SIS_WithoutElse;
   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
-
   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;



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


[PATCH] D124956: [clang-format] Fix another bug in AlignConsecutiveAssignments

2022-05-05 Thread Owen Pan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG8b626a2caa67: [clang-format] Fix another bug in 
AlignConsecutiveAssignments (authored by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124956

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
@@ -18023,6 +18023,12 @@
"}",
Style);
 
+  verifyFormat("unsigned i = 0;\n"
+   "int a[]= {\n"
+   "1234567890,\n"
+   "-1234567890};",
+   Style);
+
   Style.ColumnLimit = 120;
 
   // clang-format off
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -398,6 +398,8 @@
 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace))
   return false;
   }
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return true;
 }
 


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -18023,6 +18023,12 @@
"}",
Style);
 
+  verifyFormat("unsigned i = 0;\n"
+   "int a[]= {\n"
+   "1234567890,\n"
+   "-1234567890};",
+   Style);
+
   Style.ColumnLimit = 120;
 
   // clang-format off
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -398,6 +398,8 @@
 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace))
   return false;
   }
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return true;
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8b626a2 - [clang-format] Fix another bug in AlignConsecutiveAssignments

2022-05-05 Thread via cfe-commits

Author: owenca
Date: 2022-05-05T14:48:56-07:00
New Revision: 8b626a2caa672a174829105ff7749d8d9a080f2a

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

LOG: [clang-format] Fix another bug in AlignConsecutiveAssignments

The ShouldShiftBeAdded lambda checks if extra space should be
added before the wrapped part of a braced list. If the first
element of the list is wrapped, no extra space should be added.

Fixes #55161.

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index cf4ef6338f1b..8563312b45bb 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -398,6 +398,8 @@ AlignTokenSequence(const FormatStyle , unsigned 
Start, unsigned End,
 Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace))
   return false;
   }
+  if (Changes[ScopeStart].NewlinesBefore > 0)
+return false;
   return true;
 }
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 78a3c21c3300..40e2cb054b24 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -18023,6 +18023,12 @@ TEST_F(FormatTest, AlignWithLineBreaks) {
"}",
Style);
 
+  verifyFormat("unsigned i = 0;\n"
+   "int a[]= {\n"
+   "1234567890,\n"
+   "-1234567890};",
+   Style);
+
   Style.ColumnLimit = 120;
 
   // clang-format off



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


[PATCH] D121733: Clean pathnames in FileManager.

2022-05-05 Thread Paul Pluzhnikov via Phabricator via cfe-commits
ppluzhnikov updated this revision to Diff 427460.
ppluzhnikov added a comment.
Herald added a subscriber: carlosgalvezp.

Fix Winx64 `clang-tidy/checkers/google-upgrade-googletest-case.cpp` failure.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121733

Files:
  clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp
  clang-tools-extra/test/clang-apply-replacements/conflict.cpp
  clang-tools-extra/test/clang-apply-replacements/order-dependent.cpp
  clang-tools-extra/test/clang-tidy/checkers/abseil-no-internal-dependencies.cpp
  clang-tools-extra/test/clang-tidy/checkers/abseil-no-namespace.cpp
  clang/bindings/python/tests/cindex/test_translation_unit.py
  clang/lib/Basic/FileManager.cpp
  clang/test/ClangScanDeps/header-search-pruning-transitive.c
  clang/test/Frontend/dependency-gen.c
  clang/test/Index/skip-parsed-bodies/compile_commands.json
  clang/test/Modules/cxx20-hu-04.cpp
  clang/test/Modules/cxx20-hu-05.cpp
  clang/test/Modules/cxx20-hu-06.cpp
  clang/test/Modules/filename.cpp
  clang/unittests/Lex/HeaderSearchTest.cpp
  clang/unittests/Tooling/Syntax/TokensTest.cpp
  clang/unittests/Tooling/TransformerTest.cpp

Index: clang/unittests/Tooling/TransformerTest.cpp
===
--- clang/unittests/Tooling/TransformerTest.cpp
+++ clang/unittests/Tooling/TransformerTest.cpp
@@ -1622,21 +1622,22 @@
   return L.getFilePath() < R.getFilePath();
 });
 
-  ASSERT_EQ(Changes[0].getFilePath(), "./input.h");
-  EXPECT_THAT(Changes[0].getInsertedHeaders(), IsEmpty());
-  EXPECT_THAT(Changes[0].getRemovedHeaders(), IsEmpty());
+  const auto _h = Changes[1];
+  ASSERT_EQ(change_h.getFilePath(), "input.h");
+  EXPECT_THAT(change_h.getInsertedHeaders(), IsEmpty());
+  EXPECT_THAT(change_h.getRemovedHeaders(), IsEmpty());
   llvm::Expected UpdatedCode =
-  clang::tooling::applyAllReplacements(Header,
-   Changes[0].getReplacements());
+  clang::tooling::applyAllReplacements(Header, change_h.getReplacements());
   ASSERT_TRUE(static_cast(UpdatedCode))
   << "Could not update code: " << llvm::toString(UpdatedCode.takeError());
   EXPECT_EQ(format(*UpdatedCode), "");
 
-  ASSERT_EQ(Changes[1].getFilePath(), "input.cc");
-  EXPECT_THAT(Changes[1].getInsertedHeaders(), IsEmpty());
-  EXPECT_THAT(Changes[1].getRemovedHeaders(), IsEmpty());
-  UpdatedCode = clang::tooling::applyAllReplacements(
-  Source, Changes[1].getReplacements());
+  const auto _cc = Changes[0];
+  ASSERT_EQ(change_cc.getFilePath(), "input.cc");
+  EXPECT_THAT(change_cc.getInsertedHeaders(), IsEmpty());
+  EXPECT_THAT(change_cc.getRemovedHeaders(), IsEmpty());
+  UpdatedCode =
+  clang::tooling::applyAllReplacements(Source, change_cc.getReplacements());
   ASSERT_TRUE(static_cast(UpdatedCode))
   << "Could not update code: " << llvm::toString(UpdatedCode.takeError());
   EXPECT_EQ(format(*UpdatedCode), format("#include \"input.h\"\n"));
@@ -1659,7 +1660,7 @@
   {{"input.h", Header}}));
 
   ASSERT_EQ(Changes.size(), 1U);
-  ASSERT_EQ(Changes[0].getFilePath(), "./input.h");
+  ASSERT_EQ(Changes[0].getFilePath(), "input.h");
   EXPECT_THAT(Changes[0].getInsertedHeaders(), ElementsAre("header.h"));
   EXPECT_THAT(Changes[0].getRemovedHeaders(), IsEmpty());
   llvm::Expected UpdatedCode =
@@ -1708,7 +1709,7 @@
   ResultOf([](const AtomicChange ) { return C.getFilePath(); },
"input.cc"),
   ResultOf([](const AtomicChange ) { return C.getFilePath(); },
-   "./input.h";
+   "input.h";
 }
 
 TEST_F(TransformerTest, GeneratesMetadata) {
Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -292,7 +292,7 @@
   {"int main() {}",
R"(expanded tokens:
   int main ( ) { }
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 int main ( ) { }
   no mappings.
@@ -301,7 +301,7 @@
   {"\t\n  int\t\n  main\t\n  (\t\n  )\t\n{\t\n  }\t\n",
R"(expanded tokens:
   int main ( ) { }
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 int main ( ) { }
   no mappings.
@@ -313,7 +313,7 @@
   )cpp",
R"(expanded tokens:
   
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 # pragma GCC visibility push ( public ) # pragma GCC visibility pop
   mappings:
@@ -322,7 +322,7 @@
   // Empty files should not crash.
   {R"cpp()cpp", R"(expanded tokens:
   
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 
   no mappings.
@@ -336,7 +336,7 @@
 )cpp",
   R"(expanded tokens:
   a
-file './input.cpp'
+file 'input.cpp'
   spelled tokens:
 a # define MACRO ( ) A # B
   mappings:
@@ -401,7 +401,7 @@
   std::string 

[clang] 16dcbb5 - [ORC] Return ExecutorAddrs rather than JITEvaluatedSymbols from LLJIT::lookup.

2022-05-05 Thread Lang Hames via cfe-commits

Author: Lang Hames
Date: 2022-05-05T13:56:00-07:00
New Revision: 16dcbb53dc7968a3752661aac731172ebe0faf64

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

LOG: [ORC] Return ExecutorAddrs rather than JITEvaluatedSymbols from 
LLJIT::lookup.

Clients don't care about linkage, and ExecutorAddr is much more ergonomic.

Added: 


Modified: 
clang/lib/Interpreter/IncrementalExecutor.cpp
llvm/examples/HowToUseLLJIT/HowToUseLLJIT.cpp
llvm/examples/OrcV2Examples/LLJITDumpObjects/LLJITDumpObjects.cpp
llvm/examples/OrcV2Examples/LLJITRemovableCode/LLJITRemovableCode.cpp

llvm/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/LLJITWithCustomObjectLinkingLayer.cpp

llvm/examples/OrcV2Examples/LLJITWithExecutorProcessControl/LLJITWithExecutorProcessControl.cpp

llvm/examples/OrcV2Examples/LLJITWithGDBRegistrationListener/LLJITWithGDBRegistrationListener.cpp

llvm/examples/OrcV2Examples/LLJITWithLazyReexports/LLJITWithLazyReexports.cpp
llvm/examples/OrcV2Examples/LLJITWithObjectCache/LLJITWithObjectCache.cpp

llvm/examples/OrcV2Examples/LLJITWithObjectLinkingLayerPlugin/LLJITWithObjectLinkingLayerPlugin.cpp

llvm/examples/OrcV2Examples/LLJITWithOptimizingIRTransform/LLJITWithOptimizingIRTransform.cpp

llvm/examples/OrcV2Examples/LLJITWithRemoteDebugging/LLJITWithRemoteDebugging.cpp

llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp
llvm/include/llvm/ExecutionEngine/Orc/LLJIT.h
llvm/lib/ExecutionEngine/Orc/LLJIT.cpp
llvm/lib/ExecutionEngine/Orc/OrcV2CBindings.cpp
llvm/tools/lli/lli.cpp

Removed: 




diff  --git a/clang/lib/Interpreter/IncrementalExecutor.cpp 
b/clang/lib/Interpreter/IncrementalExecutor.cpp
index 705235aafa070..75c385aa409f3 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.cpp
+++ b/clang/lib/Interpreter/IncrementalExecutor.cpp
@@ -68,7 +68,7 @@ IncrementalExecutor::getSymbolAddress(llvm::StringRef Name,
 
   if (!Sym)
 return Sym.takeError();
-  return Sym->getAddress();
+  return Sym->getValue();
 }
 
 } // end namespace clang

diff  --git a/llvm/examples/HowToUseLLJIT/HowToUseLLJIT.cpp 
b/llvm/examples/HowToUseLLJIT/HowToUseLLJIT.cpp
index 170a899136054..cdeaa745f91ef 100644
--- a/llvm/examples/HowToUseLLJIT/HowToUseLLJIT.cpp
+++ b/llvm/examples/HowToUseLLJIT/HowToUseLLJIT.cpp
@@ -91,8 +91,8 @@ int main(int argc, char *argv[]) {
   ExitOnErr(J->addIRModule(std::move(M)));
 
   // Look up the JIT'd function, cast it to a function pointer, then call it.
-  auto Add1Sym = ExitOnErr(J->lookup("add1"));
-  int (*Add1)(int) = (int (*)(int))Add1Sym.getAddress();
+  auto Add1Addr = ExitOnErr(J->lookup("add1"));
+  int (*Add1)(int) = Add1Addr.toPtr();
 
   int Result = Add1(42);
   outs() << "add1(42) = " << Result << "\n";

diff  --git a/llvm/examples/OrcV2Examples/LLJITDumpObjects/LLJITDumpObjects.cpp 
b/llvm/examples/OrcV2Examples/LLJITDumpObjects/LLJITDumpObjects.cpp
index 2c975b188fb64..c3752cc36c060 100644
--- a/llvm/examples/OrcV2Examples/LLJITDumpObjects/LLJITDumpObjects.cpp
+++ b/llvm/examples/OrcV2Examples/LLJITDumpObjects/LLJITDumpObjects.cpp
@@ -61,8 +61,8 @@ int main(int argc, char *argv[]) {
   ExitOnErr(J->addIRModule(std::move(M)));
 
   // Look up the JIT'd function, cast it to a function pointer, then call it.
-  auto Add1Sym = ExitOnErr(J->lookup("add1"));
-  int (*Add1)(int) = (int (*)(int))Add1Sym.getAddress();
+  auto Add1Addr = ExitOnErr(J->lookup("add1"));
+  int (*Add1)(int) = Add1Addr.toPtr();
 
   int Result = Add1(42);
   outs() << "add1(42) = " << Result << "\n";

diff  --git 
a/llvm/examples/OrcV2Examples/LLJITRemovableCode/LLJITRemovableCode.cpp 
b/llvm/examples/OrcV2Examples/LLJITRemovableCode/LLJITRemovableCode.cpp
index 29735d11f70d7..4739efc2eccf1 100644
--- a/llvm/examples/OrcV2Examples/LLJITRemovableCode/LLJITRemovableCode.cpp
+++ b/llvm/examples/OrcV2Examples/LLJITRemovableCode/LLJITRemovableCode.cpp
@@ -92,7 +92,7 @@ int main(int argc, char *argv[]) {
   auto PrintSymbol = [&](StringRef Name) {
 dbgs() << Name << " = ";
 if (auto Sym = J->lookup(JD, Name))
-  dbgs() << formatv("{0:x}\n", Sym->getAddress());
+  dbgs() << *Sym;
 else
   dbgs() << "error: " << toString(Sym.takeError()) << "\n";
   };

diff  --git 
a/llvm/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/LLJITWithCustomObjectLinkingLayer.cpp
 
b/llvm/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/LLJITWithCustomObjectLinkingLayer.cpp
index 907dc83f46333..16c81de54c86f 100644
--- 
a/llvm/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/LLJITWithCustomObjectLinkingLayer.cpp
+++ 
b/llvm/examples/OrcV2Examples/LLJITWithCustomObjectLinkingLayer/LLJITWithCustomObjectLinkingLayer.cpp
@@ -56,8 +56,8 @@ int main(int argc, char 

[PATCH] D125011: [MSVC] Add support for pragma alloc_text

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

Thanks for working on this compatibility extension!

This is missing all of the lexing tests which validate that we correctly 
diagnose malformed pragmas. We're also missing all sema tests for the 
diagnostics added or emitted from there. When you add the sema tests, I think 
we should have diagnostics for:

  // First case
  #pragma alloc_text("abc", does_not_exist)
  
  // Second case
  void already_defined(void) {}
  #pragma alloc_text("abc", already_defined)

Also, what should happen in a case like this?

  __declspec(code_seg("text")) static void section_mismatch(void);
  #pragma alloc_text("hoo boy", section_mismatch) // Pretty sure we want to 
diagnose this?

MSDN docs say that the pragma "can't be used in a function" which is subtly 
different from "at file scope". e.g., MSVC accepts:

  void umm(void);
  struct S {
  #pragma alloc_text("hoo boy", umm)
int a;
  };

which is a bit of a silly example, but it also accepts:

  extern "C" void umm(void);
  namespace N {
  #pragma alloc_text("hoo boy", umm)
  }
  
  // or
  extern "C" {
   void okay(void);
  #pragma alloc_text("hoo boy", okay)
  }

which are far more reasonable for users to write. I think we should have tests 
for these situations to make sure we accept the same code as MSVC unless the 
behavior there seems like a bug.

In D125011#3494014 , @steplong wrote:

> Update patch to error out if a function is not C linkage. Not sure how to 
> check if a function has been declared

At the time we're processing the pragma (within Sema), I would perform a lookup 
on the identifier given by the pragma to validate that it 1) can be found, 2) 
finds a function, 3) the function found is in an extern "C" context. To do the 
lookup, I'd probably use `Sema::LookupSingleName()` because this can't be used 
on an overloaded function. (And you should add tests for specifying a member 
function and an overloaded function.)




Comment at: clang/include/clang/Sema/Sema.h:727
 
+  /// Sections used with #pragma alloc_text
+  llvm::StringMap> FunctionToSectionMap;





Comment at: clang/include/clang/Sema/Sema.h:10337
 
+  void AddSectionMSAllocText(FunctionDecl *FD);
+

This could probably have some comments with it.



Comment at: clang/lib/Parse/ParsePragma.cpp:1160-1165
+  if (Tok.isNot(tok::l_paren)) {
+PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
+<< PragmaName;
+return false;
+  }
+  PP.Lex(Tok);

This looks like it can be replaced with `ExpectAndConsume()`. However, should 
we be diagnosing use of this pragma for non-MSVC compatible triples before we 
start parsing?



Comment at: clang/lib/Parse/ParsePragma.cpp:1176-1179
+  if (SegmentName->getCharByteWidth() != 1) {
+PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
+<< PragmaName;
+return false;

I think we want to test `isAscii()` instead of looking at the byte width; we 
don't want to accept `u8"whatever"` any more than we want to accept 
`L"whatever"`.

(The diagnostic text is also pretty bad because it'll diagnose non-wide 
literals as being wide, but that's an existing deficiency with the diagnostic 
and can be addressed separately.)



Comment at: clang/lib/Parse/ParsePragma.cpp:1182
+
+  if (Tok.isNot(tok::comma)) {
+PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_comma) << PragmaName;

`ExpectAndConsume()`



Comment at: clang/lib/Parse/ParsePragma.cpp:1205-1209
+  if (Tok.isNot(tok::r_paren)) {
+PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
+return false;
+  }
+  PP.Lex(Tok);

`ExpectAndConsume()`



Comment at: clang/lib/Parse/ParsePragma.cpp:1216
+  }
+  PP.Lex(Tok);
+

`ExpectAndConsume()`



Comment at: clang/lib/Sema/SemaAttr.cpp:1094-1095
+void Sema::AddSectionMSAllocText(FunctionDecl *FD) {
+  if (!FD->getIdentifier())
+return;
+

Do we have to treat `main()` as being special?



Comment at: clang/lib/Sema/SemaAttr.cpp:1104
+
+if (!FD->isExternC()) {
+  Diag(Loc, diag::err_pragma_alloc_text_c_linkage);

I think you need to use `isInExternCContext()` instead (and add test coverage 
for `extern "C" { void func(void); }`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125011

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


[PATCH] D125026: [clang-tidy][NFC] Reimplement most of SimplifyBooleanExpr with RecursiveASTVisitors

2022-05-05 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 427436.
njames93 added a comment.

Remove SimplifyBoolExprMatchers header


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h

Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprMatchers.h
+++ /dev/null
@@ -1,68 +0,0 @@
-//===-- SimplifyBooleanExprMatchers.h - clang-tidy ===//
-//
-// 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/ASTMatchers/ASTMatchersInternal.h"
-#include "clang/ASTMatchers/ASTMatchersMacros.h"
-
-namespace clang {
-namespace ast_matchers {
-
-/// Matches the substatement associated with a case, default or label statement.
-///
-/// Given
-/// \code
-///   switch (1) { case 1: break; case 2: return; break; default: return; break;
-///   }
-///   foo: return;
-///   bar: break;
-/// \endcode
-///
-/// caseStmt(hasSubstatement(returnStmt()))
-///   matches "case 2: return;"
-/// defaultStmt(hasSubstatement(returnStmt()))
-///   matches "default: return;"
-/// labelStmt(hasSubstatement(breakStmt()))
-///   matches "bar: break;"
-AST_POLYMORPHIC_MATCHER_P(hasSubstatement,
-  AST_POLYMORPHIC_SUPPORTED_TYPES(CaseStmt, DefaultStmt,
-  LabelStmt),
-  internal::Matcher, InnerMatcher) {
-  return InnerMatcher.matches(*Node.getSubStmt(), Finder, Builder);
-}
-
-/// Matches two consecutive statements within a compound statement.
-///
-/// Given
-/// \code
-///   { if (x > 0) return true; return false; }
-/// \endcode
-/// compoundStmt(hasSubstatementSequence(ifStmt(), returnStmt()))
-///   matches '{ if (x > 0) return true; return false; }'
-AST_POLYMORPHIC_MATCHER_P2(hasSubstatementSequence,
-   AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
-   StmtExpr),
-   internal::Matcher, InnerMatcher1,
-   internal::Matcher, InnerMatcher2) {
-  if (const CompoundStmt *CS = CompoundStmtMatcher::get(Node)) {
-auto It = matchesFirstInPointerRange(InnerMatcher1, CS->body_begin(),
- CS->body_end(), Finder, Builder);
-while (It != CS->body_end()) {
-  ++It;
-  if (It == CS->body_end())
-return false;
-  if (InnerMatcher2.matches(**It, Finder, Builder))
-return true;
-  It = matchesFirstInPointerRange(InnerMatcher1, It, CS->body_end(), Finder,
-  Builder);
-}
-  }
-  return false;
-}
-
-} // namespace ast_matchers
-} // namespace clang
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
@@ -34,73 +34,32 @@
 private:
   class Visitor;
 
-  void reportBinOp(const ast_matchers::MatchFinder::MatchResult ,
-   const BinaryOperator *Op);
+  void reportBinOp(const ASTContext , const BinaryOperator *Op);
 
-  void matchBoolCondition(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef BooleanId);
+  void replaceWithThenStatement(const ASTContext ,
+const IfStmt *IfStatement,
+const Expr *BoolLiteral);
 
-  void matchTernaryResult(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void replaceWithElseStatement(const ASTContext ,
+const IfStmt *IfStatement,
+const Expr *BoolLiteral);
 
-  void matchIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void replaceWithCondition(const ASTContext ,
+const ConditionalOperator *Ternary, bool Negated);
 
-  void matchIfAssignsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void replaceWithReturnCondition(const ASTContext , const IfStmt *If,
+  const Expr *BoolLiteral, bool Negated);
 
-  void matchCompoundIfReturnsBool(ast_matchers::MatchFinder *Finder, 

[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.

It looks like all of my comments are resolved now, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D124965: [clang][dataflow] Centralize expression skipping logic

2022-05-05 Thread Eric Li 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 rG45643cfcc12e: [clang][dataflow] Centralize expression 
skipping logic (authored by li.zhe.hua).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124965

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -46,7 +46,7 @@
   : CFCtx(CFCtx), BlockToState(BlockToState) {}
 
   const Environment *getEnvironment(const Stmt ) const override {
-auto BlockIT = CFCtx.getStmtToBlock().find();
+auto BlockIT = CFCtx.getStmtToBlock().find((S));
 assert(BlockIT != CFCtx.getStmtToBlock().end());
 const auto  = BlockToState[BlockIT->getSecond()->getBlockID()];
 assert(State.hasValue());
@@ -77,26 +77,26 @@
   : StmtToEnv(StmtToEnv), Env(Env), BlockSuccIdx(BlockSuccIdx) {}
 
   void VisitIfStmt(const IfStmt *S) {
-auto *Cond = ignoreExprWithCleanups(S->getCond())->IgnoreParens();
+auto *Cond = S->getCond();
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
 
   void VisitWhileStmt(const WhileStmt *S) {
-auto *Cond = ignoreExprWithCleanups(S->getCond())->IgnoreParens();
+auto *Cond = S->getCond();
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
 
   void VisitBinaryOperator(const BinaryOperator *S) {
 assert(S->getOpcode() == BO_LAnd || S->getOpcode() == BO_LOr);
-auto *LHS = ignoreExprWithCleanups(S->getLHS())->IgnoreParens();
+auto *LHS = S->getLHS();
 assert(LHS != nullptr);
 extendFlowCondition(*LHS);
   }
 
   void VisitConditionalOperator(const ConditionalOperator *S) {
-auto *Cond = ignoreExprWithCleanups(S->getCond())->IgnoreParens();
+auto *Cond = S->getCond();
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -33,27 +33,12 @@
 namespace clang {
 namespace dataflow {
 
-const Expr *ignoreExprWithCleanups(const Expr *E) {
-  if (auto *C = dyn_cast_or_null(E))
-return C->getSubExpr();
-  return E;
-}
-
 static BoolValue (const Expr , const Expr ,
   Environment ) {
-  // Equality of booleans involves implicit integral casts. Ignore these casts
-  // for now and focus on the values associated with the wrapped expressions.
-  // FIXME: Consider changing this once the framework offers better support for
-  // integral casts.
-  const Expr *LHSNorm = LHS.IgnoreCasts();
-  const Expr *RHSNorm = RHS.IgnoreCasts();
-  assert(LHSNorm != nullptr);
-  assert(RHSNorm != nullptr);
-
-  if (auto *LHSValue = dyn_cast_or_null(
-  Env.getValue(*LHSNorm, SkipPast::Reference)))
-if (auto *RHSValue = dyn_cast_or_null(
-Env.getValue(*RHSNorm, SkipPast::Reference)))
+  if (auto *LHSValue =
+  dyn_cast_or_null(Env.getValue(LHS, SkipPast::Reference)))
+if (auto *RHSValue =
+dyn_cast_or_null(Env.getValue(RHS, SkipPast::Reference)))
   return Env.makeIff(*LHSValue, *RHSValue);
 
   return Env.makeAtomicBoolValue();
@@ -65,14 +50,10 @@
   : StmtToEnv(StmtToEnv), Env(Env) {}
 
   void VisitBinaryOperator(const BinaryOperator *S) {
-// The CFG does not contain `ParenExpr` as top-level statements in basic
-// blocks, however sub-expressions can still be of that type.
-assert(S->getLHS() != nullptr);
-const Expr *LHS = S->getLHS()->IgnoreParens();
+const Expr *LHS = S->getLHS();
 assert(LHS != nullptr);
 
-assert(S->getRHS() != nullptr);
-const Expr *RHS = S->getRHS()->IgnoreParens();
+const Expr *RHS = S->getRHS();
 assert(RHS != nullptr);
 
 switch (S->getOpcode()) {
@@ -155,7 +136,7 @@
   return;
 }
 
-InitExpr = ignoreExprWithCleanups(D.getInit());
+InitExpr = D.getInit();
 assert(InitExpr != nullptr);
 
 if (D.getType()->isReferenceType()) {
@@ -476,8 +457,7 @@
   assert(S->getArg(0) != nullptr);
   // `__builtin_expect` returns by-value, so strip away any potential
   // references in the argument.
-  auto *ArgLoc = 

[clang] 45643cf - [clang][dataflow] Centralize expression skipping logic

2022-05-05 Thread Eric Li via cfe-commits

Author: Eric Li
Date: 2022-05-05T20:28:11Z
New Revision: 45643cfcc12ea6152fb9516ed24f5adf7469eb4c

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

LOG: [clang][dataflow] Centralize expression skipping logic

A follow-up to 62b2a47 to centralize the logic that skips expressions
that the CFG does not emit. This allows client code to avoid
sprinkling this logic everywhere.

Add redirects in the transfer function to similarly skip such
expressions by forwarding the visit to the sub-expression.

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/include/clang/Analysis/FlowSensitive/Transfer.h
clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/lib/Analysis/FlowSensitive/Transfer.cpp
clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp

Removed: 




diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
index a762cb9de48bd..e2820fcb55655 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
@@ -31,6 +31,19 @@
 namespace clang {
 namespace dataflow {
 
+/// Skip past nodes that the CFG does not emit. These nodes are invisible to
+/// flow-sensitive analysis, and should be ignored as they will effectively not
+/// exist.
+///
+///   * `ParenExpr` - The CFG takes the operator precedence into account, but
+///   otherwise omits the node afterwards.
+///
+///   * `ExprWithCleanups` - The CFG will generate the appropriate calls to
+///   destructors and then omit the node.
+///
+const Expr (const Expr );
+const Stmt (const Stmt );
+
 /// Owns objects that encompass the state of a program and stores context that
 /// is used during dataflow analysis.
 class DataflowAnalysisContext {
@@ -95,14 +108,15 @@ class DataflowAnalysisContext {
   ///
   ///  `E` must not be assigned a storage location.
   void setStorageLocation(const Expr , StorageLocation ) {
-assert(ExprToLoc.find() == ExprToLoc.end());
-ExprToLoc[] = 
+const Expr  = ignoreCFGOmittedNodes(E);
+assert(ExprToLoc.find() == ExprToLoc.end());
+ExprToLoc[] = 
   }
 
   /// Returns the storage location assigned to `E` or null if `E` has no
   /// assigned storage location.
   StorageLocation *getStorageLocation(const Expr ) const {
-auto It = ExprToLoc.find();
+auto It = ExprToLoc.find((E));
 return It == ExprToLoc.end() ? nullptr : It->second;
   }
 

diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index 019d07c9b7f72..0a2c75f804c2a 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -172,10 +172,6 @@ class Environment {
   /// Creates a storage location for `E`. Does not assign the returned storage
   /// location to `E` in the environment. Does not assign a value to the
   /// returned storage location in the environment.
-  ///
-  /// Requirements:
-  ///
-  ///  `E` must not be a `ExprWithCleanups`.
   StorageLocation (const Expr );
 
   /// Assigns `Loc` as the storage location of `D` in the environment.
@@ -195,16 +191,11 @@ class Environment {
   /// Requirements:
   ///
   ///  `E` must not be assigned a storage location in the environment.
-  ///  `E` must not be a `ExprWithCleanups`.
   void setStorageLocation(const Expr , StorageLocation );
 
   /// Returns the storage location assigned to `E` in the environment, applying
   /// the `SP` policy for skipping past indirections, or null if `E` isn't
   /// assigned a storage location in the environment.
-  ///
-  /// Requirements:
-  ///
-  ///  `E` must not be a `ExprWithCleanups`.
   StorageLocation *getStorageLocation(const Expr , SkipPast SP) const;
 
   /// Returns the storage location assigned to the `this` pointee in the
@@ -235,12 +226,6 @@ class Environment {
 
   /// Equivalent to `getValue(getStorageLocation(E, SP), SkipPast::None)` if 
`E`
   /// is assigned a storage location in the environment, otherwise returns 
null.
-  ///
-  /// Requirements:
-  ///
-  ///  `E` must not be a `ExprWithCleanups`.
-  ///
-  /// FIXME: `Environment` should ignore any `ExprWithCleanups` it sees.
   Value *getValue(const Expr , SkipPast SP) const;
 
   /// Transfers ownership of `Loc` to the analysis context and returns a

diff  --git 

[PATCH] D125026: [clang-tidy][NFC] Reimplement most of SimplifyBooleanExpr with RecursiveASTVisitors

2022-05-05 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 427430.
njames93 added a comment.

Transform final matcher, Benchmark -> 0.82s.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h

Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
@@ -10,6 +10,8 @@
 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_SIMPLIFY_BOOLEAN_EXPR_H
 
 #include "../ClangTidyCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Stmt.h"
 
 namespace clang {
 namespace tidy {
@@ -34,73 +36,32 @@
 private:
   class Visitor;
 
-  void reportBinOp(const ast_matchers::MatchFinder::MatchResult ,
-   const BinaryOperator *Op);
+  void reportBinOp(const ASTContext , const BinaryOperator *Op);
 
-  void matchBoolCondition(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef BooleanId);
+  void replaceWithThenStatement(const ASTContext ,
+const IfStmt *IfStatement,
+const Expr *BoolLiteral);
 
-  void matchTernaryResult(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void replaceWithElseStatement(const ASTContext ,
+const IfStmt *IfStatement,
+const Expr *BoolLiteral);
 
-  void matchIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void replaceWithCondition(const ASTContext ,
+const ConditionalOperator *Ternary, bool Negated);
 
-  void matchIfAssignsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void replaceWithReturnCondition(const ASTContext , const IfStmt *If,
+  const Expr *BoolLiteral, bool Negated);
 
-  void matchCompoundIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void replaceWithAssignment(const ASTContext , const IfStmt *If,
+ const Expr *Var, SourceLocation Loc, bool Negated);
 
-  void matchCaseIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void replaceCompoundReturnWithCondition(const ASTContext ,
+  const ReturnStmt *Ret, bool Negated,
+  const IfStmt *If);
 
-  void matchDefaultIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
- StringRef Id);
-
-  void matchLabelIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-   StringRef Id);
-
-  void
-  replaceWithThenStatement(const ast_matchers::MatchFinder::MatchResult ,
-   const Expr *BoolLiteral);
-
-  void
-  replaceWithElseStatement(const ast_matchers::MatchFinder::MatchResult ,
-   const Expr *BoolLiteral);
-
-  void
-  replaceWithCondition(const ast_matchers::MatchFinder::MatchResult ,
-   const ConditionalOperator *Ternary, bool Negated);
-
-  void replaceWithReturnCondition(
-  const ast_matchers::MatchFinder::MatchResult , const IfStmt *If,
-  bool Negated);
-
-  void
-  replaceWithAssignment(const ast_matchers::MatchFinder::MatchResult ,
-const IfStmt *If, bool Negated);
-
-  void replaceCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult ,
-  const CompoundStmt *Compound, bool Negated);
-
-  void replaceCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated,
-  const IfStmt *If);
-
-  void replaceCaseCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated);
-
-  void replaceDefaultCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated);
-
-  void replaceLabelCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated);
-
-  void issueDiag(const ast_matchers::MatchFinder::MatchResult ,
- SourceLocation Loc, StringRef Description,
- SourceRange ReplacementRange, StringRef Replacement);
+  void issueDiag(const ASTContext , SourceLocation Loc,
+ StringRef Description, SourceRange ReplacementRange,
+ StringRef Replacement);
 
   const bool ChainedConditionalReturn;
   const bool ChainedConditionalAssignment;
Index: 

[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added a comment.

In D121120#3494427 , @xazax.hun wrote:

> Overall this looks good to me. However, I think this might not use the full 
> potential of the check itself. With the information that the dataflow 
> framework have it could distinguish between **potentially** unsafe accesses 
> and **provably** unsafe accesses depending on whether the `has_value` 
> property is constrained to be false. From the user point of view, it would be 
> nice to emit different warning messages for the above two cases. This can 
> help to gradually introduce this check to a larger codebase and focus on the 
> higher severity diagnostics first.

Agreed. I've filed this in our issue tracker (which I'm still planning to port 
over to github...).




Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:84
+  if (!BlockToOutputState ||
+  BlockToOutputState->size() <= Context->getCFG().getExit().getBlockID())
+return;

xazax.hun wrote:
> xazax.hun wrote:
> > ymandel wrote:
> > > xazax.hun wrote:
> > > > xazax.hun wrote:
> > > > > Could the size of the vector ever be wrong? Should this be an assert 
> > > > > instead?
> > > > Whoops, after the update this comment is out of place, now it supposed 
> > > > to be on line 60. 
> > > Based on my reading, it is a rare, but possible condition. Basically, we 
> > > need code where the exit block is unreachable, which I believe can happen 
> > > in weird cases like:
> > > 
> > > ```
> > > while(true) {...}
> > > ```
> > > https://godbolt.org/z/rfEnfaWTv -- notice the lack of predecessors for 
> > > the exit block.
> > > 
> > > See the code here, which follows the ordering of the blocks and doesn't 
> > > force blocks to be processed:
> > > 
> > > https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp#L337-L364
> > Interesting. Since we already have optionals in the vector, I assumed we 
> > will always have matching size. I think we might want to change this so 
> > there is only one way for the analysis to not provide a state for a basic 
> > block to make this a bit less confusing, 
> Actually, in the linked code I see ` 
> BlockStates.resize(CFCtx.getCFG().size(), llvm::None);`. So I would expect 
> the size to be always right with possibly some `None`s for the nodes that 
> were not processed.
> Actually, in the linked code I see ` 
> BlockStates.resize(CFCtx.getCFG().size(), llvm::None);`. So I would expect 
> the size to be always right with possibly some `None`s for the nodes that 
> were not processed.
Ah, my mistake! I thought `resize` only allocated the space. #TIL

Changed to an assert. Thanks.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 427429.
ymandel marked an inline comment as done.
ymandel added a comment.

add assert


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/types/optional.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp

Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -13,6 +13,7 @@
 
 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/Stmt.h"
@@ -29,13 +30,9 @@
 
 namespace clang {
 namespace dataflow {
-namespace {
-
-using namespace ::clang::ast_matchers;
 
-using LatticeTransferState = TransferState;
-
-auto optionalClass() {
+ast_matchers::DeclarationMatcher optionalClass() {
+  using namespace ::clang::ast_matchers;
   return classTemplateSpecializationDecl(
   anyOf(hasName("std::optional"), hasName("std::__optional_storage_base"),
 hasName("__optional_destruct_base"), hasName("absl::optional"),
@@ -43,6 +40,12 @@
   hasTemplateArgument(0, refersToType(type().bind("T";
 }
 
+namespace {
+
+using namespace ::clang::ast_matchers;
+
+using LatticeTransferState = TransferState;
+
 auto hasOptionalType() { return hasType(optionalClass()); }
 
 auto isOptionalMemberCallWithName(
@@ -230,6 +233,8 @@
   }
 
   // Record that this unwrap is *not* provably safe.
+  // FIXME: include either the name of the optional (if applicable) or a source
+  // range of the access for easier intepretation of the result.
   State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc());
 }
 
Index: clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
===
--- clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -36,6 +36,9 @@
   bool IgnoreSmartPointerDereference = false;
 };
 
+/// A matcher for the optional classes covered by this model.
+ast_matchers::DeclarationMatcher optionalClass();
+
 /// Dataflow analysis that discovers unsafe accesses of optional values and
 /// adds the respective source locations to the lattice.
 ///
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
@@ -0,0 +1,112 @@
+// RUN: %check_clang_tidy %s bugprone-unchecked-optional-access %t -- -- -I %S/Inputs/
+
+#include "absl/types/optional.h"
+
+void unchecked_value_access(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
+}
+
+void unchecked_deref_operator_access(const absl::optional ) {
+  *opt;
+  // CHECK-MESSAGES: :[[@LINE-1]]:4: warning: unchecked access to optional value
+}
+
+struct Foo {
+  void foo() const {}
+};
+
+void unchecked_arrow_operator_access(const absl::optional ) {
+  opt->foo();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void f2(const absl::optional ) {
+  if (opt.has_value()) {
+opt.value();
+  }
+}
+
+template 
+void function_template_without_user(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template 
+void function_template_with_user(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void function_template_user(const absl::optional ) {
+  // Instantiate the f3 function template so that it gets matched by the check.
+  function_template_with_user(opt);
+}
+
+template 
+void function_template_with_specialization(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template <>
+void 

[PATCH] D124965: [clang][dataflow] Centralize expression skipping logic

2022-05-05 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua marked an inline comment as done.
li.zhe.hua added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:38-41
+  if (auto *LHSValue =
+  dyn_cast_or_null(Env.getValue(LHS, SkipPast::Reference)))
+if (auto *RHSValue =
+dyn_cast_or_null(Env.getValue(RHS, 
SkipPast::Reference)))

ymandel wrote:
> li.zhe.hua wrote:
> > ymandel wrote:
> > > Is the idea that the skipping is now built into `getValue` via 
> > > `getStorageLocation`?
> > I don't believe I fixed this. d002495 addressed this by having integral 
> > casts route to the sub-expression.
> Great. Just to be sure I understand: you mean that the `IgnoreCasts()` calls 
> were already redundant because of d002495?
Correct, that's my understanding. This diff hunk could be separately committed 
first. (And maybe it should, for blame clarity.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124965

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

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



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:84
+  if (!BlockToOutputState ||
+  BlockToOutputState->size() <= Context->getCFG().getExit().getBlockID())
+return;

xazax.hun wrote:
> ymandel wrote:
> > xazax.hun wrote:
> > > xazax.hun wrote:
> > > > Could the size of the vector ever be wrong? Should this be an assert 
> > > > instead?
> > > Whoops, after the update this comment is out of place, now it supposed to 
> > > be on line 60. 
> > Based on my reading, it is a rare, but possible condition. Basically, we 
> > need code where the exit block is unreachable, which I believe can happen 
> > in weird cases like:
> > 
> > ```
> > while(true) {...}
> > ```
> > https://godbolt.org/z/rfEnfaWTv -- notice the lack of predecessors for the 
> > exit block.
> > 
> > See the code here, which follows the ordering of the blocks and doesn't 
> > force blocks to be processed:
> > 
> > https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp#L337-L364
> Interesting. Since we already have optionals in the vector, I assumed we will 
> always have matching size. I think we might want to change this so there is 
> only one way for the analysis to not provide a state for a basic block to 
> make this a bit less confusing, 
Actually, in the linked code I see ` BlockStates.resize(CFCtx.getCFG().size(), 
llvm::None);`. So I would expect the size to be always right with possibly some 
`None`s for the nodes that were not processed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

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



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:84
+  if (!BlockToOutputState ||
+  BlockToOutputState->size() <= Context->getCFG().getExit().getBlockID())
+return;

ymandel wrote:
> xazax.hun wrote:
> > xazax.hun wrote:
> > > Could the size of the vector ever be wrong? Should this be an assert 
> > > instead?
> > Whoops, after the update this comment is out of place, now it supposed to 
> > be on line 60. 
> Based on my reading, it is a rare, but possible condition. Basically, we need 
> code where the exit block is unreachable, which I believe can happen in weird 
> cases like:
> 
> ```
> while(true) {...}
> ```
> https://godbolt.org/z/rfEnfaWTv -- notice the lack of predecessors for the 
> exit block.
> 
> See the code here, which follows the ordering of the blocks and doesn't force 
> blocks to be processed:
> 
> https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp#L337-L364
Interesting. Since we already have optionals in the vector, I assumed we will 
always have matching size. I think we might want to change this so there is 
only one way for the analysis to not provide a state for a basic block to make 
this a bit less confusing, 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D54943: [clang-tidy] implement new check 'misc-const-correctness' to add 'const' to unmodified variables

2022-05-05 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth marked an inline comment as done.
JonasToth added a comment.

Thank you for the review! I adjusted the patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 3 inline comments as done.
ymandel added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:84
+  if (!BlockToOutputState ||
+  BlockToOutputState->size() <= Context->getCFG().getExit().getBlockID())
+return;

xazax.hun wrote:
> xazax.hun wrote:
> > Could the size of the vector ever be wrong? Should this be an assert 
> > instead?
> Whoops, after the update this comment is out of place, now it supposed to be 
> on line 60. 
Based on my reading, it is a rare, but possible condition. Basically, we need 
code where the exit block is unreachable, which I believe can happen in weird 
cases like:

```
while(true) {...}
```
https://godbolt.org/z/rfEnfaWTv -- notice the lack of predecessors for the exit 
block.

See the code here, which follows the ordering of the blocks and doesn't force 
blocks to be processed:

https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp#L337-L364


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D54943: [clang-tidy] implement new check 'misc-const-correctness' to add 'const' to unmodified variables

2022-05-05 Thread Jonas Toth via Phabricator via cfe-commits
JonasToth updated this revision to Diff 427423.
JonasToth marked 3 inline comments as done.
JonasToth added a comment.

- addressing review comments and remove unrelated changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D54943

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp
  clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.h
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/misc-const-correctness.rst
  clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-cxx17.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-pointer-as-values.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-templates.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-transform-pointer-as-values.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-transform-values.cpp
  
clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-unaligned.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-values.cpp
  clang/lib/Analysis/ExprMutationAnalyzer.cpp
  clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp

Index: clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
===
--- clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -1251,13 +1251,13 @@
   AST =
   buildASTFromCode("void f() { int* x[2]; for (int* e : x) e = nullptr; }");
   Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
-  EXPECT_FALSE(isMutated(Results, AST.get()));
+  EXPECT_TRUE(isMutated(Results, AST.get()));
 
   AST = buildASTFromCode(
   "typedef int* IntPtr;"
   "void f() { int* x[2]; for (IntPtr e : x) e = nullptr; }");
   Results = match(withEnclosingCompound(declRefTo("x")), AST->getASTContext());
-  EXPECT_FALSE(isMutated(Results, AST.get()));
+  EXPECT_TRUE(isMutated(Results, AST.get()));
 }
 
 TEST(ExprMutationAnalyzerTest, RangeForArrayByConstRef) {
Index: clang/lib/Analysis/ExprMutationAnalyzer.cpp
===
--- clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -445,14 +445,16 @@
   // array is considered modified if the loop-variable is a non-const reference.
   const auto DeclStmtToNonRefToArray = declStmt(hasSingleDecl(varDecl(hasType(
   hasUnqualifiedDesugaredType(referenceType(pointee(arrayType(;
-  const auto RefToArrayRefToElements = match(
-  findAll(stmt(cxxForRangeStmt(
-   hasLoopVariable(varDecl(hasType(nonConstReferenceType()))
-   .bind(NodeID::value)),
-   hasRangeStmt(DeclStmtToNonRefToArray),
-   hasRangeInit(canResolveToExpr(equalsNode(Exp)
-  .bind("stmt")),
-  Stm, Context);
+  const auto RefToArrayRefToElements =
+  match(findAll(stmt(cxxForRangeStmt(
+ hasLoopVariable(
+ varDecl(anyOf(hasType(nonConstReferenceType()),
+   hasType(nonConstPointerType(
+ .bind(NodeID::value)),
+ hasRangeStmt(DeclStmtToNonRefToArray),
+ hasRangeInit(canResolveToExpr(equalsNode(Exp)
+.bind("stmt")),
+Stm, Context);
 
   if (const auto *BadRangeInitFromArray =
   selectFirst("stmt", RefToArrayRefToElements))
Index: clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-values.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc-const-correctness-values.cpp
@@ -0,0 +1,958 @@
+// RUN: %check_clang_tidy %s misc-const-correctness %t -- \
+// RUN:   -config="{CheckOptions: [\
+// RUN:   {key: 'misc-const-correctness.TransformValues', value: true}, \
+// RUN:   {key: 'misc-const-correctness.WarnPointersAsValues', value: false}, \
+// RUN:   {key: 'misc-const-correctness.TransformPointersAsValues', value: false}, \
+// RUN:   ]}" -- -fno-delayed-template-parsing
+
+// --- Provide test samples for primitive builtins -
+// - every 'p_*' variable is a 'potential_const_*' variable
+// - every 'np_*' variable is a 'non_potential_const_*' variable
+
+bool global;
+char np_global = 0; // globals can't be known to be const
+
+// FIXME: 'static' globals are not matched right now. They could be analyzed but aren't right now.
+static int p_static_global = 42;
+
+namespace foo {
+int scoped;

[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

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

In D124998#3494814 , @erichkeane 
wrote:

> First: I care very little about `FunctionNoProtoType`.

I care insomuch as it doesn't break valid user code.

> Second, it is used only in "C" afaik, where our memory pressure isn't that 
> big of a deal.  I'd be OK with having the `FunctionTypeExtraBits` be just 
> added to `FunctionNoProtoType`, but stay in `FunctionProtoType` trailing 
> storage.

I agree that the memory pressure here shouldn't be overly concerning, and I 
would most likely be okay if we adds the bits that way. However, I think we 
could also just make `FunctionNoProtoType` have the same memory layout as 
`FunctionProtoType` by using trailing objects again.

> It WOULD be more work, but I would wonder if we could combine all 3 classes 
> into `FunctionType` and replace the `NoProtoType`-ness with a single bit to 
> differentiate.  The result is the non-prototyped versions needing to carry 
> around extra information, but since:
> a- our C implementation has low memory pressure
> b- prototypeless functions were a mistake
>
> I would think the extra memory they end up carrying might be ok?

We do a fair amount of checks via `isa()` (or similar) that 
would need to be updated to check for a `FunctionType` and whether that bit is 
set, and I don't have a good handle on what that would do to the code. If it 
doesn't cause significant maintenance issues, I would still want to see some 
measurements for what it does to compiler performance on large projects (it'd 
be a good thing to try on http://llvm-compile-time-tracker.com/).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

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

I don't want to change with the distinction between FunctionProtoType and 
FunctionNoProtoType; that would involve auditing a bunch of code we don't 
really want to mess with.

FunctionProtoType and FunctionNoProtoType don't have any member variables at 
the moment, though.  The only difference is that FunctionProtoType has 
TrailingObjects, and FunctionNoProtoType doesn't. It should be fine to just 
require the same TrailingObjects for FunctionNoProtoType.  So FunctionProtoType 
and FunctionNoProtoType would have the same memory layout.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D124965: [clang][dataflow] Centralize expression skipping logic

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:38-41
+  if (auto *LHSValue =
+  dyn_cast_or_null(Env.getValue(LHS, SkipPast::Reference)))
+if (auto *RHSValue =
+dyn_cast_or_null(Env.getValue(RHS, 
SkipPast::Reference)))

li.zhe.hua wrote:
> ymandel wrote:
> > Is the idea that the skipping is now built into `getValue` via 
> > `getStorageLocation`?
> I don't believe I fixed this. d002495 addressed this by having integral casts 
> route to the sub-expression.
Great. Just to be sure I understand: you mean that the `IgnoreCasts()` calls 
were already redundant because of d002495?



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:545-561
+  void VisitParenExpr(const ParenExpr *S) {
+// The CFG does not contain `ParenExpr` as top-level statements in basic
+// blocks, however manual traversal to sub-expressions may encounter them.
+// Redirect to the sub-expression.
+auto *SubExpr = S->getSubExpr();
+assert(SubExpr != nullptr);
+Visit(SubExpr);

li.zhe.hua wrote:
> ymandel wrote:
> > I thought this is the default behavior?
> The default behavior of `StmtVisitor` is that `VisitFoo` will call 
> `VisitFooBase` where `Foo` derives from `FooBase` (e.g. the default 
> implementation of `VisitExprWithCleanups` calls `VisitFullExpr`). The base 
> case is a `VisitStmt` implementation that does [approximately 
> nothing](https://github.com/llvm/llvm-project/blob/c2a5a87500d92c7c2e76c595f1b0f439b98b0aff/clang/include/clang/AST/StmtVisitor.h#L170-L171),
>  especially if `RetTy = void`.
> 
> So in this case, I'm changing this to automatically ignore `ParenExpr` and 
> `ExprWithCleanups` and visit the sub-expression, which is not the default 
> behavior.
> 
> This isn't used when we call the transfer function from CFG-provided 
> statements, because the CFG doesn't emit these nodes. However, this is 
> relevant when we manually call the transfer function, e.g. from 
> [here](https://github.com/llvm/llvm-project/blob/c2a5a87500d92c7c2e76c595f1b0f439b98b0aff/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp#L108).
Interesting. Thanks for the explanation!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124965

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


[PATCH] D125037: [pseudo] Add fuzzer for the pseudoparser.

2022-05-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: hokein.
Herald added a subscriber: mgorny.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, alextsao1999.
Herald added a project: clang-tools-extra.

As confirmation, running this locally found 2 crashes:

- trivial: crashes on file with no tokens
- lexer: hits an assertion failure on bytes: 0x5c,0xa,0x5c,0x1,0x65,0x5c,0xa


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125037

Files:
  clang-tools-extra/pseudo/CMakeLists.txt
  clang-tools-extra/pseudo/fuzzer/CMakeLists.txt
  clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
  clang-tools-extra/pseudo/fuzzer/Main.cpp
  clang-tools-extra/pseudo/test/CMakeLists.txt
  clang-tools-extra/pseudo/test/fuzzer.cpp

Index: clang-tools-extra/pseudo/test/fuzzer.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/test/fuzzer.cpp
@@ -0,0 +1,4 @@
+// RUN: clang-pseudo-fuzzer -grammar=%cxx-bnf-file -print %s | FileCheck %s
+int x;
+// CHECK: translation-unit := declaration-seq
+// CHECK: simple-type-specifier := INT
Index: clang-tools-extra/pseudo/test/CMakeLists.txt
===
--- clang-tools-extra/pseudo/test/CMakeLists.txt
+++ clang-tools-extra/pseudo/test/CMakeLists.txt
@@ -1,5 +1,6 @@
 set(CLANG_PSEUDO_TEST_DEPS
   clang-pseudo
+  clang-pseudo-fuzzer
   ClangPseudoTests
   )
 
Index: clang-tools-extra/pseudo/fuzzer/Main.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/fuzzer/Main.cpp
@@ -0,0 +1,16 @@
+//===--- Main.cpp - Entry point to sanity check the fuzzer ===//
+//
+// 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 "llvm/FuzzMutate/FuzzerCLI.h"
+
+extern "C" int LLVMFuzzerInitialize(int *, char ***);
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *, size_t);
+int main(int argc, char *argv[]) {
+  return llvm::runFuzzerOnInputs(argc, argv, LLVMFuzzerTestOneInput,
+ LLVMFuzzerInitialize);
+}
Index: clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
===
--- /dev/null
+++ clang-tools-extra/pseudo/fuzzer/Fuzzer.cpp
@@ -0,0 +1,105 @@
+//===-- Fuzzer.cpp - Fuzz the pseudoparser ===//
+//
+// 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-pseudo/DirectiveTree.h"
+#include "clang-pseudo/Forest.h"
+#include "clang-pseudo/GLR.h"
+#include "clang-pseudo/Grammar.h"
+#include "clang-pseudo/LRTable.h"
+#include "clang-pseudo/Token.h"
+#include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/raw_ostream.h"
+
+namespace clang {
+namespace pseudo {
+namespace {
+
+class Fuzzer {
+  clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
+  std::unique_ptr G;
+  LRTable T;
+  bool Print;
+
+public:
+  Fuzzer(llvm::StringRef GrammarPath, bool Print) : Print(Print) {
+llvm::ErrorOr> GrammarText =
+llvm::MemoryBuffer::getFile(GrammarPath);
+if (std::error_code EC = GrammarText.getError()) {
+  llvm::errs() << "Error: can't read grammar file '" << GrammarPath
+   << "': " << EC.message() << "\n";
+  std::exit(1);
+}
+std::vector Diags;
+G = Grammar::parseBNF(GrammarText->get()->getBuffer(), Diags);
+if (!Diags.empty()) {
+  for (const auto  : Diags)
+llvm::errs() << Diag << "\n";
+  std::exit(1);
+}
+T = LRTable::buildSLR(*G);
+  }
+
+  void operator()(llvm::StringRef Code) {
+std::string CodeStr = Code.str(); // Must be null-terminated.
+auto RawStream = lex(CodeStr, LangOpts);
+auto DirectiveStructure = DirectiveTree::parse(RawStream);
+clang::pseudo::chooseConditionalBranches(DirectiveStructure, RawStream);
+// FIXME: strip preprocessor directives
+auto ParseableStream =
+clang::pseudo::stripComments(cook(RawStream, LangOpts));
+
+clang::pseudo::ForestArena Arena;
+clang::pseudo::GSS GSS;
+auto  = glrParse(ParseableStream,
+  clang::pseudo::ParseParams{*G, T, Arena, GSS});
+if (Print)
+  llvm::outs() << Root.dumpRecursive(*G);
+  }
+};
+
+Fuzzer *Fuzz = nullptr;
+
+} // namespace
+} // namespace pseudo
+} // namespace clang
+
+extern "C" {
+
+// Set up the fuzzer from command line flags:

[PATCH] D117829: [Clang] Add integer mul reduction builtin

2022-05-05 Thread Florian Hahn via Phabricator via cfe-commits
fhahn accepted this revision.
fhahn added a comment.
This revision is now accepted and ready to land.

LGTM, thanks!

IIRC @scanon had some opinions about `__builtin_reduce_mul` during some earlier 
discussions. Please wait a few days in case there are additional comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D117829

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


[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Jez Ng via Phabricator via cfe-commits
int3 added inline comments.



Comment at: clang/lib/CodeGen/BackendUtil.cpp:456
   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
+  Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;

smeenai wrote:
> smeenai wrote:
> > int3 wrote:
> > > smeenai wrote:
> > > > int3 wrote:
> > > > > this code doesn't execute if clang is passed an assembly file instead 
> > > > > of a .c file, so this option doesn't have the desired effect on 
> > > > > assembly inputs. I'm not sure what's the right way to tackle this, or 
> > > > > if this behavior inconsistency is acceptable
> > > > > 
> > > > > 
> > > > It seems unfortunate to have that inconsistency. From what I can tell, 
> > > > clang/tools/driver/cc1as_main.cpp looks like it might be the rough 
> > > > equivalent of this for the integrated assembler?
> > > that's what I'd thought too, but I set a breakpoint on `cc1as_main` & 
> > > `ExecuteAssemblerImpl` and then ran `clang -c foo.s`; neither breakpoint 
> > > triggered
> > Hmm, interesting. If you run with `-###`, is `-cc1as` being invoked 
> > in-process or out of process? Idk if the in-process cc1as has a different 
> > entry point.
> Nah, looks like in-process cc1as should be calling `cc1as_main` as well: 
> https://github.com/llvm/llvm-project/blob/98616cfc02613d98964588fac6494ec7583c495f/clang/tools/driver/driver.cpp#L319
> 
> (If it's out of process you'd need to debug the cc1as process and not the 
> driver process, of course, but I'd be surprised if you end up with an out of 
> process cc1as)
ah yeah I guess that's it. I'd enabled `settings set 
target.process.follow-fork-mode child` but that doesn't seem to have the 
desired effect; but modifying cc1as_main itself shows that it is indeed being 
called.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

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


[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added inline comments.



Comment at: clang/lib/CodeGen/BackendUtil.cpp:456
   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
+  Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;

smeenai wrote:
> int3 wrote:
> > smeenai wrote:
> > > int3 wrote:
> > > > this code doesn't execute if clang is passed an assembly file instead 
> > > > of a .c file, so this option doesn't have the desired effect on 
> > > > assembly inputs. I'm not sure what's the right way to tackle this, or 
> > > > if this behavior inconsistency is acceptable
> > > > 
> > > > 
> > > It seems unfortunate to have that inconsistency. From what I can tell, 
> > > clang/tools/driver/cc1as_main.cpp looks like it might be the rough 
> > > equivalent of this for the integrated assembler?
> > that's what I'd thought too, but I set a breakpoint on `cc1as_main` & 
> > `ExecuteAssemblerImpl` and then ran `clang -c foo.s`; neither breakpoint 
> > triggered
> Hmm, interesting. If you run with `-###`, is `-cc1as` being invoked 
> in-process or out of process? Idk if the in-process cc1as has a different 
> entry point.
Nah, looks like in-process cc1as should be calling `cc1as_main` as well: 
https://github.com/llvm/llvm-project/blob/98616cfc02613d98964588fac6494ec7583c495f/clang/tools/driver/driver.cpp#L319

(If it's out of process you'd need to debug the cc1as process and not the 
driver process, of course, but I'd be surprised if you end up with an out of 
process cc1as)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

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


[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

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

In D124998#3494785 , @aaron.ballman 
wrote:

> In D124998#3494500 , @erichkeane 
> wrote:
>
>> In D124998#3494442 , @efriedma 
>> wrote:
>>
>>> In D124998#3494426 , @erichkeane 
>>> wrote:
>>>
 In D124998#3494424 , @efriedma 
 wrote:

> If you're really concerned about the size of FunctionProtoType 
> increasing, can we just shove the infrequently used calling convention 
> bits into TrailingObjects?

 I don't believe so.  These are parts of the bitfield and are intrinsic to 
 the type.
>>>
>>> I don't follow. Everything stored in FunctionProtoType, including 
>>> information stored in TrailingObjects, is "intrinsic to the type".  It's 
>>> just stored differently.  (FunctionTypeExtraBitfields already exists, 
>>> even...)
>>
>> Ah, I see what you mean.  I misread and thought you meant on the 
>> FunctionDecl itself, so mea culpa.
>>
>> I was unaware of `FunctionTypeExtraBitfields`!  We perhaps should consider 
>> what of the `ExtInfo` we can move over to the `FunctionTypeExtraBitfields`.  
>> In that list, there are MAYBE 5 bits of the 13 that are used with any level 
>> of commonness (though I have no idea what CmseNSCall means). If most of 
>> those moved, I'd be pretty ok with having even EXTRA bits added for calling 
>> convention (though, if we go over 32, we probably need to have a discussion 
>> as to whether they are valuable).
>
> Not to be a party pooper, but that only works for `FunctionProtoType` and 
> users can write calling conventions on functions without prototypes too, 
> which has no trailing objects currently. However, functions without 
> prototypes aren't a worry for deep template instantiations or the like 
> (because they don't exist in C++), and if users are making heavy use of 
> functions without prototypes (never been a feature in any ISO C standard), I 
> don't particularly mind if their compilation goes slower because we now need 
> to tail allocate data for each non-prototype function. However, we should be 
> careful not to duplicate code as I'm pretty sure that's why `ExtInfo` is in 
> `FunctionType` in the first place (there's no way to add a trailing object to 
> `FunctionType` because it's subclassed).

First: I care very little about `FunctionNoProtoType`.  Second, it is used only 
in "C" afaik, where our memory pressure isn't that big of a deal.  I'd be OK 
with having the `FunctionTypeExtraBits` be just added to `FunctionNoProtoType`, 
but stay in `FunctionProtoType` trailing storage.

It WOULD be more work, but I would wonder if we could combine all 3 classes 
into `FunctionType` and replace the `NoProtoType`-ness with a single bit to 
differentiate.  The result is the non-prototyped versions needing to carry 
around extra information, but since:
a- our C implementation has low memory pressure
b- prototypeless functions were a mistake

I would think the extra memory they end up carrying might be ok?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added inline comments.



Comment at: clang/lib/CodeGen/BackendUtil.cpp:456
   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
+  Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;

int3 wrote:
> smeenai wrote:
> > int3 wrote:
> > > this code doesn't execute if clang is passed an assembly file instead of 
> > > a .c file, so this option doesn't have the desired effect on assembly 
> > > inputs. I'm not sure what's the right way to tackle this, or if this 
> > > behavior inconsistency is acceptable
> > > 
> > > 
> > It seems unfortunate to have that inconsistency. From what I can tell, 
> > clang/tools/driver/cc1as_main.cpp looks like it might be the rough 
> > equivalent of this for the integrated assembler?
> that's what I'd thought too, but I set a breakpoint on `cc1as_main` & 
> `ExecuteAssemblerImpl` and then ran `clang -c foo.s`; neither breakpoint 
> triggered
Hmm, interesting. If you run with `-###`, is `-cc1as` being invoked in-process 
or out of process? Idk if the in-process cc1as has a different entry point.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

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


[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

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

In D124998#3494500 , @erichkeane 
wrote:

> In D124998#3494442 , @efriedma 
> wrote:
>
>> In D124998#3494426 , @erichkeane 
>> wrote:
>>
>>> In D124998#3494424 , @efriedma 
>>> wrote:
>>>
 If you're really concerned about the size of FunctionProtoType increasing, 
 can we just shove the infrequently used calling convention bits into 
 TrailingObjects?
>>>
>>> I don't believe so.  These are parts of the bitfield and are intrinsic to 
>>> the type.
>>
>> I don't follow. Everything stored in FunctionProtoType, including 
>> information stored in TrailingObjects, is "intrinsic to the type".  It's 
>> just stored differently.  (FunctionTypeExtraBitfields already exists, 
>> even...)
>
> Ah, I see what you mean.  I misread and thought you meant on the FunctionDecl 
> itself, so mea culpa.
>
> I was unaware of `FunctionTypeExtraBitfields`!  We perhaps should consider 
> what of the `ExtInfo` we can move over to the `FunctionTypeExtraBitfields`.  
> In that list, there are MAYBE 5 bits of the 13 that are used with any level 
> of commonness (though I have no idea what CmseNSCall means). If most of those 
> moved, I'd be pretty ok with having even EXTRA bits added for calling 
> convention (though, if we go over 32, we probably need to have a discussion 
> as to whether they are valuable).

Not to be a party pooper, but that only works for `FunctionProtoType` and users 
can write calling conventions on functions without prototypes too, which has no 
trailing objects currently. However, functions without prototypes aren't a 
worry for deep template instantiations or the like (because they don't exist in 
C++), and if users are making heavy use of functions without prototypes (never 
been a feature in any ISO C standard), I don't particularly mind if their 
compilation goes slower because we now need to tail allocate data for each 
non-prototype function. However, we should be careful not to duplicate code as 
I'm pretty sure that's why `ExtInfo` is in `FunctionType` in the first place 
(there's no way to add a trailing object to `FunctionType` because it's 
subclassed).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D125026: [clang-tidy][NFC] Reimplement most of SimplifyBooleanExpr with RecursiveASTVisitors

2022-05-05 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 427418.
njames93 added a comment.

Remove redundant traversal of CompoundStmt in a replace method.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125026

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h

Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
@@ -34,73 +34,36 @@
 private:
   class Visitor;
 
-  void reportBinOp(const ast_matchers::MatchFinder::MatchResult ,
-   const BinaryOperator *Op);
-
-  void matchBoolCondition(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef BooleanId);
-
-  void matchTernaryResult(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
-
-  void matchIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void reportBinOp(const ASTContext , const BinaryOperator *Op);
 
   void matchIfAssignsBool(ast_matchers::MatchFinder *Finder, bool Value,
   StringRef Id);
 
-  void matchCompoundIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
-
-  void matchCaseIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
-
-  void matchDefaultIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
- StringRef Id);
-
-  void matchLabelIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-   StringRef Id);
+  void replaceWithThenStatement(const ASTContext ,
+const IfStmt *IfStatement,
+const Expr *BoolLiteral);
 
-  void
-  replaceWithThenStatement(const ast_matchers::MatchFinder::MatchResult ,
-   const Expr *BoolLiteral);
-
-  void
-  replaceWithElseStatement(const ast_matchers::MatchFinder::MatchResult ,
-   const Expr *BoolLiteral);
+  void replaceWithElseStatement(const ASTContext ,
+const IfStmt *IfStatement,
+const Expr *BoolLiteral);
 
-  void
-  replaceWithCondition(const ast_matchers::MatchFinder::MatchResult ,
-   const ConditionalOperator *Ternary, bool Negated);
+  void replaceWithCondition(const ASTContext ,
+const ConditionalOperator *Ternary, bool Negated);
 
-  void replaceWithReturnCondition(
-  const ast_matchers::MatchFinder::MatchResult , const IfStmt *If,
-  bool Negated);
+  void replaceWithReturnCondition(const ASTContext , const IfStmt *If,
+  const Expr *BoolLiteral, bool Negated);
 
   void
   replaceWithAssignment(const ast_matchers::MatchFinder::MatchResult ,
 const IfStmt *If, bool Negated);
 
-  void replaceCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult ,
-  const CompoundStmt *Compound, bool Negated);
-
-  void replaceCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated,
-  const IfStmt *If);
-
-  void replaceCaseCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated);
-
-  void replaceDefaultCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated);
-
-  void replaceLabelCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated);
+  void replaceCompoundReturnWithCondition(const ASTContext ,
+  const ReturnStmt *Ret, bool Negated,
+  const IfStmt *If);
 
-  void issueDiag(const ast_matchers::MatchFinder::MatchResult ,
- SourceLocation Loc, StringRef Description,
- SourceRange ReplacementRange, StringRef Replacement);
+  void issueDiag(const ASTContext , SourceLocation Loc,
+ StringRef Description, SourceRange ReplacementRange,
+ StringRef Replacement);
 
   const bool ChainedConditionalReturn;
   const bool ChainedConditionalAssignment;
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -10,6 +10,7 @@
 #include "SimplifyBooleanExprMatchers.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include 

[PATCH] D124965: [clang][dataflow] Centralize expression skipping logic

2022-05-05 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:38-41
+  if (auto *LHSValue =
+  dyn_cast_or_null(Env.getValue(LHS, SkipPast::Reference)))
+if (auto *RHSValue =
+dyn_cast_or_null(Env.getValue(RHS, 
SkipPast::Reference)))

ymandel wrote:
> Is the idea that the skipping is now built into `getValue` via 
> `getStorageLocation`?
I don't believe I fixed this. d002495 addressed this by having integral casts 
route to the sub-expression.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:545-561
+  void VisitParenExpr(const ParenExpr *S) {
+// The CFG does not contain `ParenExpr` as top-level statements in basic
+// blocks, however manual traversal to sub-expressions may encounter them.
+// Redirect to the sub-expression.
+auto *SubExpr = S->getSubExpr();
+assert(SubExpr != nullptr);
+Visit(SubExpr);

ymandel wrote:
> I thought this is the default behavior?
The default behavior of `StmtVisitor` is that `VisitFoo` will call 
`VisitFooBase` where `Foo` derives from `FooBase` (e.g. the default 
implementation of `VisitExprWithCleanups` calls `VisitFullExpr`). The base case 
is a `VisitStmt` implementation that does [approximately 
nothing](https://github.com/llvm/llvm-project/blob/c2a5a87500d92c7c2e76c595f1b0f439b98b0aff/clang/include/clang/AST/StmtVisitor.h#L170-L171),
 especially if `RetTy = void`.

So in this case, I'm changing this to automatically ignore `ParenExpr` and 
`ExprWithCleanups` and visit the sub-expression, which is not the default 
behavior.

This isn't used when we call the transfer function from CFG-provided 
statements, because the CFG doesn't emit these nodes. However, this is relevant 
when we manually call the transfer function, e.g. from 
[here](https://github.com/llvm/llvm-project/blob/c2a5a87500d92c7c2e76c595f1b0f439b98b0aff/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp#L108).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124965

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


[PATCH] D124965: [clang][dataflow] Centralize expression skipping logic

2022-05-05 Thread Eric Li via Phabricator via cfe-commits
li.zhe.hua updated this revision to Diff 427417.
li.zhe.hua marked 3 inline comments as done.
li.zhe.hua added a comment.

Address reviewer comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124965

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/Transfer.h
  clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp

Index: clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
===
--- clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
+++ clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
@@ -46,7 +46,7 @@
   : CFCtx(CFCtx), BlockToState(BlockToState) {}
 
   const Environment *getEnvironment(const Stmt ) const override {
-auto BlockIT = CFCtx.getStmtToBlock().find();
+auto BlockIT = CFCtx.getStmtToBlock().find((S));
 assert(BlockIT != CFCtx.getStmtToBlock().end());
 const auto  = BlockToState[BlockIT->getSecond()->getBlockID()];
 assert(State.hasValue());
@@ -77,26 +77,26 @@
   : StmtToEnv(StmtToEnv), Env(Env), BlockSuccIdx(BlockSuccIdx) {}
 
   void VisitIfStmt(const IfStmt *S) {
-auto *Cond = ignoreExprWithCleanups(S->getCond())->IgnoreParens();
+auto *Cond = S->getCond();
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
 
   void VisitWhileStmt(const WhileStmt *S) {
-auto *Cond = ignoreExprWithCleanups(S->getCond())->IgnoreParens();
+auto *Cond = S->getCond();
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
 
   void VisitBinaryOperator(const BinaryOperator *S) {
 assert(S->getOpcode() == BO_LAnd || S->getOpcode() == BO_LOr);
-auto *LHS = ignoreExprWithCleanups(S->getLHS())->IgnoreParens();
+auto *LHS = S->getLHS();
 assert(LHS != nullptr);
 extendFlowCondition(*LHS);
   }
 
   void VisitConditionalOperator(const ConditionalOperator *S) {
-auto *Cond = ignoreExprWithCleanups(S->getCond())->IgnoreParens();
+auto *Cond = S->getCond();
 assert(Cond != nullptr);
 extendFlowCondition(*Cond);
   }
Index: clang/lib/Analysis/FlowSensitive/Transfer.cpp
===
--- clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -33,27 +33,12 @@
 namespace clang {
 namespace dataflow {
 
-const Expr *ignoreExprWithCleanups(const Expr *E) {
-  if (auto *C = dyn_cast_or_null(E))
-return C->getSubExpr();
-  return E;
-}
-
 static BoolValue (const Expr , const Expr ,
   Environment ) {
-  // Equality of booleans involves implicit integral casts. Ignore these casts
-  // for now and focus on the values associated with the wrapped expressions.
-  // FIXME: Consider changing this once the framework offers better support for
-  // integral casts.
-  const Expr *LHSNorm = LHS.IgnoreCasts();
-  const Expr *RHSNorm = RHS.IgnoreCasts();
-  assert(LHSNorm != nullptr);
-  assert(RHSNorm != nullptr);
-
-  if (auto *LHSValue = dyn_cast_or_null(
-  Env.getValue(*LHSNorm, SkipPast::Reference)))
-if (auto *RHSValue = dyn_cast_or_null(
-Env.getValue(*RHSNorm, SkipPast::Reference)))
+  if (auto *LHSValue =
+  dyn_cast_or_null(Env.getValue(LHS, SkipPast::Reference)))
+if (auto *RHSValue =
+dyn_cast_or_null(Env.getValue(RHS, SkipPast::Reference)))
   return Env.makeIff(*LHSValue, *RHSValue);
 
   return Env.makeAtomicBoolValue();
@@ -65,14 +50,10 @@
   : StmtToEnv(StmtToEnv), Env(Env) {}
 
   void VisitBinaryOperator(const BinaryOperator *S) {
-// The CFG does not contain `ParenExpr` as top-level statements in basic
-// blocks, however sub-expressions can still be of that type.
-assert(S->getLHS() != nullptr);
-const Expr *LHS = S->getLHS()->IgnoreParens();
+const Expr *LHS = S->getLHS();
 assert(LHS != nullptr);
 
-assert(S->getRHS() != nullptr);
-const Expr *RHS = S->getRHS()->IgnoreParens();
+const Expr *RHS = S->getRHS();
 assert(RHS != nullptr);
 
 switch (S->getOpcode()) {
@@ -155,7 +136,7 @@
   return;
 }
 
-InitExpr = ignoreExprWithCleanups(D.getInit());
+InitExpr = D.getInit();
 assert(InitExpr != nullptr);
 
 if (D.getType()->isReferenceType()) {
@@ -476,8 +457,7 @@
   assert(S->getArg(0) != nullptr);
   // `__builtin_expect` returns by-value, so strip away any potential
   // references in the argument.
-  auto *ArgLoc = Env.getStorageLocation(
-  *S->getArg(0)->IgnoreParenImpCasts(), SkipPast::Reference);
+  auto *ArgLoc 

[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Jez Ng via Phabricator via cfe-commits
int3 added inline comments.



Comment at: clang/lib/CodeGen/BackendUtil.cpp:456
   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
+  Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;

smeenai wrote:
> int3 wrote:
> > this code doesn't execute if clang is passed an assembly file instead of a 
> > .c file, so this option doesn't have the desired effect on assembly inputs. 
> > I'm not sure what's the right way to tackle this, or if this behavior 
> > inconsistency is acceptable
> > 
> > 
> It seems unfortunate to have that inconsistency. From what I can tell, 
> clang/tools/driver/cc1as_main.cpp looks like it might be the rough equivalent 
> of this for the integrated assembler?
that's what I'd thought too, but I set a breakpoint on `cc1as_main` & 
`ExecuteAssemblerImpl` and then ran `clang -c foo.s`; neither breakpoint 
triggered


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

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



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst:29
+
+Checking if a value exists, then accessing the value
+

ymandel wrote:
> xazax.hun wrote:
> > I wonder if it would be easier to read if we had two top level categories, 
> > one for safe and one for unsafe accesses instead of switching back and 
> > forth between examples.
> Sounds good, done. Let me know if that's what you had in mind.
Yup, this is exactly what I had in mind, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked an inline comment as done.
ymandel added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst:29
+
+Checking if a value exists, then accessing the value
+

xazax.hun wrote:
> I wonder if it would be easier to read if we had two top level categories, 
> one for safe and one for unsafe accesses instead of switching back and forth 
> between examples.
Sounds good, done. Let me know if that's what you had in mind.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 427412.
ymandel added a comment.

reorder examples


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/types/optional.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp

Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -13,6 +13,7 @@
 
 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/Stmt.h"
@@ -29,13 +30,9 @@
 
 namespace clang {
 namespace dataflow {
-namespace {
-
-using namespace ::clang::ast_matchers;
 
-using LatticeTransferState = TransferState;
-
-auto optionalClass() {
+ast_matchers::DeclarationMatcher optionalClass() {
+  using namespace ::clang::ast_matchers;
   return classTemplateSpecializationDecl(
   anyOf(hasName("std::optional"), hasName("std::__optional_storage_base"),
 hasName("__optional_destruct_base"), hasName("absl::optional"),
@@ -43,6 +40,12 @@
   hasTemplateArgument(0, refersToType(type().bind("T";
 }
 
+namespace {
+
+using namespace ::clang::ast_matchers;
+
+using LatticeTransferState = TransferState;
+
 auto hasOptionalType() { return hasType(optionalClass()); }
 
 auto isOptionalMemberCallWithName(
@@ -230,6 +233,8 @@
   }
 
   // Record that this unwrap is *not* provably safe.
+  // FIXME: include either the name of the optional (if applicable) or a source
+  // range of the access for easier intepretation of the result.
   State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc());
 }
 
Index: clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
===
--- clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -36,6 +36,9 @@
   bool IgnoreSmartPointerDereference = false;
 };
 
+/// A matcher for the optional classes covered by this model.
+ast_matchers::DeclarationMatcher optionalClass();
+
 /// Dataflow analysis that discovers unsafe accesses of optional values and
 /// adds the respective source locations to the lattice.
 ///
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
@@ -0,0 +1,112 @@
+// RUN: %check_clang_tidy %s bugprone-unchecked-optional-access %t -- -- -I %S/Inputs/
+
+#include "absl/types/optional.h"
+
+void unchecked_value_access(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
+}
+
+void unchecked_deref_operator_access(const absl::optional ) {
+  *opt;
+  // CHECK-MESSAGES: :[[@LINE-1]]:4: warning: unchecked access to optional value
+}
+
+struct Foo {
+  void foo() const {}
+};
+
+void unchecked_arrow_operator_access(const absl::optional ) {
+  opt->foo();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void f2(const absl::optional ) {
+  if (opt.has_value()) {
+opt.value();
+  }
+}
+
+template 
+void function_template_without_user(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template 
+void function_template_with_user(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void function_template_user(const absl::optional ) {
+  // Instantiate the f3 function template so that it gets matched by the check.
+  function_template_with_user(opt);
+}
+
+template 
+void function_template_with_specialization(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template <>
+void function_template_with_specialization(
+const absl::optional ) {

[PATCH] D124774: [clang][ASTImporter][NFC]: Move clang::ImportError into own header.

2022-05-05 Thread Shivam Rajput via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGdcb906757ada: [clang][ASTImporter][NFC]: Move 
clang::ImportError into own header. (authored by phyBrackets).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124774

Files:
  clang/include/clang/AST/ASTImportError.h
  clang/include/clang/AST/ASTImporter.h
  clang/include/clang/AST/ASTImporterSharedState.h

Index: clang/include/clang/AST/ASTImporterSharedState.h
===
--- clang/include/clang/AST/ASTImporterSharedState.h
+++ clang/include/clang/AST/ASTImporterSharedState.h
@@ -14,11 +14,10 @@
 #ifndef LLVM_CLANG_AST_ASTIMPORTERSHAREDSTATE_H
 #define LLVM_CLANG_AST_ASTIMPORTERSHAREDSTATE_H
 
+#include "clang/AST/ASTImportError.h"
 #include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/AST/Decl.h"
 #include "llvm/ADT/DenseMap.h"
-// FIXME We need this because of ImportError.
-#include "clang/AST/ASTImporter.h"
 
 namespace clang {
 
Index: clang/include/clang/AST/ASTImporter.h
===
--- clang/include/clang/AST/ASTImporter.h
+++ clang/include/clang/AST/ASTImporter.h
@@ -14,7 +14,7 @@
 #ifndef LLVM_CLANG_AST_ASTIMPORTER_H
 #define LLVM_CLANG_AST_ASTIMPORTER_H
 
-#include "clang/AST/APValue.h"
+#include "clang/AST/ASTImportError.h"
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
@@ -29,7 +29,6 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/Support/Error.h"
 #include 
 
 namespace clang {
@@ -49,33 +48,6 @@
 class TranslationUnitDecl;
 class TypeSourceInfo;
 
-  class ImportError : public llvm::ErrorInfo {
-  public:
-/// \brief Kind of error when importing an AST component.
-enum ErrorKind {
-NameConflict, /// Naming ambiguity (likely ODR violation).
-UnsupportedConstruct, /// Not supported node or case.
-Unknown /// Other error.
-};
-
-ErrorKind Error;
-
-static char ID;
-
-ImportError() : Error(Unknown) {}
-ImportError(const ImportError ) : Error(Other.Error) {}
-ImportError =(const ImportError ) {
-  Error = Other.Error;
-  return *this;
-}
-ImportError(ErrorKind Error) : Error(Error) { }
-
-std::string toString() const;
-
-void log(raw_ostream ) const override;
-std::error_code convertToErrorCode() const override;
-  };
-
   // \brief Returns with a list of declarations started from the canonical decl
   // then followed by subsequent decls in the translation unit.
   // This gives a canonical list for each entry in the redecl chain.
Index: clang/include/clang/AST/ASTImportError.h
===
--- /dev/null
+++ clang/include/clang/AST/ASTImportError.h
@@ -0,0 +1,50 @@
+//===- ASTImportError.h - Define errors while importing AST -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the ASTImportError class which basically defines the kind
+//  of error while importing AST .
+//
+//===--===//
+
+#ifndef LLVM_CLANG_AST_ASTIMPORTERROR_H
+#define LLVM_CLANG_AST_ASTIMPORTERROR_H
+
+#include "llvm/Support/Error.h"
+
+namespace clang {
+
+class ImportError : public llvm::ErrorInfo {
+public:
+  /// \brief Kind of error when importing an AST component.
+  enum ErrorKind {
+NameConflict, /// Naming ambiguity (likely ODR violation).
+UnsupportedConstruct, /// Not supported node or case.
+Unknown   /// Other error.
+  };
+
+  ErrorKind Error;
+
+  static char ID;
+
+  ImportError() : Error(Unknown) {}
+  ImportError(const ImportError ) : Error(Other.Error) {}
+  ImportError =(const ImportError ) {
+Error = Other.Error;
+return *this;
+  }
+  ImportError(ErrorKind Error) : Error(Error) {}
+
+  std::string toString() const;
+
+  void log(llvm::raw_ostream ) const override;
+  std::error_code convertToErrorCode() const override;
+};
+
+} // namespace clang
+
+#endif // LLVM_CLANG_AST_ASTIMPORTERROR_H
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] dcb9067 - [clang][ASTImporter][NFC]: Move clang::ImportError into own header.

2022-05-05 Thread via cfe-commits

Author: phyBrackets
Date: 2022-05-06T00:14:32+05:30
New Revision: dcb906757ada24edf8da89439c72d015b53f204b

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

LOG: [clang][ASTImporter][NFC]: Move clang::ImportError into own header.

Reviewed By: martong

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

Added: 
clang/include/clang/AST/ASTImportError.h

Modified: 
clang/include/clang/AST/ASTImporter.h
clang/include/clang/AST/ASTImporterSharedState.h

Removed: 




diff  --git a/clang/include/clang/AST/ASTImportError.h 
b/clang/include/clang/AST/ASTImportError.h
new file mode 100644
index 0..034bd50cc7e15
--- /dev/null
+++ b/clang/include/clang/AST/ASTImportError.h
@@ -0,0 +1,50 @@
+//===- ASTImportError.h - Define errors while importing AST -*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the ASTImportError class which basically defines the kind
+//  of error while importing AST .
+//
+//===--===//
+
+#ifndef LLVM_CLANG_AST_ASTIMPORTERROR_H
+#define LLVM_CLANG_AST_ASTIMPORTERROR_H
+
+#include "llvm/Support/Error.h"
+
+namespace clang {
+
+class ImportError : public llvm::ErrorInfo {
+public:
+  /// \brief Kind of error when importing an AST component.
+  enum ErrorKind {
+NameConflict, /// Naming ambiguity (likely ODR violation).
+UnsupportedConstruct, /// Not supported node or case.
+Unknown   /// Other error.
+  };
+
+  ErrorKind Error;
+
+  static char ID;
+
+  ImportError() : Error(Unknown) {}
+  ImportError(const ImportError ) : Error(Other.Error) {}
+  ImportError =(const ImportError ) {
+Error = Other.Error;
+return *this;
+  }
+  ImportError(ErrorKind Error) : Error(Error) {}
+
+  std::string toString() const;
+
+  void log(llvm::raw_ostream ) const override;
+  std::error_code convertToErrorCode() const override;
+};
+
+} // namespace clang
+
+#endif // LLVM_CLANG_AST_ASTIMPORTERROR_H

diff  --git a/clang/include/clang/AST/ASTImporter.h 
b/clang/include/clang/AST/ASTImporter.h
index c8bdae10a6e6c..7d413115d769c 100644
--- a/clang/include/clang/AST/ASTImporter.h
+++ b/clang/include/clang/AST/ASTImporter.h
@@ -14,7 +14,7 @@
 #ifndef LLVM_CLANG_AST_ASTIMPORTER_H
 #define LLVM_CLANG_AST_ASTIMPORTER_H
 
-#include "clang/AST/APValue.h"
+#include "clang/AST/ASTImportError.h"
 #include "clang/AST/DeclBase.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExprCXX.h"
@@ -29,7 +29,6 @@
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/Optional.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/Support/Error.h"
 #include 
 
 namespace clang {
@@ -49,33 +48,6 @@ class TagDecl;
 class TranslationUnitDecl;
 class TypeSourceInfo;
 
-  class ImportError : public llvm::ErrorInfo {
-  public:
-/// \brief Kind of error when importing an AST component.
-enum ErrorKind {
-NameConflict, /// Naming ambiguity (likely ODR violation).
-UnsupportedConstruct, /// Not supported node or case.
-Unknown /// Other error.
-};
-
-ErrorKind Error;
-
-static char ID;
-
-ImportError() : Error(Unknown) {}
-ImportError(const ImportError ) : Error(Other.Error) {}
-ImportError =(const ImportError ) {
-  Error = Other.Error;
-  return *this;
-}
-ImportError(ErrorKind Error) : Error(Error) { }
-
-std::string toString() const;
-
-void log(raw_ostream ) const override;
-std::error_code convertToErrorCode() const override;
-  };
-
   // \brief Returns with a list of declarations started from the canonical decl
   // then followed by subsequent decls in the translation unit.
   // This gives a canonical list for each entry in the redecl chain.

diff  --git a/clang/include/clang/AST/ASTImporterSharedState.h 
b/clang/include/clang/AST/ASTImporterSharedState.h
index 686a8e22b2fa6..7be6f1460a856 100644
--- a/clang/include/clang/AST/ASTImporterSharedState.h
+++ b/clang/include/clang/AST/ASTImporterSharedState.h
@@ -14,11 +14,10 @@
 #ifndef LLVM_CLANG_AST_ASTIMPORTERSHAREDSTATE_H
 #define LLVM_CLANG_AST_ASTIMPORTERSHAREDSTATE_H
 
+#include "clang/AST/ASTImportError.h"
 #include "clang/AST/ASTImporterLookupTable.h"
 #include "clang/AST/Decl.h"
 #include "llvm/ADT/DenseMap.h"
-// FIXME We need this because of ImportError.
-#include "clang/AST/ASTImporter.h"
 
 namespace clang {
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org

[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Shoaib Meenai via Phabricator via cfe-commits
smeenai added inline comments.



Comment at: clang/lib/CodeGen/BackendUtil.cpp:456
   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
+  Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;

int3 wrote:
> this code doesn't execute if clang is passed an assembly file instead of a .c 
> file, so this option doesn't have the desired effect on assembly inputs. I'm 
> not sure what's the right way to tackle this, or if this behavior 
> inconsistency is acceptable
> 
> 
It seems unfortunate to have that inconsistency. From what I can tell, 
clang/tools/driver/cc1as_main.cpp looks like it might be the rough equivalent 
of this for the integrated assembler?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

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


[clang] f6dff93 - Pedantically warn about // comments in gnu89 mode

2022-05-05 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-05T14:35:47-04:00
New Revision: f6dff93641b2259623e686eb13a1884b8b9f4a00

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

LOG: Pedantically warn about // comments in gnu89 mode

GCC warns with a pedantic warning when -std=gnu89, but Clang would only
diagnose in -std=c89 mode. Clang now matches the GCC behavior in both
modes.

Fixes #18427

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/LangStandards.def
clang/test/Lexer/c90.c
clang/test/Sema/gnu89.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 87e4df50ae0f2..090b4c6b1b6c6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -147,6 +147,9 @@ Bug Fixes
   because there is no way to fully qualify the enumerator name, so this
   "extension" was unintentional and useless. This fixes
   `Issue 42372 `_.
+- Now correctly diagnose use of ``//`` comments in ``gnu89`` mode (which
+  matches the behavior of GCC) in addition to ``c89`` mode. This fixes
+  `Issue 18427 `_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/include/clang/Basic/LangStandards.def 
b/clang/include/clang/Basic/LangStandards.def
index 323032f41da02..d4e42b4cd6d86 100644
--- a/clang/include/clang/Basic/LangStandards.def
+++ b/clang/include/clang/Basic/LangStandards.def
@@ -46,7 +46,7 @@ LANGSTANDARD(c94, "iso9899:199409",
 
 LANGSTANDARD(gnu89, "gnu89",
  C, "ISO C 1990 with GNU extensions",
- LineComment | Digraphs | GNUMode)
+ Digraphs | GNUMode)
 LANGSTANDARD_ALIAS(gnu89, "gnu90")
 
 // C99-ish modes

diff  --git a/clang/test/Lexer/c90.c b/clang/test/Lexer/c90.c
index 8752404c1c199..39ffdc170b108 100644
--- a/clang/test/Lexer/c90.c
+++ b/clang/test/Lexer/c90.c
@@ -1,5 +1,7 @@
 /* RUN: %clang_cc1 -std=c90 -fsyntax-only %s -verify -pedantic-errors
  */
+/* RUN: %clang_cc1 -std=gnu89 -fsyntax-only %s -verify -pedantic-errors
+ */
 
 enum { cast_hex = (long) (
   0x0p-1   /* expected-error {{hexadecimal floating constants are a C99 
feature}} */

diff  --git a/clang/test/Sema/gnu89.c b/clang/test/Sema/gnu89.c
index 1be717f54260e..d96d3536fbfff 100644
--- a/clang/test/Sema/gnu89.c
+++ b/clang/test/Sema/gnu89.c
@@ -1,5 +1,6 @@
-// RUN: %clang_cc1 %s -std=gnu89 -pedantic -fsyntax-only -verify
+/* RUN: %clang_cc1 %s -std=gnu89 -pedantic -fsyntax-only -verify
+ */
 
 int f(int restrict);
 
-void main(void) {} // expected-warning {{return type of 'main' is not 'int'}} 
expected-note {{change return type to 'int'}}
+void main(void) {} /* expected-warning {{return type of 'main' is not 'int'}} 
expected-note {{change return type to 'int'}} */



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


[PATCH] D124774: [clang][ASTImporter][NFC]: Move clang::ImportError into own header.

2022-05-05 Thread Shivam Rajput via Phabricator via cfe-commits
phyBrackets added a comment.

Thanks @martong @balazske for the Review .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124774

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


[PATCH] D124669: [flang][driver] Add support for -save-temps

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

Pre-merge CI is  . If there are no new comments, I'd like to merge this 
tomorrow.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124669

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


[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Jez Ng via Phabricator via cfe-commits
int3 added inline comments.



Comment at: clang/lib/CodeGen/BackendUtil.cpp:456
   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
+  Options.MCOptions.EmitDwarfUnwind = CodeGenOpts.getEmitDwarfUnwind();
   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;

this code doesn't execute if clang is passed an assembly file instead of a .c 
file, so this option doesn't have the desired effect on assembly inputs. I'm 
not sure what's the right way to tackle this, or if this behavior inconsistency 
is acceptable




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

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


[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Jez Ng via Phabricator via cfe-commits
int3 updated this revision to Diff 427398.
int3 added a comment.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/femit-dwarf-unwind.c
  llvm/include/llvm/MC/MCContext.h
  llvm/include/llvm/MC/MCTargetOptions.h
  llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h
  llvm/lib/CodeGen/LLVMTargetMachine.cpp
  llvm/lib/CodeGen/MachineModuleInfo.cpp
  llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp
  llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp
  llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp
  llvm/lib/MC/MCContext.cpp
  llvm/lib/MC/MCDwarf.cpp
  llvm/lib/MC/MCObjectFileInfo.cpp
  llvm/lib/MC/MCTargetOptions.cpp
  llvm/lib/MC/MCTargetOptionsCommandFlags.cpp
  llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
  llvm/test/MC/MachO/force-dwarf-unwind.s
  llvm/test/MC/X86/compact-unwind-mode-dwarf.s

Index: llvm/test/MC/X86/compact-unwind-mode-dwarf.s
===
--- /dev/null
+++ llvm/test/MC/X86/compact-unwind-mode-dwarf.s
@@ -0,0 +1,50 @@
+// RUN: llvm-mc -triple x86_64-apple-macos10.6 -filetype=obj %s -o %t.o
+// RUN: llvm-objdump --macho --unwind-info --dwarf=frames %t.o | FileCheck %s
+
+/// For functions whose unwind info cannot be encoded with compact unwind, make
+/// sure that we encode them using DWARF unwind, and make sure we emit a compact
+/// unwind entry that indicates that a DWARF encoding is being used.
+
+_f:
+  .cfi_startproc
+  ## This encodes DW_CFA_GNU_args_size which cannot be expressed using compact
+  ## unwind, so we must use DWARF unwind instead.
+  .cfi_escape 0x2e, 0x10
+  ret
+  .cfi_endproc
+
+_g:
+  .cfi_startproc
+  ## This encodes DW_CFA_GNU_args_size which cannot be expressed using compact
+  ## unwind, so we must use DWARF unwind instead.
+  .cfi_escape 0x2e, 0x10
+  ret
+  .cfi_endproc
+
+// CHECK: Contents of __compact_unwind section:
+// CHECK:   Entry at offset 0x0:
+// CHECK: start:0x[[#%x,F:]] _f
+// CHECK: length:   0x1
+// CHECK: compact encoding: 0x0400
+// CHECK:   Entry at offset 0x20:
+// CHECK: start:0x[[#%x,G:]] _g
+// CHECK: length:   0x1
+// CHECK: compact encoding: 0x0400
+
+// CHECK: .eh_frame contents:
+// CHECK:  0014  CIE
+// CHECK:   Format:DWARF32
+// CHECK:   Version:   1
+// CHECK:   Augmentation:  "zR"
+// CHECK:   Code alignment factor: 1
+// CHECK:   Data alignment factor: -8
+// CHECK:   Return address column: 16
+// CHECK:   Augmentation data: 10
+
+// CHECK: FDE cie= pc=[[#%.8x,F]]...
+// CHECK:   Format:   DWARF32
+// CHECK:   DW_CFA_GNU_args_size: +16
+
+// CHECK: FDE cie= pc=[[#%.8x,G]]...
+// CHECK:   Format:   DWARF32
+// CHECK:   DW_CFA_GNU_args_size: +16
Index: llvm/test/MC/MachO/force-dwarf-unwind.s
===
--- /dev/null
+++ llvm/test/MC/MachO/force-dwarf-unwind.s
@@ -0,0 +1,33 @@
+// RUN: rm -rf %t; mkdir %t
+// RUN: llvm-mc -triple x86_64-apple-macos11.0 %s -filetype=obj -o %t/x86_64.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/x86_64.o | FileCheck %s --check-prefix TWO-FDES
+// RUN: llvm-mc -triple arm64-apple-macos11.0 %s -filetype=obj -o %t/arm64.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/arm64.o | FileCheck %s --check-prefix ONE-FDE
+// RUN: llvm-mc -triple x86_64-apple-macos11.0 %s -filetype=obj --emit-dwarf-unwind no-compact-unwind -o %t/x86_64-no-dwarf.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/x86_64-no-dwarf.o | FileCheck %s --check-prefix ONE-FDE
+// RUN: llvm-mc -triple arm64-apple-macos11.0 %s -filetype=obj --emit-dwarf-unwind always -o %t/arm64-dwarf.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/arm64-dwarf.o | FileCheck %s --check-prefix TWO-FDES
+
+// TWO-FDES: FDE
+// TWO-FDES: FDE
+
+// ONE-FDE-NOT: FDE
+// ONE-FDE: FDE
+// ONE-FDE-NOT: FDE
+
+_main:
+  .cfi_startproc
+  .cfi_def_cfa_offset 16
+  ret
+  .cfi_endproc
+
+_foo:
+  .cfi_startproc
+  .cfi_def_cfa_offset 16
+  /// This encodes DW_CFA_GNU_args_size which cannot be expressed using compact
+  /// unwind, so we must use DWARf unwind for this function.
+  .cfi_escape 0x2e, 0x10
+  ret
+  .cfi_endproc
+
+.subsections_via_symbols
Index: llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
===
--- llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
+++ llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
@@ -1377,7 +1377,7 @@
   default:
 // Any other CFI directives indicate a frame that we aren't prepared
 // to represent via compact unwind, so just bail out.
-return 0;
+  

[PATCH] D124965: [clang][dataflow] Centralize expression skipping logic

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel accepted this revision.
ymandel added a comment.
This revision is now accepted and ready to land.

Thanks!




Comment at: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp:368
 void Environment::setStorageLocation(const Expr , StorageLocation ) {
-  assert(!isa());
-  assert(ExprToLoc.find() == ExprToLoc.end());
-  ExprToLoc[] = 
+  assert(ExprToLoc.find((E)) == ExprToLoc.end());
+  ExprToLoc[(E)] = 

maybe bind to a temporary to avoid doing this twice (in debug code, that is)? 
arguably not that important to optimize debug mode but may also improve 
readability.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:38-41
+  if (auto *LHSValue =
+  dyn_cast_or_null(Env.getValue(LHS, SkipPast::Reference)))
+if (auto *RHSValue =
+dyn_cast_or_null(Env.getValue(RHS, 
SkipPast::Reference)))

Is the idea that the skipping is now built into `getValue` via 
`getStorageLocation`?



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:545-561
+  void VisitParenExpr(const ParenExpr *S) {
+// The CFG does not contain `ParenExpr` as top-level statements in basic
+// blocks, however manual traversal to sub-expressions may encounter them.
+// Redirect to the sub-expression.
+auto *SubExpr = S->getSubExpr();
+assert(SubExpr != nullptr);
+Visit(SubExpr);

I thought this is the default behavior?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124965

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


[PATCH] D122258: [MC] Omit DWARF unwind info if compact unwind is present where eligible

2022-05-05 Thread Jez Ng via Phabricator via cfe-commits
int3 updated this revision to Diff 427396.
int3 retitled this revision from "[MC] Omit DWARF unwind info if compact unwind 
is present for all archs" to "[MC] Omit DWARF unwind info if compact unwind is 
present where eligible".
int3 edited the summary of this revision.
int3 added a comment.
Herald added a subscriber: ormris.

update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122258

Files:
  clang/include/clang/Basic/CodeGenOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/femit-dwarf-unwind.c
  lld/test/MachO/compact-unwind-both-local-and-dylib-personality.s
  llvm/include/llvm/MC/MCContext.h
  llvm/include/llvm/MC/MCTargetOptions.h
  llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h
  llvm/lib/CodeGen/LLVMTargetMachine.cpp
  llvm/lib/CodeGen/MachineModuleInfo.cpp
  llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp
  llvm/lib/ExecutionEngine/Orc/CompileUtils.cpp
  llvm/lib/ExecutionEngine/RuntimeDyld/RTDyldMemoryManager.cpp
  llvm/lib/MC/MCContext.cpp
  llvm/lib/MC/MCDwarf.cpp
  llvm/lib/MC/MCObjectFileInfo.cpp
  llvm/lib/MC/MCTargetOptions.cpp
  llvm/lib/MC/MCTargetOptionsCommandFlags.cpp
  llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp
  llvm/test/MC/MachO/force-dwarf-unwind.s
  llvm/test/MC/X86/compact-unwind-mode-dwarf.s

Index: llvm/test/MC/X86/compact-unwind-mode-dwarf.s
===
--- /dev/null
+++ llvm/test/MC/X86/compact-unwind-mode-dwarf.s
@@ -0,0 +1,50 @@
+// RUN: llvm-mc -triple x86_64-apple-macos10.6 -filetype=obj %s -o %t.o
+// RUN: llvm-objdump --macho --unwind-info --dwarf=frames %t.o | FileCheck %s
+
+/// For functions whose unwind info cannot be encoded with compact unwind, make
+/// sure that we encode them using DWARF unwind, and make sure we emit a compact
+/// unwind entry that indicates that a DWARF encoding is being used.
+
+_f:
+  .cfi_startproc
+  ## This encodes DW_CFA_GNU_args_size which cannot be expressed using compact
+  ## unwind, so we must use DWARF unwind instead.
+  .cfi_escape 0x2e, 0x10
+  ret
+  .cfi_endproc
+
+_g:
+  .cfi_startproc
+  ## This encodes DW_CFA_GNU_args_size which cannot be expressed using compact
+  ## unwind, so we must use DWARF unwind instead.
+  .cfi_escape 0x2e, 0x10
+  ret
+  .cfi_endproc
+
+// CHECK: Contents of __compact_unwind section:
+// CHECK:   Entry at offset 0x0:
+// CHECK: start:0x[[#%x,F:]] _f
+// CHECK: length:   0x1
+// CHECK: compact encoding: 0x0400
+// CHECK:   Entry at offset 0x20:
+// CHECK: start:0x[[#%x,G:]] _g
+// CHECK: length:   0x1
+// CHECK: compact encoding: 0x0400
+
+// CHECK: .eh_frame contents:
+// CHECK:  0014  CIE
+// CHECK:   Format:DWARF32
+// CHECK:   Version:   1
+// CHECK:   Augmentation:  "zR"
+// CHECK:   Code alignment factor: 1
+// CHECK:   Data alignment factor: -8
+// CHECK:   Return address column: 16
+// CHECK:   Augmentation data: 10
+
+// CHECK: FDE cie= pc=[[#%.8x,F]]...
+// CHECK:   Format:   DWARF32
+// CHECK:   DW_CFA_GNU_args_size: +16
+
+// CHECK: FDE cie= pc=[[#%.8x,G]]...
+// CHECK:   Format:   DWARF32
+// CHECK:   DW_CFA_GNU_args_size: +16
Index: llvm/test/MC/MachO/force-dwarf-unwind.s
===
--- /dev/null
+++ llvm/test/MC/MachO/force-dwarf-unwind.s
@@ -0,0 +1,33 @@
+// RUN: rm -rf %t; mkdir %t
+// RUN: llvm-mc -triple x86_64-apple-macos11.0 %s -filetype=obj -o %t/x86_64.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/x86_64.o | FileCheck %s --check-prefix TWO-FDES
+// RUN: llvm-mc -triple arm64-apple-macos11.0 %s -filetype=obj -o %t/arm64.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/arm64.o | FileCheck %s --check-prefix ONE-FDE
+// RUN: llvm-mc -triple x86_64-apple-macos11.0 %s -filetype=obj --emit-dwarf-unwind no-compact-unwind -o %t/x86_64-no-dwarf.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/x86_64-no-dwarf.o | FileCheck %s --check-prefix ONE-FDE
+// RUN: llvm-mc -triple arm64-apple-macos11.0 %s -filetype=obj --emit-dwarf-unwind always -o %t/arm64-dwarf.o
+// RUN: llvm-objdump --macho --dwarf=frames %t/arm64-dwarf.o | FileCheck %s --check-prefix TWO-FDES
+
+// TWO-FDES: FDE
+// TWO-FDES: FDE
+
+// ONE-FDE-NOT: FDE
+// ONE-FDE: FDE
+// ONE-FDE-NOT: FDE
+
+_main:
+  .cfi_startproc
+  .cfi_def_cfa_offset 16
+  ret
+  .cfi_endproc
+
+_foo:
+  .cfi_startproc
+  .cfi_def_cfa_offset 16
+  /// This encodes DW_CFA_GNU_args_size which cannot be expressed using compact
+  /// unwind, so we must use DWARf unwind for this function.
+  .cfi_escape 0x2e, 0x10
+  ret
+  .cfi_endproc
+
+.subsections_via_symbols
Index: llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp

[clang] 967137c - No longer accept scoped enumerations in C

2022-05-05 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-05-05T14:00:01-04:00
New Revision: 967137ca3cb7cf38b2fedf0415946ff3ffd0ef50

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

LOG: No longer accept scoped enumerations in C

We had a think-o that would allow a user to declare a scoped
enumeration in C language modes "as a C++11 extension". This is a
think-o because there's no way for the user to spell the name of the
enumerators; C does not have '::' for a fully-qualified name. See
commit d0d87b597259a2b74ae5c2825a081c7e336cb1d0 for details on why this
is unintentional for C.

Fixes #42372

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Parse/ParseDecl.cpp
clang/test/Sema/enum.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f5e9cd941e091..87e4df50ae0f2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -142,6 +142,11 @@ Bug Fixes
 - Fixed a false positive diagnostic about an unevaluated expression having no
   side effects when the expression is of VLA type and is an operand of the
   ``sizeof`` operator. Fixes `Issue 48010 
`_.
+- Fixed a false positive diagnostic about scoped enumerations being a C++11
+  extension in C mode. A scoped enumeration's enumerators cannot be named in C
+  because there is no way to fully qualify the enumerator name, so this
+  "extension" was unintentional and useless. This fixes
+  `Issue 42372 `_.
 
 Improvements to Clang's diagnostics
 ^^^

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 3d18ffe07ee6b..8d6e84b924c32 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -4531,7 +4531,7 @@ void Parser::ParseEnumSpecifier(SourceLocation StartLoc, 
DeclSpec ,
   bool IsScopedUsingClassTag = false;
 
   // In C++11, recognize 'enum class' and 'enum struct'.
-  if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
+  if (Tok.isOneOf(tok::kw_class, tok::kw_struct) && getLangOpts().CPlusPlus) {
 Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
 : diag::ext_scoped_enum);
 IsScopedUsingClassTag = Tok.is(tok::kw_class);

diff  --git a/clang/test/Sema/enum.c b/clang/test/Sema/enum.c
index ae4a8a357e179..0fe54d791aff5 100644
--- a/clang/test/Sema/enum.c
+++ b/clang/test/Sema/enum.c
@@ -159,3 +159,16 @@ struct EnumRedeclStruct {
 PR15071_One // expected-error {{redefinition of enumerator 'PR15071_One'}}
   } e;
 };
+
+enum struct GH42372_1 { // expected-error {{expected identifier or '{'}} 
expected-warning {{declaration does not declare anything}}
+  One
+};
+
+// Because class is not a keyword in C, this looks like a forward declaration.
+// expected-error@+4 {{expected ';' after top level declarator}}
+// expected-error@+3 {{tentative definition has type 'enum class' that is 
never completed}}
+// expected-warning@+2 {{ISO C forbids forward references to 'enum' types}}
+// expected-note@+1 {{forward declaration of 'enum class'}}
+enum class GH42372_2 {
+  One
+};



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


[PATCH] D125026: [clang-tidy][NFC] Reimplement most of SimplifyBooleanExpr with RecursiveASTVisitors

2022-05-05 Thread Nathan James via Phabricator via cfe-commits
njames93 created this revision.
njames93 added reviewers: alexfh, klimek, aaron.ballman.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
njames93 requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Reimplement most of the matching logic using Visitors instead of matchers.

Benchmarks from running the check over SemaCodeComplete.cpp
Before 1.02s, After 0.87s


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D125026

Files:
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h

Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.h
@@ -34,73 +34,40 @@
 private:
   class Visitor;
 
-  void reportBinOp(const ast_matchers::MatchFinder::MatchResult ,
-   const BinaryOperator *Op);
-
-  void matchBoolCondition(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef BooleanId);
-
-  void matchTernaryResult(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
-
-  void matchIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void reportBinOp(const ASTContext , const BinaryOperator *Op);
 
   void matchIfAssignsBool(ast_matchers::MatchFinder *Finder, bool Value,
   StringRef Id);
 
-  void matchCompoundIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
-
-  void matchCaseIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-  StringRef Id);
+  void replaceWithThenStatement(const ASTContext ,
+const IfStmt *IfStatement,
+const Expr *BoolLiteral);
 
-  void matchDefaultIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
- StringRef Id);
+  void replaceWithElseStatement(const ASTContext ,
+const IfStmt *IfStatement,
+const Expr *BoolLiteral);
 
-  void matchLabelIfReturnsBool(ast_matchers::MatchFinder *Finder, bool Value,
-   StringRef Id);
+  void replaceWithCondition(const ASTContext ,
+const ConditionalOperator *Ternary, bool Negated);
 
-  void
-  replaceWithThenStatement(const ast_matchers::MatchFinder::MatchResult ,
-   const Expr *BoolLiteral);
-
-  void
-  replaceWithElseStatement(const ast_matchers::MatchFinder::MatchResult ,
-   const Expr *BoolLiteral);
-
-  void
-  replaceWithCondition(const ast_matchers::MatchFinder::MatchResult ,
-   const ConditionalOperator *Ternary, bool Negated);
-
-  void replaceWithReturnCondition(
-  const ast_matchers::MatchFinder::MatchResult , const IfStmt *If,
-  bool Negated);
+  void replaceWithReturnCondition(const ASTContext , const IfStmt *If,
+  const Expr *BoolLiteral, bool Negated);
 
   void
   replaceWithAssignment(const ast_matchers::MatchFinder::MatchResult ,
 const IfStmt *If, bool Negated);
 
-  void replaceCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult ,
-  const CompoundStmt *Compound, bool Negated);
-
-  void replaceCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated,
-  const IfStmt *If);
-
-  void replaceCaseCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated);
-
-  void replaceDefaultCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated);
+  void replaceCompoundReturnWithCondition(const ASTContext ,
+  const CompoundStmt *Compound,
+  const ReturnStmt *Ret, bool Negated);
 
-  void replaceLabelCompoundReturnWithCondition(
-  const ast_matchers::MatchFinder::MatchResult , bool Negated);
+  void replaceCompoundReturnWithCondition(const ASTContext ,
+  const ReturnStmt *Ret, bool Negated,
+  const IfStmt *If);
 
-  void issueDiag(const ast_matchers::MatchFinder::MatchResult ,
- SourceLocation Loc, StringRef Description,
- SourceRange ReplacementRange, StringRef Replacement);
+  void issueDiag(const ASTContext , SourceLocation Loc,
+ StringRef Description, SourceRange ReplacementRange,
+ StringRef Replacement);
 
   const bool 

[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

2022-05-05 Thread Thorsten via Phabricator via cfe-commits
tschuett added inline comments.



Comment at: clang/include/clang-c/Index.h:3448
+  CXCallingConv_AArch64SVEPcs= 17,
+  CXCallingConv_SwiftAsync = 18,
 

tschuett wrote:
> aaron.ballman wrote:
> > peterwaller-arm wrote:
> > > peterwaller-arm wrote:
> > > > It shouldn't matter in principle (... "but in practice" ...) we should 
> > > > probably avoid renumbering existing things in the enum and instead add 
> > > > to the end of it.
> > > > 
> > > > Nit, this is missing a space before the equals.
> > > > Nit, SVE is an acronym, so is PCS, so capitalization should be 
> > > > consistent between the two. I see 'PCS' capitalized in AAPCS for 
> > > > example so probably all upper case makes the sense.
> > > > 
> > > I retract my sloppy "it shouldn't matter in principle [at the source 
> > > level]", of course it does matter, and it likely matters in this case 
> > > (see 'alias for compatibility' comment above).
> > > 
> > > To be more specific, changing the enum is an ABI break, and breaks if 
> > > these things are ever serialized and therefore not something you want to 
> > > do.
> > +1 -- I was just making that comment when you beat me to it.
> Could you please add your CC as 18 and add a comment the next CC will 19 and 
> do not touch the other ones.
Do you want to add a `static_assert` to prevent people from doing stupid things?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

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

In D124998#3494426 , @erichkeane 
wrote:

> In D124998#3494424 , @efriedma 
> wrote:
>
>> If you're really concerned about the size of FunctionProtoType increasing, 
>> can we just shove the infrequently used calling convention bits into 
>> TrailingObjects?
>
> I don't believe so.  These are parts of the bitfield and are intrinsic to the 
> type.

I don't follow. Everything stored in FunctionProtoType, including information 
stored in TrailingObjects, is "intrinsic to the type".  It's just stored 
differently.  (FunctionTypeExtraBitfields already exists, even...)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added a comment.
This revision is now accepted and ready to land.

Overall this looks good to me. However, I think this might not use the full 
potential of the check itself. With the information that the dataflow framework 
have it could distinguish between **potentially** unsafe accesses and 
**provably** unsafe accesses depending on whether the `has_value` property is 
constrained to be false. From the user point of view, it would be nice to emit 
different warning messages for the above two cases. This can help to gradually 
introduce this check to a larger codebase and focus on the higher severity 
diagnostics first.




Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst:29
+
+Checking if a value exists, then accessing the value
+

I wonder if it would be easier to read if we had two top level categories, one 
for safe and one for unsafe accesses instead of switching back and forth 
between examples.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

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

In D124998#3494424 , @efriedma wrote:

> If you're really concerned about the size of FunctionProtoType increasing, 
> can we just shove the infrequently used calling convention bits into 
> TrailingObjects?

I don't believe so.  These are parts of the bitfield and are intrinsic to the 
type.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

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

If you're really concerned about the size of FunctionProtoType increasing, can 
we just shove the infrequently used calling convention bits into 
TrailingObjects?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

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



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:84
+  if (!BlockToOutputState ||
+  BlockToOutputState->size() <= Context->getCFG().getExit().getBlockID())
+return;

xazax.hun wrote:
> Could the size of the vector ever be wrong? Should this be an assert instead?
Whoops, after the update this comment is out of place, now it supposed to be on 
line 60. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

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



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:84
+  if (!BlockToOutputState ||
+  BlockToOutputState->size() <= Context->getCFG().getExit().getBlockID())
+return;

Could the size of the vector ever be wrong? Should this be an assert instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 427381.
ymandel added a comment.

Factor out analysis code into separate function.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/types/optional.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp

Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -13,6 +13,7 @@
 
 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/Stmt.h"
@@ -29,13 +30,9 @@
 
 namespace clang {
 namespace dataflow {
-namespace {
-
-using namespace ::clang::ast_matchers;
 
-using LatticeTransferState = TransferState;
-
-auto optionalClass() {
+ast_matchers::DeclarationMatcher optionalClass() {
+  using namespace ::clang::ast_matchers;
   return classTemplateSpecializationDecl(
   anyOf(hasName("std::optional"), hasName("std::__optional_storage_base"),
 hasName("__optional_destruct_base"), hasName("absl::optional"),
@@ -43,6 +40,12 @@
   hasTemplateArgument(0, refersToType(type().bind("T";
 }
 
+namespace {
+
+using namespace ::clang::ast_matchers;
+
+using LatticeTransferState = TransferState;
+
 auto hasOptionalType() { return hasType(optionalClass()); }
 
 auto isOptionalMemberCallWithName(
@@ -230,6 +233,8 @@
   }
 
   // Record that this unwrap is *not* provably safe.
+  // FIXME: include either the name of the optional (if applicable) or a source
+  // range of the access for easier intepretation of the result.
   State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc());
 }
 
Index: clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
===
--- clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -36,6 +36,9 @@
   bool IgnoreSmartPointerDereference = false;
 };
 
+/// A matcher for the optional classes covered by this model.
+ast_matchers::DeclarationMatcher optionalClass();
+
 /// Dataflow analysis that discovers unsafe accesses of optional values and
 /// adds the respective source locations to the lattice.
 ///
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
@@ -0,0 +1,112 @@
+// RUN: %check_clang_tidy %s bugprone-unchecked-optional-access %t -- -- -I %S/Inputs/
+
+#include "absl/types/optional.h"
+
+void unchecked_value_access(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
+}
+
+void unchecked_deref_operator_access(const absl::optional ) {
+  *opt;
+  // CHECK-MESSAGES: :[[@LINE-1]]:4: warning: unchecked access to optional value
+}
+
+struct Foo {
+  void foo() const {}
+};
+
+void unchecked_arrow_operator_access(const absl::optional ) {
+  opt->foo();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void f2(const absl::optional ) {
+  if (opt.has_value()) {
+opt.value();
+  }
+}
+
+template 
+void function_template_without_user(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template 
+void function_template_with_user(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void function_template_user(const absl::optional ) {
+  // Instantiate the f3 function template so that it gets matched by the check.
+  function_template_with_user(opt);
+}
+
+template 
+void function_template_with_specialization(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template <>
+void 

[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

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

In D124998#3494388 , @paulwalker-arm 
wrote:

> In D124998#3494127 , @aaron.ballman 
> wrote:
>
>> In D124998#3493791 , 
>> @paulwalker-arm wrote:
>>
>>> Just wanted to say this is not a new calling convention as such, but rather 
>>> an existing one that is generally auto-detected based on function 
>>> signature.  The problem we're trying to solve here is that we need a way to 
>>> allow a user to force the calling convention when the function signature 
>>> would not normally choose it.
>>
>> Thanks for this information! It's still not clear to me whether there's 
>> sufficient need for this extension. From this description, it sounds like 
>> this will be rarely used because it's only necessary in one-off situations. 
>> If that's correct, can those users make use of inline assembly instead of a 
>> devoted named calling convention?
>
> It's hard to say how often this will be used but when used it will be 
> fundamental to performance. I don't see inline assembly as a workable 
> solution. It presents an unreasonable burden on a framework's user and will 
> impact compiler optimisations.  The ACLE exists to stop developers from 
> needing to use inline assembly.
>
> You have to forgive my naivety here but some of the calling conventions are 
> target specific.  Is it possible for them to safely alias for the parts of 
> the code where memory is constrained?  Or to put it another way, do the X86 
> and AArch64 calling conventions need to be uniquely identifiable?

This would alleviate my concerns if we were to do something like that. It _IS_ 
quite unfair how many calling convention bits we burn on old 32-bit-MSVC and 
X86/x86-64 calling conventions that don't seem particularly well used/valuable.

I looked into doing that at one point about 2 years ago, but it ended up being 
not possible/beneficial thanks to our multi-target-at-the-same-time compilation 
model for offload.  Basically: we need to identify TWO calling convention lists 
at the same time, and there are combos that result in us having more than 16 
items, thus not saving any bits.  If you can come up with a way of doing this 
that I was unable to come up with at the time, I'm all for it!  At that point, 
it would be up to the individual targets to manage themselves in a way to stay 
sub-16.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D124998: [AArch64][SVE] Add aarch64_sve_pcs attribute to Clang

2022-05-05 Thread Paul Walker via Phabricator via cfe-commits
paulwalker-arm added a comment.

In D124998#3494127 , @aaron.ballman 
wrote:

> In D124998#3493791 , 
> @paulwalker-arm wrote:
>
>> Just wanted to say this is not a new calling convention as such, but rather 
>> an existing one that is generally auto-detected based on function signature. 
>>  The problem we're trying to solve here is that we need a way to allow a 
>> user to force the calling convention when the function signature would not 
>> normally choose it.
>
> Thanks for this information! It's still not clear to me whether there's 
> sufficient need for this extension. From this description, it sounds like 
> this will be rarely used because it's only necessary in one-off situations. 
> If that's correct, can those users make use of inline assembly instead of a 
> devoted named calling convention?

It's hard to say how often this will be used but when used it will be 
fundamental to performance. I don't see inline assembly as a workable solution. 
It presents an unreasonable burden on a framework's user and will impact 
compiler optimisations.  The ACLE exists to stop developers from needing to use 
inline assembly.

You have to forgive my naivety here but some the calling conventions are target 
specific.  Is it possible for them to safely alias for the parts of the code 
where memory is constrained?  Or to put it another way, do the X86 and AArch64 
calling conventions need to be uniquely identifiable?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124998

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added inline comments.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:38
+
+  auto HasOptionalCallDescendant = hasDescendant(callExpr(callee(cxxMethodDecl(
+  ofClass(anyOf(hasName("std::optional"), hasName("absl::optional"),

xazax.hun wrote:
> I am a bit afraid that we have two places to update the list of supported 
> optional types and they can get out of sync. I wonder whether creating a 
> function in `clang/Analysis/FlowSensitive/Models/UncheckedOptionalUseModel.h` 
> to return a matcher that matches the supported optional types is a better 
> approach.
Yes, it is a better approach. :) Done.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:49
+  this);
+  Finder->addMatcher(
+  cxxConstructorDecl(hasAnyConstructorInitializer(

xazax.hun wrote:
> If we have a `CXXConstructorDecl` where both the initializer and the body has 
> calls to optional types, i.e. both matchers would match, would we process the 
> body of that twice? 
Yes, we would. Good catch. Fixed.



Comment at: 
clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp:92
+  for (const SourceLocation  : ExitBlockLattice.getSourceLocations()) {
+diag(Loc, "unchecked access to optional value");
+  }

xazax.hun wrote:
> Is there a way in the future to include either the name of the optional or a 
> source range of the access? This can be confusing when we have multiple 
> optionals in the same line. The of course, the column information helps. But 
> the more visual guides we have the better :)
Yes -- we have access to the object expression at the time of detection. So 
both are reasonable to include. We just need to extend the 
SourceLocationsLattice to accomodate.  Added a FIXME in the model.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 427377.
ymandel marked 2 inline comments as done.
ymandel added a comment.

added fixme


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/types/optional.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp

Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -13,6 +13,7 @@
 
 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/Stmt.h"
@@ -29,13 +30,9 @@
 
 namespace clang {
 namespace dataflow {
-namespace {
-
-using namespace ::clang::ast_matchers;
 
-using LatticeTransferState = TransferState;
-
-auto optionalClass() {
+ast_matchers::DeclarationMatcher optionalClass() {
+  using namespace ::clang::ast_matchers;
   return classTemplateSpecializationDecl(
   anyOf(hasName("std::optional"), hasName("std::__optional_storage_base"),
 hasName("__optional_destruct_base"), hasName("absl::optional"),
@@ -43,6 +40,12 @@
   hasTemplateArgument(0, refersToType(type().bind("T";
 }
 
+namespace {
+
+using namespace ::clang::ast_matchers;
+
+using LatticeTransferState = TransferState;
+
 auto hasOptionalType() { return hasType(optionalClass()); }
 
 auto isOptionalMemberCallWithName(
@@ -230,6 +233,8 @@
   }
 
   // Record that this unwrap is *not* provably safe.
+  // FIXME: include either the name of the optional (if applicable) or a source
+  // range of the access for easier intepretation of the result.
   State.Lattice.getSourceLocations().insert(ObjectExpr->getBeginLoc());
 }
 
Index: clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
===
--- clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -36,6 +36,9 @@
   bool IgnoreSmartPointerDereference = false;
 };
 
+/// A matcher for the optional classes covered by this model.
+ast_matchers::DeclarationMatcher optionalClass();
+
 /// Dataflow analysis that discovers unsafe accesses of optional values and
 /// adds the respective source locations to the lattice.
 ///
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
@@ -0,0 +1,112 @@
+// RUN: %check_clang_tidy %s bugprone-unchecked-optional-access %t -- -- -I %S/Inputs/
+
+#include "absl/types/optional.h"
+
+void unchecked_value_access(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
+}
+
+void unchecked_deref_operator_access(const absl::optional ) {
+  *opt;
+  // CHECK-MESSAGES: :[[@LINE-1]]:4: warning: unchecked access to optional value
+}
+
+struct Foo {
+  void foo() const {}
+};
+
+void unchecked_arrow_operator_access(const absl::optional ) {
+  opt->foo();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void f2(const absl::optional ) {
+  if (opt.has_value()) {
+opt.value();
+  }
+}
+
+template 
+void function_template_without_user(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template 
+void function_template_with_user(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void function_template_user(const absl::optional ) {
+  // Instantiate the f3 function template so that it gets matched by the check.
+  function_template_with_user(opt);
+}
+
+template 
+void function_template_with_specialization(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template <>
+void 

[PATCH] D124974: [clang] Include clang config.h in LangStandards.cpp

2022-05-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

In D124974#3494279 , @dexonsmith 
wrote:

> Can we add a test for this?

I think the problem with testing it is that this variable comes from the CMake 
config, and in the default configuration (as used by all the bots) it's not set.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124974

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


[PATCH] D121120: [clang-tidy] New check for safe usage of `std::optional` and like types.

2022-05-05 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 427374.
ymandel marked 2 inline comments as done.
ymandel added a comment.
Herald added a project: clang.

address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121120

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone-unchecked-optional-access.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/test/clang-tidy/checkers/Inputs/absl/types/optional.h
  
clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp

Index: clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
===
--- clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -13,6 +13,7 @@
 
 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/Stmt.h"
@@ -29,13 +30,9 @@
 
 namespace clang {
 namespace dataflow {
-namespace {
-
-using namespace ::clang::ast_matchers;
 
-using LatticeTransferState = TransferState;
-
-auto optionalClass() {
+ast_matchers::DeclarationMatcher optionalClass() {
+  using namespace ::clang::ast_matchers;
   return classTemplateSpecializationDecl(
   anyOf(hasName("std::optional"), hasName("std::__optional_storage_base"),
 hasName("__optional_destruct_base"), hasName("absl::optional"),
@@ -43,6 +40,12 @@
   hasTemplateArgument(0, refersToType(type().bind("T";
 }
 
+namespace {
+
+using namespace ::clang::ast_matchers;
+
+using LatticeTransferState = TransferState;
+
 auto hasOptionalType() { return hasType(optionalClass()); }
 
 auto isOptionalMemberCallWithName(
Index: clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
===
--- clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -36,6 +36,9 @@
   bool IgnoreSmartPointerDereference = false;
 };
 
+/// A matcher for the optional classes covered by this model.
+ast_matchers::DeclarationMatcher optionalClass();
+
 /// Dataflow analysis that discovers unsafe accesses of optional values and
 /// adds the respective source locations to the lattice.
 ///
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone-unchecked-optional-access.cpp
@@ -0,0 +1,112 @@
+// RUN: %check_clang_tidy %s bugprone-unchecked-optional-access %t -- -- -I %S/Inputs/
+
+#include "absl/types/optional.h"
+
+void unchecked_value_access(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value [bugprone-unchecked-optional-access]
+}
+
+void unchecked_deref_operator_access(const absl::optional ) {
+  *opt;
+  // CHECK-MESSAGES: :[[@LINE-1]]:4: warning: unchecked access to optional value
+}
+
+struct Foo {
+  void foo() const {}
+};
+
+void unchecked_arrow_operator_access(const absl::optional ) {
+  opt->foo();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void f2(const absl::optional ) {
+  if (opt.has_value()) {
+opt.value();
+  }
+}
+
+template 
+void function_template_without_user(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template 
+void function_template_with_user(const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+void function_template_user(const absl::optional ) {
+  // Instantiate the f3 function template so that it gets matched by the check.
+  function_template_with_user(opt);
+}
+
+template 
+void function_template_with_specialization(const absl::optional ) {
+  opt.value(); // no-warning
+}
+
+template <>
+void function_template_with_specialization(
+const absl::optional ) {
+  opt.value();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: unchecked access to optional value
+}
+
+template 
+class ClassTemplateWithSpecializations {
+  void f(const absl::optional ) {
+opt.value(); // no-warning
+  

[PATCH] D124221: Reimplement `__builtin_dump_struct` in Sema.

2022-05-05 Thread Wang Yihan via Phabricator via cfe-commits
yihanaa added a comment.

This is unfortunately true, unless we generate some code that calculates the 
length of the string at runtime. I find it difficult to draw the line between 
defining this built-in functionality and developers developing printf-like 
functionality, if built-in does too much, flexibility will decrease, if 
built-in does less, (features like length limits) then develop personnel may 
need to do some work.   o(≧口≦)o


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124221

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


[PATCH] D124669: [flang][driver] Add support for -save-temps

2022-05-05 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski updated this revision to Diff 427367.
awarzynski added a comment.

Mark the tests as unsupported on Windows

Pre-merge testing is failing on Windows. Here is the error message:

  flang-new: error: there is no external assembler that can be used on this 
platform

I will update the commit message accordingly before merging this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124669

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/Types.def
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/fno-integrated-as.f90
  flang/test/Driver/save-temps.f90

Index: flang/test/Driver/save-temps.f90
===
--- /dev/null
+++ flang/test/Driver/save-temps.f90
@@ -0,0 +1,55 @@
+! Tests for the `-save-temps` flag. As `flang` does not implement `-fc1as` (i.e. a driver for the integrated assembler), we need to
+! use `-fno-integrated-as` here.
+
+! UNSUPPORTED: system-windows
+
+!--
+! Basic case: `-save-temps`
+!--
+! RUN: %flang -save-temps -fno-integrated-as %s -### 2>&1 | FileCheck %s
+! CHECK: "-o" "save-temps.i"
+! CHECK-NEXT: "-o" "save-temps.bc"
+! CHECK-NEXT: "-o" "save-temps.s"
+! CHECK-NEXT: "-o" "save-temps.o"
+! CHECK-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=cwd`
+!--
+! This should work the same as -save-temps above
+
+! RUN: %flang -save-temps=cwd -fno-integrated-as  %s -### 2>&1 | FileCheck %s -check-prefix=CWD
+! CWD: "-o" "save-temps.i"
+! CWD-NEXT: "-o" "save-temps.bc"
+! CWD-NEXT: "-o" "save-temps.s"
+! CWD-NEXT: "-o" "save-temps.o"
+! CWD-NEXT: "-o" "a.out"
+
+!--
+! `-save-temps=obj`
+!--
+! Check that temp files are saved in the same directory as the output file
+! regardless of whether -o is specified.
+
+! RUN: %flang -save-temps=obj -fno-integrated-as -o obj/dir/a.out %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ
+! CHECK-OBJ: "-o" "obj/dir/save-temps.i"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.bc"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.s"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/save-temps.o"
+! CHECK-OBJ-NEXT: "-o" "obj/dir/a.out"
+
+! RUN: %flang -save-temps=obj -fno-integrated-as %s -### 2>&1 | FileCheck %s -check-prefix=CHECK-OBJ-NOO
+! CHECK-OBJ-NOO: "-o" "save-temps.i"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.bc"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.s"
+! CHECK-OBJ-NOO-NEXT: "-o" "save-temps.o"
+! CHECK-OBJ-NOO-NEXT: "-o" "a.out"
+
+!--
+! `-S` without `-save-temps`
+!--
+! Check for a single `flang -fc1` invocation when NOT using -save-temps.
+! RUN: %flang -S %s -### 2>&1 | FileCheck %s -check-prefix=NO-TEMPS
+! NO-TEMPS: "-fc1"
+! NO-TEMPS-SAME: "-S"
+! NO-TEMPS-SAME: "-o" "save-temps.s"
Index: flang/test/Driver/fno-integrated-as.f90
===
--- /dev/null
+++ flang/test/Driver/fno-integrated-as.f90
@@ -0,0 +1,20 @@
+! Tests for the `-fno-integrated-as` flag.
+
+! UNSUPPORTED: system-windows
+
+!--
+! With `-fno-integrated-as`
+!--
+! Verify that there _is_ a separate line with an assembler invocation
+! RUN: %flang -c -fno-integrated-as %s -### 2>&1 | FileCheck %s
+! CHECK-LABEL: "-fc1"
+! CHECK-SAME: "-o" "[[assembly_file:.*]].s"
+! CHECK-NEXT: "-o" "{{.*}}.o" "[[assembly_file:.*]].s"
+
+!-
+! Without `-fno-integrated-as`
+!-
+! Verify that there _is no_ separate line with an assembler invocation
+! RUN: %flang -c %s -### 2>&1 | FileCheck %s -check-prefix=DEFAULT
+! DEFAULT-LABEL: "-fc1"
+! DEFAULT-SAME: "-o" "{{.*}}.o" "{{.*}}fno-integrated-as.f90"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -42,6 +42,7 @@
 ! HELP-NEXT: -flogical-abbreviations Enable logical abbreviations
 ! HELP-NEXT: -fno-automatic Implies the SAVE attribute for non-automatic local objects in subprograms unless RECURSIVE
 ! HELP-NEXT: -fno-color-diagnostics  Disable colors in diagnostics
+! HELP-NEXT: -fno-integrated-as  Disable the integrated assembler
 ! HELP-NEXT: -fopenacc  Enable OpenACC
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
 ! HELP-NEXT: -fxor-operator Enable .XOR. as a synonym of .NEQV.
@@ -56,6 +57,8 @@
 ! HELP-NEXT: -print-effective-triple Print the effective target triple
 ! HELP-NEXT: -print-target-triplePrint the normalized target triple
 ! HELP-NEXT: -P Disable linemarker output in -E mode
+! HELP-NEXT: -save-temps=Save intermediate compilation results.
+! HELP-NEXT: 

  1   2   3   >