[PATCH] D154357: [Driver] Recognize powerpc-unknown-eabi as a bare-metal toolchain

2023-07-21 Thread Christian Walther via Phabricator via cfe-commits
cwalther added inline comments.



Comment at: clang/test/Driver/baremetal.cpp:348
 
+// RUN: %clang %s -### --target=powerpc-unknown-eabi 2>&1 \
+// RUN:   | FileCheck --check-prefix=CHECK-PPCEABI %s

MaskRay wrote:
> MaskRay wrote:
> > Without a sysroot, we may pick up powerpc-unknown-eabi-gcc (if installed) 
> > and the paths below may be incorrect.
> I managed to notice an issue. See the commit message of the follow-up fix: 
> eddc4850d81f4c9f79d0b17869d67eac8ca88070 (really obscure,  I forgot it...)
I see. Thanks for the fix!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154357

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


[PATCH] D155661: [ASTImporter] Fix friend class template import within dependent context

2023-07-21 Thread Ding Fei via Phabricator via cfe-commits
danix800 updated this revision to Diff 542778.
danix800 added a comment.

Apply git-clang-format.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155661

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

Index: clang/unittests/AST/ASTImporterTest.cpp
===
--- clang/unittests/AST/ASTImporterTest.cpp
+++ clang/unittests/AST/ASTImporterTest.cpp
@@ -3968,8 +3968,31 @@
   EXPECT_EQ(ToDef->getPreviousDecl(), ToProto);
 }
 
-
-struct ImportFriendClasses : ASTImporterOptionSpecificTestBase {};
+struct ImportFriendClasses : ASTImporterOptionSpecificTestBase {
+  void testRecursiveFriendClassTemplate(Decl *FromTu) {
+auto *FromD = FirstDeclMatcher().match(
+FromTu, classTemplateDecl());
+auto *ToD = Import(FromD, Lang_CXX03);
+
+auto Pattern = classTemplateDecl(
+has(cxxRecordDecl(has(friendDecl(has(classTemplateDecl()));
+ASSERT_TRUE(MatchVerifier{}.match(FromD, Pattern));
+EXPECT_TRUE(MatchVerifier{}.match(ToD, Pattern));
+
+auto *FromFriend =
+FirstDeclMatcher().match(FromD, friendDecl());
+auto *FromClass =
+FirstDeclMatcher().match(FromD, classTemplateDecl());
+EXPECT_NE(FromFriend->getFriendDecl(), FromClass);
+EXPECT_TRUE(FromFriend->getFriendDecl()->getPreviousDecl() == nullptr);
+
+auto *Class =
+FirstDeclMatcher().match(ToD, classTemplateDecl());
+auto *Friend = FirstDeclMatcher().match(ToD, friendDecl());
+EXPECT_NE(Friend->getFriendDecl(), Class);
+EXPECT_TRUE(Friend->getFriendDecl()->getPreviousDecl() == nullptr);
+  }
+};
 
 TEST_P(ImportFriendClasses, ImportOfFriendRecordDoesNotMergeDefinition) {
   Decl *FromTU = getTuDecl(
@@ -4074,20 +4097,19 @@
   )",
   Lang_CXX03, "input.cc");
 
-  auto *FromD =
-  FirstDeclMatcher().match(FromTu, classTemplateDecl());
-  auto *ToD = Import(FromD, Lang_CXX03);
-
-  auto Pattern = classTemplateDecl(
-  has(cxxRecordDecl(has(friendDecl(has(classTemplateDecl()));
-  ASSERT_TRUE(MatchVerifier{}.match(FromD, Pattern));
-  EXPECT_TRUE(MatchVerifier{}.match(ToD, Pattern));
+  testRecursiveFriendClassTemplate(FromTu);
+}
 
-  auto *Class =
-  FirstDeclMatcher().match(ToD, classTemplateDecl());
-  auto *Friend = FirstDeclMatcher().match(ToD, friendDecl());
-  EXPECT_NE(Friend->getFriendDecl(), Class);
-  EXPECT_EQ(Friend->getFriendDecl()->getPreviousDecl(), Class);
+TEST_P(ImportFriendClasses,
+   ImportOfRecursiveFriendClassTemplateWithNonTypeParm) {
+  Decl *FromTu = getTuDecl(
+  R"(
+  template class declToImport {
+template friend class declToImport;
+  };
+  )",
+  Lang_CXX03, "input.cc");
+  testRecursiveFriendClassTemplate(FromTu);
 }
 
 TEST_P(ImportFriendClasses, ProperPrevDeclForClassTemplateDecls) {
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -2857,6 +2857,10 @@
   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
 
+  bool IsDependentContext = DC != LexicalDC ? LexicalDC->isDependentContext()
+: DC->isDependentContext();
+  bool ShouldAddRedecl = !(IsFriendTemplate && IsDependentContext);
+
   // We may already have a record of the same name; try to find and match it.
   RecordDecl *PrevDecl = nullptr;
   if (!DC->isFunctionOrMethod() && !D->isLambda()) {
@@ -2897,7 +2901,7 @@
 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
   continue;
 
-if (IsStructuralMatch(D, FoundRecord)) {
+if (!ShouldAddRedecl || IsStructuralMatch(D, FoundRecord)) {
   RecordDecl *FoundDef = FoundRecord->getDefinition();
   if (D->isThisDeclarationADefinition() && FoundDef) {
 // FIXME: Structural equivalence check should check for same
@@ -2955,7 +2959,7 @@
 return CDeclOrErr.takeError();
   Numbering.ContextDecl = *CDeclOrErr;
   D2CXX->setLambdaNumbering(Numbering);
-   } else if (DCXX->isInjectedClassName()) {
+} else if (DCXX->isInjectedClassName()) {
   // We have to be careful to do a similar dance to the one in
   // Sema::ActOnStartCXXMemberDeclarations
   const bool DelayTypeCreation = true;
@@ -2967,10 +2971,11 @@
   Importer.getToContext().getTypeDeclType(
   D2CXX, dyn_cast(DC));
 } else {
-  if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
-  D->getTagKind(), DC, *BeginLocOrErr, Loc,
-  Name.getAsIdentifierInfo(),
-  cast_or_null(PrevDecl)))
+  if (GetImportedOrCreateDecl(
+  D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
+  *BeginLocOrErr, 

[PATCH] D155421: [clangd] Add BlockEnd comments for control flow statements

2023-07-21 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.

Thanks, this looks like in a good shape. I left comments with some thoughts and 
nits, but they're not blockers, feel free to land it.




Comment at: clang-tools-extra/clangd/InlayHints.cpp:252
+// This is used to summarize e.g. the condition of a while loop.
+std::string summarizeExpr(const Expr *E) {
+  struct Namer : ConstStmtVisitor {

This looks like a complicated implementation to get an abbreviated-form of cond 
expression for the inlay label text.


A different idea would be if the user can just click the inlay label text, then 
the editor jumps to the corresponding for statement (looks like it is supported 
with the 
[InlayHintLabelPart::Location](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#inlayHintLabelPart))
 with that we probably don't need to emit an abbreviated-form text (`// for` 
should be clear enough).



Comment at: clang-tools-extra/clangd/InlayHints.cpp:578
+  //   } else if (cond2) {
+  //   } // mark as "cond1" or "cond2"?
+  // For now, the answer is neither, just mark as "if".

my opinion for this case would be (the marking result is also consistent with 
the brackets)

```
if (cond1) {
} // mark as cond1
else if (cond2) {
} // mark as cond2.
```



Comment at: clang-tools-extra/clangd/InlayHints.cpp:599
+llvm::StringRef Name = "") {
+if (const auto *CS = llvm::dyn_cast_or_null(Body))
+  addBlockEndHint(CS->getSourceRange(), Label, Name, "");

it looks like we will mark the block end for single-statement `CompoundStmt` 
without `{}`, it doesn't seem to add much value to this case (the body is short 
enough to spot the for statement).

```
for (int i = 0; i < 10; ++i)
  foo();
```



Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:1786
+
+   if (auto X = cond) {
+   $init[[}]]

nit: add a case `if (int i = 0; i > 10) { ... }`.



Comment at: clang-tools-extra/clangd/unittests/InlayHintTests.cpp:1859
+  ExpectedHint{" // while \"foo\"", "string"},
+  ExpectedHint{" // while \"...\"", "string_long"},
+  ExpectedHint{" // while true", "boolean"},

nit: I guess showing `foo...` is better.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155421

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


[PATCH] D155694: [NFC][analyzer] Enable implicit destructor for cfg-lifetime tests

2023-07-21 Thread Tomasz Kamiński via Phabricator via cfe-commits
tomasz-kaminski-sonarsource updated this revision to Diff 542779.
tomasz-kaminski-sonarsource added a comment.

Added generic FIXME comment for covering test cases for types with trivial 
destructor.
This affects nearly all tests cases from file, so some tought needs to be put 
on how
to apporach it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155694

Files:
  clang/test/Analysis/lifetime-cfg-output.cpp

Index: clang/test/Analysis/lifetime-cfg-output.cpp
===
--- clang/test/Analysis/lifetime-cfg-output.cpp
+++ clang/test/Analysis/lifetime-cfg-output.cpp
@@ -1,6 +1,11 @@
-// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -analyze -analyzer-checker=debug.DumpCFG -analyzer-config cfg-lifetime=true,cfg-temporary-dtors=false,cfg-rich-constructors=false -analyzer-config cfg-implicit-dtors=false %s > %t 2>&1
+// RUN: %clang_cc1 -fcxx-exceptions -fexceptions -analyze -analyzer-checker=debug.DumpCFG -analyzer-config cfg-lifetime=true %s > %t 2>&1
 // RUN: FileCheck --input-file=%t %s
 
+// FIXME Most of the cases in this file test only with the objects of type `A`,
+// that has non-trivial destructor. As the behavior for such types is different
+// from ones with trivial destructor - later ends they lifetime last, we
+// should extended the test cases. 
+
 extern bool UV;
 class A {
 public:
@@ -58,19 +63,21 @@
 // CHECK:   [B2 (ENTRY)]
 // CHECK-NEXT:Succs (1): B1
 // CHECK:   [B1]
-// CHECK-NEXT:1:  (CXXConstructExpr, A)
+// CHECK-NEXT:1:  (CXXConstructExpr, [B1.2], A)
 // CHECK-NEXT:2: A a;
 // CHECK-NEXT:3: a
 // CHECK-NEXT:4: [B1.3] (ImplicitCastExpr, NoOp, const A)
 // CHECK-NEXT:5: const A &b = a;
-// CHECK-NEXT:6: A() (CXXConstructExpr, A)
+// CHECK-NEXT:6: A() (CXXConstructExpr, [B1.9], A)
 // CHECK-NEXT:7: [B1.6] (BindTemporary)
 // CHECK-NEXT:8: [B1.7] (ImplicitCastExpr, NoOp, const A)
 // CHECK-NEXT:9: [B1.8]
 // CHECK-NEXT:   10: const A &c = A();
-// CHECK-NEXT:   11: [B1.10] (Lifetime ends)
-// CHECK-NEXT:   12: [B1.2] (Lifetime ends)
-// CHECK-NEXT:   13: [B1.5] (Lifetime ends)
+// CHECK-NEXT:   11: [B1.10].~A() (Implicit destructor)
+// CHECK-NEXT:   12: [B1.10] (Lifetime ends)
+// CHECK-NEXT:   13: [B1.2].~A() (Implicit destructor)
+// CHECK-NEXT:   14: [B1.2] (Lifetime ends)
+// CHECK-NEXT:   15: [B1.5] (Lifetime ends)
 // CHECK-NEXT:Preds (1): B2
 // CHECK-NEXT:Succs (1): B0
 // CHECK:   [B0 (EXIT)]
@@ -84,14 +91,15 @@
 // CHECK:  [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1
 // CHECK:   [B1]
-// CHECK-NEXT:1:  (CXXConstructExpr, A[2])
+// CHECK-NEXT:1:  (CXXConstructExpr, [B1.2], A[2])
 // CHECK-NEXT:2: A a[2];
-// CHECK-NEXT:3:  (CXXConstructExpr, A[0])
+// CHECK-NEXT:3:  (CXXConstructExpr, [B1.4], A[0])
 // CHECK-NEXT:4: A b[0];
+// CHECK-NEXT:5: [B1.2].~A[2]() (Implicit destructor)
 // lifetime of a ends when its destructors are run
-// CHECK-NEXT:5: [B1.2] (Lifetime ends)
+// CHECK-NEXT:6: [B1.2] (Lifetime ends)
 // lifetime of b ends when its storage duration ends
-// CHECK-NEXT:6: [B1.4] (Lifetime ends)
+// CHECK-NEXT:7: [B1.4] (Lifetime ends)
 // CHECK-NEXT:Preds (1): B2
 // CHECK-NEXT:Succs (1): B0
 // CHECK:  [B0 (EXIT)]
@@ -104,18 +112,22 @@
 // CHECK:  [B2 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B1
 // CHECK:   [B1]
-// CHECK-NEXT:1:  (CXXConstructExpr, A)
+// CHECK-NEXT:1:  (CXXConstructExpr, [B1.2], A)
 // CHECK-NEXT:2: A a;
-// CHECK-NEXT:3:  (CXXConstructExpr, A)
+// CHECK-NEXT:3:  (CXXConstructExpr, [B1.4], A)
 // CHECK-NEXT:4: A c;
-// CHECK-NEXT:5:  (CXXConstructExpr, A)
+// CHECK-NEXT:5:  (CXXConstructExpr, [B1.6], A)
 // CHECK-NEXT:6: A d;
-// CHECK-NEXT:7: [B1.6] (Lifetime ends)
-// CHECK-NEXT:8: [B1.4] (Lifetime ends)
-// CHECK-NEXT:9:  (CXXConstructExpr, A)
-// CHECK-NEXT:   10: A b;
-// CHECK-NEXT:   11: [B1.10] (Lifetime ends)
-// CHECK-NEXT:   12: [B1.2] (Lifetime ends)
+// CHECK-NEXT:7: [B1.6].~A() (Implicit destructor)
+// CHECK-NEXT:8: [B1.6] (Lifetime ends)
+// CHECK-NEXT:9: [B1.4].~A() (Implicit destructor)
+// CHECK-NEXT:   10: [B1.4] (Lifetime ends)
+// CHECK-NEXT:   11:  (CXXConstructExpr, [B1.12], A)
+// CHECK-NEXT:   12: A b;
+// CHECK-NEXT:   13: [B1.12].~A() (Implicit destructor)
+// CHECK-NEXT:   14: [B1.12] (Lifetime ends)
+// CHECK-NEXT:   15: [B1.2].~A() (Implicit destructor)
+// CHECK-NEXT:   16: [B1.2] (Lifetime ends)
 // CHECK-NEXT:Preds (1): B2
 // CHECK-NEXT:Succs (1): B0
 // CHECK:  [B0 (EXIT)]
@@ -132,30 +144,34 @@
 // CHECK:  [B4 (ENTRY)]
 // CHECK-NEXT:   Succs (1): B3
 // CHECK:   [B1]
-// CHECK-NEXT:1:  (CXXConstructExpr, A)
+// CHECK-NEXT:1:  (CXXConstructExpr, [B1.2], A)
 // CHECK-NEXT:2: A c;
-// CHECK-NEXT:3: [B1.2] (Lifetime ends)
-// CHECK-NEXT:4: [B3.4]

[PATCH] D155809: [NFC] [Clang] Fix strict weak ordering in ItaniumVTableBuilder

2023-07-21 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

This looks correct to me, but it's still a little subtle. Perhaps it'd be 
clearer to map the method to an integer (0 for copy assignment, 1 for move 
assignment, 2 for destructor, 3 for equality comparison), and then order them 
by that integer? That'd be more obviously a strict weak order.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155809

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


[PATCH] D152793: [RISCV] Add MC layer support for Zicfisslp.

2023-07-21 Thread Yeting Kuo via Phabricator via cfe-commits
fakepaper56 updated this revision to Diff 542785.
fakepaper56 added a comment.

Make the patch only focus on Zicfiss.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152793

Files:
  clang/test/Preprocessor/riscv-target-features.c
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
  llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
  llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
  llvm/lib/Target/RISCV/RISCVFeatures.td
  llvm/lib/Target/RISCV/RISCVInstrInfo.td
  llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td
  llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp
  llvm/lib/Target/RISCV/RISCVRegisterInfo.td
  llvm/test/MC/RISCV/attribute-arch.s
  llvm/test/MC/RISCV/zicfiss-invalid.s
  llvm/test/MC/RISCV/zicfiss-valid.s

Index: llvm/test/MC/RISCV/zicfiss-valid.s
===
--- /dev/null
+++ llvm/test/MC/RISCV/zicfiss-valid.s
@@ -0,0 +1,110 @@
+# RUN: llvm-mc %s -triple=riscv32 -mattr=+experimental-zicfiss,+c -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc %s -triple=riscv64 -mattr=+experimental-zicfiss,+c -riscv-no-aliases -show-encoding \
+# RUN: | FileCheck -check-prefixes=CHECK-ASM,CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv32 -mattr=+experimental-zicfiss,+c < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfiss -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+# RUN: llvm-mc -filetype=obj -triple=riscv64 -mattr=+experimental-zicfiss,+c < %s \
+# RUN: | llvm-objdump --mattr=+experimental-zicfiss -M no-aliases -d -r - \
+# RUN: | FileCheck --check-prefix=CHECK-ASM-AND-OBJ %s
+#
+# RUN: not llvm-mc -triple riscv32 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+# RUN: not llvm-mc -triple riscv64 -riscv-no-aliases -show-encoding < %s 2>&1 \
+# RUN: | FileCheck -check-prefixes=CHECK-NO-EXT %s
+
+# CHECK-ASM-AND-OBJ: ssload x1
+# CHECK-ASM: encoding: [0x73,0xc0,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload x1
+
+# CHECK-ASM-AND-OBJ: ssload x1
+# CHECK-ASM: encoding: [0x73,0xc0,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload ra
+
+# CHECK-ASM-AND-OBJ: ssload x5
+# CHECK-ASM: encoding: [0x73,0xc0,0xc2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload x5
+
+# CHECK-ASM-AND-OBJ: ssload x5
+# CHECK-ASM: encoding: [0x73,0xc0,0xc2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssload t0
+
+# CHECK-ASM-AND-OBJ: sspopchk x1
+# CHECK-ASM: encoding: [0xf3,0x40,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk x1
+
+# CHECK-ASM-AND-OBJ: sspopchk x1
+# CHECK-ASM: encoding: [0xf3,0x40,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk ra
+
+# CHECK-ASM-AND-OBJ: sspopchk x5
+# CHECK-ASM: encoding: [0xf3,0x42,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk x5
+
+# CHECK-ASM-AND-OBJ: sspopchk x5
+# CHECK-ASM: encoding: [0xf3,0x42,0xc0,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspopchk t0
+
+# CHECK-ASM-AND-OBJ: sspinc 4
+# CHECK-ASM: encoding: [0x73,0x40,0xd2,0x81]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspinc 4
+
+# CHECK-ASM-AND-OBJ: sspush ra
+# CHECK-ASM: encoding: [0x73,0x40,0x10,0x8a]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush x1
+
+# CHECK-ASM-AND-OBJ: sspush ra
+# CHECK-ASM: encoding: [0x73,0x40,0x10,0x8a]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush ra
+
+# check-asm-and-obj: sspush t0
+# check-asm: encoding: [0x73,0x40,0x50,0x8a]
+# check-no-ext: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush x5
+
+# check-asm-and-obj: sspush t0
+# check-asm: encoding: [0x73,0x40,0x50,0x8a]
+# check-no-ext: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+sspush t0
+
+# CHECK-ASM-AND-OBJ: ssprr ra
+# CHECK-ASM: encoding: [0xf3,0x40,0x00,0x86]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssprr ra
+
+# CHECK-ASM-AND-OBJ: ssamoswap t0, zero, (a0)
+# CHECK-ASM: encoding: [0xf3,0x42,0x05,0x82]
+# CHECK-NO-EXT: error: instruction requires the following: 'Zicfiss' (Shadow stack)
+ssamoswap t0, x0, (a0)
+
+# CHECK-ASM-AND-OBJ: c.sspush x1
+# CHECK-ASM: encoding: [0x81,0x60]
+# CHECK-NO-EXT: error: instruction requires the following: 'C' (Compressed Instructions), 'Zicfiss' (Shadow stack)
+c.sspush x1
+
+# C

[PATCH] D155794: [OpenMP][OpenMPIRBuilder] Migrate setPropertyExecutionMode() from Clang to OpenMPIRBuilder.

2023-07-21 Thread Raghu via Phabricator via cfe-commits
raghavendhra updated this revision to Diff 542786.
raghavendhra added a comment.

Addressed review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155794

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/CodeGen/CodeGenModule.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4900,6 +4900,22 @@
   emitBlock(ContBlock, CurFn, /*IsFinished=*/true);
 }
 
+void OpenMPIRBuilder::setPropertyExecutionMode(
+StringRef Name, bool isSPMDMode,
+std::vector LLVMCompilerUsed) {
+  auto *GVMode = new llvm::GlobalVariable(
+  M, llvm::Type::getInt8Ty(M.getContext()), /*isConstant=*/true,
+  llvm::GlobalValue::WeakAnyLinkage,
+  llvm::ConstantInt::get(llvm::Type::getInt8Ty(M.getContext()),
+ isSPMDMode ? OMP_TGT_EXEC_MODE_SPMD
+: OMP_TGT_EXEC_MODE_GENERIC),
+  Twine(Name, "_exec_mode"));
+  GVMode->setVisibility(llvm::GlobalVariable::ProtectedVisibility);
+  assert(!GVMode->isDeclaration() &&
+ "Only globals with definition can force usage.");
+  LLVMCompilerUsed.emplace_back(GVMode);
+}
+
 bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(
 const LocationDescription &Loc, llvm::AtomicOrdering AO, AtomicKind AK) {
   assert(!(AO == AtomicOrdering::NotAtomic ||
Index: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
===
--- llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -1493,6 +1493,21 @@
   void emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen,
 BodyGenCallbackTy ElseGen, InsertPointTy AllocaIP = {});
 
+  /// Create a unique global variable to indicate the execution mode of this
+  /// target region. The execution mode is either 'generic', or 'spmd' depending
+  /// on the target directive. This variable is picked up by the offload library
+  /// to setup the device appropriately before kernel launch. If the execution
+  /// mode is 'generic', the runtime reserves one warp for the master,
+  /// otherwise, all warps participate in parallel work.
+  /// \param Name The symbol name associated with the global.
+  /// \param isSPMDMode is boolean to indicate if the kernel is an SPMD kernel
+  /// or not.
+  /// \param LLVMCompilerUsed List of global values which are required to be
+  /// present in the object file.
+  void
+  setPropertyExecutionMode(StringRef Name, bool isSPMDMode,
+   std::vector LLVMCompilerUsed);
+
   /// Create the global variable holding the offload mappings information.
   GlobalVariable *createOffloadMaptypes(SmallVectorImpl &Mappings,
 std::string VarName);
Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -1005,6 +1005,10 @@
 return EmittedGlobalBlocks.lookup(BE);
   }
 
+  std::vector getLLVMCompilerUsed() {
+return static_cast &>(LLVMCompilerUsed);
+  }
+
   /// Notes that BE's global block is available via Addr. Asserts that BE
   /// isn't already emitted.
   void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
Index: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -833,24 +833,6 @@
   IsInTTDRegion = false;
 }
 
-// Create a unique global variable to indicate the execution mode of this target
-// region. The execution mode is either 'generic', or 'spmd' depending on the
-// target directive. This variable is picked up by the offload library to setup
-// the device appropriately before kernel launch. If the execution mode is
-// 'generic', the runtime reserves one warp for the master, otherwise, all
-// warps participate in parallel work.
-static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
- bool Mode) {
-  auto *GVMode = new llvm::GlobalVariable(
-  CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
-  llvm::GlobalValue::WeakAnyLinkage,
-  llvm::ConstantInt::get(CGM.Int8Ty, Mode ? OMP_TGT_EXEC_MODE_SPMD
-  : OMP_TGT_EXEC_MODE_GENERIC),
-  Twine(Name, "_exec_mode"));
-  GVMode->setVisibility(llvm::GlobalVariable::ProtectedVisibility);
-  CGM.addCompilerUsedGlobal(GVMode);
-}
-
 void CGOpenMPRuntimeGPU::emitTargetOutlinedFunction(
 const OMPExecutableDirective &D, StringRef ParentName,
 llvm

[PATCH] D155794: [OpenMP][OpenMPIRBuilder] Migrate setPropertyExecutionMode() from Clang to OpenMPIRBuilder.

2023-07-21 Thread Raghu via Phabricator via cfe-commits
raghavendhra updated this revision to Diff 542787.
raghavendhra added a comment.

Rebased patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155794

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/CodeGen/CodeGenModule.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4900,6 +4900,22 @@
   emitBlock(ContBlock, CurFn, /*IsFinished=*/true);
 }
 
+void OpenMPIRBuilder::setPropertyExecutionMode(
+StringRef Name, bool isSPMDMode,
+std::vector LLVMCompilerUsed) {
+  auto *GVMode = new llvm::GlobalVariable(
+  M, llvm::Type::getInt8Ty(M.getContext()), /*isConstant=*/true,
+  llvm::GlobalValue::WeakAnyLinkage,
+  llvm::ConstantInt::get(llvm::Type::getInt8Ty(M.getContext()),
+ isSPMDMode ? OMP_TGT_EXEC_MODE_SPMD
+: OMP_TGT_EXEC_MODE_GENERIC),
+  Twine(Name, "_exec_mode"));
+  GVMode->setVisibility(llvm::GlobalVariable::ProtectedVisibility);
+  assert(!GVMode->isDeclaration() &&
+ "Only globals with definition can force usage.");
+  LLVMCompilerUsed.emplace_back(GVMode);
+}
+
 bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(
 const LocationDescription &Loc, llvm::AtomicOrdering AO, AtomicKind AK) {
   assert(!(AO == AtomicOrdering::NotAtomic ||
Index: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
===
--- llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -1493,6 +1493,21 @@
   void emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen,
 BodyGenCallbackTy ElseGen, InsertPointTy AllocaIP = {});
 
+  /// Create a unique global variable to indicate the execution mode of this
+  /// target region. The execution mode is either 'generic', or 'spmd' depending
+  /// on the target directive. This variable is picked up by the offload library
+  /// to setup the device appropriately before kernel launch. If the execution
+  /// mode is 'generic', the runtime reserves one warp for the master,
+  /// otherwise, all warps participate in parallel work.
+  /// \param Name The symbol name associated with the global.
+  /// \param isSPMDMode is boolean to indicate if the kernel is an SPMD kernel
+  /// or not.
+  /// \param LLVMCompilerUsed List of global values which are required to be
+  /// present in the object file.
+  void
+  setPropertyExecutionMode(StringRef Name, bool isSPMDMode,
+   std::vector LLVMCompilerUsed);
+
   /// Create the global variable holding the offload mappings information.
   GlobalVariable *createOffloadMaptypes(SmallVectorImpl &Mappings,
 std::string VarName);
Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -1005,6 +1005,10 @@
 return EmittedGlobalBlocks.lookup(BE);
   }
 
+  std::vector getLLVMCompilerUsed() {
+return static_cast &>(LLVMCompilerUsed);
+  }
+
   /// Notes that BE's global block is available via Addr. Asserts that BE
   /// isn't already emitted.
   void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
Index: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -833,24 +833,6 @@
   IsInTTDRegion = false;
 }
 
-// Create a unique global variable to indicate the execution mode of this target
-// region. The execution mode is either 'generic', or 'spmd' depending on the
-// target directive. This variable is picked up by the offload library to setup
-// the device appropriately before kernel launch. If the execution mode is
-// 'generic', the runtime reserves one warp for the master, otherwise, all
-// warps participate in parallel work.
-static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
- bool Mode) {
-  auto *GVMode = new llvm::GlobalVariable(
-  CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
-  llvm::GlobalValue::WeakAnyLinkage,
-  llvm::ConstantInt::get(CGM.Int8Ty, Mode ? OMP_TGT_EXEC_MODE_SPMD
-  : OMP_TGT_EXEC_MODE_GENERIC),
-  Twine(Name, "_exec_mode"));
-  GVMode->setVisibility(llvm::GlobalVariable::ProtectedVisibility);
-  CGM.addCompilerUsedGlobal(GVMode);
-}
-
 void CGOpenMPRuntimeGPU::emitTargetOutlinedFunction(
 const OMPExecutableDirective &D, StringRef ParentName,
 llvm::Function *

[PATCH] D155381: [clangd] Allow indexing of __reserved_names outside system headers

2023-07-21 Thread Nathan Ridge via Phabricator via cfe-commits
nridge accepted this revision.
nridge added a comment.
This revision is now accepted and ready to land.

Thanks! I agree that this no-configuration approach is nicer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155381

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


[PATCH] D155921: [clang][dataflow] Reverse course on `getValue()` deprecation.

2023-07-21 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

In the value categories RFC , I proposed
that the end state of the migration should be that `getValue()` should only be
legal to call on prvalues.

As a stepping stone, to allow migrating off existing calls to `getValue()`, I
proposed introducing `getValueStrict()`, which would already have the new
semantics.

However, I've now reconsidered this. Any expression, whether prvalue or glvalue,
has a value, so really there isn't any reason to forbid calling `getValue()`
on glvalues. I'm therefore removing the deprecation from `getValue()` and
transitioning existing `getValueStrict()` calls back to `getValue()`.

The other "strict" accessors are a different case. `setValueStrict()` should
only be called on prvalues because glvalues need to have a storage location
associated with them; it doesn't make sense to only set a value for them. And,
of course, `getStorageLocationStrict()` and `setStorageLocationStrict()` should
obviously only be called on glvalues because prvalues don't have storage
locations.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155921

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp
  clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -390,7 +390,7 @@
 if (const auto *E = selectFirst(
 "call", match(cxxConstructExpr(HasSpecialBoolType).bind("call"), *S,
   getASTContext( {
-  cast(Env.getValueStrict(*E))
+  cast(Env.getValue(*E))
   ->setProperty("is_set", Env.getBoolLiteralValue(false));
 } else if (const auto *E = selectFirst(
"call", match(cxxMemberCallExpr(callee(cxxMethodDecl(ofClass(
@@ -547,7 +547,7 @@
 *S, getASTContext());
 if (const auto *E = selectFirst(
 "construct", Matches)) {
-  cast(Env.getValueStrict(*E))
+  cast(Env.getValue(*E))
   ->setProperty("has_value", Env.getBoolLiteralValue(false));
 } else if (const auto *E =
selectFirst("operator", Matches)) {
Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -5491,7 +5491,7 @@
   ASTCtx));
 
 ASSERT_THAT(ImplicitCast, NotNull());
-EXPECT_THAT(Env.getValueStrict(*ImplicitCast), IsNull());
+EXPECT_THAT(Env.getValue(*ImplicitCast), IsNull());
   });
 }
 
Index: clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
@@ -114,7 +114,7 @@
 return {nullptr, {}, {}};
 
   // Value of the unary op.
-  auto *UnaryOpValue = State.Env.getValueStrict(*UO);
+  auto *UnaryOpValue = State.Env.getValue(*UO);
   if (!UnaryOpValue) {
 UnaryOpValue = &State.Env.makeAtomicBoolValue();
 State.Env.setValueStrict(*UO, *UnaryOpValue);
@@ -133,7 +133,7 @@
 LatticeTransferState &State) {
   auto &A = State.Env.arena();
   const Formula *Comp;
-  if (BoolValue *V = cast_or_null(State.Env.getValueStrict(*BO))) {
+  if (BoolValue *V = cast_or_null(State.Env.getValue(*BO))) {
 Comp = &V->formula();
   } else {
 Comp = &A.makeAtomRef(A.makeAtom());
@@ -143,8 +143,8 @@
   // FIXME Use this as well:
   // auto *NegatedComp = &State.Env.makeNot(*Comp);
 
-  auto *LHS = State.Env.getValueStrict(*BO->getLHS());
-  auto *RHS = State.Env.getValueStrict(*BO->getRHS());
+  auto *LHS = State.Env.getValue(*BO->getLHS());
+  auto *RHS = State.Env.getValue(*BO->getRHS());
 
   if (!LHS || !RHS)
 return;
@@ -271,7 +271,7 @@
   Env.setValue(*Loc, *Val);
 }
   } else {
-Val = Env.getValueStrict(*E);
+Val = Env.getValue(*E);
 if (!Val) {
   Val = Env.createValue(E->getType());
   Env.setValueStrict(*E, *Val);

[PATCH] D155922: [clang][dataflow] Eliminate `ReferenceValue`.

2023-07-21 Thread Martin Böhme via Phabricator via cfe-commits
mboehme created this revision.
Herald added subscribers: martong, xazax.hun.
Herald added a reviewer: NoQ.
Herald added a project: All.
mboehme requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

There are no remaining uses of this class in the framework.

This patch is part of the ongoing migration to strict handling of value
categories (see https://discourse.llvm.org/t/70086 for details).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155922

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
  clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
  clang/lib/Analysis/FlowSensitive/Value.cpp
  clang/unittests/Analysis/FlowSensitive/ValueTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/ValueTest.cpp
@@ -29,14 +29,6 @@
   EXPECT_FALSE(areEquivalentValues(V1, V2));
 }
 
-TEST(ValueTest, AliasedReferencesEquivalent) {
-  auto L = ScalarStorageLocation(QualType());
-  ReferenceValue V1(L);
-  ReferenceValue V2(L);
-  EXPECT_TRUE(areEquivalentValues(V1, V2));
-  EXPECT_TRUE(areEquivalentValues(V2, V1));
-}
-
 TEST(ValueTest, AliasedPointersEquivalent) {
   auto L = ScalarStorageLocation(QualType());
   PointerValue V1(L);
@@ -68,21 +60,12 @@
 TEST(ValueTest, DifferentKindsNotEquivalent) {
   Arena A;
   auto L = ScalarStorageLocation(QualType());
-  ReferenceValue V1(L);
+  PointerValue V1(L);
   TopBoolValue V2(A.makeAtomRef(Atom(0)));
   EXPECT_FALSE(areEquivalentValues(V1, V2));
   EXPECT_FALSE(areEquivalentValues(V2, V1));
 }
 
-TEST(ValueTest, NotAliasedReferencesNotEquivalent) {
-  auto L1 = ScalarStorageLocation(QualType());
-  ReferenceValue V1(L1);
-  auto L2 = ScalarStorageLocation(QualType());
-  ReferenceValue V2(L2);
-  EXPECT_FALSE(areEquivalentValues(V1, V2));
-  EXPECT_FALSE(areEquivalentValues(V2, V1));
-}
-
 TEST(ValueTest, NotAliasedPointersNotEquivalent) {
   auto L1 = ScalarStorageLocation(QualType());
   PointerValue V1(L1);
Index: clang/lib/Analysis/FlowSensitive/Value.cpp
===
--- clang/lib/Analysis/FlowSensitive/Value.cpp
+++ clang/lib/Analysis/FlowSensitive/Value.cpp
@@ -19,10 +19,6 @@
 
 static bool areEquivalentIndirectionValues(const Value &Val1,
const Value &Val2) {
-  if (auto *IndVal1 = dyn_cast(&Val1)) {
-auto *IndVal2 = cast(&Val2);
-return &IndVal1->getReferentLoc() == &IndVal2->getReferentLoc();
-  }
   if (auto *IndVal1 = dyn_cast(&Val1)) {
 auto *IndVal2 = cast(&Val2);
 return &IndVal1->getPointeeLoc() == &IndVal2->getPointeeLoc();
@@ -38,10 +34,6 @@
 
 raw_ostream &operator<<(raw_ostream &OS, const Value &Val) {
   switch (Val.getKind()) {
-  case Value::Kind::Reference: {
-const auto *RV = cast(&Val);
-return OS << "Reference(" << &RV->getReferentLoc() << ")";
-  }
   case Value::Kind::Pointer: {
 const auto *PV = dyn_cast(&Val);
 return OS << "Pointer(" << &PV->getPointeeLoc() << ")";
Index: clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
===
--- clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
+++ clang/lib/Analysis/FlowSensitive/HTMLLogger.cpp
@@ -99,10 +99,6 @@
 case Value::Kind::AtomicBool:
 case Value::Kind::FormulaBool:
   break;
-case Value::Kind::Reference:
-  JOS.attributeObject(
-  "referent", [&] { dump(cast(V).getReferentLoc()); });
-  break;
 case Value::Kind::Pointer:
   JOS.attributeObject(
   "pointee", [&] { dump(cast(V).getPointeeLoc()); });
Index: clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
===
--- clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
+++ clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
@@ -26,8 +26,6 @@
   switch (Kind) {
   case Value::Kind::Integer:
 return "Integer";
-  case Value::Kind::Reference:
-return "Reference";
   case Value::Kind::Pointer:
 return "Pointer";
   case Value::Kind::Struct:
Index: clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
===
--- clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -68,7 +68,6 @@
   case ComparisonResult::Unknown:
 switch (Val1.getKind()) {
 case Value::Kind::Integer:
-case Value::Kind::Reference:
 case Value::Kind::Pointer:
 case Value::Kind::Struct:
   // FIXME: this choice intentionally introduces unsoundness to allow
@@ -140,11 +139,6 @@
 
   // FIXME: Consider 

[PATCH] D153946: [clangd] Add a flag to allow indexing of reserved identifiers

2023-07-21 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

Yeah, I'm happy to go with D155381  instead.

In D153946#4503585 , @sammccall wrote:

> (Stupid over-flexible config system is too slow... I've learned my lesson 
> from that one!)

The issues with the config system are not entirely obvious to me. If, by 
chance, you've written some sort of post-mortem / discussion of the 
shortcomings and how you might design a config system in the future, I'd be 
interested to read it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153946

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


[PATCH] D154471: [clang] Add serialization support for the DynamicAllocLValue variant of APValue::LValueBase::Ptr

2023-07-21 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 542793.
nridge added a comment.

Add testcase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154471

Files:
  clang/include/clang/AST/PropertiesBase.td
  clang/test/AST/dynamic-alloc-lvalue.cpp


Index: clang/test/AST/dynamic-alloc-lvalue.cpp
===
--- /dev/null
+++ clang/test/AST/dynamic-alloc-lvalue.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -emit-pch -o %t %s
+
+// Test that serialization/deserialization of a DynamicAllocLValue
+// variant of APValue does not crash.
+
+#ifndef HEADER
+#define HEADER
+
+struct A {  int *p; };
+const A &w = A{ new int(10) };
+
+#endif
Index: clang/include/clang/AST/PropertiesBase.td
===
--- clang/include/clang/AST/PropertiesBase.td
+++ clang/include/clang/AST/PropertiesBase.td
@@ -450,10 +450,13 @@
 lvalueBase ? lvalueBase.dyn_cast() : nullptr;
 bool lvalueBaseIsExpr = (bool) expr;
 bool lvalueBaseIsTypeInfo = lvalueBase.is();
+bool lvalueBaseIsDynamicAlloc = lvalueBase.is();
 QualType elemTy;
 if (lvalueBase) {
   if (lvalueBaseIsTypeInfo) {
 elemTy = lvalueBase.getTypeInfoType();
+  } else if (lvalueBaseIsDynamicAlloc) {
+elemTy = lvalueBase.getDynamicAllocType();
   } else if (lvalueBaseIsExpr) {
 elemTy = expr->getType();
   } else {
@@ -473,6 +476,9 @@
   def : Property<"isTypeInfo", Bool> {
 let Read = [{ lvalueBaseIsTypeInfo }];
   }
+  def : Property<"isDynamicAlloc", Bool> {
+let Read = [{ lvalueBaseIsDynamicAlloc }];
+  }
   def : Property<"hasBase", Bool> {
 let Read = [{ static_cast(lvalueBase) }];
   }
@@ -485,9 +491,17 @@
   QualType(node.getLValueBase().get().getType(), 0)
 }];
   }
+  def : Property<"dynamicAlloc", UInt32> {
+let Conditional = [{ hasBase && isDynamicAlloc }];
+let Read = [{ node.getLValueBase().get().getIndex() }];
+  }
   def : Property<"type", QualType> {
-let Conditional = [{ hasBase && isTypeInfo }];
-let Read = [{ node.getLValueBase().getTypeInfoType() }];
+let Conditional = [{ hasBase && (isTypeInfo || isDynamicAlloc) }];
+let Read = [{ 
+  isTypeInfo
+? node.getLValueBase().getTypeInfoType()
+: node.getLValueBase().getDynamicAllocType()
+}];
   }
   def : Property<"callIndex", UInt32> {
 let Conditional = [{ hasBase && !isTypeInfo }];
@@ -502,7 +516,7 @@
 let Read = [{ const_cast(expr) }];
   }
   def : Property<"decl", DeclRef> {
-let Conditional = [{ hasBase && !isTypeInfo && !isExpr }];
+let Conditional = [{ hasBase && !isTypeInfo && !isDynamicAlloc && !isExpr 
}];
 let Read = [{ lvalueBase.get() }];
   }
   def : Property<"offsetQuantity", UInt32> {
@@ -521,6 +535,9 @@
   if (isTypeInfo) {
 base = APValue::LValueBase::getTypeInfo(
 TypeInfoLValue(typeInfo->getTypePtr()), *type);
+  } else if (isDynamicAlloc) {
+base = APValue::LValueBase::getDynamicAlloc(
+DynamicAllocLValue(*dynamicAlloc), *type);
   } else if (isExpr) {
 base = APValue::LValueBase(cast(*stmt),
*callIndex, *version);


Index: clang/test/AST/dynamic-alloc-lvalue.cpp
===
--- /dev/null
+++ clang/test/AST/dynamic-alloc-lvalue.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -emit-pch -o %t %s
+
+// Test that serialization/deserialization of a DynamicAllocLValue
+// variant of APValue does not crash.
+
+#ifndef HEADER
+#define HEADER
+
+struct A {  int *p; };
+const A &w = A{ new int(10) };
+
+#endif
Index: clang/include/clang/AST/PropertiesBase.td
===
--- clang/include/clang/AST/PropertiesBase.td
+++ clang/include/clang/AST/PropertiesBase.td
@@ -450,10 +450,13 @@
 lvalueBase ? lvalueBase.dyn_cast() : nullptr;
 bool lvalueBaseIsExpr = (bool) expr;
 bool lvalueBaseIsTypeInfo = lvalueBase.is();
+bool lvalueBaseIsDynamicAlloc = lvalueBase.is();
 QualType elemTy;
 if (lvalueBase) {
   if (lvalueBaseIsTypeInfo) {
 elemTy = lvalueBase.getTypeInfoType();
+  } else if (lvalueBaseIsDynamicAlloc) {
+elemTy = lvalueBase.getDynamicAllocType();
   } else if (lvalueBaseIsExpr) {
 elemTy = expr->getType();
   } else {
@@ -473,6 +476,9 @@
   def : Property<"isTypeInfo", Bool> {
 let Read = [{ lvalueBaseIsTypeInfo }];
   }
+  def : Property<"isDynamicAlloc", Bool> {
+let Read = [{ lvalueBaseIsDynamicAlloc }];
+  }
   def : Property<"hasBase", Bool> {
 let Read = [{ static_cast(lvalueBase) }];
   }
@@ -485,9 +491,17 @@
   QualType(node.getLValueBase().get().getType(), 0)
 }];
   }
+  def : Property<"dynamicAlloc", UInt32> {
+let Conditional = [{ hasBase && isDynamicAlloc }];
+let R

[clang] 086ee99 - Reapply [IR] Mark and constant expressions as undesirable

2023-07-21 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2023-07-21T10:10:50+02:00
New Revision: 086ee99564afbb11449c08ea2e094f7f49fadde5

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

LOG: Reapply [IR] Mark and constant expressions as undesirable

Reapply after fixing an issue in canonicalizeLogicFirst() exposed
by this change (218f97578b26f7a89f7f8ed0748c31ef0181f80a).

-

In preparation for removing support for and expressions, mark them
as undesirable. As such, we will no longer implicitly create such
expressions, but they still exist.

Added: 


Modified: 
clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
llvm/lib/IR/ConstantFold.cpp
llvm/lib/IR/Constants.cpp
llvm/test/CodeGen/Hexagon/atomic-opaque-basic.ll
llvm/test/Transforms/InstCombine/and-xor-or.ll
llvm/test/Transforms/InstCombine/bswap-fold.ll
llvm/test/Transforms/InstSimplify/ConstProp/constant-expr.ll
llvm/test/Transforms/InstSimplify/compare.ll

Removed: 




diff  --git a/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c 
b/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
index 551ccc4810bcd3..0e0a9b157464a6 100644
--- a/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
+++ b/clang/test/CodeGen/catch-nullptr-and-nonzero-offset.c
@@ -303,7 +303,8 @@ char *one_zero(void) {
 char *one_one_OK(void) {
   // CHECK:   define{{.*}} ptr @one_one_OK()
   // CHECK-NEXT:  [[ENTRY:.*]]:
-  // CHECK-SANITIZE-C-NEXT: br i1 and (i1 icmp ne (ptr inttoptr 
(i64 1 to ptr), ptr null), i1 icmp ne (i64 add (i64 sub (i64 ptrtoint (ptr 
getelementptr inbounds (i8, ptr inttoptr (i64 1 to ptr), i64 1) to i64), i64 
1), i64 1), i64 0)), label %[[CONT:.*]], label 
%[[HANDLER_POINTER_OVERFLOW:[^,]+]],{{.*}} !nosanitize
+  // CHECK-SANITIZE-C-NEXT: %[[AND:.*]] = and i1 icmp ne (ptr 
inttoptr (i64 1 to ptr), ptr null), icmp ne (i64 add (i64 sub (i64 ptrtoint 
(ptr getelementptr inbounds (i8, ptr inttoptr (i64 1 to ptr), i64 1) to i64), 
i64 1), i64 1), i64 0), !nosanitize
+  // CHECK-SANITIZE-C-NEXT: br i1 %[[AND]], label %[[CONT:.*]], 
label %[[HANDLER_POINTER_OVERFLOW:[^,]+]],{{.*}} !nosanitize
   // CHECK-SANITIZE-CPP-NEXT:   br i1 xor (i1 icmp eq (ptr inttoptr 
(i64 1 to ptr), ptr null), i1 icmp ne (i64 add (i64 sub (i64 ptrtoint (ptr 
getelementptr inbounds (i8, ptr inttoptr (i64 1 to ptr), i64 1) to i64), i64 
1), i64 1), i64 0)), label %[[CONT:.*]], label 
%[[HANDLER_POINTER_OVERFLOW:[^,]+]],{{.*}} !nosanitize
   // CHECK-SANITIZE:  [[HANDLER_POINTER_OVERFLOW]]:
   // CHECK-SANITIZE-NORECOVER-NEXT: call void 
@__ubsan_handle_pointer_overflow_abort(ptr @[[LINE_1100]], i64 1, i64 add (i64 
sub (i64 ptrtoint (ptr getelementptr inbounds (i8, ptr inttoptr (i64 1 to ptr), 
i64 1) to i64), i64 1), i64 1))
@@ -321,7 +322,8 @@ char *one_one_OK(void) {
 char *one_allones_BAD(void) {
   // CHECK:   define{{.*}} ptr @one_allones_BAD()
   // CHECK-NEXT:  [[ENTRY:.*]]:
-  // CHECK-SANITIZE-C-NEXT: br i1 and (i1 icmp ne (ptr inttoptr 
(i64 1 to ptr), ptr null), i1 icmp ne (i64 add (i64 sub (i64 ptrtoint (ptr 
getelementptr inbounds (i8, ptr inttoptr (i64 1 to ptr), i64 -1) to i64), i64 
1), i64 1), i64 0)), label %[[CONT:.*]], label 
%[[HANDLER_POINTER_OVERFLOW:[^,]+]],{{.*}} !nosanitize
+  // CHECK-SANITIZE-C-NEXT: %[[AND:.*]] = and i1 icmp ne (ptr 
inttoptr (i64 1 to ptr), ptr null), icmp ne (i64 add (i64 sub (i64 ptrtoint 
(ptr getelementptr inbounds (i8, ptr inttoptr (i64 1 to ptr), i64 -1) to i64), 
i64 1), i64 1), i64 0), !nosanitize
+  // CHECK-SANITIZE-C-NEXT: br i1 %[[AND]], label %[[CONT:.*]], 
label %[[HANDLER_POINTER_OVERFLOW:[^,]+]],{{.*}} !nosanitize
   // CHECK-SANITIZE-CPP-NEXT:   br i1 xor (i1 icmp eq (ptr inttoptr 
(i64 1 to ptr), ptr null), i1 icmp ne (i64 add (i64 sub (i64 ptrtoint (ptr 
getelementptr inbounds (i8, ptr inttoptr (i64 1 to ptr), i64 -1) to i64), i64 
1), i64 1), i64 0)), label %[[CONT:.*]], label 
%[[HANDLER_POINTER_OVERFLOW:[^,]+]],{{.*}} !nosanitize
   // CHECK-SANITIZE:  [[HANDLER_POINTER_OVERFLOW]]:
   // CHECK-SANITIZE-NORECOVER-NEXT: call void 
@__ubsan_handle_pointer_overflow_abort(ptr @[[LINE_1200]], i64 1, i64 add (i64 
sub (i64 ptrtoint (ptr getelementptr inbounds (i8, ptr inttoptr (i64 1 to ptr), 
i64 -1) to i64), i64 1), i64 1))
@@ -390,7 +392,8 @@ char *allones_zero_OK(void) {
 char *allones_one_BAD(void) {
   // CHECK: define{{.*}} ptr @allones_one_BAD()
   // CHECK-NEXT: [[ENTRY:.*]]:
-  // CHECK-SANITIZE-C-NEXT: br i1 and (i1 icmp ne (ptr inttoptr 
(i64 -1 to ptr), ptr null), i1 icmp ne (i64 add (i64 sub (i64 ptrtoint (ptr 
getelementptr inbounds (i8, ptr 

[PATCH] D155794: [OpenMP][OpenMPIRBuilder] Migrate setPropertyExecutionMode() from Clang to OpenMPIRBuilder.

2023-07-21 Thread Jan-Patrick Lehr via Phabricator via cfe-commits
jplehr added inline comments.



Comment at: clang/lib/CodeGen/CodeGenModule.h:1009
+  std::vector getLLVMCompilerUsed() {
+return static_cast &>(LLVMCompilerUsed);
+  }

I believe that this can be simplified to

```
std::vector &getLLVMCompilerUsed() {
  return LLVMCompilerUsed;
}
```



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:1509
+  setPropertyExecutionMode(StringRef Name, bool isSPMDMode,
+   std::vector LLVMCompilerUsed);
+

```, bool IsSPMDMode, std::vector 
&LLVMCompilerUsed);```



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:4905
+StringRef Name, bool isSPMDMode,
+std::vector LLVMCompilerUsed) {
+  auto *GVMode = new llvm::GlobalVariable(

```, std::vector &LLVMCompilerUsed) {



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:4914
+  GVMode->setVisibility(llvm::GlobalVariable::ProtectedVisibility);
+  assert(!GVMode->isDeclaration() &&
+ "Only globals with definition can force usage.");

Can this assertion ever be not be met? I'm just curious, given that you create 
that `GVMode` yourself.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155794

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


[PATCH] D154471: [clang] Add serialization support for the DynamicAllocLValue variant of APValue::LValueBase::Ptr

2023-07-21 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.

Thanks, looks good to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154471

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


[PATCH] D152589: [clang-tidy] Add readability test for not allowing relative includes

2023-07-21 Thread Erez Amihud via Phabricator via cfe-commits
ErezAmihud abandoned this revision.
ErezAmihud added a comment.

Closed, because I don't have time to work on it


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152589

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


[clang] f9caa12 - [Clang] Fix constraint checking of non-generic lambdas.

2023-07-21 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2023-07-21T10:59:36+02:00
New Revision: f9caa12328b265b77221fe7a310d4504673d814a

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

LOG: [Clang] Fix constraint checking of non-generic lambdas.

A lambda call operator can be a templated entity -
and therefore have constraints while not being a function template

   template void f() {
 []() requires false { }();
   }

In that case, we would check the constraints of the call operator
which is non-viable. However, we would find a viable candidate:
the conversion operator to function pointer, and use it to
perform a surrogate call.
These constraints were not checked because:
 * We never check the constraints of surrogate functions
 * The lambda conversion operator has non constraints.

>From the wording, it is not clear what the intent is but
it seems reasonable to expect the constraints of the lambda conversion
operator to be checked and it is consistent with GCC and MSVC.

This patch also improve the diagnostics for constraint failure
on surrogate calls.

Fixes #63181

Reviewed By: #clang-language-wg, aaron.ballman

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaLambda.cpp
clang/lib/Sema/SemaOverload.cpp
clang/test/SemaTemplate/concepts.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 05a7ec04d60c31..45381e7aad4ffc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -777,6 +777,8 @@ Bug Fixes to C++ Support
 - Fix location of default member initialization in parenthesized aggregate
   initialization.
   (`#63903 `_)
+- Fix constraint checking of non-generic lambdas.
+  (`#63181 `_)
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 569c6a054e7102..99917f190d82a1 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -4732,6 +4732,8 @@ def note_ovl_candidate_bad_target : Note<
 def note_ovl_candidate_constraints_not_satisfied : Note<
 "candidate %sub{select_ovl_candidate_kind}0,1,2 not viable: constraints "
 "not satisfied">;
+def note_ovl_surrogate_constraints_not_satisfied : Note<
+"conversion candidate %0 not viable: constraints not satisfied">;
 def note_implicit_member_target_infer_collision : Note<
 "implicit %sub{select_special_member_kind}0 inferred target collision: 
call to both "
 "%select{__device__|__global__|__host__|__host__ __device__}1 and "

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index f562e85009282a..f24b549dd2ef7a 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -679,6 +679,15 @@ bool Sema::CheckFunctionConstraints(const FunctionDecl *FD,
 return false;
   }
 
+  // A lambda conversion operator has the same constraints as the call operator
+  // and constraints checking relies on whether we are in a lambda call 
operator
+  // (and may refer to its parameters), so check the call operator instead.
+  if (const auto *MD = dyn_cast(FD);
+  MD && isLambdaConversionOperator(const_cast(MD)))
+return CheckFunctionConstraints(MD->getParent()->getLambdaCallOperator(),
+Satisfaction, UsageLoc,
+ForOverloadResolution);
+
   DeclContext *CtxToSave = const_cast(FD);
 
   while (isLambdaCallOperator(CtxToSave) || FD->isTransparentContext()) {

diff  --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp
index 339d16b080ee22..06fc53591a7643 100644
--- a/clang/lib/Sema/SemaLambda.cpp
+++ b/clang/lib/Sema/SemaLambda.cpp
@@ -1633,6 +1633,11 @@ static void addFunctionPointerConversion(Sema &S, 
SourceRange IntroducerRange,
   Conversion->setAccess(AS_public);
   Conversion->setImplicit(true);
 
+  // A non-generic lambda may still be a templated entity. We need to preserve
+  // constraints when converting the lambda to a function pointer. See GH63181.
+  if (Expr *Requires = CallOperator->getTrailingRequiresClause())
+Conversion->setTrailingRequiresClause(Requires);
+
   if (Class->isGenericLambda()) {
 // Create a template version of the conversion operator, using the template
 // parameter list of the function call operator.

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index c70d37de0a0130..42a367dca531d5 100644
--- a/clang

[PATCH] D154368: [Clang] Fix constraint checking of non-generic lambdas.

2023-07-21 Thread Corentin Jabot via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf9caa12328b2: [Clang] Fix constraint checking of non-generic 
lambdas. (authored by cor3ntin).

Changed prior to commit:
  https://reviews.llvm.org/D154368?vs=541858&id=542806#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154368

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaLambda.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/SemaTemplate/concepts.cpp

Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -410,8 +410,8 @@
 
 template 
 void SingleDepthReferencesTopLambda(U &&u) {
-  []()
-requires IsInt
+  []() // #SDRTL_OP
+requires IsInt // #SDRTL_REQ
   {}();
 }
 
@@ -434,8 +434,8 @@
 
 template 
 void DoubleDepthReferencesTopLambda(U &&u) {
-  []() { []()
-   requires IsInt
+  []() { []() // #DDRTL_OP
+   requires IsInt // #DDRTL_REQ
  {}(); }();
 }
 
@@ -459,10 +459,11 @@
 
 template 
 void DoubleDepthReferencesAllLambda(U &&u) {
-  [](U &&u2) {
-[](U && u3)
-  requires IsInt &&
-   IsInt && IsInt
+  [](U &&u2) { // #DDRAL_OP1
+[](U && u3) // #DDRAL_OP2
+  requires IsInt // #DDRAL_REQ
+&& IsInt
+&& IsInt
 {}(u2);
   }(u);
 }
@@ -484,8 +485,8 @@
 template 
 void ChecksLocalVar(T x) {
   T Local;
-  []()
-requires(IsInt)
+  []() // #CLV_OP
+requires(IsInt) // #CLV_REQ
   {}();
 }
 
@@ -527,8 +528,12 @@
   SingleDepthReferencesTopNotCalled(will_fail);
   SingleDepthReferencesTopCalled(v); // #SDRTC
   SingleDepthReferencesTopLambda(v);
-  // FIXME: This should error on constraint failure! (Lambda!)
   SingleDepthReferencesTopLambda(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-error@#SDRTL_OP{{no matching function for call to object of type}}
+  // expected-note@#SDRTL_OP{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#SDRTL_REQ{{because 'IsInt' evaluated to false}}
+
   DoubleDepthReferencesTop(v);
   DoubleDepthReferencesTop(will_fail);
   // expected-error@#DDRT_CALL{{no matching function for call to object of type 'lc2'}}
@@ -538,8 +543,12 @@
   // expected-note@#DDRT_REQ{{'IsInt' evaluated to false}}
 
   DoubleDepthReferencesTopLambda(v);
-  // FIXME: This should error on constraint failure! (Lambda!)
   DoubleDepthReferencesTopLambda(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-error@#DDRTL_OP{{no matching function for call to object of type}}
+  // expected-note@#DDRTL_OP{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#DDRTL_OP{{while substituting into a lambda expression here}}
+  // expected-note@#DDRTL_REQ{{because 'IsInt' evaluated to false}}
   DoubleDepthReferencesAll(v);
   DoubleDepthReferencesAll(will_fail);
   // expected-error@#DDRA_CALL{{no matching function for call to object of type 'lc2'}}
@@ -549,8 +558,12 @@
   // expected-note@#DDRA_REQ{{'IsInt' evaluated to false}}
 
   DoubleDepthReferencesAllLambda(v);
-  // FIXME: This should error on constraint failure! (Lambda!)
   DoubleDepthReferencesAllLambda(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-note@#DDRAL_OP1{{while substituting into a lambda expression here}}
+  // expected-error@#DDRAL_OP2{{no matching function for call to object of type}}
+  // expected-note@#DDRAL_OP2{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#DDRAL_REQ{{because 'IsInt' evaluated to false}}
 
   CausesFriendConstraint CFC;
   FriendFunc(CFC, 1);
@@ -563,8 +576,13 @@
   // ChecksCapture(v);
 
   ChecksLocalVar(v);
-  // FIXME: This should error on constraint failure! (Lambda!)
   ChecksLocalVar(will_fail);
+  // expected-note@-1{{in instantiation of function template specialization}}
+  // expected-error@#CLV_OP{{no matching function for call to object of type}}
+  // expected-note@#CLV_OP{{candidate function not viable: constraints not satisfied}}
+  // expected-note@#CLV_REQ{{because 'IsInt' evaluated to false}}
+
+
 
   LocalStructMemberVar(v);
   LocalStructMemberVar(will_fail);
@@ -701,6 +719,18 @@
 } // namespace SelfFriend
 
 
+namespace Surrogates {
+int f1(int);
+template 
+struct A {
+using F = int(int);
+operator F*() requires N { return f1; } // expected-note{{conversion candidate 'operator int (*)(int)' not viable: constraints not satisfied}}
+};
+int i = A{}(0);
+int j = A{}(0); // expected-error{{no matching function for call to object of type 'A'}}
+}
+
+
 namespace ConstrainedMemberVarTemplate {
 template  struct Container {
   static co

[PATCH] D146242: [ARM] Fixing ABI mismatch for packed structs passed as function arguments

2023-07-21 Thread Jirui Wu via Phabricator via cfe-commits
JiruiWu added inline comments.



Comment at: clang/test/CodeGen/aarch64-ABI-align-packed-assembly.c:100
   struct packed_struct on_callee_stack;
   on_callee_stack = va_arg(vl, struct packed_struct);
 }

chill wrote:
> Can we add some `CHECK:` lines here and to other variadic functions as well 
> (I recognize it might not be straightforward)?
I compared the assembly output before and after applying my patch, there is no 
change in this part and thus I think there is no need for additional `CHECK:` 
lines.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146242

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


[PATCH] D146242: [ARM] Fixing ABI mismatch for packed structs passed as function arguments

2023-07-21 Thread Jirui Wu via Phabricator via cfe-commits
JiruiWu added a comment.

Ping: @rjmccall


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146242

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


[PATCH] D154696: [Clang] Diagnose jumps into statement expressions

2023-07-21 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 542813.
cor3ntin added a comment.

Rebase + add test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154696

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/JumpDiagnostics.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
  clang/test/Sema/asm-goto.cpp
  clang/test/Sema/scope-check.c
  clang/test/SemaCXX/constant-expression-cxx14.cpp
  clang/test/SemaObjC/scope-check.m

Index: clang/test/SemaObjC/scope-check.m
===
--- clang/test/SemaObjC/scope-check.m
+++ clang/test/SemaObjC/scope-check.m
@@ -15,7 +15,7 @@
   } @finally {// expected-note {{jump bypasses initialization of @finally block}}
 L3: ;
   }
-  
+
   @try {
 goto L4; // expected-error{{cannot jump}}
 goto L5; // expected-error{{cannot jump}}
@@ -27,8 +27,8 @@
   } @finally { // expected-note {{jump bypasses initialization of @finally block}}
   L4: ;
   }
- 
-  
+
+
   @try { // expected-note 2 {{jump bypasses initialization of @try block}}
   L7: ;
   } @catch (C *c) {
@@ -36,21 +36,18 @@
   } @finally {
 goto L7; // expected-error{{cannot jump}}
   }
-  
+
   goto L8;  // expected-error{{cannot jump}}
-  @try { 
+  @try {
   } @catch (A *c) {
   } @catch (B *c) {
   } @catch (C *c) { // expected-note {{jump bypasses initialization of @catch block}}
   L8: ;
   }
-  
-  // rdar://6810106
   id X;
   goto L9;// expected-error{{cannot jump}}
-  goto L10;   // ok
-  @synchronized// expected-note {{jump bypasses initialization of @synchronized block}}
-  ( ({ L10: ; X; })) {
+  @synchronized (X)  // expected-note {{jump bypasses initialization of @synchronized block}}
+  {
   L9:
 ;
   }
@@ -90,7 +87,7 @@
 goto L0; // expected-error {{cannot jump}}
 typedef int A[n];  // expected-note {{jump bypasses initialization of VLA typedef}}
   L0:
-
+
 goto L1;  // expected-error {{cannot jump}}
 A b, c[10];// expected-note 2 {{jump bypasses initialization of variable length array}}
   L1:
Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -831,8 +831,9 @@
 case 0:
   return 0;
 
-  ({
-case 1: // expected-note {{not supported}}
+  ({  // expected-note {{jump enters a statement expression}}
+case 1:// expected-error {{cannot jump from switch statement to this case label}} \
+   // expected-note  {{not supported}}
   return 1;
   });
 }
Index: clang/test/Sema/scope-check.c
===
--- clang/test/Sema/scope-check.c
+++ clang/test/Sema/scope-check.c
@@ -65,7 +65,8 @@
 
   // Statement expressions.
   goto L3;   // expected-error {{cannot jump from this goto statement to its label}}
-  int Y = ({  int a[x];   // expected-note {{jump bypasses initialization of variable length array}}  
+  int Y = ({  int a[x];   // expected-note {{jump bypasses initialization of variable length array}} \
+  // expected-note {{jump enters a statement expression}}
L3: 4; });
   
   goto L4; // expected-error {{cannot jump from this goto statement to its label}}
@@ -107,25 +108,25 @@
4; })];
   L10:; // bad
   }
-  
+
   {
 // FIXME: Crashes goto checker.
 //goto L11;// ok
 //int A[({   L11: 4; })];
   }
-  
+
   {
 goto L12;
-
+
 int y = 4;   // fixme-warn: skips initializer.
   L12:
 ;
   }
-  
+
   // Statement expressions 2.
   goto L1; // expected-error {{cannot jump from this goto statement to its label}}
-  return x == ({
- int a[x];   // expected-note {{jump bypasses initialization of variable length array}}  
+  return x == ({ // expected-note {{jump enters a statement expression}}
+ int a[x];   // expected-note {{jump bypasses initialization of variable length array}}
L1:
  42; });
 }
@@ -232,3 +233,27 @@
 
 // rdar://9024687
 int test16(int [sizeof &&z]); // expected-error {{use of address-of-label extension outside of a function body}}
+
+void GH63682() {
+  {
+goto L; // expected-error {{cannot jump from this goto statement to its label}}
+(void)sizeof (int){({ L:; 1; })}; // expected-note {{jump enters a statement expression}}
+  }
+  {
+goto M; // expected-error {{cannot jump from this goto statement to its label}}
+(void)({ M:; 1; }); // expected-note {{jump enters a statement expression}}
+  }
+  {
+(void)({ goto N; 1; });  // ok
+N: ;
+  }
+  {
+(void)sizeof (int){({ goto O; 1; })}; // ok (not evaluated)
+O: ;
+  }
+  {
+(void)sizeof(({goto P;}

[PATCH] D155321: [clang][Analysis] ExprMutationAnalyzer: break infinite recursion on recursive function call

2023-07-21 Thread Ding Fei via Phabricator via cfe-commits
danix800 updated this revision to Diff 542824.
danix800 added a comment.

Apply git-clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155321

Files:
  
clang-tools-extra/test/clang-tidy/checkers/readability/use-anyofallof-nocrash.cpp
  clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
  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
@@ -1309,6 +1309,30 @@
   EXPECT_FALSE(isMutated(Results, AST.get()));
 }
 
+TEST(ExprMutationAnalyzerTest, RangeForNonArrayByConstRefNoCrash) {
+  const auto AST = buildASTFromCode(R"(
+struct V {
+  V* begin() const;
+  V* end() const;
+};
+void f(V &elem) {
+  auto rec = [](const auto& e, auto&& self) -> bool {
+for (auto& child : e) {
+  if (!self(child, self)) {
+return false;
+  }
+}
+return true;
+  };
+
+  rec(elem, rec);
+}
+  )");
+  const auto Results =
+  match(withEnclosingCompound(declRefTo("elem")), AST->getASTContext());
+  EXPECT_FALSE(isMutated(Results, AST.get()));
+}
+
 // section: unevaluated expressions
 
 TEST(ExprMutationAnalyzerTest, UnevaluatedExpressions) {
Index: clang/lib/Analysis/ExprMutationAnalyzer.cpp
===
--- clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -568,6 +568,11 @@
 if (!Func->getBody() || !Func->getPrimaryTemplate())
   return Exp;
 
+if (DeclAnalyzed->contains(Func)) {
+  return nullptr;
+}
+DeclAnalyzed->insert(Func);
+
 const auto *Parm = Nodes.getNodeAs("parm");
 const ArrayRef AllParams =
 Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
@@ -586,7 +591,8 @@
 std::unique_ptr &Analyzer =
 FuncParmAnalyzer[Func];
 if (!Analyzer)
-  Analyzer.reset(new FunctionParmMutationAnalyzer(*Func, Context));
+  Analyzer.reset(
+  new FunctionParmMutationAnalyzer(*Func, Context, DeclAnalyzed));
 if (Analyzer->findMutation(Parm))
   return Exp;
 continue;
@@ -599,8 +605,8 @@
 }
 
 FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
-const FunctionDecl &Func, ASTContext &Context)
-: BodyAnalyzer(*Func.getBody(), Context) {
+const FunctionDecl &Func, ASTContext &Context, DeclSet *DeclAnalyzed)
+: BodyAnalyzer(*Func.getBody(), Context, DeclAnalyzed) {
   if (const auto *Ctor = dyn_cast(&Func)) {
 // CXXCtorInitializer might also mutate Param but they're not part of
 // function body, check them eagerly here since they're typically trivial.
Index: clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
===
--- clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
+++ clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
@@ -18,12 +18,20 @@
 
 class FunctionParmMutationAnalyzer;
 
+using DeclSet = llvm::DenseSet;
+
 /// Analyzes whether any mutative operations are applied to an expression within
 /// a given statement.
 class ExprMutationAnalyzer {
 public:
-  ExprMutationAnalyzer(const Stmt &Stm, ASTContext &Context)
-  : Stm(Stm), Context(Context) {}
+  ExprMutationAnalyzer(const Stmt &Stm, ASTContext &Context,
+   DeclSet *DeclAnalyzed = nullptr)
+  : Stm(Stm), Context(Context), DeclAnalyzed(DeclAnalyzed) {
+if (nullptr == DeclAnalyzed) {
+  OwningDeclAnalyzed = std::make_unique();
+  this->DeclAnalyzed = OwningDeclAnalyzed.get();
+}
+  }
 
   bool isMutated(const Expr *Exp) { return findMutation(Exp) != nullptr; }
   bool isMutated(const Decl *Dec) { return findMutation(Dec) != nullptr; }
@@ -74,13 +82,16 @@
   FuncParmAnalyzer;
   ResultMap Results;
   ResultMap PointeeResults;
+  DeclSet *DeclAnalyzed;
+  std::unique_ptr OwningDeclAnalyzed;
 };
 
 // A convenient wrapper around ExprMutationAnalyzer for analyzing function
 // params.
 class FunctionParmMutationAnalyzer {
 public:
-  FunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context);
+  FunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context,
+   DeclSet *DeclAnalyzed = nullptr);
 
   bool isMutated(const ParmVarDecl *Parm) {
 return findMutation(Parm) != nullptr;
Index: clang-tools-extra/test/clang-tidy/checkers/readability/use-anyofallof-nocrash.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability/use-anyofallof-nocrash.cpp
@@ -0,0 +1,20 @@
+

[PATCH] D155452: [Flang] Add support for fsave-optimization-record

2023-07-21 Thread victorkingi via Phabricator via cfe-commits
victorkingi updated this revision to Diff 542838.
victorkingi added a comment.

No changes rebasing


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155452

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CodeGenOptions.h
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/FrontendActions.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/frontend-forwarding.f90
  flang/test/Driver/fsave-optimization-record.f90

Index: flang/test/Driver/fsave-optimization-record.f90
===
--- /dev/null
+++ flang/test/Driver/fsave-optimization-record.f90
@@ -0,0 +1,42 @@
+! Tests for the '-f[no-]save-optimization-record[=]' flag.
+
+! Test -foptimization-record-file produces YAML file with given content
+! RUN: rm -f %t.opt.yaml
+! RUN: %flang -foptimization-record-file=%t.opt.yaml -c %s
+! RUN: cat %t.opt.yaml | FileCheck %s
+
+! Test -fsave-optimization-record produces YAML file with given content
+! RUN: rm -f %t.opt.yaml
+! RUN: %flang -fsave-optimization-record -c -o %t.o %s
+! RUN: cat %t.opt.yaml | FileCheck %s
+
+! RUN: rm -f %t.opt.yaml
+! RUN: %flang -fsave-optimization-record -S -o %t.s %s
+! RUN: cat %t.opt.yaml | FileCheck %s
+
+! Produces an empty file
+! RUN: rm -f %t.opt.yaml
+! RUN: %flang -fsave-optimization-record -S -emit-llvm -o %t.ll %s
+! RUN: cat %t.opt.yaml
+
+!Test unknown format produces error
+! RUN: not %flang -fsave-optimization-record=hello %s 2>&1 \
+! RUN:   | FileCheck --check-prefix=CHECK-FORMAT-ERROR %s
+
+! CHECK: --- !Analysis
+! CHECK: Pass:prologepilog
+! CHECK: Name:StackSize
+! CHECK: Function:_QQmain
+! CHECK: Pass:asm-printer
+! CHECK: Name:InstructionMix
+! CHECK: Name:InstructionCount
+
+! CHECK-FORMAT-ERROR: error: unknown remark serializer format: 'hello'
+
+program forttest
+implicit none
+integer :: n
+
+n = 1 * 1
+
+end program forttest
Index: flang/test/Driver/frontend-forwarding.f90
===
--- flang/test/Driver/frontend-forwarding.f90
+++ flang/test/Driver/frontend-forwarding.f90
@@ -15,6 +15,7 @@
 ! RUN: -fassociative-math \
 ! RUN: -freciprocal-math \
 ! RUN: -fpass-plugin=Bye%pluginext \
+! RUN: -fsave-optimization-record \
 ! RUN: -fversion-loops-for-stride \
 ! RUN: -flang-experimental-polymorphism \
 ! RUN: -mllvm -print-before-all \
@@ -22,6 +23,10 @@
 ! RUN: -P \
 ! RUN:   | FileCheck %s
 
+! RUN: %flang -### %s 2>&1 \
+! RUN: -foptimization-record-file=%t.opt.yaml \
+! RUN:   | FileCheck --check-prefix=YAML %s
+
 ! CHECK: "-P"
 ! CHECK: "-finput-charset=utf-8"
 ! CHECK: "-fdefault-double-8"
@@ -38,5 +43,10 @@
 ! CHECK: "-fpass-plugin=Bye
 ! CHECK: "-flang-experimental-polymorphism"
 ! CHECK: "-fversion-loops-for-stride"
+! CHECK: "-opt-record-file" "{{.+}}.opt.yaml"
+! CHECK: "-opt-record-format" "yaml"
 ! CHECK: "-mllvm" "-print-before-all"
 ! CHECK: "-save-temps=obj"
+
+! YAML: "-opt-record-file" "{{.+}}.opt.yaml"
+! YAML: "-opt-record-format" "yaml"
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -54,8 +54,16 @@
 ! HELP-NEXT: -fopenmp-version=
 ! HELP-NEXT:Set OpenMP version (e.g. 45 for OpenMP 4.5, 50 for OpenMP 5.0). Default value is 50 for Clang and 11 for Flang
 ! HELP-NEXT: -fopenmp   Parse OpenMP pragmas and generate parallel code.
+! HELP-NEXT: -foptimization-record-file=
+! HELP-NEXT:Specify the output name of the file containing the optimization remarks. Implies -fsave-optimization-record. On Darwin platforms, this cannot be used with multiple -arch  options.
+! HELP-NEXT: -foptimization-record-passes=
+! HELP-NEXT:Only include passes which match a specified regular expression in the generated optimization record (by default, include all passes)
 ! HELP-NEXT: -fpass-plugin= Load pass plugin from a dynamic shared object file (only with new pass manager).
 ! HELP-NEXT: -freciprocal-math  Allow division operations to be reassociated
+! HELP-NEXT: -fsave-optimization-record=
+! HELP-NEXT:Generate an optimization record file in a specific format
+! HELP-NEXT: -fsave-optimization-record
+! HELP-NEXT:Generate a YAML optimization record file
 ! HELP-NEXT: -fstack-arrays Attempt to allocate array temporaries on the stack, no matter their size
 ! HELP-NEXT: -fsyntax-only  Run the preprocessor, parser and semantic analysis stages
 ! HELP-NEXT: -funderscoring Appends one trailing underscore to external names
@@ -186,6 

[PATCH] D155396: [Sema][ObjC] Propagating value-dependent errors into BlockExpr

2023-07-21 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

thanks!




Comment at: clang/lib/Sema/SemaStmt.cpp:3736
+BlockDecl *BD = CurBlock->TheDecl;
+if (!BD->isInvalidDecl() && RetValExp && RetValExp->containsErrors())
+  BD->setInvalidDecl();

nit: the `isInvalidDecl` check is not need, we can inline the `RetValExpr` to 
the above if as well.

```
if (auto *CurBlock = dyn_cast(CurCap); CurBlock && 
CurCap->HasImplicitReturnType && RetValExp && RetValExp->containsErrors()) 
  CurBlock->TheDecl->setInvalidDecl();
```



Comment at: clang/test/SemaObjC/crash-on-val-dep-block-expr.m:1
+// RUN: %clang_cc1 -fblocks -fsyntax-only -verify %s
+// no crash

can you move these tests to `llvm-project/clang/test/AST/ast-dump-recovery.c`?


Repository:
  rZORG LLVM Github Zorg

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

https://reviews.llvm.org/D155396

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


[PATCH] D155457: [clang] Skip tautological comparison if the comparison involves the 'size_t' type

2023-07-21 Thread Shivam Gupta via Phabricator via cfe-commits
xgupta updated this revision to Diff 542846.
xgupta added a comment.

update test for Windows system


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155457

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/type-limit-compare.cpp


Index: clang/test/Sema/type-limit-compare.cpp
===
--- /dev/null
+++ clang/test/Sema/type-limit-compare.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 %s -fsyntax-only -Wtautological-type-limit-compare -verify
+
+// expected-no-diagnostics
+#if defined(_WIN32)
+typedef unsigned long long uint64_t;
+#else
+typedef unsigned long uint64_t;
+#endif
+
+namespace std {
+using size_t = decltype(sizeof(0));
+} // namespace std
+
+bool func(uint64_t Size) {
+  if (sizeof(std::size_t) < sizeof(uint64_t) &&
+ Size > (uint64_t)(__SIZE_MAX__))
+return false;
+  return true;
+}
+
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13804,6 +13804,13 @@
   if (InRange && IsEnumConstOrFromMacro(S, Constant))
 return false;
 
+  // Don't warn if the comparison involves the 'size_t' type.
+  QualType SizeT = S.Context.getSizeType();
+  if (S.Context.hasSameType(Constant->getType().getCanonicalType(), SizeT) &&
+  S.Context.hasSameType(Other->getType().getCanonicalType(), SizeT)) {
+return false;
+  }
+
   // A comparison of an unsigned bit-field against 0 is really a type problem,
   // even though at the type level the bit-field might promote to 'signed int'.
   if (Other->refersToBitField() && InRange && Value == 0 &&


Index: clang/test/Sema/type-limit-compare.cpp
===
--- /dev/null
+++ clang/test/Sema/type-limit-compare.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 %s -fsyntax-only -Wtautological-type-limit-compare -verify
+
+// expected-no-diagnostics
+#if defined(_WIN32)
+typedef unsigned long long uint64_t;
+#else
+typedef unsigned long uint64_t;
+#endif
+
+namespace std {
+using size_t = decltype(sizeof(0));
+} // namespace std
+
+bool func(uint64_t Size) {
+  if (sizeof(std::size_t) < sizeof(uint64_t) &&
+ Size > (uint64_t)(__SIZE_MAX__))
+return false;
+  return true;
+}
+
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -13804,6 +13804,13 @@
   if (InRange && IsEnumConstOrFromMacro(S, Constant))
 return false;
 
+  // Don't warn if the comparison involves the 'size_t' type.
+  QualType SizeT = S.Context.getSizeType();
+  if (S.Context.hasSameType(Constant->getType().getCanonicalType(), SizeT) &&
+  S.Context.hasSameType(Other->getType().getCanonicalType(), SizeT)) {
+return false;
+  }
+
   // A comparison of an unsigned bit-field against 0 is really a type problem,
   // even though at the type level the bit-field might promote to 'signed int'.
   if (Other->refersToBitField() && InRange && Value == 0 &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155935: [RISCV] Enable multiversion function

2023-07-21 Thread Piyou Chen via Phabricator via cfe-commits
BeMg created this revision.
Herald added subscribers: jobnoorman, luke, VincentWu, vkmr, frasercrmck, 
luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, 
PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, 
shiva0217, kito-cheng, niosHD, sabuasal, simoncook, johnrusso, rbar, asb, 
arichardson.
Herald added a project: All.
BeMg requested review of this revision.
Herald added subscribers: cfe-commits, wangpc, eopXD, MaskRay.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155935

Files:
  clang/include/clang/Basic/TargetInfo.h
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/RISCV/riscv-fmv.c

Index: clang/test/CodeGen/RISCV/riscv-fmv.c
===
--- /dev/null
+++ clang/test/CodeGen/RISCV/riscv-fmv.c
@@ -0,0 +1,98 @@
+// REQUIRES: riscv-registered-target
+// RUN: %clang_cc1 -triple riscv64 -target-feature +zifencei \
+// RUN:  -target-feature +m -target-feature +a   \
+// RUN:  -target-feature +f -target-feature +d   \
+// RUN:  -emit-llvm %s -o - | FileCheck %s   \
+// RUN:  --check-prefix=CHECK-IR
+
+__attribute__((target("arch=+v"))) void test1(void) {}
+__attribute__((target("arch=+v,+zbb"))) void test1(void) {}
+__attribute__((target("arch=+v,+zbb,+zihintntl0p2"))) void test1(void) {}
+__attribute__((target("arch=rv64gc"))) void test1(void) {}
+__attribute__((target("default"))) void test1(void) {}
+
+__attribute__((target("default"))) void test2(void) {}
+
+void test3() { test1(); test2(); }
+
+// CHECK-IR: @0 = private unnamed_addr constant [2 x i8] c"v\00", align 1
+// CHECK-IR: @1 = private unnamed_addr constant [6 x i8] c"v;zbb\00", align 1
+// CHECK-IR: @2 = private unnamed_addr constant [29 x i8] c"v;zbb;experimental-zihintntl\00", align 1
+// CHECK-IR: @3 = private unnamed_addr constant [25 x i8] c"m;a;f;d;c;zicsr;zifencei\00", align 1
+
+// CHECK-IR: @test1.ifunc = weak_odr ifunc void (), ptr @test1.resolver
+// CHECK-IR: @test2.ifunc = weak_odr ifunc void (), ptr @test2.resolver
+
+// CHECK-IR-LABEL: define dso_local void @test1.v
+// CHECK-IR-SAME: () #[[ATTR0:[0-9]+]] {
+// CHECK-IR-NEXT:  entry:
+// CHECK-IR-NEXT:ret void
+//
+//
+// CHECK-IR-LABEL: define dso_local void @test1.v_zbb
+// CHECK-IR-SAME: () #[[ATTR1:[0-9]+]] {
+// CHECK-IR-NEXT:  entry:
+// CHECK-IR-NEXT:ret void
+//
+//
+// CHECK-IR-LABEL: define dso_local void @test1.v_zbb_experimental-zihintntl
+// CHECK-IR-SAME: () #[[ATTR2:[0-9]+]] {
+// CHECK-IR-NEXT:  entry:
+// CHECK-IR-NEXT:ret void
+//
+//
+// CHECK-IR-LABEL: define dso_local void @test1.m_a_f_d_c_zicsr_zifencei
+// CHECK-IR-SAME: () #[[ATTR3:[0-9]+]] {
+// CHECK-IR-NEXT:  entry:
+// CHECK-IR-NEXT:ret void
+//
+//
+// CHECK-IR-LABEL: define dso_local void @test1
+// CHECK-IR-SAME: () #[[ATTR4:[0-9]+]] {
+// CHECK-IR-NEXT:  entry:
+// CHECK-IR-NEXT:ret void
+//
+//
+// CHECK-IR-LABEL: define dso_local void @test2
+// CHECK-IR-SAME: () #[[ATTR4]] {
+// CHECK-IR-NEXT:  entry:
+// CHECK-IR-NEXT:ret void
+//
+//
+// CHECK-IR-LABEL: define dso_local void @test3
+// CHECK-IR-SAME: () #[[ATTR4]] {
+// CHECK-IR-NEXT:  entry:
+// CHECK-IR-NEXT:call void @test1.ifunc()
+// CHECK-IR-NEXT:call void @test2.ifunc()
+// CHECK-IR-NEXT:ret void
+//
+//
+// CHECK-IR-LABEL: define weak_odr ptr @test1.resolver() comdat {
+// CHECK-IR-NEXT:  resolver_entry:
+// CHECK-IR-NEXT:[[TMP0:%.*]] = call i1 @__riscv_ifunc_select(ptr @[[GLOB0:[0-9]+]])
+// CHECK-IR-NEXT:br i1 [[TMP0]], label [[RESOLVER_RETURN:%.*]], label [[RESOLVER_ELSE:%.*]]
+// CHECK-IR:   resolver_return:
+// CHECK-IR-NEXT:ret ptr @test1.v
+// CHECK-IR:   resolver_else:
+// CHECK-IR-NEXT:[[TMP1:%.*]] = call i1 @__riscv_ifunc_select(ptr @[[GLOB1:[0-9]+]])
+// CHECK-IR-NEXT:br i1 [[TMP1]], label [[RESOLVER_RETURN1:%.*]], label [[RESOLVER_ELSE2:%.*]]
+// CHECK-IR:   resolver_return1:
+// CHECK-IR-NEXT:ret ptr @test1.v_zbb
+// CHECK-IR:   resolver_else2:
+// CHECK-IR-NEXT:[[TMP2:%.*]] = call i1 @__riscv_ifunc_select(ptr @[[GLOB2:[0-9]+]])
+// CHECK-IR-NEXT:br i1 [[TMP2]], label [[RESOLVER_RETURN3:%.*]], label [[RESOLVER_ELSE4:%.*]]
+// CHECK-IR:   resolver_return3:
+// CHECK-IR-NEXT:ret ptr @test1.v_zbb_experimental-zihintntl
+// CHECK-IR:   resolver_else4:
+// CHECK-IR-NEXT:[[TMP3:%.*]] = call i1 @__riscv_ifunc_select(ptr @[[GLOB3:[0-9]+]])
+// CHECK-IR-NEXT:br i1 [[TMP3]], label [[RESOLVER_RETURN5:%.*]], label [[RESOLVER_ELSE6:%.*]]
+// CHECK-IR:   resolver_return5:
+// CHECK-IR-NEXT:ret ptr @test1.m_a_f_d_c_zicsr_zifencei
+// CHECK-IR:   resolver_else6:
+// CHECK-IR-NEXT:ret ptr @test1
+//
+//
+// CHECK-IR-LABEL: define weak_odr ptr @test2.resolver() comdat {
+// CHECK-IR-NEXT:  resolver_entry:
+// CHECK-IR-NEXT:ret ptr @t

[clang] 33c2e4e - [Clang] Fix access to an unitinialized variable

2023-07-21 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2023-07-21T12:34:35+02:00
New Revision: 33c2e4ec7c3efb7d77df0d9f5c3f1c423aac6b0f

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

LOG: [Clang] Fix access to an unitinialized variable

This fixes the spurious test failure introduced in f9caa12328b2

Added: 


Modified: 
clang/lib/Sema/SemaOverload.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 42a367dca531d5..a3d9abb1537789 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -11658,7 +11658,8 @@ static void NoteSurrogateCandidate(Sema &S, 
OverloadCandidate *Cand) {
   if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
   if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
 
-  if (Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
+  if (!Cand->Viable &&
+  Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
 S.Diag(Cand->Surrogate->getLocation(),
diag::note_ovl_surrogate_constraints_not_satisfied)
 << Cand->Surrogate;



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


[PATCH] D155898: [clangd] Fix go-to-type target location

2023-07-21 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 accepted this revision.
usaxena95 added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/XRefs.cpp:347
+void enhanceLocatedSymbolsFromIndex(
+llvm::MutableArrayRef Result,
+const llvm::DenseMap &ResultIndex,

nit: ResultIndex looks like an implementation detail of this function and the 
callers do not need it. SymbolID is already present as LocatedSymbol::ID so we 
can compute this map in this function itself.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155898

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


[PATCH] D154696: [Clang] Diagnose jumps into statement expressions

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

LG!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154696

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


[PATCH] D151683: [clang] Enable C++11-style attributes in all language modes

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151683

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


[PATCH] D154688: [clang] Show verify prefix in error messages

2023-07-21 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Precommit CI found relevant failures that should be addressed.


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

https://reviews.llvm.org/D154688

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


[PATCH] D155290: [PGO] Use Unique Profile Files when New Processes are Forked

2023-07-21 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 added a comment.

Ping for review. We'd like to get this in to LLVM 17 if possible. Please let me 
know if there are comments/suggestions. Thanks so much!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155290

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


[PATCH] D133843: [clangd] Prefer definitions for gototype and implementation

2023-07-21 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet abandoned this revision.
kadircet added a comment.

abandoning in favor of D155898 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133843

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


[clang-tools-extra] 209694d - [clangd] Make the order of missing-include edits deterministic

2023-07-21 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-07-21T14:16:16+02:00
New Revision: 209694ded0e06edfed11d6e67b396112dae21629

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

LOG: [clangd] Make the order of missing-include edits deterministic

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

Added: 


Modified: 
clang-tools-extra/clangd/IncludeCleaner.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/IncludeCleaner.cpp 
b/clang-tools-extra/clangd/IncludeCleaner.cpp
index 2ecc15973337a7..9708c67ca2883c 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.cpp
+++ b/clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -38,7 +38,6 @@
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -47,6 +46,7 @@
 #include "llvm/Support/Regex.h"
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -256,7 +256,7 @@ addAllMissingIncludes(llvm::ArrayRef 
MissingIncludeDiags) {
   AddAllMissing.Message = "add all missing includes";
   // A map to deduplicate the edits with the same new text.
   // newText (#include "my_missing_header.h") -> TextEdit.
-  llvm::StringMap Edits;
+  std::map Edits;
   for (const auto &Diag : MissingIncludeDiags) {
 assert(Diag.Fixes.size() == 1 && "Expected exactly one fix.");
 for (const auto &Edit : Diag.Fixes.front().Edits) {
@@ -272,7 +272,7 @@ addAllMissingIncludes(llvm::ArrayRef 
MissingIncludeDiags) {
   unsigned I = 0;
   for (auto &It : Edits) {
 ChangeAnnotationIdentifier ID = AddAllMissingID + std::to_string(I++);
-AddAllMissing.Edits.push_back(std::move(It.getValue()));
+AddAllMissing.Edits.push_back(std::move(It.second));
 AddAllMissing.Edits.back().annotationId = ID;
 
 AddAllMissing.Annotations.push_back({ID, Annotation});



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


[PATCH] D155290: [PGO] Use Unique Profile Files when New Processes are Forked

2023-07-21 Thread wael yehia via Phabricator via cfe-commits
w2yehia added inline comments.



Comment at: clang/lib/Driver/ToolChains/AIX.cpp:440
+  if (NeedsProfileRT || needsGCovInstrumentation(Args))
+CmdArgs.push_back("-lpthreads");
+

The change in `compiler-rt/lib/profile/InstrProfilingFile.c` affects non-AIX 
platforms too, so won't they need `-lpthreads` too?




Comment at: clang/lib/Driver/ToolChains/AIX.cpp:440
+  if (NeedsProfileRT || needsGCovInstrumentation(Args))
+CmdArgs.push_back("-lpthreads");
+

w2yehia wrote:
> The change in `compiler-rt/lib/profile/InstrProfilingFile.c` affects non-AIX 
> platforms too, so won't they need `-lpthreads` too?
> 
In order to avoid adding -lpthreads, we can leave it to the user to decide 
whether to add or not (i.e. they would add -lpthreads to their application's 
link command if they want to).
And so to avoid a link error due to undefined symbol, we can define 
`pthread_atfork` as a weak empty stub in the compiler-rt.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155290

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


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

2023-07-21 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx added inline comments.



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:5542
+  if (!getLangOpts().HIPStdPar)
+ErrorUnsupported(E, "builtin function");
 

efriedma wrote:
> AlexVlx wrote:
> > efriedma wrote:
> > > This doesn't make sense; we can't just ignore bits of the source code.  I 
> > > guess this is related to "the decision on their validity is deferred", 
> > > but I don't see how you expect this to work.
> > This is one of the weirder parts, so let's consider the following example:
> > 
> > ```cpp
> > void foo() { __builtin_ia32_pause(); }
> > void bar() { __builtin_trap(); }
> > 
> > void baz(const vector& v) {
> > return for_each(par_unseq, cbegin(v), cend(v), [](auto&& x) { if (x == 
> > 42) bar(); });
> > }
> > ```
> > 
> > In the case above, what we'd offload to the accelerator, and ask the target 
> > BE to lower, is the implementation of `for_each`, and `bar`, because it is 
> > reachable from the latter. `foo` is not reachable by any execution path on 
> > the accelerator side, however it includes a builtin that is unsupported by 
> > the accelerator (unless said accelerator is x86, which is not impossible, 
> > but not something we're dealing with at the moment). If we were to actually 
> > error out early, in the FE, in these cases, there's almost no appeal to 
> > what is being proposed, because standard headers, as well as other 
> > libraries, are littered with various target specific builtins that are not 
> > going to be supported. This all builds on the core invariant of this model 
> > / extension / thingamabob, which is that the algorithms, and only the 
> > algorithms, are targets for offload. It thus follows that as long as code 
> > that is reachable from an algorithm's implementation is safe, all is fine, 
> > but we cannot know this in the FE / on an AST level, because we need the 
> > actual CFG. This part is handled in LLVM in the `SelectAcceleratorCodePass` 
> > that's in the last patch in this series.
> > 
> > Now, you will quite correctly observe that there's nothing preventing an 
> > user from calling `foo` in the callable they pass to an algorithm; they 
> > might read the docs / appreciate that this won't work, but even there they 
> > are not safe, because there via some opaque call chain they might end up 
> > touching some unsupported builtin. My intuition here, which is reflected 
> > above in letting builtins just flow through, is that such cases are better 
> > served with a compile time error, which is what will obtain once the target 
> > BE chokes trying to lower an unsupported builtin. It's not going to be a 
> > beautiful error, and we could probably prettify it somewhat if we were to 
> > check after we've done the accelerator code selection pass, but it will 
> > happen at compile time. Another solution would be to emit these as traps 
> > (poison + trap for value returning ones), but I am concerned that it would 
> > lead to really fascinating debug journeys.
> > 
> > Having said this, if there's a better way to deal with these scenarios, it 
> > would be rather nice. Similarly, if the above doesn't make sense, please 
> > let me know.
> > 
> Oh, I see; you "optimistically" compile everything assuming it might run on 
> the accelerator, then run LLVM IR optimizations, then determine late which 
> bits of code will actually run on the accelerator, which then prunes the code 
> which shouldn't run.
> 
> I'm not sure I really like this... would it be possible to infer which 
> functions need to be run on the accelerator based on the AST?  I mean, if 
> your API takes a lambda expression that runs on the accelerator, you can mark 
> the lambda's body as "must be emitted for GPU", then recursively mark all the 
> functions referred to by the lambda.
> 
> Emiting errors lazily from the backend means you get different diagnostics 
> depending on the optimization level.
> 
> If you do go with this codegen-based approach, it's not clear to me how you 
> detect that a forbidden builtin was called; if you skip the error handling, 
> you just get a literal "undef".
`I'm not sure I really like this...` - actually, I am not a big fan either, 
however I think it's about the best one can do, given the constraints (consume 
standard C++, no annotations on the user side etc.). Having tried a few times 
in the past (and at least once in a different compiler), I don't quite think 
this can be done on an AST level. It would add some fairly awkward checking 
during template instantiation (no way to know earlier that a `CallableFoo` was 
passed to an offloadable algorithm), and it's a bit unwieldy to basically 
compute the CFG on the AST and mark reachable Callees at that point. Ignoring 
those, the main reason for which we cannot do this is that the interface is not 
constrained to only take lambdas, but callables in general, and that includes 
pointers to function as well. We don't deal with those today, but plan to, and 
ther

[PATCH] D133843: [clangd] Prefer definitions for gototype and implementation

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

Yeah, having used this feature for a while, you're right about all of this of 
course, the current behavior is infuriating.
Sorry!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133843

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


[PATCH] D155890: [clang-tidy] Add folly::Optional to unchecked-optional-access

2023-07-21 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

In D155890#4521266 , @carlosgalvezp 
wrote:

> This should be a configuration option, we should not hardcore 
> project-specific things in the source code.

I agree, but we already are hardcoding specific types -- I think this is a 
separate (and valid) critique of the design. I'd propose filing an issue on the 
github tracker and we can follow up there.  I, for one, would love to review 
such a change but don't have the time to write it.




Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:844-846
+  .CaseOfCFGStmt(
+  isOptionalMemberCallWithName("hasValue"),
+  transferOptionalHasValueCall)

A few concerns:
1. This will allow `hasValue` on *any* of the optional types. While we know 
that the other types don't have this call, this is bad hygiene. At the least, 
we should note this potential problem in the comments.
2. I don't think its worth duplicating the case above just to change the name, 
given that the action is identical. Instead, please generalize 
`isOptionalMemberCallWithName` to take a name matcher, and pass 
`hasAnyName("has_value", "hasValue")` for this case.  The other calls to 
`isOptionalMemberCallWithName` will need to be changed to pass just 
`hasName(...)`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155890

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


[PATCH] D155921: [clang][dataflow] Reverse course on `getValue()` deprecation.

2023-07-21 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.

This sounds reasonable to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155921

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


[clang-tools-extra] 0a093f6 - [clangd] Prefer definitions for gototype and implementation

2023-07-21 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2023-07-21T14:38:51+02:00
New Revision: 0a093f62d15468f2b6ac4bfdc7a2dc7ba88364d0

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

LOG: [clangd] Prefer definitions for gototype and implementation

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

Added: 


Modified: 
clang-tools-extra/clangd/ClangdLSPServer.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp 
b/clang-tools-extra/clangd/ClangdLSPServer.cpp
index 65ee60382ba991..a87da252b7a7e9 100644
--- a/clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1451,7 +1451,7 @@ void ClangdLSPServer::onGoToType(const 
TextDocumentPositionParams &Params,
   return Reply(Types.takeError());
 std::vector Response;
 for (const LocatedSymbol &Sym : *Types)
-  Response.push_back(Sym.PreferredDeclaration);
+  
Response.push_back(Sym.Definition.value_or(Sym.PreferredDeclaration));
 return Reply(std::move(Response));
   });
 }
@@ -1467,7 +1467,7 @@ void ClangdLSPServer::onGoToImplementation(
   return Reply(Overrides.takeError());
 std::vector Impls;
 for (const LocatedSymbol &Sym : *Overrides)
-  Impls.push_back(Sym.PreferredDeclaration);
+  Impls.push_back(Sym.Definition.value_or(Sym.PreferredDeclaration));
 return Reply(std::move(Impls));
   });
 }



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


[PATCH] D133843: [clangd] Prefer definitions for gototype and implementation

2023-07-21 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG0a093f62d154: [clangd] Prefer definitions for gototype and 
implementation (authored by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D133843?vs=460003&id=542874#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133843

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp


Index: clang-tools-extra/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1451,7 +1451,7 @@
   return Reply(Types.takeError());
 std::vector Response;
 for (const LocatedSymbol &Sym : *Types)
-  Response.push_back(Sym.PreferredDeclaration);
+  
Response.push_back(Sym.Definition.value_or(Sym.PreferredDeclaration));
 return Reply(std::move(Response));
   });
 }
@@ -1467,7 +1467,7 @@
   return Reply(Overrides.takeError());
 std::vector Impls;
 for (const LocatedSymbol &Sym : *Overrides)
-  Impls.push_back(Sym.PreferredDeclaration);
+  Impls.push_back(Sym.Definition.value_or(Sym.PreferredDeclaration));
 return Reply(std::move(Impls));
   });
 }


Index: clang-tools-extra/clangd/ClangdLSPServer.cpp
===
--- clang-tools-extra/clangd/ClangdLSPServer.cpp
+++ clang-tools-extra/clangd/ClangdLSPServer.cpp
@@ -1451,7 +1451,7 @@
   return Reply(Types.takeError());
 std::vector Response;
 for (const LocatedSymbol &Sym : *Types)
-  Response.push_back(Sym.PreferredDeclaration);
+  Response.push_back(Sym.Definition.value_or(Sym.PreferredDeclaration));
 return Reply(std::move(Response));
   });
 }
@@ -1467,7 +1467,7 @@
   return Reply(Overrides.takeError());
 std::vector Impls;
 for (const LocatedSymbol &Sym : *Overrides)
-  Impls.push_back(Sym.PreferredDeclaration);
+  Impls.push_back(Sym.Definition.value_or(Sym.PreferredDeclaration));
 return Reply(std::move(Impls));
   });
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2021910 - [Clang] Diagnose jumps into statement expressions

2023-07-21 Thread Corentin Jabot via cfe-commits

Author: Corentin Jabot
Date: 2023-07-21T15:08:51+02:00
New Revision: 20219106060208f0c2f5d096eb3aed7b712f5067

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

LOG: [Clang] Diagnose jumps into statement expressions

Such jumps are not allowed by GCC and allowing them
can lead to situations where we jumps into unevaluated
statements.

Fixes #63682

Reviewed By: aaron.ballman, #clang-language-wg

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/JumpDiagnostics.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
clang/test/Sema/asm-goto.cpp
clang/test/Sema/scope-check.c
clang/test/SemaCXX/constant-expression-cxx14.cpp
clang/test/SemaObjC/scope-check.m

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 45381e7aad4ffc..f412e790d88b8a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -660,6 +660,9 @@ Bug Fixes in This Version
 - Fixed false positive error diagnostic observed from mixing ``asm goto`` with
   ``__attribute__((cleanup()))`` variables falsely warning that jumps to
   non-targets would skip cleanup.
+- Correcly diagnose jumps into statement expressions.
+  This ensures the behavior of Clang is consistent with GCC.
+  (`#63682 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
@@ -949,7 +952,7 @@ AST Matchers
 
 - The ``hasBody`` matcher now matches coroutine body nodes in
   ``CoroutineBodyStmts``.
-  
+
 - Add ``arrayInitIndexExpr`` and ``arrayInitLoopExpr`` matchers.
 
 clang-format

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 99917f190d82a1..b87414d91c238f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6219,6 +6219,8 @@ def note_enters_block_captures_non_trivial_c_struct : 
Note<
   "to destroy">;
 def note_enters_compound_literal_scope : Note<
   "jump enters lifetime of a compound literal that is non-trivial to 
destruct">;
+def note_enters_statement_expression : Note<
+  "jump enters a statement expression">;
 
 def note_exits_cleanup : Note<
   "jump exits scope of variable with __attribute__((cleanup))">;

diff  --git a/clang/lib/Sema/JumpDiagnostics.cpp 
b/clang/lib/Sema/JumpDiagnostics.cpp
index 5a6df56323a98b..45ff36d5fe237b 100644
--- a/clang/lib/Sema/JumpDiagnostics.cpp
+++ b/clang/lib/Sema/JumpDiagnostics.cpp
@@ -466,6 +466,21 @@ void JumpScopeChecker::BuildScopeInformation(Stmt *S,
 return;
   }
 
+  case Stmt::StmtExprClass: {
+// [GNU]
+// Jumping into a statement expression with goto or using
+// a switch statement outside the statement expression with
+// a case or default label inside the statement expression is not 
permitted.
+// Jumping out of a statement expression is permitted.
+StmtExpr *SE = cast(S);
+unsigned NewParentScope = Scopes.size();
+Scopes.push_back(GotoScope(ParentScope,
+   diag::note_enters_statement_expression,
+   /*OutDiag=*/0, SE->getBeginLoc()));
+BuildScopeInformation(SE->getSubStmt(), NewParentScope);
+return;
+  }
+
   case Stmt::ObjCAtTryStmtClass: {
 // Disallow jumps into any part of an @try statement by pushing a scope and
 // walking all sub-stmts in that scope.

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 2a7ae730a9084f..240f1520efad2b 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -16509,6 +16509,8 @@ ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 
SourceLocation LabLoc,
 
 void Sema::ActOnStartStmtExpr() {
   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
+  // Make sure we diagnose jumping into a statement expression.
+  setFunctionHasBranchProtectedScope();
 }
 
 void Sema::ActOnStmtExprError() {

diff  --git a/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp 
b/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
index 0c357db764a92a..55af13bfc0ef3a 100644
--- a/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
+++ b/clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
@@ -153,7 +153,8 @@ a:  if constexpr(sizeof(n) == 4) // expected-error 
{{redefinition}} expected-not
 
   void evil_things() {
 goto evil_label; // expected-error {{cannot jump}}
-if constexpr (true || ({evil_label: false;})) {} // expected-note 
{{constexpr if}}
+if constexpr (true || ({evil_label: false;})) {} // expected-note 
{{constexpr if}} \
+  

[PATCH] D154696: [Clang] Diagnose jumps into statement expressions

2023-07-21 Thread Corentin Jabot 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 rG202191060602: [Clang] Diagnose jumps into statement 
expressions (authored by cor3ntin).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154696

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/JumpDiagnostics.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CXX/stmt.stmt/stmt.select/stmt.if/p2.cpp
  clang/test/Sema/asm-goto.cpp
  clang/test/Sema/scope-check.c
  clang/test/SemaCXX/constant-expression-cxx14.cpp
  clang/test/SemaObjC/scope-check.m

Index: clang/test/SemaObjC/scope-check.m
===
--- clang/test/SemaObjC/scope-check.m
+++ clang/test/SemaObjC/scope-check.m
@@ -15,7 +15,7 @@
   } @finally {// expected-note {{jump bypasses initialization of @finally block}}
 L3: ;
   }
-  
+
   @try {
 goto L4; // expected-error{{cannot jump}}
 goto L5; // expected-error{{cannot jump}}
@@ -27,8 +27,8 @@
   } @finally { // expected-note {{jump bypasses initialization of @finally block}}
   L4: ;
   }
- 
-  
+
+
   @try { // expected-note 2 {{jump bypasses initialization of @try block}}
   L7: ;
   } @catch (C *c) {
@@ -36,21 +36,18 @@
   } @finally {
 goto L7; // expected-error{{cannot jump}}
   }
-  
+
   goto L8;  // expected-error{{cannot jump}}
-  @try { 
+  @try {
   } @catch (A *c) {
   } @catch (B *c) {
   } @catch (C *c) { // expected-note {{jump bypasses initialization of @catch block}}
   L8: ;
   }
-  
-  // rdar://6810106
   id X;
   goto L9;// expected-error{{cannot jump}}
-  goto L10;   // ok
-  @synchronized// expected-note {{jump bypasses initialization of @synchronized block}}
-  ( ({ L10: ; X; })) {
+  @synchronized (X)  // expected-note {{jump bypasses initialization of @synchronized block}}
+  {
   L9:
 ;
   }
@@ -90,7 +87,7 @@
 goto L0; // expected-error {{cannot jump}}
 typedef int A[n];  // expected-note {{jump bypasses initialization of VLA typedef}}
   L0:
-
+
 goto L1;  // expected-error {{cannot jump}}
 A b, c[10];// expected-note 2 {{jump bypasses initialization of variable length array}}
   L1:
Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -831,8 +831,9 @@
 case 0:
   return 0;
 
-  ({
-case 1: // expected-note {{not supported}}
+  ({  // expected-note {{jump enters a statement expression}}
+case 1:// expected-error {{cannot jump from switch statement to this case label}} \
+   // expected-note  {{not supported}}
   return 1;
   });
 }
Index: clang/test/Sema/scope-check.c
===
--- clang/test/Sema/scope-check.c
+++ clang/test/Sema/scope-check.c
@@ -65,7 +65,8 @@
 
   // Statement expressions.
   goto L3;   // expected-error {{cannot jump from this goto statement to its label}}
-  int Y = ({  int a[x];   // expected-note {{jump bypasses initialization of variable length array}}  
+  int Y = ({  int a[x];   // expected-note {{jump bypasses initialization of variable length array}} \
+  // expected-note {{jump enters a statement expression}}
L3: 4; });
   
   goto L4; // expected-error {{cannot jump from this goto statement to its label}}
@@ -107,25 +108,25 @@
4; })];
   L10:; // bad
   }
-  
+
   {
 // FIXME: Crashes goto checker.
 //goto L11;// ok
 //int A[({   L11: 4; })];
   }
-  
+
   {
 goto L12;
-
+
 int y = 4;   // fixme-warn: skips initializer.
   L12:
 ;
   }
-  
+
   // Statement expressions 2.
   goto L1; // expected-error {{cannot jump from this goto statement to its label}}
-  return x == ({
- int a[x];   // expected-note {{jump bypasses initialization of variable length array}}  
+  return x == ({ // expected-note {{jump enters a statement expression}}
+ int a[x];   // expected-note {{jump bypasses initialization of variable length array}}
L1:
  42; });
 }
@@ -232,3 +233,27 @@
 
 // rdar://9024687
 int test16(int [sizeof &&z]); // expected-error {{use of address-of-label extension outside of a function body}}
+
+void GH63682() {
+  {
+goto L; // expected-error {{cannot jump from this goto statement to its label}}
+(void)sizeof (int){({ L:; 1; })}; // expected-note {{jump enters a statement expression}}
+  }
+  {
+goto M; // expected-error {{cannot jump from this goto statement to its label}}
+(void)({ M:; 1; }); // expected-note {{jump enters a statement expression}}
+  }
+  {
+(void)({ goto N; 1;

[clang] 26b19a6 - [clang][analyzer]Fix non-effective taint sanitation

2023-07-21 Thread Daniel Krupp via cfe-commits

Author: Daniel Krupp
Date: 2023-07-21T15:11:13+02:00
New Revision: 26b19a67e5c398a30b26214544878ec364dc59af

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

LOG: [clang][analyzer]Fix non-effective taint sanitation

There was a bug in alpha.security.taint.TaintPropagation checker
in Clang Static Analyzer.
Taint filtering could only sanitize const arguments.
After this patch, taint filtering is effective also
on non-const parameters.

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
clang/test/Analysis/Inputs/taint-generic-config.yaml
clang/test/Analysis/taint-generic.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
index 4bf8ce13e0572c..3dcb45c0b11038 100644
--- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -926,7 +926,9 @@ void GenericTaintRule::process(const GenericTaintChecker 
&Checker,
   });
 
   /// Check for taint propagation sources.
-  /// A rule is relevant if PropSrcArgs is empty, or if any of its signified
+  /// A rule will make the destination variables tainted if PropSrcArgs
+  /// is empty (taints the destination
+  /// arguments unconditionally), or if any of its signified
   /// args are tainted in context of the current CallEvent.
   bool IsMatching = PropSrcArgs.isEmpty();
   std::vector TaintedSymbols;
@@ -949,6 +951,8 @@ void GenericTaintRule::process(const GenericTaintChecker 
&Checker,
 }
   });
 
+  // Early return for propagation rules which dont match.
+  // Matching propagations, Sinks and Filters will pass this point.
   if (!IsMatching)
 return;
 
@@ -975,10 +979,13 @@ void GenericTaintRule::process(const GenericTaintChecker 
&Checker,
   Result = F.add(Result, I);
 }
 
+// Taint property gets lost if the variable is passed as a
+// non-const pointer or reference to a function which is
+// not inlined. For matching rules we want to preserve the taintedness.
 // TODO: We should traverse all reachable memory regions via the
 // escaping parameter. Instead of doing that we simply mark only the
 // referred memory region as tainted.
-if (WouldEscape(V, E->getType())) {
+if (WouldEscape(V, E->getType()) && getTaintedPointeeOrPointer(State, 
V)) {
   LLVM_DEBUG(if (!Result.contains(I)) {
 llvm::dbgs() << "PreCall<";
 Call.dump(llvm::dbgs());

diff  --git a/clang/test/Analysis/Inputs/taint-generic-config.yaml 
b/clang/test/Analysis/Inputs/taint-generic-config.yaml
index 39b52ccc32e67c..d025bb2a1ed3c8 100755
--- a/clang/test/Analysis/Inputs/taint-generic-config.yaml
+++ b/clang/test/Analysis/Inputs/taint-generic-config.yaml
@@ -69,6 +69,11 @@ Filters:
 Scope: "myAnotherNamespace::"
 Args:  [0]
 
+  # char *str; // str is tainted
+  # sanitizeCmd(str) // str is not tainted anymore
+  - Name: sanitizeCmd
+Args: [0]
+
 # A list of sink functions
 Sinks:
   # int x, y; // x and y are tainted

diff  --git a/clang/test/Analysis/taint-generic.c 
b/clang/test/Analysis/taint-generic.c
index 62e1f570b6622a..84b7cc51dd6df8 100644
--- a/clang/test/Analysis/taint-generic.c
+++ b/clang/test/Analysis/taint-generic.c
@@ -1010,7 +1010,8 @@ void mySource2(int*);
 void myScanf(const char*, ...);
 int myPropagator(int, int*);
 int mySnprintf(char*, size_t, const char*, ...);
-bool isOutOfRange(const int*);
+bool isOutOfRange(const int*); // const filter function
+void sanitizeCmd(char*); // non-const filter function
 void mySink(int, int, int);
 
 void testConfigurationSources1(void) {
@@ -1044,6 +1045,19 @@ void testConfigurationFilter(void) {
   Buffer[x] = 1; // no-warning
 }
 
+void testConfigurationFilterNonConst(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  system(buffer); // expected-warning {{Untrusted data is passed to a system 
call}}
+}
+
+void testConfigurationFilterNonConst2(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  sanitizeCmd(buffer); // removes taintedness
+  system(buffer); // no-warning
+}
+
 void testConfigurationSinks(void) {
   int x = mySource1();
   mySink(x, 1, 2);



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


[PATCH] D155848: [clang][analyzer]Fix non-effective taint sanitation

2023-07-21 Thread Daniel Krupp via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
dkrupp marked an inline comment as done.
Closed by commit rG26b19a67e5c3: [clang][analyzer]Fix non-effective taint 
sanitation (authored by dkrupp).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D155848?vs=542619&id=542885#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155848

Files:
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  clang/test/Analysis/Inputs/taint-generic-config.yaml
  clang/test/Analysis/taint-generic.c


Index: clang/test/Analysis/taint-generic.c
===
--- clang/test/Analysis/taint-generic.c
+++ clang/test/Analysis/taint-generic.c
@@ -1010,7 +1010,8 @@
 void myScanf(const char*, ...);
 int myPropagator(int, int*);
 int mySnprintf(char*, size_t, const char*, ...);
-bool isOutOfRange(const int*);
+bool isOutOfRange(const int*); // const filter function
+void sanitizeCmd(char*); // non-const filter function
 void mySink(int, int, int);
 
 void testConfigurationSources1(void) {
@@ -1044,6 +1045,19 @@
   Buffer[x] = 1; // no-warning
 }
 
+void testConfigurationFilterNonConst(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  system(buffer); // expected-warning {{Untrusted data is passed to a system 
call}}
+}
+
+void testConfigurationFilterNonConst2(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  sanitizeCmd(buffer); // removes taintedness
+  system(buffer); // no-warning
+}
+
 void testConfigurationSinks(void) {
   int x = mySource1();
   mySink(x, 1, 2);
Index: clang/test/Analysis/Inputs/taint-generic-config.yaml
===
--- clang/test/Analysis/Inputs/taint-generic-config.yaml
+++ clang/test/Analysis/Inputs/taint-generic-config.yaml
@@ -69,6 +69,11 @@
 Scope: "myAnotherNamespace::"
 Args:  [0]
 
+  # char *str; // str is tainted
+  # sanitizeCmd(str) // str is not tainted anymore
+  - Name: sanitizeCmd
+Args: [0]
+
 # A list of sink functions
 Sinks:
   # int x, y; // x and y are tainted
Index: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -926,7 +926,9 @@
   });
 
   /// Check for taint propagation sources.
-  /// A rule is relevant if PropSrcArgs is empty, or if any of its signified
+  /// A rule will make the destination variables tainted if PropSrcArgs
+  /// is empty (taints the destination
+  /// arguments unconditionally), or if any of its signified
   /// args are tainted in context of the current CallEvent.
   bool IsMatching = PropSrcArgs.isEmpty();
   std::vector TaintedSymbols;
@@ -949,6 +951,8 @@
 }
   });
 
+  // Early return for propagation rules which dont match.
+  // Matching propagations, Sinks and Filters will pass this point.
   if (!IsMatching)
 return;
 
@@ -975,10 +979,13 @@
   Result = F.add(Result, I);
 }
 
+// Taint property gets lost if the variable is passed as a
+// non-const pointer or reference to a function which is
+// not inlined. For matching rules we want to preserve the taintedness.
 // TODO: We should traverse all reachable memory regions via the
 // escaping parameter. Instead of doing that we simply mark only the
 // referred memory region as tainted.
-if (WouldEscape(V, E->getType())) {
+if (WouldEscape(V, E->getType()) && getTaintedPointeeOrPointer(State, 
V)) {
   LLVM_DEBUG(if (!Result.contains(I)) {
 llvm::dbgs() << "PreCall<";
 Call.dump(llvm::dbgs());


Index: clang/test/Analysis/taint-generic.c
===
--- clang/test/Analysis/taint-generic.c
+++ clang/test/Analysis/taint-generic.c
@@ -1010,7 +1010,8 @@
 void myScanf(const char*, ...);
 int myPropagator(int, int*);
 int mySnprintf(char*, size_t, const char*, ...);
-bool isOutOfRange(const int*);
+bool isOutOfRange(const int*); // const filter function
+void sanitizeCmd(char*); // non-const filter function
 void mySink(int, int, int);
 
 void testConfigurationSources1(void) {
@@ -1044,6 +1045,19 @@
   Buffer[x] = 1; // no-warning
 }
 
+void testConfigurationFilterNonConst(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  system(buffer); // expected-warning {{Untrusted data is passed to a system call}}
+}
+
+void testConfigurationFilterNonConst2(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  sanitizeCmd(buffer); // removes taintedness
+  system(b

[PATCH] D155175: [Clang] Fix consteval propagation for aggregates and defaulted constructors

2023-07-21 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a subscriber: rjmccall.
aaron.ballman added a comment.

In D155175#4518366 , @cor3ntin wrote:

> Remove an assert (added in a previous iteration of this PR).
>
> Unfortunately, we sometimes do emit the address of an immediate function,
> after we establish the program is ill-formed - as we still proceed to code 
> gen.
>
>   cpp
>   
>   consteval int id(int i) { return i; }
>   constexpr int f(auto t) { 
>   return t + id(t); 
>   }
>   
>   auto b = &f;
>
> We establish taking the address of &f is not possible
> when exiting the evaluation context.
> At this point b has an init expression, which codegen will try to emit.
> Ideally we should try to remove the init all together after the fact but so 
> far
> I have not been able to do so.

The removed code was this:

  llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
   llvm::Type *Ty,
   bool ForVTable,
   bool DontDefer,
ForDefinition_t 
IsForDefinition) {
assert(!cast(GD.getDecl())->isImmediateFunction() &&
   "an immediate function should never be emitted");

which seems like very reasonable assertion to have. Should we be marking the 
init expression/declaration as invalid to force codegen not to run on the 
expression? So it's not removing the init, but is marking the declaration its 
attached to as invalid. CC @efriedma @rjmccall


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155175

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


[PATCH] D154503: [Sema] Fix handling of functions that hide classes

2023-07-21 Thread John Brawn via Phabricator via cfe-commits
john.brawn updated this revision to Diff 542893.
john.brawn edited the summary of this revision.
john.brawn added a comment.

Restructured to check for hidden tags in the main loop. Also add a bunch of 
extra tests.


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

https://reviews.llvm.org/D154503

Files:
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaCXX/using-hiding.cpp

Index: clang/test/SemaCXX/using-hiding.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/using-hiding.cpp
@@ -0,0 +1,373 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+namespace A {
+  class X { }; // expected-note{{candidate found by name lookup is 'A::X'}}
+   // expected-note@-1{{candidate found by name lookup is 'A::X'}}
+}
+namespace B {
+  void X(int); // expected-note{{candidate found by name lookup is 'B::X'}}
+   // expected-note@-1{{candidate found by name lookup is 'B::X'}}
+}
+
+// Using directive doesn't cause A::X to be hidden, so X is ambiguous.
+namespace Test1a {
+  using namespace A;
+  using namespace B;
+
+  void f() {
+X(1); // expected-error{{reference to 'X' is ambiguous}}
+  }
+}
+
+namespace Test1b {
+  using namespace B;
+  using namespace A;
+
+  void f() {
+X(1); // expected-error{{reference to 'X' is ambiguous}}
+  }
+}
+
+// The behaviour here should be the same as using namespaces A and B directly
+namespace Test2a {
+  namespace C {
+using A::X; // expected-note{{candidate found by name lookup is 'Test2a::C::X'}}
+  }
+  namespace D {
+using B::X; // expected-note{{candidate found by name lookup is 'Test2a::D::X'}}
+  }
+  using namespace C;
+  using namespace D;
+
+  void f() {
+X(1); // expected-error{{reference to 'X' is ambiguous}}
+  }
+}
+
+namespace Test2b {
+  namespace C {
+using A::X; // expected-note{{candidate found by name lookup is 'Test2b::C::X'}}
+  }
+  namespace D {
+using B::X; // expected-note{{candidate found by name lookup is 'Test2b::D::X'}}
+  }
+  using namespace D;
+  using namespace C;
+
+  void f() {
+X(1); // expected-error{{reference to 'X' is ambiguous}}
+  }
+}
+
+// Defining a function X inside C should hide using A::X in C but not D, so the result is ambiguous.
+namespace Test3a {
+  namespace C {
+using A::X;
+void X(int); // expected-note{{candidate found by name lookup is 'Test3a::C::X'}}
+  }
+  namespace D {
+using A::X; // expected-note{{candidate found by name lookup is 'Test3a::D::X'}}
+  }
+  using namespace C;
+  using namespace D;
+  void f() {
+X(1); // expected-error{{reference to 'X' is ambiguous}}
+  }
+}
+
+namespace Test3b {
+  namespace C {
+using A::X;
+void X(int); // expected-note{{candidate found by name lookup is 'Test3b::C::X'}}
+  }
+  namespace D {
+using A::X; // expected-note{{candidate found by name lookup is 'Test3b::D::X'}}
+  }
+  using namespace D;
+  using namespace C;
+  void f() {
+X(1); // expected-error{{reference to 'X' is ambiguous}}
+  }
+}
+
+namespace Test3c {
+  namespace C {
+void X(int); // expected-note{{candidate found by name lookup is 'Test3c::C::X'}}
+using A::X;
+  }
+  namespace D {
+using A::X; // expected-note{{candidate found by name lookup is 'Test3c::D::X'}}
+  }
+  using namespace C;
+  using namespace D;
+  void f() {
+X(1); // expected-error{{reference to 'X' is ambiguous}}
+  }
+}
+
+namespace Test3d {
+  namespace C {
+void X(int); // expected-note{{candidate found by name lookup is 'Test3d::C::X'}}
+using A::X;
+  }
+  namespace D {
+using A::X; // expected-note{{candidate found by name lookup is 'Test3d::D::X'}}
+  }
+  using namespace D;
+  using namespace C;
+  void f() {
+X(1); // expected-error{{reference to 'X' is ambiguous}}
+  }
+}
+
+// A::X hidden in both C and D by overloaded function, so the result is not ambiguous.
+namespace Test4a {
+  namespace C {
+using A::X;
+void X(int);
+  }
+  namespace D {
+using A::X;
+void X(int, int);
+  }
+  using namespace C;
+  using namespace D;
+  void f() {
+X(1);
+  }
+}
+
+namespace Test4b {
+  namespace C {
+using A::X;
+void X(int);
+  }
+  namespace D {
+using A::X;
+void X(int, int);
+  }
+  using namespace D;
+  using namespace C;
+  void f() {
+X(1);
+  }
+}
+
+namespace Test4c {
+  namespace C {
+void X(int);
+using A::X;
+  }
+  namespace D {
+void X(int, int);
+using A::X;
+  }
+  using namespace C;
+  using namespace D;
+  void f() {
+X(1);
+  }
+}
+
+namespace Test4d {
+  namespace C {
+void X(int);
+using A::X;
+  }
+  namespace D {
+void X(int, int);
+using A::X;
+  }
+  using namespace D;
+  using namespace C;
+  void f() {
+X(1);
+  }
+}
+
+// B::X hides class X in C, so the the result is not ambiguous
+namespace Test5a {
+  namespace C {
+using B::X;
+class X { };
+  }
+  namespace D {
+using B::X;
+  }
+  using namespace C;
+  using namespace D;
+  void

[PATCH] D155895: Anonymous unions should be transparent wrt `[[clang::trivial_abi]]`.

2023-07-21 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:10325
 
-  for (const auto *FD : RD.fields()) {
-// Ill-formed if the field is an ObjectiveC pointer or of a type that is
-// non-trivial for the purpose of calls.
-QualType FT = FD->getType();
-if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
-  PrintDiagAndRemoveAttr(4);
-  return;
-}
-
-if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs())
-  if (!RT->isDependentType() &&
-  !cast(RT->getDecl())->canPassInRegisters()) {
-PrintDiagAndRemoveAttr(5);
+  std::queue RecordsWithFieldsToCheck;
+  RecordsWithFieldsToCheck.push(&RD);

It looks like we don't need to visit the fields in a specific order. If that's 
the case, please use SmallVector and pop_back_val. (See 
AnalyzeImplicitConversions for an example of a typical worklist algorithm.)



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:10330
+  // Ill-formed if the field is an ObjectiveC pointer or of a type that is
+  // non-trivial for the purpose of calls.
+  QualType FT = FD->getType();

Please split off the part of the comment that talks about "non-trivial for the 
purpose of calls", move it to the newly added if statement below, and enhance 
the comment to explain the new rule about anonymous unions.



Comment at: clang/test/SemaCXX/attr-trivial-abi.cpp:201-202
+
+  // `S2` is like `S1`, but `field` is wrapped in an anonymous union (and it
+  // seems that trivial relocatability of `S1` and `S2` should be the same).
+  //





Comment at: clang/test/SemaCXX/attr-trivial-abi.cpp:232
+  // `S2` and `S3` examples above show that `[[clang::trivial_abi]]`
+  // *implicitly* propagates into anonymous union and structs.  The example
+  // below shows that it is still *not* okay to *explicitly* apply

That's not exactly true, we don't propagate the trivial_abi attribute onto the 
union type. After this patch, the type of the union (which is impossible to get 
ahold of) is still non-trivial.

What we do though, is that we ignore the trivial relocatability of the union 
itself, and instead look at the members.



Comment at: clang/test/SemaCXX/attr-trivial-abi.cpp:251
+  // Like `S2`, but the field of the anonymous union is *not* trivial.
+  struct [[clang::trivial_abi]] S5 { // expected-warning {{'trivial_abi' 
cannot be applied to 'S5'}} expected-note {{trivial_abi' is disallowed on 'S5' 
because it has a field of a non-trivial class type}}
+S5(S5&& other) {}

Could you replace the numbers in S1-S5 with more meaningful phrases?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155895

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


[PATCH] D155848: [clang][analyzer]Fix non-effective taint sanitation

2023-07-21 Thread Daniel Krupp via Phabricator via cfe-commits
dkrupp updated this revision to Diff 542903.
dkrupp added a comment.

-formatting issues fixed
-sanitizecCmd changed to void


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

https://reviews.llvm.org/D155848

Files:
  clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
  clang/test/Analysis/Inputs/taint-generic-config.yaml
  clang/test/Analysis/taint-generic.c


Index: clang/test/Analysis/taint-generic.c
===
--- clang/test/Analysis/taint-generic.c
+++ clang/test/Analysis/taint-generic.c
@@ -1010,7 +1010,8 @@
 void myScanf(const char*, ...);
 int myPropagator(int, int*);
 int mySnprintf(char*, size_t, const char*, ...);
-bool isOutOfRange(const int*);
+bool isOutOfRange(const int*); // const filter function
+void sanitizeCmd(char*); // non-const filter function
 void mySink(int, int, int);
 
 void testConfigurationSources1(void) {
@@ -1044,6 +1045,19 @@
   Buffer[x] = 1; // no-warning
 }
 
+void testConfigurationFilterNonConst(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  system(buffer); // expected-warning {{Untrusted data is passed to a system 
call}}
+}
+
+void testConfigurationFilterNonConst2(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  sanitizeCmd(buffer); // removes taintedness
+  system(buffer); // no-warning
+}
+
 void testConfigurationSinks(void) {
   int x = mySource1();
   mySink(x, 1, 2);
Index: clang/test/Analysis/Inputs/taint-generic-config.yaml
===
--- clang/test/Analysis/Inputs/taint-generic-config.yaml
+++ clang/test/Analysis/Inputs/taint-generic-config.yaml
@@ -69,6 +69,11 @@
 Scope: "myAnotherNamespace::"
 Args:  [0]
 
+  # char *str; // str is tainted
+  # sanitizeCmd(str) // str is not tainted anymore
+  - Name: sanitizeCmd
+Args: [0]
+
 # A list of sink functions
 Sinks:
   # int x, y; // x and y are tainted
Index: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -926,7 +926,9 @@
   });
 
   /// Check for taint propagation sources.
-  /// A rule is relevant if PropSrcArgs is empty, or if any of its signified
+  /// A rule will make the destination variables tainted if PropSrcArgs
+  /// is empty (taints the destination
+  /// arguments unconditionally), or if any of its signified
   /// args are tainted in context of the current CallEvent.
   bool IsMatching = PropSrcArgs.isEmpty();
   std::vector TaintedSymbols;
@@ -949,6 +951,8 @@
 }
   });
 
+  // Early return for propagation rules which dont match.
+  // Matching propagations, Sinks and Filters will pass this point.
   if (!IsMatching)
 return;
 
@@ -975,10 +979,13 @@
   Result = F.add(Result, I);
 }
 
+// Taint property gets lost if the variable is passed as a
+// non-const pointer or reference to a function which is
+// not inlined. For matching rules we want to preserve the taintedness.
 // TODO: We should traverse all reachable memory regions via the
 // escaping parameter. Instead of doing that we simply mark only the
 // referred memory region as tainted.
-if (WouldEscape(V, E->getType())) {
+if (WouldEscape(V, E->getType()) && getTaintedPointeeOrPointer(State, 
V)) {
   LLVM_DEBUG(if (!Result.contains(I)) {
 llvm::dbgs() << "PreCall<";
 Call.dump(llvm::dbgs());


Index: clang/test/Analysis/taint-generic.c
===
--- clang/test/Analysis/taint-generic.c
+++ clang/test/Analysis/taint-generic.c
@@ -1010,7 +1010,8 @@
 void myScanf(const char*, ...);
 int myPropagator(int, int*);
 int mySnprintf(char*, size_t, const char*, ...);
-bool isOutOfRange(const int*);
+bool isOutOfRange(const int*); // const filter function
+void sanitizeCmd(char*); // non-const filter function
 void mySink(int, int, int);
 
 void testConfigurationSources1(void) {
@@ -1044,6 +1045,19 @@
   Buffer[x] = 1; // no-warning
 }
 
+void testConfigurationFilterNonConst(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  system(buffer); // expected-warning {{Untrusted data is passed to a system call}}
+}
+
+void testConfigurationFilterNonConst2(void) {
+  char buffer[1000];
+  myScanf("%s", buffer); // makes buffer tainted
+  sanitizeCmd(buffer); // removes taintedness
+  system(buffer); // no-warning
+}
+
 void testConfigurationSinks(void) {
   int x = mySource1();
   mySink(x, 1, 2);
Index: clang/test/Analysis/Inputs/taint-generic-config.yaml
===
--- clang/test/Analysis/Inputs/taint-generic-config.yaml
+++ clang/test/Analysis/Inputs/taint-generic-config.yam

[PATCH] D155848: [clang][analyzer]Fix non-effective taint sanitation

2023-07-21 Thread Daniel Krupp via Phabricator via cfe-commits
dkrupp added inline comments.



Comment at: clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp:970
-  ForEachCallArg(
-  [&](ArgIdxTy I, const Expr *E, SVal V) {
-if (PropDstArgs.contains(I)) {

steakhal wrote:
> dkrupp wrote:
> > dkrupp wrote:
> > > steakhal wrote:
> > > > Is it only a formatting hunk?
> > > > I cannot really tell from my phone xd
> > > yeap. formatting only.
> > Yes. Only formatting.
> I would suggest not mixing formatting changes with semantic changes in a 
> single revision. Consider not doing the formatting, or at least format in a 
> different revision.
> 
> Adding and updating comments are fine.
Yes. I realized. I reverted the formatting change.


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

https://reviews.llvm.org/D155848

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


[PATCH] D155955: [Clang] Improve the handling of large arrays evaluation.

2023-07-21 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin created this revision.
Herald added a project: All.
cor3ntin requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is a temporary fix (for clang 17) that caps the size of
any array we try to constant evaluate:

There are 2 limits:

- We cap to UINT_MAX the size of ant constant evaluated array, because the 
constant evaluator does not support size_t.
- We cap to 100MB the size of allocations made during constant folding and 
other non-mandated constant evaluations so that we reduce the risk of crashing 
when compiling programs that are valid. Constant folding may still happen in 
the backend otherwise the code will be runtime evaluated.

  The 100MB linit is a bit arbitrary, but it seems like something that would be 
readily available on any system compiling a non trivial c++ program.

Fixes #63562


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155955

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Type.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/AST/Type.cpp
  clang/test/SemaCXX/cxx2a-constexpr-dynalloc-limits.cpp

Index: clang/test/SemaCXX/cxx2a-constexpr-dynalloc-limits.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/cxx2a-constexpr-dynalloc-limits.cpp
@@ -0,0 +1,66 @@
+// RUN: %clang_cc1 -std=c++2a -verify %s
+// RUN: %clang_cc1 -std=c++2a -verify=constexpr %s -DCONSTEXPR
+// expected-no-diagnostics
+
+namespace std {
+  using size_t = decltype(sizeof(0));
+  template struct allocator {
+constexpr T *allocate(size_t N) {
+  return (T*)operator new(sizeof(T) * N); // #alloc
+}
+constexpr void deallocate(void *p) {
+  operator delete(p);
+}
+  };
+}
+void *operator new(std::size_t, void *p) { return p; }
+
+namespace std {
+  template
+  constexpr void construct_at(void *p, Args &&...args) {
+new (p) T((Args&&)args...);
+  }
+}
+
+namespace GH63562 {
+
+template 
+struct S {
+constexpr S(unsigned long long N)
+: data(nullptr){
+data = alloc.allocate(N);  // #call
+for(std::size_t i = 0; i < N; i ++)
+std::construct_at(data + i, i);
+
+}
+constexpr ~S() {
+alloc.deallocate(data);
+}
+std::allocator alloc;
+T* data;
+};
+
+#ifdef CONSTEXPR
+constexpr S s(109951162); // constexpr-error {{constexpr variable 's' must be initialized by a constant expression}} \// expected-note@#alloc {{annot allocate array; evaluated array bound 109951162 is too large}} \
+   // constexpr-note@#call {{in call to 'this->alloc.allocate(109951162)'}} \
+   // constexpr-note@#alloc {{cannot allocate array; evaluated array bound 109951162 is too large}} \
+   // constexpr-note {{in call to 'S(109951162)'}}
+#else
+// Check that we do not try to fold very large arrays
+S s2(109951162);
+S s3(~0ULL);
+#endif
+
+// Check we do not perform constant initialization in the presence
+// of very large arrays (this used to crash)
+
+constexpr int stack_array(auto N) {
+char BIG[N];
+return 0;
+}
+
+int a = stack_array(~0U);
+int b = stack_array(~0ULL);
+
+}
+
Index: clang/lib/AST/Type.cpp
===
--- clang/lib/AST/Type.cpp
+++ clang/lib/AST/Type.cpp
@@ -175,6 +175,11 @@
   return TotalSize.getActiveBits();
 }
 
+unsigned
+ConstantArrayType::getNumAddressingBits(const ASTContext &Context) const {
+  return getNumAddressingBits(Context, getElementType(), getSize());
+}
+
 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
   unsigned Bits = Context.getTypeSize(Context.getSizeType());
 
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -1019,6 +1019,43 @@
   return false;
 }
 
+bool IsArrayTooLarge(unsigned BitWidth, uint64_t ElemCount) {
+  if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx))
+return true;
+
+  // FIXME: GH63562
+  // APValue stores array extents as unsigned,
+  // so anything that is greater that unsigned would overflow when
+  // constructing the array, we catch this here.
+  if (ElemCount > std::numeric_limits::max())
+return true;
+
+  // FIXME: GH63562
+  // Arrays allocate an APValue per element.
+  // When constant folding avoid allocating arrays larger than 100MB to
+  // avoid running out of memory when compiling reasonable programs.
+  // Constant Expression evaluation can still exhaust the sytem resources
+  // and crash the compiler.
+  bool RequiresConstantEvaluation =
+  !(checkingPotentialConstantExpression() ||
+EvalMode == EvalInfo::EM_IgnoreSideEffects ||
+ 

[PATCH] D155714: [clang] Fix diagnostics for defaulted, implicitly deleted 'operator=='.

2023-07-21 Thread Amirreza Ashouri via Phabricator via cfe-commits
AMP999 updated this revision to Diff 542909.
AMP999 added a comment.

An entry added to clang/docs/ReleaseNotes.rst
Thank You for the review!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155714

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
  clang/test/CXX/class/class.compare/class.compare.default/p4.cpp
  clang/test/CXX/class/class.compare/class.compare.secondary/p2.cpp
  clang/test/CXX/class/class.compare/class.eq/p2.cpp
  clang/test/CXX/class/class.compare/class.spaceship/p1.cpp

Index: clang/test/CXX/class/class.compare/class.spaceship/p1.cpp
===
--- clang/test/CXX/class/class.compare/class.spaceship/p1.cpp
+++ clang/test/CXX/class/class.compare/class.spaceship/p1.cpp
@@ -80,7 +80,7 @@
   // expected-note@#base {{deleted comparison function for base class 'C'}}
   // expected-note@#base {{no viable three-way comparison function for base class 'D1'}}
   // expected-note@#base {{three-way comparison cannot be synthesized because there is no viable function for '<' comparison}}
-  // expected-note@#base {{no viable three-way comparison function for base class 'D2'}}
+  // expected-note@#base {{no viable 'operator==' for base class 'D2'}}
   // expected-note@#base {{three-way comparison cannot be synthesized because there is no viable function for '==' comparison}}
   // expected-note@#base {{deleted comparison function for base class 'E'}}
   // expected-note@#base {{implied comparison for base class 'F' is ambiguous}}
@@ -112,7 +112,7 @@
   // expected-note@#arr {{deleted comparison function for member 'arr'}}
   // expected-note@#arr {{no viable three-way comparison function for member 'arr'}}
   // expected-note@#arr {{three-way comparison cannot be synthesized because there is no viable function for '<' comparison}}
-  // expected-note@#arr {{no viable three-way comparison function for member 'arr'}}
+  // expected-note@#arr {{no viable 'operator==' for member 'arr'}}
   // expected-note@#arr {{three-way comparison cannot be synthesized because there is no viable function for '==' comparison}}
   // expected-note@#arr {{deleted comparison function for member 'arr'}}
   // expected-note@#arr {{implied comparison for member 'arr' is ambiguous}}
Index: clang/test/CXX/class/class.compare/class.eq/p2.cpp
===
--- clang/test/CXX/class/class.compare/class.eq/p2.cpp
+++ clang/test/CXX/class/class.compare/class.eq/p2.cpp
@@ -37,7 +37,7 @@
 template struct X {
   X();
   bool operator==(const X&) const = default; // #x expected-note 4{{deleted here}}
-  T t; // expected-note 3{{because there is no viable three-way comparison function for member 't'}}
+  T t; // expected-note 3{{because there is no viable 'operator==' for member 't'}}
// expected-note@-1 {{because it would invoke a deleted comparison function for member 't'}}
 };
 
Index: clang/test/CXX/class/class.compare/class.compare.secondary/p2.cpp
===
--- clang/test/CXX/class/class.compare/class.compare.secondary/p2.cpp
+++ clang/test/CXX/class/class.compare/class.compare.secondary/p2.cpp
@@ -5,6 +5,14 @@
   // expected-note@-1 {{defaulted 'operator!=' is implicitly deleted because there is no viable 'operator==' for 'A'}}
 };
 
+struct A2 {
+  struct E {};
+  E e;
+  bool operator==(const A2&) const = default; // expected-warning {{explicitly defaulted equality comparison operator is implicitly deleted}} expected-note{{replace 'default'}}
+  // expected-note@-2 {{defaulted 'operator==' is implicitly deleted because there is no viable 'operator==' for member 'e'}}
+};
+
+
 struct Q {};
 bool operator!=(Q, Q); // expected-note {{defaulted 'operator!=' is implicitly deleted because this non-rewritten comparison function would be the best match for the comparison}}
 struct B {
Index: clang/test/CXX/class/class.compare/class.compare.default/p4.cpp
===
--- clang/test/CXX/class/class.compare/class.compare.default/p4.cpp
+++ clang/test/CXX/class/class.compare/class.compare.default/p4.cpp
@@ -100,7 +100,7 @@
   struct Q {
 struct X {
   friend std::strong_ordering operator<=>(const X&, const X&);
-} x; // expected-note {{no viable three-way comparison}}
+} x; // expected-note {{no viable 'operator=='}}
 // expected-error@+1 {{defaulting the corresponding implicit 'operator==' for this defaulted 'operator<=>' would delete it after its first declaration}}
 friend std::strong_ordering operator<=>(const Q&, const Q&) = default;
   };
Index: clang/test/CXX/class/class.compare/class.compare.default/p1.cpp
===
--- clang/test/CXX/class/class.compare/c

[PATCH] D155290: [PGO] Use Unique Profile Files when New Processes are Forked

2023-07-21 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 marked 2 inline comments as done.
qiongsiwu1 added inline comments.



Comment at: clang/lib/Driver/ToolChains/AIX.cpp:440
+  if (NeedsProfileRT || needsGCovInstrumentation(Args))
+CmdArgs.push_back("-lpthreads");
+

w2yehia wrote:
> w2yehia wrote:
> > The change in `compiler-rt/lib/profile/InstrProfilingFile.c` affects 
> > non-AIX platforms too, so won't they need `-lpthreads` too?
> > 
> In order to avoid adding -lpthreads, we can leave it to the user to decide 
> whether to add or not (i.e. they would add -lpthreads to their application's 
> link command if they want to).
> And so to avoid a link error due to undefined symbol, we can define 
> `pthread_atfork` as a weak empty stub in the compiler-rt.
> The change in `compiler-rt/lib/profile/InstrProfilingFile.c` affects non-AIX 
> platforms too, so won't they need `-lpthreads` too?
> 

This is a good question. On Linux we are ok because `pthread_atfork` is 
actually implemented by `__register_atfork`, which is available in `libc.so`, 
so we do not need `-lpthreads`. I am not sure about other platforms. @davidxl 
@vsk @ellis may I get your comments? 



Comment at: clang/lib/Driver/ToolChains/AIX.cpp:440
+  if (NeedsProfileRT || needsGCovInstrumentation(Args))
+CmdArgs.push_back("-lpthreads");
+

qiongsiwu1 wrote:
> w2yehia wrote:
> > w2yehia wrote:
> > > The change in `compiler-rt/lib/profile/InstrProfilingFile.c` affects 
> > > non-AIX platforms too, so won't they need `-lpthreads` too?
> > > 
> > In order to avoid adding -lpthreads, we can leave it to the user to decide 
> > whether to add or not (i.e. they would add -lpthreads to their 
> > application's link command if they want to).
> > And so to avoid a link error due to undefined symbol, we can define 
> > `pthread_atfork` as a weak empty stub in the compiler-rt.
> > The change in `compiler-rt/lib/profile/InstrProfilingFile.c` affects 
> > non-AIX platforms too, so won't they need `-lpthreads` too?
> > 
> 
> This is a good question. On Linux we are ok because `pthread_atfork` is 
> actually implemented by `__register_atfork`, which is available in `libc.so`, 
> so we do not need `-lpthreads`. I am not sure about other platforms. @davidxl 
> @vsk @ellis may I get your comments? 
> In order to avoid adding -lpthreads, we can leave it to the user to decide 
> whether to add or not (i.e. they would add -lpthreads to their application's 
> link command if they want to).
> And so to avoid a link error due to undefined symbol, we can define 
> `pthread_atfork` as a weak empty stub in the compiler-rt.

@w2yehia and I discussed offline, and we think it is ok to pass in `-lpthread` 
on AIX. There should not be any functional issues. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155290

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


[PATCH] D154324: [C++20] [Modules] [ODRHash] Use CanonicalType for base classes

2023-07-21 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In D154324#4520096 , @alexfh wrote:

> In D154324#4516964 , @alexfh wrote:
>
>> In D154324#4516917 , @ChuanqiXu 
>> wrote:
>>
>>> Maybe we got something wrong with this. I'd like to revert this patch in 
>>> case it breaks something. But would you like to reduce your reproducer 
>>> further to a state without external includes to STL or protobuf? Then we 
>>> can add the reduced reproducer to the tests to avoid further regressions.
>>
>> That turned out to be quite time-consuming, but I can try nevertheless. I 
>> also asked @rsmith if he could figure out what the problem is. Hopefully, he 
>> can help with the test case, if gets to the bottom of the problem.
>
> I have a reduced reproducer, but I still depends on the internal build setup. 
> I need a bit more time to make the reproducer standalone.

Okay, here's the repro:
F28380583: modules-repro.tar.gz 

And my observations with it:

  $ cat a.cppmap
  module "a" {
export *
module "a.h" {
  export *
  header "a.h"
}
use "c"
  }
  $ cat b.cppmap
  module "b" {
export *
module "b.h" {
  export *
  header "b.h"
}
use "c"
  }
  $ cat c.cppmap
  module "c" {
export *
module "c1.h" {
  export *
  textual header "c1.h"
}
module "c2.h" {
  export *
  textual header "c2.h"
}
module "c3.h" {
  export *
  textual header "c3.h"
}
  }
  $ cat test.cppmap
  module "test" {
export *
use "a"
use "b"
  }
  $ cat a.h
  #ifndef A_H_
  #define A_H_
  
  #include "c1.h"
  
  namespace q {
  template ::value>::type>
  class X {};
  }  // namespace q
  
  #include "c3.h"
  
  #endif  // A_H_
  $ cat b.h
  #ifndef B_H_
  #define B_H_
  
  #include "c2.h"
  
  #endif  // B_H_
  $ cat c1.h
  #ifndef C1_H_
  #define C1_H_
  
  namespace std {
  template 
  struct integral_constant {
static constexpr const _Tp value = __v;
typedef _Tp value_type;
typedef integral_constant type;
constexpr operator value_type() const noexcept { return value; }
constexpr value_type operator()() const noexcept { return value; }
  };
  
  template 
  constexpr const _Tp integral_constant<_Tp, __v>::value;
  
  typedef integral_constant true_type;
  typedef integral_constant false_type;
  
  template 
  struct enable_if {};
  template 
  struct enable_if {
typedef _Tp type;
  };
  }  // namespace std
  
  namespace p {
  template 
  struct P : ::std::false_type {};
  }
  
  #endif  // C1_H_
  $ cat c2.h
  #ifndef C2_H_
  #define C2_H_
  
  #include "c3.h"
  
  enum E {};
  namespace p {
  template <>
  struct P : std::true_type {};
  }  // namespace proto2
  
  inline void f(::util::EnumErrorSpace) {}
  
  #endif  // C2_H_
  $ cat c3.h
  #ifndef C3_H_
  #define C3_H_
  
  #include "c1.h"
  
  namespace util {
  
  template 
  class ErrorSpaceImpl;
  
  class ErrorSpace {
   protected:
template 
struct OdrUse {
  constexpr OdrUse() : b(*addr) {}
  bool& b;
};
template 
struct Registerer {
  static bool register_token;
  static constexpr OdrUse<®ister_token> kRegisterTokenUse{};
};
  
   private:
template 
static const ErrorSpace* GetBase() {
  return 0;
}
  
static bool Register(const ErrorSpace* (*space)()) { return true; }
  };
  
  template 
  bool ErrorSpace::Registerer::register_token =
  Register(&ErrorSpace::GetBase);
  
  template 
  class ErrorSpaceImpl : public ErrorSpace {
   private:
static constexpr Registerer kRegisterer{};
  };
  
  template ::value>::type>
  class EnumErrorSpace : public ErrorSpaceImpl> {};
  
  }  // namespace util
  #endif  // C3_H_
  $ cat test.cc
  #include "a.h"
  #include "b.h"
  
  int main(int, char**) {}
  $ clang -fmodules -fno-implicit-modules -fno-implicit-module-maps 
-fmodule-name=c -fmodule-map-file=c.cppmap -xc++ -c c.cppmap 
-Xclang=-emit-module -o c.pcm
  $ clang -fmodules -fno-implicit-modules -fno-implicit-module-maps 
-fmodule-name=a -fmodule-map-file=a.cppmap -fmodule-map-file=c.cppmap -xc++ -c 
a.cppmap -Xclang=-emit-module -o a.pcm
  $ clang -fmodules -fno-implicit-modules -fno-implicit-module-maps 
-fmodule-name=b -fmodule-map-file=b.cppmap -fmodule-map-file=c.cppmap -xc++ -c 
b.cppmap -Xclang=-emit-module -o b.pcm
  $ clang -fmodules -fno-implicit-modules -fno-implicit-module-maps 
-fmodule-name=test -fmodule-map-file=test.cppmap -fmodule-map-file=a.cppmap 
-fmodule-map-file=b.cppmap -Xclang=-fmodule-file=a.pcm 
-Xclang=-fmodule-file=b.pcm -xc++ -c test.cc -o test.pcm
  In module 'b':
  ./c3.h:44:7: error: 'util::EnumErrorSpace' has different definitions in 
different modules; definition in module 'b.b.h' is here
 44 | class EnumErrorSpace : public ErrorSpaceImpl> {};
|   ^
  ./c3.h:44:7: note: definition in module 'a.a.h' is here
 44 | class 

[PATCH] D155714: [clang] Fix diagnostics for defaulted, implicitly deleted 'operator=='.

2023-07-21 Thread Amirreza Ashouri via Phabricator via cfe-commits
AMP999 added a comment.

I appreciate if you take a look at another patch I sent to address the ci build 
failure when calling `clang/utils/ci/run-buildbot check-format` caused by some 
extra white spaces. 
https://reviews.llvm.org/D155814


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155714

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


[PATCH] D154324: [C++20] [Modules] [ODRHash] Use CanonicalType for base classes

2023-07-21 Thread Alexander Kornienko via Phabricator via cfe-commits
alexfh added a comment.

In D154324#4522541 , @alexfh wrote:

> In D154324#4520096 , @alexfh wrote:
>
>> In D154324#4516964 , @alexfh wrote:
>>
>>> In D154324#4516917 , @ChuanqiXu 
>>> wrote:
>>>
 Maybe we got something wrong with this. I'd like to revert this patch in 
 case it breaks something. But would you like to reduce your reproducer 
 further to a state without external includes to STL or protobuf? Then we 
 can add the reduced reproducer to the tests to avoid further regressions.
>>>
>>> That turned out to be quite time-consuming, but I can try nevertheless. I 
>>> also asked @rsmith if he could figure out what the problem is. Hopefully, 
>>> he can help with the test case, if gets to the bottom of the problem.
>>
>> I have a reduced reproducer, but I still depends on the internal build 
>> setup. I need a bit more time to make the reproducer standalone.
>
> Okay, here's the repro:
> F28380583: modules-repro.tar.gz 
>
> And my observations with it:
>
>   $ cat a.cppmap
>   module "a" {
> export *
> module "a.h" {
>   export *
>   header "a.h"
> }
> use "c"
>   }
>   $ cat b.cppmap
>   module "b" {
> export *
> module "b.h" {
>   export *
>   header "b.h"
> }
> use "c"
>   }
>   $ cat c.cppmap
>   module "c" {
> export *
> module "c1.h" {
>   export *
>   textual header "c1.h"
> }
> module "c2.h" {
>   export *
>   textual header "c2.h"
> }
> module "c3.h" {
>   export *
>   textual header "c3.h"
> }
>   }
>   $ cat test.cppmap
>   module "test" {
> export *
> use "a"
> use "b"
>   }
>   $ cat a.h
>   #ifndef A_H_
>   #define A_H_
>   
>   #include "c1.h"
>   
>   namespace q {
>   template  typename std::enable_if<::p::P::value>::type>
>   class X {};
>   }  // namespace q
>   
>   #include "c3.h"
>   
>   #endif  // A_H_
>   $ cat b.h
>   #ifndef B_H_
>   #define B_H_
>   
>   #include "c2.h"
>   
>   #endif  // B_H_
>   $ cat c1.h
>   #ifndef C1_H_
>   #define C1_H_
>   
>   namespace std {
>   template 
>   struct integral_constant {
> static constexpr const _Tp value = __v;
> typedef _Tp value_type;
> typedef integral_constant type;
> constexpr operator value_type() const noexcept { return value; }
> constexpr value_type operator()() const noexcept { return value; }
>   };
>   
>   template 
>   constexpr const _Tp integral_constant<_Tp, __v>::value;
>   
>   typedef integral_constant true_type;
>   typedef integral_constant false_type;
>   
>   template 
>   struct enable_if {};
>   template 
>   struct enable_if {
> typedef _Tp type;
>   };
>   }  // namespace std
>   
>   namespace p {
>   template 
>   struct P : ::std::false_type {};
>   }
>   
>   #endif  // C1_H_
>   $ cat c2.h
>   #ifndef C2_H_
>   #define C2_H_
>   
>   #include "c3.h"
>   
>   enum E {};
>   namespace p {
>   template <>
>   struct P : std::true_type {};
>   }  // namespace proto2
>   
>   inline void f(::util::EnumErrorSpace) {}
>   
>   #endif  // C2_H_
>   $ cat c3.h
>   #ifndef C3_H_
>   #define C3_H_
>   
>   #include "c1.h"
>   
>   namespace util {
>   
>   template 
>   class ErrorSpaceImpl;
>   
>   class ErrorSpace {
>protected:
> template 
> struct OdrUse {
>   constexpr OdrUse() : b(*addr) {}
>   bool& b;
> };
> template 
> struct Registerer {
>   static bool register_token;
>   static constexpr OdrUse<®ister_token> kRegisterTokenUse{};
> };
>   
>private:
> template 
> static const ErrorSpace* GetBase() {
>   return 0;
> }
>   
> static bool Register(const ErrorSpace* (*space)()) { return true; }
>   };
>   
>   template 
>   bool ErrorSpace::Registerer::register_token =
>   Register(&ErrorSpace::GetBase);
>   
>   template 
>   class ErrorSpaceImpl : public ErrorSpace {
>private:
> static constexpr Registerer kRegisterer{};
>   };
>   
>   template  std::enable_if::value>::type>
>   class EnumErrorSpace : public ErrorSpaceImpl> {};
>   
>   }  // namespace util
>   #endif  // C3_H_
>   $ cat test.cc
>   #include "a.h"
>   #include "b.h"
>   
>   int main(int, char**) {}
>   $ clang -fmodules -fno-implicit-modules -fno-implicit-module-maps 
> -fmodule-name=c -fmodule-map-file=c.cppmap -xc++ -c c.cppmap 
> -Xclang=-emit-module -o c.pcm
>   $ clang -fmodules -fno-implicit-modules -fno-implicit-module-maps 
> -fmodule-name=a -fmodule-map-file=a.cppmap -fmodule-map-file=c.cppmap -xc++ 
> -c a.cppmap -Xclang=-emit-module -o a.pcm
>   $ clang -fmodules -fno-implicit-modules -fno-implicit-module-maps 
> -fmodule-name=b -fmodule-map-file=b.cppmap -fmodule-map-file=c.cppmap -xc++ 
> -c b.cppmap -Xclang=-emit-module -o b.pcm
>   $ clang -fmodules -fno-implicit-modules -fno-i

[PATCH] D154324: [C++20] [Modules] [ODRHash] Use CanonicalType for base classes

2023-07-21 Thread Jonas Hahnfeld via Phabricator via cfe-commits
Hahnfeld added a comment.

In D154324#4522551 , @alexfh wrote:

> BTW, if in a.h I change
>
>   typename std::enable_if<::p::P::value>::type>
>
> to
>
>   typename std::enable_if::value>::type>
>
> Compilation succeeds.

For the fun of it, could you test https://reviews.llvm.org/D153003 on this 
reproducer and also the internal, real code?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154324

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


[PATCH] D155714: [clang] Fix diagnostics for defaulted, implicitly deleted 'operator=='.

2023-07-21 Thread Amirreza Ashouri via Phabricator via cfe-commits
AMP999 added a comment.

By the way I don't have permissions to commit so I'll send you my name and 
email:
Name: Amirreza Ashouri
Email: ar.ashouri...@gmail.com


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155714

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


[PATCH] D155175: [Clang] Fix consteval propagation for aggregates and defaulted constructors

2023-07-21 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

> Should we be marking the init expression/declaration as invalid to force 
> codegen not to run on the expression? So it's not removing the init, but is 
> marking the declaration its attached to as invalid.

We should remove the init from the declaration entirely, the tricky part is 
find the declaration. I did try but so far failed. It's an issue we can track 
and explore separately from this PR


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155175

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


[PATCH] D154093: [clang-format] Break long strings in Verilog

2023-07-21 Thread sstwcw via Phabricator via cfe-commits
sstwcw updated this revision to Diff 542916.
sstwcw added a comment.

- Add comment explaining the replacements


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154093

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/BreakableToken.cpp
  clang/lib/Format/BreakableToken.h
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/WhitespaceManager.cpp
  clang/unittests/Format/FormatTestVerilog.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1802,6 +1802,30 @@
   EXPECT_TOKEN(Tokens[2], tok::l_paren, TT_Unknown);
   EXPECT_TOKEN(Tokens[5], tok::comma, TT_Unknown);
   EXPECT_TOKEN(Tokens[8], tok::r_paren, TT_Unknown);
+
+  // String literals in concatenation.
+  Tokens = Annotate("x = {\"\"};");
+  ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::string_literal, TT_VerilogStringInConcatenation);
+  Tokens = Annotate("x = {\"\", \"\"};");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::string_literal, TT_VerilogStringInConcatenation);
+  EXPECT_TOKEN(Tokens[5], tok::string_literal, TT_VerilogStringInConcatenation);
+  Tokens = Annotate("x = '{{\"\"}};");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::string_literal, TT_VerilogStringInConcatenation);
+  // Cases where the string should not be annotated that type.  Fix the
+  // `TT_Unknown` if needed in the future.
+  Tokens = Annotate("x = {\"\" == \"\"};");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::string_literal, TT_Unknown);
+  EXPECT_TOKEN(Tokens[5], tok::string_literal, TT_Unknown);
+  Tokens = Annotate("x = {(\"\")};");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::string_literal, TT_Unknown);
+  Tokens = Annotate("x = '{\"\"};");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::string_literal, TT_Unknown);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandConstructors) {
Index: clang/unittests/Format/FormatTestVerilog.cpp
===
--- clang/unittests/Format/FormatTestVerilog.cpp
+++ clang/unittests/Format/FormatTestVerilog.cpp
@@ -1155,6 +1155,66 @@
   verifyFormat("{< 0 && Changes[i - 1].OriginalWhitespaceRange.getBegin() ==
- C.OriginalWhitespaceRange.getBegin()) {
-  // Do not generate two replacements for the same location.
-  continue;
+if (i > 0) {
+  auto Last = Changes[i - 1].OriginalWhitespaceRange;
+  auto New = Changes[i].OriginalWhitespaceRange;
+  // Do not generate two replacements for the same location.  As a special
+  // case, it is allowed if there is a replacement for the empty range
+  // between 2 tokens and another non-empty range at the start of the second
+  // token.  We didn't implement logic to combine replacements for 2
+  // consecutive source ranges into a single replacement, because the
+  // program works fine without it.
+  //
+  // We can't eliminate empty original whitespace ranges.  They appear when
+  // 2 tokens have no whitespace in between in the input.  It does not
+  // matter whether whitespace is to be added.  If no whitespace is to be
+  // added, the replacement will be empty, and it gets eliminated after this
+  // step in storeReplacement.  For example, if the input is `foo();`,
+  // there will be a replacement for the range between every consecutive
+  // pair of tokens.
+  //
+  // A replacement at the start of a token can be added by
+  // BreakableVerilogStringLiteral::insertBreak when it adds braces around
+  // the string literal.  Say Verilog code is being formatted and the first
+  // line is to become the next 2 lines.
+  // x("long string");
+  // x({"long ",
+  //"string"});
+  // There will be a replacement for the empty range between the parenthesis
+  // and the string and another replacement for the quote character.  The
+  // replacement for the empty range between the parenthesis and the quote
+  // comes from ContinuationIndenter::addTokenOnCurrentLine when it changes
+  // the original empty range between the parenthesis and the string to
+  // another empty one.  The replacement for the quote character comes from
+  // BreakableVerilogStringLiteral::insertBreak when it adds the brace.  In
+  // the example, the replacement for the empty range is the same as the
+  // original text.  However, eliminating replacements that are same as the
+  // original 

[PATCH] D155175: [Clang] Fix consteval propagation for aggregates and defaulted constructors

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

Changes LGTM as-is, I'm okay with tracking the assertion question separately. 
Please give @Fznamznon a chance to check that her concerns have all been 
addressed before landing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155175

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


[PATCH] D154130: [lit][clang] Avoid realpath on Windows due to MAX_PATH limitations

2023-07-21 Thread Tristan Labelle via Phabricator via cfe-commits
MrTrillian updated this revision to Diff 542922.
MrTrillian retitled this revision from "[lit] Avoid os.path.realpath on Windows 
due to MAX_PATH limitations" to "[lit][clang] Avoid realpath on Windows due to 
MAX_PATH limitations".
MrTrillian edited the summary of this revision.

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

https://reviews.llvm.org/D154130

Files:
  clang/include/clang/Basic/FileManager.h
  clang/lib/Basic/FileManager.cpp
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/test/Lexer/case-insensitive-include-win.c
  llvm/cmake/modules/AddLLVM.cmake
  llvm/docs/CommandGuide/lit.rst
  llvm/docs/TestingGuide.rst
  llvm/utils/lit/lit/LitConfig.py
  llvm/utils/lit/lit/TestRunner.py
  llvm/utils/lit/lit/builtin_commands/diff.py
  llvm/utils/lit/lit/cl_arguments.py
  llvm/utils/lit/lit/discovery.py
  llvm/utils/lit/lit/util.py
  llvm/utils/lit/setup.py
  llvm/utils/lit/tests/Inputs/config-map-discovery/driver.py
  llvm/utils/lit/tests/Inputs/config-map-discovery/lit.alt.cfg
  llvm/utils/lit/tests/Inputs/use-llvm-tool-required/lit.cfg
  llvm/utils/lit/tests/Inputs/use-llvm-tool/lit.cfg
  llvm/utils/lit/tests/lit.cfg
  llvm/utils/llvm-lit/llvm-lit.in

Index: llvm/utils/llvm-lit/llvm-lit.in
===
--- llvm/utils/llvm-lit/llvm-lit.in
+++ llvm/utils/llvm-lit/llvm-lit.in
@@ -8,7 +8,7 @@
 
 def map_config(source_dir, site_config):
 global config_map
-source_dir = os.path.realpath(source_dir)
+source_dir = os.path.abspath(source_dir)
 source_dir = os.path.normcase(source_dir)
 site_config = os.path.normpath(site_config)
 config_map[source_dir] = site_config
Index: llvm/utils/lit/tests/lit.cfg
===
--- llvm/utils/lit/tests/lit.cfg
+++ llvm/utils/lit/tests/lit.cfg
@@ -6,6 +6,7 @@
 import subprocess
 
 import lit.formats
+import lit.util
 from lit.llvm import llvm_config
 
 # Configuration file for the 'lit' test runner.
@@ -35,7 +36,7 @@
 lit_path = os.path.join(llvm_src_root, "utils", "lit")
 else:
 lit_path = os.path.join(config.test_source_root, "..")
-lit_path = os.path.abspath(lit_path)
+lit_path = lit.util.abs_path_preserve_drive(lit_path)
 
 # Required because some tests import the lit module
 if llvm_config:
Index: llvm/utils/lit/tests/Inputs/use-llvm-tool/lit.cfg
===
--- llvm/utils/lit/tests/Inputs/use-llvm-tool/lit.cfg
+++ llvm/utils/lit/tests/Inputs/use-llvm-tool/lit.cfg
@@ -1,4 +1,5 @@
 import lit.formats
+import lit.util
 
 config.name = "use-llvm-tool"
 config.suffixes = [".txt"]
@@ -7,7 +8,7 @@
 config.test_exec_root = None
 import os.path
 
-this_dir = os.path.realpath(os.path.dirname(__file__))
+this_dir = os.path.dirname(lit.util.abs_path_preserve_drive(__file__))
 config.llvm_tools_dir = os.path.join(this_dir, "build")
 import lit.llvm
 
Index: llvm/utils/lit/tests/Inputs/use-llvm-tool-required/lit.cfg
===
--- llvm/utils/lit/tests/Inputs/use-llvm-tool-required/lit.cfg
+++ llvm/utils/lit/tests/Inputs/use-llvm-tool-required/lit.cfg
@@ -1,4 +1,5 @@
 import lit.formats
+import lit.util
 
 config.name = "use-llvm-tool-required"
 config.suffixes = [".txt"]
@@ -7,7 +8,7 @@
 config.test_exec_root = None
 import os.path
 
-config.llvm_tools_dir = os.path.realpath(os.path.dirname(__file__))
+config.llvm_tools_dir = os.path.dirname(lit.util.abs_path_preserve_drive(__file__))
 import lit.llvm
 
 lit.llvm.initialize(lit_config, config)
Index: llvm/utils/lit/tests/Inputs/config-map-discovery/lit.alt.cfg
===
--- llvm/utils/lit/tests/Inputs/config-map-discovery/lit.alt.cfg
+++ llvm/utils/lit/tests/Inputs/config-map-discovery/lit.alt.cfg
@@ -5,5 +5,5 @@
 config.test_format = lit.formats.ShTest()
 
 import os
-config.test_exec_root = os.path.realpath(os.path.dirname(__file__))
+config.test_exec_root = os.path.dirname(lit.util.abs_path_preserve_drive(__file__))
 config.test_source_root = os.path.join(config.test_exec_root, "tests")
Index: llvm/utils/lit/tests/Inputs/config-map-discovery/driver.py
===
--- llvm/utils/lit/tests/Inputs/config-map-discovery/driver.py
+++ llvm/utils/lit/tests/Inputs/config-map-discovery/driver.py
@@ -2,9 +2,7 @@
 import os
 import sys
 
-main_config = sys.argv[1]
-main_config = os.path.realpath(main_config)
-main_config = os.path.normcase(main_config)
+main_config = lit.util.abs_path_preserve_drive(sys.argv[1])
 
 config_map = {main_config: sys.argv[2]}
 builtin_parameters = {"config_map": config_map}
Index: llvm/utils/lit/setup.py
===
--- llvm/utils/lit/setup.py
+++ llvm/utils/lit/setup.py
@@ -7,7 +7,7 @@
 # is nice to allow:
 #   python path/to/setup.py install
 # to work (for scripts,

[PATCH] D154130: [lit][clang] Avoid realpath on Windows due to MAX_PATH limitations

2023-07-21 Thread Tristan Labelle via Phabricator via cfe-commits
MrTrillian added a comment.

In D154130#4516226 , @tahonermann 
wrote:

> It is unclear to me why/when we would ever want the substitute drive 
> expansion; the modified tests aren't very elucidating. My naive expectation 
> is that we effectively want to restore the Python 3.7 behavior.

It took some more investigation to figure out why I still needed realpaths 
there. In the end:

- `case-insensitive-include.win.c`: still needs it, added a comment.
- `relative_module.m`: required a fix in `ExtractAPIConsumer.cpp` to avoid 
calling `getRealPath`.


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

https://reviews.llvm.org/D154130

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


[PATCH] D155396: [Sema][ObjC] Propagating value-dependent errors into BlockExpr

2023-07-21 Thread Ding Fei via Phabricator via cfe-commits
danix800 added inline comments.



Comment at: clang/lib/Sema/SemaStmt.cpp:3736
+BlockDecl *BD = CurBlock->TheDecl;
+if (!BD->isInvalidDecl() && RetValExp && RetValExp->containsErrors())
+  BD->setInvalidDecl();

hokein wrote:
> nit: the `isInvalidDecl` check is not need, we can inline the `RetValExpr` to 
> the above if as well.
> 
> ```
> if (auto *CurBlock = dyn_cast(CurCap); CurBlock && 
> CurCap->HasImplicitReturnType && RetValExp && RetValExp->containsErrors()) 
>   CurBlock->TheDecl->setInvalidDecl();
> ```
Nice, look more cleaner!



Comment at: clang/test/SemaObjC/crash-on-val-dep-block-expr.m:1
+// RUN: %clang_cc1 -fblocks -fsyntax-only -verify %s
+// no crash

hokein wrote:
> can you move these tests to `llvm-project/clang/test/AST/ast-dump-recovery.c`?
No problem. But I noticed `llvm-project/clang/test/AST/ast-dump-recovery.m` 
also exists,
should I put them into this `.m` file instead?


Repository:
  rZORG LLVM Github Zorg

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

https://reviews.llvm.org/D155396

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


[PATCH] D155396: [Sema][ObjC] Propagating value-dependent errors into BlockExpr

2023-07-21 Thread Ding Fei via Phabricator via cfe-commits
danix800 added inline comments.



Comment at: clang/test/SemaObjC/crash-on-val-dep-block-expr.m:1
+// RUN: %clang_cc1 -fblocks -fsyntax-only -verify %s
+// no crash

danix800 wrote:
> hokein wrote:
> > can you move these tests to 
> > `llvm-project/clang/test/AST/ast-dump-recovery.c`?
> No problem. But I noticed `llvm-project/clang/test/AST/ast-dump-recovery.m` 
> also exists,
> should I put them into this `.m` file instead?
I'd prefer `ast-dump-recovery.m` since this file is much shorter. Either file 
needs appending `-fblocks`.


Repository:
  rZORG LLVM Github Zorg

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

https://reviews.llvm.org/D155396

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


[PATCH] D155457: [clang] Skip tautological comparison if the comparison involves the 'size_t' type

2023-07-21 Thread Shivam Gupta via Phabricator via cfe-commits
xgupta added a comment.

Just normal ping, @aaron.ballman, can please take a look, pre-merge checks are 
also passing now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155457

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


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

2023-07-21 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

Since we need to support -O0, we need to be prepared that we may not be able to 
remove all the calls of unsupported functions even though they may never be 
called at run time.

We could simply replace them with traps in the middle end. This should work if 
such functions are not called at run time. The only issue is that if they are 
called at run time, how do we tell users that they used unsupported functions 
and where. A trap does not help since it only crashes the program without 
useful information.

We could emit calls of any unsupported functions as calls of 
`__clang_unsupported(file_name, line_number, function_name)`.

In the middle-end pass where we eliminate functions not referenced by kernels, 
we could emit reports about calls of `__clang_unsupported` under a certain -R 
option. We could turn on that option for `-stdpar` in clang driver.

We can emit printf of file_name, line_number and function_name for the first 
active lane then emit trap for a call of `__clang_unsupported(file_name, 
line_number, function_name)` under an option in the middle-end pass to 
facilitate users debugging their code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155850

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


[PATCH] D155396: [Sema][ObjC] Propagating value-dependent errors into BlockExpr

2023-07-21 Thread Ding Fei via Phabricator via cfe-commits
danix800 updated this revision to Diff 542950.
danix800 added a comment.

1. Remove unnecessary condition & cleanup code
2. Move testcase into correct place.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155396

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/test/AST/ast-dump-recovery.m


Index: clang/test/AST/ast-dump-recovery.m
===
--- clang/test/AST/ast-dump-recovery.m
+++ clang/test/AST/ast-dump-recovery.m
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -frecovery-ast 
-frecovery-ast-type -ast-dump %s | FileCheck -strict-whitespace %s
+// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -frecovery-ast 
-frecovery-ast-type -fblocks -ast-dump %s | FileCheck -strict-whitespace %s
 
 @interface Foo
 - (void)method:(int)n;
@@ -16,3 +16,11 @@
   // CHECK-NEXT:   `-DeclRefExpr {{.*}} 'foo'
   foo.undef;
 }
+
+// CHECK: |-VarDecl {{.*}} 'int (^)()' cinit
+// CHECK: | `-RecoveryExpr {{.*}} ' (^)(void)' contains-errors 
lvalue
+// CHECK: |   `-BlockExpr {{.*}} ' (^)(void)'
+// CHECK: | `-BlockDecl {{.*}} invalid
+int (^a)() = ^() {
+  return c;
+};
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3730,6 +3730,11 @@
   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
 
+  if (auto *CurBlock = dyn_cast(CurCap);
+  CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
+  RetValExp->containsErrors())
+CurBlock->TheDecl->setInvalidDecl();
+
   return Result;
 }
 
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17159,6 +17159,9 @@
   if (getCurFunction())
 getCurFunction()->addBlock(BD);
 
+  if (BD->isInvalidDecl())
+return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
+  {Result}, Result->getType());
   return Result;
 }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -663,6 +663,10 @@
 - Correcly diagnose jumps into statement expressions.
   This ensures the behavior of Clang is consistent with GCC.
   (`#63682 `_)
+- Invalidate BlockDecl with implicit return type, in case any of the return
+  value exprs is invalid. Propagating the error info up by replacing BlockExpr
+  with a RecoveryExpr. This fixes:
+  (`#63863 _`)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/AST/ast-dump-recovery.m
===
--- clang/test/AST/ast-dump-recovery.m
+++ clang/test/AST/ast-dump-recovery.m
@@ -1,4 +1,4 @@
-// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -frecovery-ast -frecovery-ast-type -ast-dump %s | FileCheck -strict-whitespace %s
+// RUN: not %clang_cc1 -triple x86_64-unknown-unknown -frecovery-ast -frecovery-ast-type -fblocks -ast-dump %s | FileCheck -strict-whitespace %s
 
 @interface Foo
 - (void)method:(int)n;
@@ -16,3 +16,11 @@
   // CHECK-NEXT:   `-DeclRefExpr {{.*}} 'foo'
   foo.undef;
 }
+
+// CHECK: |-VarDecl {{.*}} 'int (^)()' cinit
+// CHECK: | `-RecoveryExpr {{.*}} ' (^)(void)' contains-errors lvalue
+// CHECK: |   `-BlockExpr {{.*}} ' (^)(void)'
+// CHECK: | `-BlockDecl {{.*}} invalid
+int (^a)() = ^() {
+  return c;
+};
Index: clang/lib/Sema/SemaStmt.cpp
===
--- clang/lib/Sema/SemaStmt.cpp
+++ clang/lib/Sema/SemaStmt.cpp
@@ -3730,6 +3730,11 @@
   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
 
+  if (auto *CurBlock = dyn_cast(CurCap);
+  CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
+  RetValExp->containsErrors())
+CurBlock->TheDecl->setInvalidDecl();
+
   return Result;
 }
 
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -17159,6 +17159,9 @@
   if (getCurFunction())
 getCurFunction()->addBlock(BD);
 
+  if (BD->isInvalidDecl())
+return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
+  {Result}, Result->getType());
   return Result;
 }
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -663,6 +663,10 @@
 - Correcly diagnose jumps into statem

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

2023-07-21 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added a comment.

In D155064#4514893 , @cor3ntin wrote:

> This looks good to me modulo nitpicks. 
> When you land that, please make an issue on github for the missing narrowing 
> warning, it seems important.
>
> I'll wait before approving in case @aaron.ballman spot things i missed

I've already prepared another patch to fix the narrowing issue. Should I add 
the diff to this patch or open another revision?

FWIW, I believe `const bool c = std::is_constant_evaluated();` this particular 
case should also be diagnosed because it could be a common mistake as was 
mentioned in 
https://github.com/llvm/llvm-project/issues/43760#issuecomment-981022686.


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

https://reviews.llvm.org/D155064

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


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

2023-07-21 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx added a comment.

@yaxunl interesting point - are you worried about cases where due to missing 
inlining / const prop an indirect call site that can be replaced with a direct 
one would remain indirect? I think the problem in that case would actually be 
different, in that possibly reachable functions would not be identified as such 
and would be erroneously removed. I'm not sure there's any case where we'd fail 
to remove a meant to be unreachable function. We can definitely go with the 
`__clang_unsupported` approach, but I think I'd prefer these to be compile time 
errors rather than remarks + runtime `printf`, not in the least because 
`printf` adds some overhead. A way to ensure we don't "miss a spot" might be to 
check after removal for any remaining unsupported builtins, instead of doing it 
during reachability computation (this is coupled with the special naming from 
the prior post).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155850

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


[PATCH] D155848: [clang][analyzer]Fix non-effective taint sanitation

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

Thanks, all good!


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

https://reviews.llvm.org/D155848

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


[clang] 0517a9c - clang/Debian: add Debian Trixie now that it is in unstable

2023-07-21 Thread Sylvestre Ledru via cfe-commits

Author: Sylvestre Ledru
Date: 2023-07-21T18:23:14+02:00
New Revision: 0517a9cae90fafbc36267a81df40ce4eef73eb30

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

LOG: clang/Debian: add Debian Trixie now that it is in unstable

Added: 


Modified: 
clang/lib/Driver/Distro.cpp

Removed: 




diff  --git a/clang/lib/Driver/Distro.cpp b/clang/lib/Driver/Distro.cpp
index e86b589a1cfb5e..6e0087565941ea 100644
--- a/clang/lib/Driver/Distro.cpp
+++ b/clang/lib/Driver/Distro.cpp
@@ -170,6 +170,7 @@ static Distro::DistroType 
DetectDistro(llvm::vfs::FileSystem &VFS) {
 .Case("buster/sid", Distro::DebianBuster)
 .Case("bullseye/sid", Distro::DebianBullseye)
 .Case("bookworm/sid", Distro::DebianBookworm)
+.Case("trixie/sid", Distro::DebianTrixie)
 .Default(Distro::UnknownDistro);
   }
 



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


[PATCH] D155814: Fix the linting problems which causes `clang/utils/ci/run-buildbot check-format` to return 1.

2023-07-21 Thread Amirreza Ashouri via Phabricator via cfe-commits
AMP999 updated this revision to Diff 542972.

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

https://reviews.llvm.org/D155814

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp


Index: clang/lib/Analysis/UnsafeBufferUsage.cpp
===
--- clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1889,11 +1889,11 @@
   const ParmVarDecl *Parm = FD->getParamDecl(i);
 
   if (Parm->isImplicit())
-continue;  
+continue;
   // FIXME: If a parameter has no name, it is unused in the
   // definition. So we could just leave it as it is.
-  if (!Parm->getIdentifier()) 
-   // If a parameter of a function definition has no name:
+  if (!Parm->getIdentifier())
+// If a parameter of a function definition has no name:
 return std::nullopt;
   if (i == ParmIdx)
 // This is our spanified paramter!
@@ -2208,7 +2208,6 @@
UnsafeBufferUsageHandler &Handler,
bool EmitSuggestions) {
   assert(D && D->getBody());
-  
   // We do not want to visit a Lambda expression defined inside a method 
independently.
   // Instead, it should be visited along with the outer method.
   if (const auto *fd = dyn_cast(D)) {


Index: clang/lib/Analysis/UnsafeBufferUsage.cpp
===
--- clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1889,11 +1889,11 @@
   const ParmVarDecl *Parm = FD->getParamDecl(i);
 
   if (Parm->isImplicit())
-continue;  
+continue;
   // FIXME: If a parameter has no name, it is unused in the
   // definition. So we could just leave it as it is.
-  if (!Parm->getIdentifier()) 
-	// If a parameter of a function definition has no name:
+  if (!Parm->getIdentifier())
+// If a parameter of a function definition has no name:
 return std::nullopt;
   if (i == ParmIdx)
 // This is our spanified paramter!
@@ -2208,7 +2208,6 @@
UnsafeBufferUsageHandler &Handler,
bool EmitSuggestions) {
   assert(D && D->getBody());
-  
   // We do not want to visit a Lambda expression defined inside a method independently.
   // Instead, it should be visited along with the outer method.
   if (const auto *fd = dyn_cast(D)) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151587: [clang][ConstantEmitter] have tryEmitPrivate[ForVarInit] try ConstExprEmitter fast-path first

2023-07-21 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers planned changes to this revision.
nickdesaulniers added a comment.

Cool, looks like the libc++ presubmit tests have already spotted some 
unintended changes. Will root cause+fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151587

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


[PATCH] D148654: Modify BoundsSan to improve debuggability

2023-07-21 Thread Oskar Wirga via Phabricator via cfe-commits
oskarwirga added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D148654

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


[PATCH] D155457: [clang] Skip tautological comparison if the comparison involves the 'size_t' type

2023-07-21 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D155457#4513812 , @xgupta wrote:

> In D155457#4511652 , @aaron.ballman 
> wrote:
>
>> In the x86 compilation: `sizeof(std::size_t) < sizeof(uint64_t)` is true, so 
>> we test the other expression; because `Size` is greater than `__SIZE_MAX__` 
>> the function returns false and the second static assertion fails as expected.
>> In the x64 compilation: `sizeof(std::size_t) < sizeof(uint64_t)` is false 
>> (first static assertion fails) so we shouldn't even be evaluating the RHS of 
>> the `&&` to see if it's tautological because it can't contribute to the 
>> expression result, right?
>
> Yes, I agree with both statements but what is odd in current behavior?

It's a false positive -- the tautological bit is diagnosed but it doesn't 
contribute to the result of the expression. The first part of the predicate is 
specifically intended to ensure the second part of the predicate is *not* 
tautological.

> It seems to me uint64_t is unsigned long in , not unsigned long long 
> so the new test added in this patch (with `typedef unsigned long uint64_t`) 
> is now passing.
>
> Behavior when the patch is applied-
>
>   $ ./bin/clang++ -Wall -fsyntax-only test.cpp -m64  -Wtype-limits 
>   test.cpp:8:11: warning: result of comparison 'uint64_t' (aka 'unsigned long 
> long') > 18446744073709551615 is always false 
> [-Wtautological-type-limit-compare]
>   8 |  Size > static_cast(__SIZE_MAX__)) // no-warning
> |   ^ ~~~
>   test.cpp:13:15: error: static assertion failed due to requirement 
> 'sizeof(unsigned long) < sizeof(unsigned long long)': 
>  13 | static_assert(sizeof(std::size_t) < sizeof(uint64_t), "");
> |   ^~
>   test.cpp:13:35: note: expression evaluates to '8 < 8'
>  13 | static_assert(sizeof(std::size_t) < sizeof(uint64_t), "");
> |   ^~
>   1 warning and 1 error generated.
>
>   $ ./bin/clang++ -Wall -fsyntax-only test1.cpp -m64  -Wtype-limits 
>   test1.cpp:12:15: error: static assertion failed due to requirement 
> 'sizeof(unsigned long) < sizeof(unsigned long)': 
>  12 | static_assert(sizeof(std::size_t) < sizeof(uint64_t), "");
> |   ^~
>   test1.cpp:12:35: note: expression evaluates to '8 < 8'
>  12 | static_assert(sizeof(std::size_t) < sizeof(uint64_t), "");
> |   ^~
>   1 error generated.
>
> where test.cpp using wrapper and test1.cpp is using standard headers.




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155457

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


[PATCH] D151587: [clang][ConstantEmitter] have tryEmitPrivate[ForVarInit] try ConstExprEmitter fast-path first

2023-07-21 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:8384-8385
 const MaterializeTemporaryExpr *E) {
+  if (Info.EvalMode == EvalInfo::EM_ConstantFold)
+return false;
+

removing these two lines fixes the following regressions:

Failed Tests (6):
  llvm-libc++-shared.cfg.in :: 
std/algorithms/alg.modifying.operations/alg.fill/ranges.fill.pass.cpp
  llvm-libc++-shared.cfg.in :: 
std/algorithms/alg.modifying.operations/alg.fill/ranges.fill_n.pass.cpp
  llvm-libc++-shared.cfg.in :: 
std/strings/basic.string/string.cons/dtor.pass.cpp
  llvm-libc++-shared.cfg.in :: 
std/strings/basic.string/string.cons/pointer_assignment.pass.cpp
  llvm-libc++-shared.cfg.in :: 
std/strings/basic.string/string.modifiers/string_assign/pointer.pass.cpp
  llvm-libc++-shared.cfg.in :: 
std/utilities/utility/pairs/pairs.pair/assign.pair_like_rv.pass.cpp

The condition probably needs further specification. Let me see if I can work 
out what's missing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151587

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


[PATCH] D155890: [clang-tidy] Add folly::Optional to unchecked-optional-access

2023-07-21 Thread Anton Dukeman via Phabricator via cfe-commits
adukeman added a comment.

In D155890#4522266 , @ymandel wrote:

> In D155890#4521266 , @carlosgalvezp 
> wrote:
>
>> This should be a configuration option, we should not hardcore 
>> project-specific things in the source code.
>
> I agree, but we already are hardcoding specific types -- I think this is a 
> separate (and valid) critique of the design. I'd propose filing an issue on 
> the github tracker and we can follow up there.  I, for one, would love to 
> review such a change but don't have the time to write it.

Is moving these values to config an appropriate task for somebody like me new 
to working on clang-tidy? I'd be happy to merge this and then try the 
transition to a config assuming there's some similar examples I can borrow from 
elsewhere in the codebase.




Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:844-846
+  .CaseOfCFGStmt(
+  isOptionalMemberCallWithName("hasValue"),
+  transferOptionalHasValueCall)

ymandel wrote:
> A few concerns:
> 1. This will allow `hasValue` on *any* of the optional types. While we know 
> that the other types don't have this call, this is bad hygiene. At the least, 
> we should note this potential problem in the comments.
> 2. I don't think its worth duplicating the case above just to change the 
> name, given that the action is identical. Instead, please generalize 
> `isOptionalMemberCallWithName` to take a name matcher, and pass 
> `hasAnyName("has_value", "hasValue")` for this case.  The other calls to 
> `isOptionalMemberCallWithName` will need to be changed to pass just 
> `hasName(...)`.
Sure. I can make that change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155890

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


[PATCH] D151587: [clang][ConstantEmitter] have tryEmitPrivate[ForVarInit] try ConstExprEmitter fast-path first

2023-07-21 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:8384-8385
 const MaterializeTemporaryExpr *E) {
+  if (Info.EvalMode == EvalInfo::EM_ConstantFold)
+return false;
+

nickdesaulniers wrote:
> removing these two lines fixes the following regressions:
> 
> Failed Tests (6):
>   llvm-libc++-shared.cfg.in :: 
> std/algorithms/alg.modifying.operations/alg.fill/ranges.fill.pass.cpp
>   llvm-libc++-shared.cfg.in :: 
> std/algorithms/alg.modifying.operations/alg.fill/ranges.fill_n.pass.cpp
>   llvm-libc++-shared.cfg.in :: 
> std/strings/basic.string/string.cons/dtor.pass.cpp
>   llvm-libc++-shared.cfg.in :: 
> std/strings/basic.string/string.cons/pointer_assignment.pass.cpp
>   llvm-libc++-shared.cfg.in :: 
> std/strings/basic.string/string.modifiers/string_assign/pointer.pass.cpp
>   llvm-libc++-shared.cfg.in :: 
> std/utilities/utility/pairs/pairs.pair/assign.pair_like_rv.pass.cpp
> 
> The condition probably needs further specification. Let me see if I can work 
> out what's missing.
Might need to restore the `E->getStorageDuration() == SD_Static && ` check.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151587

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


[clang] b0bb68f - [test] Unsupport CodeGenCXX/destructors for LLVM_ENABLE_REVERSE_ITERATION builds

2023-07-21 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2023-07-21T10:28:52-07:00
New Revision: b0bb68fd3cb7bfbaf669d25f3149e24638cfb179

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

LOG: [test] Unsupport CodeGenCXX/destructors for LLVM_ENABLE_REVERSE_ITERATION 
builds

_ZN5test312_GLOBAL__N_11CD2Ev and _ZN5test312_GLOBAL__N_11DD0Ev are
swapped in LLVM_ENABLE_REVERSE_ITERATION builds. Unsupport for now.

Added: 


Modified: 
clang/test/CMakeLists.txt
clang/test/CodeGenCXX/destructors.cpp
clang/test/lit.site.cfg.py.in

Removed: 




diff  --git a/clang/test/CMakeLists.txt b/clang/test/CMakeLists.txt
index df73c869490ce5..31b494f39cce57 100644
--- a/clang/test/CMakeLists.txt
+++ b/clang/test/CMakeLists.txt
@@ -14,6 +14,7 @@ llvm_canonicalize_cmake_booleans(
   LLVM_ENABLE_ZSTD
   LLVM_ENABLE_PER_TARGET_RUNTIME_DIR
   LLVM_ENABLE_THREADS
+  LLVM_ENABLE_REVERSE_ITERATION
   LLVM_WITH_Z3
   PPC_LINUX_DEFAULT_IEEELONGDOUBLE
   LLVM_TOOL_LLVM_DRIVER_BUILD

diff  --git a/clang/test/CodeGenCXX/destructors.cpp 
b/clang/test/CodeGenCXX/destructors.cpp
index 99c82ec76989ac..9fc605175f6d01 100644
--- a/clang/test/CodeGenCXX/destructors.cpp
+++ b/clang/test/CodeGenCXX/destructors.cpp
@@ -12,6 +12,7 @@
 // RUN: FileCheck --check-prefixes=CHECK5,CHECK5v11 --input-file=%t2 %s
 // RUN: FileCheck --check-prefix=CHECK6--input-file=%t2 %s
 // REQUIRES: asserts
+// UNSUPPORTED: reverse_iteration
 
 struct A {
   int a;

diff  --git a/clang/test/lit.site.cfg.py.in b/clang/test/lit.site.cfg.py.in
index 89fedd47b00859..ef75770a2c3c9a 100644
--- a/clang/test/lit.site.cfg.py.in
+++ b/clang/test/lit.site.cfg.py.in
@@ -31,6 +31,7 @@ config.clang_examples = @CLANG_BUILD_EXAMPLES@
 config.enable_shared = @ENABLE_SHARED@
 config.enable_backtrace = @ENABLE_BACKTRACES@
 config.enable_threads = @LLVM_ENABLE_THREADS@
+config.reverse_iteration = @LLVM_ENABLE_REVERSE_ITERATION@
 config.host_arch = "@HOST_ARCH@"
 config.python_executable = "@Python3_EXECUTABLE@"
 config.use_z3_solver = lit_config.params.get('USE_Z3_SOLVER', 
"@USE_Z3_SOLVER@")



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


[PATCH] D155890: [clang-tidy] Add folly::Optional to unchecked-optional-access

2023-07-21 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel added a comment.

In D155890#4523243 , @adukeman wrote:

> In D155890#4522266 , @ymandel wrote:
>
>> In D155890#4521266 , 
>> @carlosgalvezp wrote:
>>
>>> This should be a configuration option, we should not hardcore 
>>> project-specific things in the source code.
>>
>> I agree, but we already are hardcoding specific types -- I think this is a 
>> separate (and valid) critique of the design. I'd propose filing an issue on 
>> the github tracker and we can follow up there.  I, for one, would love to 
>> review such a change but don't have the time to write it.
>
> Is moving these values to config an appropriate task for somebody like me new 
> to working on clang-tidy? I'd be happy to merge this and then try the 
> transition to a config assuming there's some similar examples I can borrow 
> from elsewhere in the codebase.

This is one of the most complex clang-tidy checks. So, if you're looking for a 
CT starter task, I wouldn't recommend this particular challenge. That said, I 
think the clang-tidy side will be relatively easy -- CT has a mature config 
system/API.  The harder part (and not CT relevant) is refactoring this code to 
consume that config. It's not terribly complicated but will require a bunch of 
changes and probably some design questions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155890

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


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

2023-07-21 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

> In what regards how to do deferred diagnostics, it think it can be done like 
> this (I crossed streams in my prior reply when discussing this part, so it's 
> actually nonsense): instead of emitting undef here, we can emit a builtin 
> with the same signature, but with the name suffixed with e.g. 
> (`__stdpar_unsupported`) or something similar. Then, when doing the 
> reachability computation later, if we stumble upon a node in the CFG that 
> contains a builtin suffixed with `__stdpar_unsupported` we error out, and can 
> provide nice diagnostics since we'd have the call-chain handy. Thoughts?

Sure, something like that.  If you stick a SourceLocation on it, you can even 
recover the original clang source location.

> We can definitely go with the __clang_unsupported approach, but I think I'd 
> prefer these to be compile time errors rather than remarks + runtime printf, 
> not in the least because printf adds some overhead.

The overhead should be pretty minimal if the code doesn't actually run.

> So TL;DR, I think it would be more complex to do this on the AST and would 
> end up more brittle / less future proof.



> Since we need to support -O0

The biggest downside of working in the backend is that it becomes very hard for 
users to predict what will compile, and will not compile.  Particularly if you 
want to support -O0.  (I was sort of assuming you just wouldn't support -O0.)  
If you work on the AST, fewer constructs will be accepted, but you can actually 
define rules about which constructs will/will not be accepted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155850

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


[PATCH] D155890: [clang-tidy] Add folly::Optional to unchecked-optional-access

2023-07-21 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added a comment.

In D155890#4523243 , @adukeman wrote:

> In D155890#4522266 , @ymandel wrote:
>
>> In D155890#4521266 , 
>> @carlosgalvezp wrote:
>>
>>> This should be a configuration option, we should not hardcore 
>>> project-specific things in the source code.
>>
>> I agree, but we already are hardcoding specific types -- I think this is a 
>> separate (and valid) critique of the design. I'd propose filing an issue on 
>> the github tracker and we can follow up there.  I, for one, would love to 
>> review such a change but don't have the time to write it.
>
> Is moving these values to config an appropriate task for somebody like me new 
> to working on clang-tidy? I'd be happy to merge this and then try the 
> transition to a config assuming there's some similar examples I can borrow 
> from elsewhere in the codebase.

I think it can be a good starter task for a new engineer on the project. 
However, don't underestimate this problem, it will require the code to be 
refactored a little bit. For example, the function `hasOptionalClassName` needs 
restructuring so that it can accept class names from a list. Not a lot of work, 
but it isn't mechanically replacing string literals with a variable either.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155890

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


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

2023-07-21 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D155850#4523051 , @AlexVlx wrote:

> @yaxunl interesting point - are you worried about cases where due to missing 
> inlining / const prop an indirect call site that can be replaced with a 
> direct one would remain indirect? I think the problem in that case would 
> actually be different, in that possibly reachable functions would not be 
> identified as such and would be erroneously removed. I'm not sure there's any 
> case where we'd fail to remove a meant to be unreachable function. We can 
> definitely go with the `__clang_unsupported` approach, but I think I'd prefer 
> these to be compile time errors rather than remarks + runtime `printf`, not 
> in the least because `printf` adds some overhead. A way to ensure we don't 
> "miss a spot" might be to check after removal for any remaining unsupported 
> builtins, instead of doing it during reachability computation (this is 
> coupled with the special naming from the prior post).

For programs having multiple TUs we cannot decide whether an unsupported 
function is used by a kernel during the compilation of a single TU. We can only 
decide that when we have the IR for the whole program. Currently, the HIP 
toolchain uses LTO of lld for multiple TUs, I am not sure whether we can emit 
clang diagnostics from lld. If not, then we need to use remarks. If we are 
confident to remove most unreachable unsupported functions at -O0, we may not 
need to use printf at run time. Remarks at LTO should be sufficient.

  if (foundGPU())
func_use_amdgpu_builtin();
  else
func_use_x64_builtin();



In D155850#4523051 , @AlexVlx wrote:

> @yaxunl interesting point - are you worried about cases where due to missing 
> inlining / const prop an indirect call site that can be replaced with a 
> direct one would remain indirect? I think the problem in that case would 
> actually be different, in that possibly reachable functions would not be 
> identified as such and would be erroneously removed. I'm not sure there's any 
> case where we'd fail to remove a meant to be unreachable function. We can 
> definitely go with the `__clang_unsupported` approach, but I think I'd prefer 
> these to be compile time errors rather than remarks + runtime `printf`, not 
> in the least because `printf` adds some overhead. A way to ensure we don't 
> "miss a spot" might be to check after removal for any remaining unsupported 
> builtins, instead of doing it during reachability computation (this is 
> coupled with the special naming from the prior post).




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155850

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


[PATCH] D155982: Partially revert "clang/HIP: Remove __llvm_amdgcn_* wrapper hacks"

2023-07-21 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm created this revision.
arsenm added a reviewer: yaxunl.
Herald added a project: All.
arsenm requested review of this revision.
Herald added a subscriber: wdng.

Revert part of f407a7399575a6821940973c54754d42e72dd9ce 
.

  

Some of the HIP headers were using the f16 rcp inline, such that it
breaks compiling code against non-top-of-tree headers. Need to wait
for a few HIP releases to expire to fully remove these.

  

Fixes #63981


https://reviews.llvm.org/D155982

Files:
  clang/lib/Headers/__clang_hip_libdevice_declares.h
  clang/test/Headers/__clang_hip_math_deprecated.hip


Index: clang/test/Headers/__clang_hip_math_deprecated.hip
===
--- /dev/null
+++ clang/test/Headers/__clang_hip_math_deprecated.hip
@@ -0,0 +1,29 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang_cc1 -include __clang_hip_runtime_wrapper.h \
+// RUN:   -internal-isystem %S/../../lib/Headers/cuda_wrappers \
+// RUN:   -internal-isystem %S/Inputs/include \
+// RUN:   -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-unknown \
+// RUN:   -target-cpu gfx906 -emit-llvm %s -fcuda-is-device -O1 -o - \
+// RUN:   -D__HIPCC_RTC__ | FileCheck %s
+
+// Test deprecated functions in the header that should be removed eventually
+
+// CHECK-LABEL: @test_rcpf16_wrapper(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[DIV_I:%.*]] = fdiv contract half 0xH3C00, [[X:%.*]]
+// CHECK-NEXT:ret half [[DIV_I]]
+//
+extern "C" __device__ _Float16 test_rcpf16_wrapper(_Float16 x) {
+  return __llvm_amdgcn_rcp_f16(x);
+}
+
+// CHECK-LABEL: @test_rcp2f16_wrapper(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[DIV_I:%.*]] = fdiv contract <2 x half> , [[X:%.*]]
+// CHECK-NEXT:ret <2 x half> [[DIV_I]]
+//
+extern "C" __device__ __2f16 test_rcp2f16_wrapper(__2f16 x) {
+  return __llvm_amdgcn_rcp_2f16(x);
+}
Index: clang/lib/Headers/__clang_hip_libdevice_declares.h
===
--- clang/lib/Headers/__clang_hip_libdevice_declares.h
+++ clang/lib/Headers/__clang_hip_libdevice_declares.h
@@ -279,6 +279,7 @@
 __device__ __attribute__((pure)) _Float16 __ocml_log_f16(_Float16);
 __device__ __attribute__((pure)) _Float16 __ocml_log10_f16(_Float16);
 __device__ __attribute__((pure)) _Float16 __ocml_log2_f16(_Float16);
+
 __device__ __attribute__((const)) _Float16 __ocml_rint_f16(_Float16);
 __device__ __attribute__((const)) _Float16 __ocml_rsqrt_f16(_Float16);
 __device__ _Float16 __ocml_sin_f16(_Float16);
@@ -312,6 +313,18 @@
 __device__ __attribute__((pure)) __2f16 __ocml_log_2f16(__2f16);
 __device__ __attribute__((pure)) __2f16 __ocml_log10_2f16(__2f16);
 __device__ __attribute__((pure)) __2f16 __ocml_log2_2f16(__2f16);
+
+// Deprecated, should be removed when rocm releases using it are no longer
+// relevant.
+__device__ inline _Float16 __llvm_amdgcn_rcp_f16(_Float16 x) {
+  return ((_Float16)1.0f) / x;
+}
+
+__device__ inline __2f16
+__llvm_amdgcn_rcp_2f16(__2f16 __x)
+{
+  return ((__2f16)1.0f) / __x;
+}
 __device__ __attribute__((const)) __2f16 __ocml_rint_2f16(__2f16);
 __device__ __attribute__((const)) __2f16 __ocml_rsqrt_2f16(__2f16);
 __device__ __2f16 __ocml_sin_2f16(__2f16);


Index: clang/test/Headers/__clang_hip_math_deprecated.hip
===
--- /dev/null
+++ clang/test/Headers/__clang_hip_math_deprecated.hip
@@ -0,0 +1,29 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang_cc1 -include __clang_hip_runtime_wrapper.h \
+// RUN:   -internal-isystem %S/../../lib/Headers/cuda_wrappers \
+// RUN:   -internal-isystem %S/Inputs/include \
+// RUN:   -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-unknown \
+// RUN:   -target-cpu gfx906 -emit-llvm %s -fcuda-is-device -O1 -o - \
+// RUN:   -D__HIPCC_RTC__ | FileCheck %s
+
+// Test deprecated functions in the header that should be removed eventually
+
+// CHECK-LABEL: @test_rcpf16_wrapper(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[DIV_I:%.*]] = fdiv contract half 0xH3C00, [[X:%.*]]
+// CHECK-NEXT:ret half [[DIV_I]]
+//
+extern "C" __device__ _Float16 test_rcpf16_wrapper(_Float16 x) {
+  return __llvm_amdgcn_rcp_f16(x);
+}
+
+// CHECK-LABEL: @test_rcp2f16_wrapper(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[DIV_I:%.*]] = fdiv contract <2 x half> , [[X:%.*]]
+// CHECK-NEXT:ret <2 x half> [[DIV_I]]
+//
+extern "C" __device__ __2f16 test_rcp2f16_wrapper(__2f16 x) {
+  return __llvm_amdgcn_rcp_2f16(x);
+}
Index: clang/lib/Headers/__clang_hip_libdevice_declares.h
===
--- clang/lib/Headers/__clang_hip_libdevice_declares.h
+++ clang/lib/Headers/__clang_hip_libdevice_declares.h
@@ -279,6 +279,7 @@
 __device__ __att

[PATCH] D155890: [clang-tidy] Add folly::Optional to unchecked-optional-access

2023-07-21 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

In D155890#4523262 , @gribozavr2 
wrote:

> In D155890#4523243 , @adukeman 
> wrote:
>
>> In D155890#4522266 , @ymandel 
>> wrote:
>>
>>> In D155890#4521266 , 
>>> @carlosgalvezp wrote:
>>>
 This should be a configuration option, we should not hardcore 
 project-specific things in the source code.
>>>
>>> I agree, but we already are hardcoding specific types -- I think this is a 
>>> separate (and valid) critique of the design. I'd propose filing an issue on 
>>> the github tracker and we can follow up there.  I, for one, would love to 
>>> review such a change but don't have the time to write it.
>>
>> Is moving these values to config an appropriate task for somebody like me 
>> new to working on clang-tidy? I'd be happy to merge this and then try the 
>> transition to a config assuming there's some similar examples I can borrow 
>> from elsewhere in the codebase.
>
> I think it can be a good starter task for a new engineer on the project. 
> However, don't underestimate this problem, it will require the code to be 
> refactored a little bit. For example, the function `hasOptionalClassName` 
> needs restructuring so that it can accept class names from a list. Not a lot 
> of work, but it isn't mechanically replacing string literals with a variable 
> either.

Indeed this is not "the standard" CT check, the core is part of Clang so I 
think it'd be good to add reviewers there as well in case this affects other 
parts of the codebase. In that sense it does not seen as trivial as I thought 
to make this user configurable, so perhaps opening a ticket and solve it there 
is a faster way forward.




Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:62
+return N != nullptr && (isTopLevelNamespaceWithName(*N, "base") ||
+isTopLevelNamespaceWithName(*N, "folly"));
   }

If there's no need for `absl` here, why do we need to add `folly`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155890

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


[PATCH] D155890: [clang-tidy] Add folly::Optional to unchecked-optional-access

2023-07-21 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp resigned from this revision.
carlosgalvezp added a comment.
This revision is now accepted and ready to land.

> I think it'd be good to add reviewers there

I realize the CodeOwners for Analysis are already in the list of reviewers, I 
won't interfere then :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155890

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


[PATCH] D155982: Partially revert "clang/HIP: Remove __llvm_amdgcn_* wrapper hacks"

2023-07-21 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: clang/lib/Headers/__clang_hip_libdevice_declares.h:319
+// relevant.
+__device__ inline _Float16 __llvm_amdgcn_rcp_f16(_Float16 x) {
+  return ((_Float16)1.0f) / x;

Can we add the deprecated attribute to urge people not to use them?



Comment at: clang/lib/Headers/__clang_hip_libdevice_declares.h:324
+__device__ inline __2f16
+__llvm_amdgcn_rcp_2f16(__2f16 __x)
+{

same as above


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

https://reviews.llvm.org/D155982

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


[PATCH] D155982: Partially revert "clang/HIP: Remove __llvm_amdgcn_* wrapper hacks"

2023-07-21 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/lib/Headers/__clang_hip_libdevice_declares.h:319
+// relevant.
+__device__ inline _Float16 __llvm_amdgcn_rcp_f16(_Float16 x) {
+  return ((_Float16)1.0f) / x;

yaxunl wrote:
> Can we add the deprecated attribute to urge people not to use them?
I initially added those, but thought it was a bit aggressive to put in always 
included headers. Is there an established practice for deprecating builtin 
header functions?


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

https://reviews.llvm.org/D155982

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


[PATCH] D155982: Partially revert "clang/HIP: Remove __llvm_amdgcn_* wrapper hacks"

2023-07-21 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/lib/Headers/__clang_hip_libdevice_declares.h:319
+// relevant.
+__device__ inline _Float16 __llvm_amdgcn_rcp_f16(_Float16 x) {
+  return ((_Float16)1.0f) / x;

arsenm wrote:
> yaxunl wrote:
> > Can we add the deprecated attribute to urge people not to use them?
> I initially added those, but thought it was a bit aggressive to put in always 
> included headers. Is there an established practice for deprecating builtin 
> header functions?
Is there a hip header version macro I could guard this on?


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

https://reviews.llvm.org/D155982

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


[PATCH] D151587: [clang][ConstantEmitter] have tryEmitPrivate[ForVarInit] try ConstExprEmitter fast-path first

2023-07-21 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers updated this revision to Diff 542990.
nickdesaulniers added a comment.

- restore E->getStorageDuration() == SD_Static check to fix libcxx regressions


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151587

Files:
  clang/lib/AST/Expr.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGExprConstant.cpp
  clang/test/CodeGenCXX/const-init-cxx11.cpp
  clang/test/CodeGenCXX/const-init-cxx1y.cpp
  clang/test/CodeGenOpenCL/amdgpu-nullptr.cl

Index: clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
===
--- clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
+++ clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
@@ -57,7 +57,7 @@
 // CHECK: @fold_generic ={{.*}} local_unnamed_addr addrspace(1) global ptr null, align 8
 generic int *fold_generic = (global int*)(generic float*)(private char*)0;
 
-// CHECK: @fold_priv ={{.*}} local_unnamed_addr addrspace(1) global ptr addrspace(5) addrspacecast (ptr null to ptr addrspace(5)), align 4
+// CHECK: @fold_priv ={{.*}} local_unnamed_addr addrspace(1) global ptr addrspace(5) addrspacecast (ptr addrspace(1) null to ptr addrspace(5)), align 4
 private short *fold_priv = (private short*)(generic int*)(global void*)0;
 
 // CHECK: @fold_priv_arith ={{.*}} local_unnamed_addr addrspace(1) global ptr addrspace(5) inttoptr (i32 9 to ptr addrspace(5)), align 4
Index: clang/test/CodeGenCXX/const-init-cxx1y.cpp
===
--- clang/test/CodeGenCXX/const-init-cxx1y.cpp
+++ clang/test/CodeGenCXX/const-init-cxx1y.cpp
@@ -34,8 +34,8 @@
   // 'c.temporary', not the value as modified by the partial evaluation within
   // the initialization of 'c.x'.
   A c = { 10, (++c.temporary, b.x) };
-  // CHECK: @_ZGRN21ModifyStaticTemporary1cE_ = internal global i32 10
   // CHECK: @_ZN21ModifyStaticTemporary1cE ={{.*}} global {{.*}} zeroinitializer
+  // CHECK: @_ZGRN21ModifyStaticTemporary1cE_ = internal global i32 10
 }
 
 // CHECK: @_ZGRN28VariableTemplateWithConstRef1iIvEE_ = linkonce_odr constant i32 5, align 4
@@ -76,6 +76,19 @@
   S *p = &s<1, 2, 3, 4>;
 }
 
+
+// CHECK: @_ZGR1z_ ={{.*}} global [2 x i32] [i32 10, i32 2]
+// CHECK: @z = global { ptr, i32 } { ptr @_ZGR1z_, i32 10 }
+typedef int v[2];
+struct Z { int &&x, y; };
+Z z = { v{1,2}[0], z.x = 10 };
+
+// CHECK: @_ZGR2z2_ ={{.*}} global %struct.R { i64 10 }
+// @z = {{.}} global %struct.Z { ptr @_ZGR1z_, %struct.R { i64 10 } }
+struct R { mutable long x; };
+struct Z2 { const R &x, y; };
+Z2 z2 = { R{1}, z2.x.x = 10 };
+
 // CHECK: __cxa_atexit({{.*}} @_ZN1BD1Ev, {{.*}} @b
 
 // CHECK: define
Index: clang/test/CodeGenCXX/const-init-cxx11.cpp
===
--- clang/test/CodeGenCXX/const-init-cxx11.cpp
+++ clang/test/CodeGenCXX/const-init-cxx11.cpp
@@ -88,7 +88,7 @@
 
   struct E {};
   struct Test2 : X, X, X, X {};
-  // CHECK: @_ZN9BaseClass2t2E ={{.*}} constant {{.*}} undef
+  // CHECK: @_ZN9BaseClass2t2E ={{.*}} constant {{.*}} zeroinitializer, align 1
   extern constexpr Test2 t2 = Test2();
 
   struct __attribute((packed)) PackedD { double y = 2; };
Index: clang/lib/CodeGen/CGExprConstant.cpp
===
--- clang/lib/CodeGen/CGExprConstant.cpp
+++ clang/lib/CodeGen/CGExprConstant.cpp
@@ -1215,11 +1215,6 @@
 return Visit(E->getSubExpr(), T);
   }
 
-  llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
-QualType T) {
-return Visit(E->getSubExpr(), T);
-  }
-
   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
 assert(CAT && "can't emit array init for non-constant-bound array");
@@ -1322,7 +1317,12 @@
   assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
  "argument to copy ctor is of wrong type");
 
-  return Visit(Arg, Ty);
+  // Look through the temporary; it's just converting the value to an
+  // lvalue to pass it to the constructor.
+  if (auto *MTE = dyn_cast(Arg))
+return Visit(MTE->getSubExpr(), Ty);
+  // Don't try to support arbitrary lvalue-to-rvalue conversions for now.
+  return nullptr;
 }
 
 return CGM.EmitNullConstant(Ty);
@@ -1654,29 +1654,22 @@
   InConstantContext = D.hasConstantInitialization();
 
   QualType destType = D.getType();
+  const Expr *E = D.getInit();
+  assert(E && "No initializer to emit");
+
+  if (!destType->isReferenceType()) {
+QualType nonMemoryDestType = getNonMemoryType(CGM, destType);
+if (llvm::Constant *C = ConstExprEmitter(*this).Visit(const_cast(E),
+  nonMemoryDestType))
+  return emitForMemory(C, destType);
+  }
 
   // Try to emit the initializer.  Note

[PATCH] D155890: [clang-tidy] Add folly::Optional to unchecked-optional-access

2023-07-21 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:62
+return N != nullptr && (isTopLevelNamespaceWithName(*N, "base") ||
+isTopLevelNamespaceWithName(*N, "folly"));
   }

carlosgalvezp wrote:
> If there's no need for `absl` here, why do we need to add `folly`?
This is the branch for `RD.getName() == "Optional"` with a capital "O" because 
`base::Optional`, `folly;:Optional` are spelled with a capital "O".

Abseil provides `absl::optional` and it is handled under `RD.getName() == 
"optional"` together with `std::optional` above.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155890

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


[PATCH] D155984: [Sema][ObjC] Invalidate BlockDecl with invalid ParmVarDecl

2023-07-21 Thread Ding Fei via Phabricator via cfe-commits
danix800 created this revision.
danix800 added reviewers: hokein, aaron.ballman.
danix800 added a project: clang.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
danix800 requested review of this revision.
Herald added a subscriber: cfe-commits.

`BlockDecl` should be invalidated because of its invalid `ParmVarDecl`.

Fixes #1 of https://github.com/llvm/llvm-project/issues/64005


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155984

Files:
  clang/lib/Sema/SemaExpr.cpp
  clang/test/AST/ast-dump-recovery.m


Index: clang/test/AST/ast-dump-recovery.m
===
--- clang/test/AST/ast-dump-recovery.m
+++ clang/test/AST/ast-dump-recovery.m
@@ -16,3 +16,9 @@
   // CHECK-NEXT:   `-DeclRefExpr {{.*}} 'foo'
   foo.undef;
 }
+
+// CHECK:  `-BlockExpr {{.*}} 'int (^)(int, int)'
+// CHECK-NEXT:   `-BlockDecl {{.*}} invalid
+int (^a)(int, int) = ^(int, undefine b) {
+   return 1;
+};
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -16959,6 +16959,9 @@
 
   PushOnScopeChains(AI, CurBlock->TheScope);
 }
+
+if (AI->isInvalidDecl())
+  CurBlock->TheDecl->setInvalidDecl();
   }
 }
 


Index: clang/test/AST/ast-dump-recovery.m
===
--- clang/test/AST/ast-dump-recovery.m
+++ clang/test/AST/ast-dump-recovery.m
@@ -16,3 +16,9 @@
   // CHECK-NEXT:   `-DeclRefExpr {{.*}} 'foo'
   foo.undef;
 }
+
+// CHECK:  `-BlockExpr {{.*}} 'int (^)(int, int)'
+// CHECK-NEXT:   `-BlockDecl {{.*}} invalid
+int (^a)(int, int) = ^(int, undefine b) {
+   return 1;
+};
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -16959,6 +16959,9 @@
 
   PushOnScopeChains(AI, CurBlock->TheScope);
 }
+
+if (AI->isInvalidDecl())
+  CurBlock->TheDecl->setInvalidDecl();
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155794: [OpenMP][OpenMPIRBuilder] Migrate setPropertyExecutionMode() from Clang to OpenMPIRBuilder.

2023-07-21 Thread Raghu via Phabricator via cfe-commits
raghavendhra marked 2 inline comments as done.
raghavendhra added inline comments.



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:4914
+  GVMode->setVisibility(llvm::GlobalVariable::ProtectedVisibility);
+  assert(!GVMode->isDeclaration() &&
+ "Only globals with definition can force usage.");

jplehr wrote:
> Can this assertion ever be not be met? I'm just curious, given that you 
> create that `GVMode` yourself.
Adopted this assert from Clang Codegen addCompilerUsedGlobal() which is called 
inside setPropertyExecutionMode() in CGOpenMPRuntimeGPU.cpp

Actual definition of addCompilerusedGlobal() in CodeGenModule.cpp

void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  assert(!GV->isDeclaration() &&
 "Only globals with definition can force usage.");
  LLVMCompilerUsed.emplace_back(GV);
}


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155794

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


[PATCH] D155985: [clang][ASTDumper] Remove redundant dump of ParmVarDecl

2023-07-21 Thread Ding Fei via Phabricator via cfe-commits
danix800 created this revision.
danix800 added reviewers: hokein, aaron.ballman.
danix800 added a project: clang.
Herald added a subscriber: kristof.beyls.
Herald added a project: All.
danix800 requested review of this revision.
Herald added a subscriber: cfe-commits.

`ParmVarDecl` of `BlockDecl` is unnecessary dumped twice.
Remove this duplication as other `FunctionDecl`s.

Fixes #2 of https://github.com/llvm/llvm-project/issues/64005


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155985

Files:
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/test/AST/ast-dump-decl-json.m
  clang/test/AST/ast-dump-decl.m


Index: clang/test/AST/ast-dump-decl.m
===
--- clang/test/AST/ast-dump-decl.m
+++ clang/test/AST/ast-dump-decl.m
@@ -142,12 +142,17 @@
 
 void TestBlockDecl(int x) {
   ^(int y, ...){ x; };
+  int z;
 }
 // CHECK:  FunctionDecl{{.*}}TestBlockDecl
 // CHECK:  BlockDecl {{.+}}  col:3 variadic
 // CHECK-NEXT:   ParmVarDecl{{.*}} y 'int'
 // CHECK-NEXT:   capture ParmVar{{.*}} 'x' 'int'
 // CHECK-NEXT:   CompoundStmt
+// CHECK-NEXT: ImplicitCastExpr
+// CHECK-NEXT:   DeclRefExpr{{.*}} 'x'
+// CHECK-NEXT: DeclStmt
+// CHECK-NEXT:   VarDecl{{.*}} z
 
 @interface B
 + (int) foo;
Index: clang/test/AST/ast-dump-decl-json.m
===
--- clang/test/AST/ast-dump-decl-json.m
+++ clang/test/AST/ast-dump-decl-json.m
@@ -1924,31 +1924,6 @@
 // CHECK-NEXT:  ]
 // CHECK-NEXT: }
 // CHECK-NEXT:]
-// CHECK-NEXT:   },
-// CHECK-NEXT:   {
-// CHECK-NEXT:"id": "0x{{.*}}",
-// CHECK-NEXT:"kind": "ParmVarDecl",
-// CHECK-NEXT:"loc": {
-// CHECK-NEXT: "offset": {{[0-9]+}},
-// CHECK-NEXT: "col": 9,
-// CHECK-NEXT: "tokLen": 1
-// CHECK-NEXT:},
-// CHECK-NEXT:"range": {
-// CHECK-NEXT: "begin": {
-// CHECK-NEXT:  "offset": {{[0-9]+}},
-// CHECK-NEXT:  "col": 5,
-// CHECK-NEXT:  "tokLen": 3
-// CHECK-NEXT: },
-// CHECK-NEXT: "end": {
-// CHECK-NEXT:  "offset": {{[0-9]+}},
-// CHECK-NEXT:  "col": 9,
-// CHECK-NEXT:  "tokLen": 1
-// CHECK-NEXT: }
-// CHECK-NEXT:},
-// CHECK-NEXT:"name": "y",
-// CHECK-NEXT:"type": {
-// CHECK-NEXT: "qualType": "int"
-// CHECK-NEXT:}
 // CHECK-NEXT:   }
 // CHECK-NEXT:  ]
 // CHECK-NEXT: }
Index: clang/include/clang/AST/ASTNodeTraverser.h
===
--- clang/include/clang/AST/ASTNodeTraverser.h
+++ clang/include/clang/AST/ASTNodeTraverser.h
@@ -104,7 +104,8 @@
 Visit(Comment, Comment);
 
   // Decls within functions are visited by the body.
-  if (!isa(*D) && !isa(*D)) {
+  if (!isa(*D) && !isa(*D) &&
+  !isa(*D)) {
 if (Traversal != TK_AsIs) {
   if (const auto *CTSD = dyn_cast(D)) 
{
 auto SK = CTSD->getSpecializationKind();


Index: clang/test/AST/ast-dump-decl.m
===
--- clang/test/AST/ast-dump-decl.m
+++ clang/test/AST/ast-dump-decl.m
@@ -142,12 +142,17 @@
 
 void TestBlockDecl(int x) {
   ^(int y, ...){ x; };
+  int z;
 }
 // CHECK:  FunctionDecl{{.*}}TestBlockDecl
 // CHECK:  BlockDecl {{.+}}  col:3 variadic
 // CHECK-NEXT:   ParmVarDecl{{.*}} y 'int'
 // CHECK-NEXT:   capture ParmVar{{.*}} 'x' 'int'
 // CHECK-NEXT:   CompoundStmt
+// CHECK-NEXT: ImplicitCastExpr
+// CHECK-NEXT:   DeclRefExpr{{.*}} 'x'
+// CHECK-NEXT: DeclStmt
+// CHECK-NEXT:   VarDecl{{.*}} z
 
 @interface B
 + (int) foo;
Index: clang/test/AST/ast-dump-decl-json.m
===
--- clang/test/AST/ast-dump-decl-json.m
+++ clang/test/AST/ast-dump-decl-json.m
@@ -1924,31 +1924,6 @@
 // CHECK-NEXT:  ]
 // CHECK-NEXT: }
 // CHECK-NEXT:]
-// CHECK-NEXT:   },
-// CHECK-NEXT:   {
-// CHECK-NEXT:"id": "0x{{.*}}",
-// CHECK-NEXT:"kind": "ParmVarDecl",
-// CHECK-NEXT:"loc": {
-// CHECK-NEXT: "offset": {{[0-9]+}},
-// CHECK-NEXT: "col": 9,
-// CHECK-NEXT: "tokLen": 1
-// CHECK-NEXT:},
-// CHECK-NEXT:"range": {
-// CHECK-NEXT: "begin": {
-// CHECK-NEXT:  "offset": {{[0-9]+}},
-// CHECK-NEXT:  "col": 5,
-// CHECK-NEXT:  "tokLen": 3
-// CHECK-NEXT: },
-// CHECK-NEXT: "end": {
-// CHECK-NEXT:  "offset": {{[0-9]+}},
-// CHECK-NEXT:  "col": 9,
-// CHECK-NEXT:  "tokLen": 1
-// CHECK-NEXT: }
-// CHECK-NEXT:},
-// CHECK-NEX

[PATCH] D155457: [clang] Skip tautological comparison if the comparison involves the 'size_t' type

2023-07-21 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

I'm not sure I understand the motivation for this change. Sure, people do that 
but they also might do the same thing for ssize_t, intmax_t, or to compare int 
to int32_t.
I think a better heuristic would be to not emit a warning for any integral (and 
floating point?) type that have the same canonical types (but we probably still 
want one if their non-canonical type if the same)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155457

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


[PATCH] D155794: [OpenMP][OpenMPIRBuilder] Migrate setPropertyExecutionMode() from Clang to OpenMPIRBuilder.

2023-07-21 Thread Raghu via Phabricator via cfe-commits
raghavendhra updated this revision to Diff 542999.
raghavendhra added a comment.

Addressed JP's review comments and rebased.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155794

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/lib/CodeGen/CodeGenModule.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4900,6 +4900,22 @@
   emitBlock(ContBlock, CurFn, /*IsFinished=*/true);
 }
 
+void OpenMPIRBuilder::setPropertyExecutionMode(
+StringRef Name, bool isSPMDMode,
+std::vector &LLVMCompilerUsed) {
+  auto *GVMode = new llvm::GlobalVariable(
+  M, llvm::Type::getInt8Ty(M.getContext()), /*isConstant=*/true,
+  llvm::GlobalValue::WeakAnyLinkage,
+  llvm::ConstantInt::get(llvm::Type::getInt8Ty(M.getContext()),
+ isSPMDMode ? OMP_TGT_EXEC_MODE_SPMD
+: OMP_TGT_EXEC_MODE_GENERIC),
+  Twine(Name, "_exec_mode"));
+  GVMode->setVisibility(llvm::GlobalVariable::ProtectedVisibility);
+  assert(!GVMode->isDeclaration() &&
+ "Only globals with definition can force usage.");
+  LLVMCompilerUsed.emplace_back(GVMode);
+}
+
 bool OpenMPIRBuilder::checkAndEmitFlushAfterAtomic(
 const LocationDescription &Loc, llvm::AtomicOrdering AO, AtomicKind AK) {
   assert(!(AO == AtomicOrdering::NotAtomic ||
Index: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
===
--- llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -1493,6 +1493,21 @@
   void emitIfClause(Value *Cond, BodyGenCallbackTy ThenGen,
 BodyGenCallbackTy ElseGen, InsertPointTy AllocaIP = {});
 
+  /// Create a unique global variable to indicate the execution mode of this
+  /// target region. The execution mode is either 'generic', or 'spmd' depending
+  /// on the target directive. This variable is picked up by the offload library
+  /// to setup the device appropriately before kernel launch. If the execution
+  /// mode is 'generic', the runtime reserves one warp for the master,
+  /// otherwise, all warps participate in parallel work.
+  /// \param Name The symbol name associated with the global.
+  /// \param isSPMDMode is boolean to indicate if the kernel is an SPMD kernel
+  /// or not.
+  /// \param LLVMCompilerUsed List of global values which are required to be
+  /// present in the object file.
+  void
+  setPropertyExecutionMode(StringRef Name, bool isSPMDMode,
+   std::vector &LLVMCompilerUsed);
+
   /// Create the global variable holding the offload mappings information.
   GlobalVariable *createOffloadMaptypes(SmallVectorImpl &Mappings,
 std::string VarName);
Index: clang/lib/CodeGen/CodeGenModule.h
===
--- clang/lib/CodeGen/CodeGenModule.h
+++ clang/lib/CodeGen/CodeGenModule.h
@@ -1005,6 +1005,10 @@
 return EmittedGlobalBlocks.lookup(BE);
   }
 
+  std::vector &getLLVMCompilerUsed() {
+return LLVMCompilerUsed;
+  }
+
   /// Notes that BE's global block is available via Addr. Asserts that BE
   /// isn't already emitted.
   void setAddrOfGlobalBlock(const BlockExpr *BE, llvm::Constant *Addr);
Index: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
===
--- clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -833,24 +833,6 @@
   IsInTTDRegion = false;
 }
 
-// Create a unique global variable to indicate the execution mode of this target
-// region. The execution mode is either 'generic', or 'spmd' depending on the
-// target directive. This variable is picked up by the offload library to setup
-// the device appropriately before kernel launch. If the execution mode is
-// 'generic', the runtime reserves one warp for the master, otherwise, all
-// warps participate in parallel work.
-static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name,
- bool Mode) {
-  auto *GVMode = new llvm::GlobalVariable(
-  CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
-  llvm::GlobalValue::WeakAnyLinkage,
-  llvm::ConstantInt::get(CGM.Int8Ty, Mode ? OMP_TGT_EXEC_MODE_SPMD
-  : OMP_TGT_EXEC_MODE_GENERIC),
-  Twine(Name, "_exec_mode"));
-  GVMode->setVisibility(llvm::GlobalVariable::ProtectedVisibility);
-  CGM.addCompilerUsedGlobal(GVMode);
-}
-
 void CGOpenMPRuntimeGPU::emitTargetOutlinedFunction(
 const OMPExecutableDirective &D, StringRef ParentName,
 

[PATCH] D154382: [ClangRepl] support code completion at a REPL

2023-07-21 Thread Fred Fu via Phabricator via cfe-commits
capfredf updated this revision to Diff 543000.
capfredf added a comment.

changes per @v.g.vassilev's comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154382

Files:
  clang/include/clang/Interpreter/CodeCompletion.h
  clang/include/clang/Interpreter/Interpreter.h
  clang/include/clang/Sema/CodeCompleteConsumer.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Interpreter/CMakeLists.txt
  clang/lib/Interpreter/CodeCompletion.cpp
  clang/lib/Interpreter/ExternalSource.cpp
  clang/lib/Interpreter/ExternalSource.h
  clang/lib/Interpreter/IncrementalParser.cpp
  clang/lib/Interpreter/IncrementalParser.h
  clang/lib/Interpreter/Interpreter.cpp
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/Parser.cpp
  clang/lib/Sema/CodeCompleteConsumer.cpp
  clang/lib/Sema/SemaCodeComplete.cpp
  clang/tools/clang-repl/ClangRepl.cpp
  clang/tools/libclang/CIndexCodeCompletion.cpp
  clang/unittests/Interpreter/CMakeLists.txt
  clang/unittests/Interpreter/CodeCompletionTest.cpp

Index: clang/unittests/Interpreter/CodeCompletionTest.cpp
===
--- /dev/null
+++ clang/unittests/Interpreter/CodeCompletionTest.cpp
@@ -0,0 +1,71 @@
+#include "clang/Interpreter/CodeCompletion.h"
+#include "clang/Interpreter/Interpreter.h"
+
+#include "clang/Frontend/CompilerInstance.h"
+#include "llvm/LineEditor/LineEditor.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+namespace {
+auto CB = clang::IncrementalCompilerBuilder();
+
+static std::unique_ptr createInterpreter() {
+  auto CI = cantFail(CB.CreateCpp());
+  return cantFail(clang::Interpreter::create(std::move(CI)));
+}
+
+TEST(CodeCompletionTest, Sanity) {
+  auto Interp = createInterpreter();
+  if (auto R = Interp->ParseAndExecute("int foo = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  auto Completer = ReplListCompleter(CB, *Interp);
+  std::vector comps =
+  Completer(std::string("f"), 1);
+  EXPECT_EQ((size_t)2, comps.size()); // foo and float
+  EXPECT_EQ(comps[0].TypedText, std::string("oo"));
+}
+
+TEST(CodeCompletionTest, SanityNoneValid) {
+  auto Interp = createInterpreter();
+  if (auto R = Interp->ParseAndExecute("int foo = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  auto Completer = ReplListCompleter(CB, *Interp);
+  std::vector comps =
+  Completer(std::string("babanana"), 8);
+  EXPECT_EQ((size_t)0, comps.size()); // foo and float
+}
+
+TEST(CodeCompletionTest, TwoDecls) {
+  auto Interp = createInterpreter();
+  if (auto R = Interp->ParseAndExecute("int application = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  if (auto R = Interp->ParseAndExecute("int apple = 12;")) {
+consumeError(std::move(R));
+return;
+  }
+  auto Completer = ReplListCompleter(CB, *Interp);
+  std::vector comps =
+  Completer(std::string("app"), 3);
+  EXPECT_EQ((size_t)2, comps.size());
+}
+
+TEST(CodeCompletionTest, CompFunDeclsNoError) {
+  auto Interp = createInterpreter();
+  auto Completer = ReplListCompleter(CB, *Interp);
+  auto Err = llvm::Error::success();
+  std::vector comps =
+  Completer(std::string("void app("), 9, Err);
+  EXPECT_EQ((bool)Err, false);
+}
+
+} // anonymous namespace
Index: clang/unittests/Interpreter/CMakeLists.txt
===
--- clang/unittests/Interpreter/CMakeLists.txt
+++ clang/unittests/Interpreter/CMakeLists.txt
@@ -9,6 +9,7 @@
 add_clang_unittest(ClangReplInterpreterTests
   IncrementalProcessingTest.cpp
   InterpreterTest.cpp
+  CodeCompletionTest.cpp
   )
 target_link_libraries(ClangReplInterpreterTests PUBLIC
   clangAST
Index: clang/tools/libclang/CIndexCodeCompletion.cpp
===
--- clang/tools/libclang/CIndexCodeCompletion.cpp
+++ clang/tools/libclang/CIndexCodeCompletion.cpp
@@ -543,6 +543,7 @@
 case CodeCompletionContext::CCC_PreprocessorExpression:
 case CodeCompletionContext::CCC_PreprocessorDirective:
 case CodeCompletionContext::CCC_Attribute:
+case CodeCompletionContext::CCC_ReplTopLevel:
 case CodeCompletionContext::CCC_TypeQualifiers: {
   //Only Clang results should be accepted, so we'll set all of the other
   //context bits to 0 (i.e. the empty set)
Index: clang/tools/clang-repl/ClangRepl.cpp
===
--- clang/tools/clang-repl/ClangRepl.cpp
+++ clang/tools/clang-repl/ClangRepl.cpp
@@ -13,6 +13,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
+#include "clang/Interpreter/CodeCompletion.h"
 #include "clang/Interpreter/Interpreter.h"
 
 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
@@ -155,8 +156,8

[PATCH] D155544: [AIX][TLS] Add -maix-small-local-exec-tls option.

2023-07-21 Thread Digger Lin via Phabricator via cfe-commits
DiggerLin added inline comments.



Comment at: llvm/test/CodeGen/PowerPC/check-aix-small-local-exec-tls-opt.ll:15
+
+; Make sure that the test was actually compiled successfully after using the
+; -maix-small-local-exec-tls option.

since the patch only add a new option "aix-small-local-exec-tls" , the the 
backend implementation for this option in not in the patch, the behavior  of 
the CodeGen do not change in the patch, I do not think we need the test case. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155544

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


  1   2   3   >