[PATCH] D121576: [clang-format] Don't unwrap lines preceded by line comments

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

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121576

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -19058,6 +19058,14 @@
" {init1, init2, init3, init4}}\n"
"};",
Style);
+  // TODO: Fix the indentations below when this option is fully functional.
+  verifyFormat("int a[][] = {\n"
+   "{\n"
+   " {0, 2}, //\n"
+   " {1, 2}  //\n"
+   "}\n"
+   "};",
+   Style);
   Style.ColumnLimit = 100;
   EXPECT_EQ(
   "test demo[] = {\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -1048,13 +1048,14 @@
   // So in here we want to see if there is a brace that falls
   // on a line that was split. If so on that line we make sure that
   // the spaces in front of the brace are enough.
-  Changes[CellIter->Index].NewlinesBefore = 0;
-  Changes[CellIter->Index].Spaces = 0;
-  for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
-   Next = Next->NextColumnElement) {
+  const auto *Next = CellIter;
+  do {
+const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
+if (Previous && Previous->isNot(TT_LineComment))
+  Changes[Next->Index].NewlinesBefore = 0;
 Changes[Next->Index].Spaces = 0;
-Changes[Next->Index].NewlinesBefore = 0;
-  }
+Next = Next->NextColumnElement;
+  } while (Next);
   // Unless the array is empty, we need the position of all the
   // immediately adjacent cells
   if (CellIter != Cells.begin()) {


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -19058,6 +19058,14 @@
" {init1, init2, init3, init4}}\n"
"};",
Style);
+  // TODO: Fix the indentations below when this option is fully functional.
+  verifyFormat("int a[][] = {\n"
+   "{\n"
+   " {0, 2}, //\n"
+   " {1, 2}  //\n"
+   "}\n"
+   "};",
+   Style);
   Style.ColumnLimit = 100;
   EXPECT_EQ(
   "test demo[] = {\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -1048,13 +1048,14 @@
   // So in here we want to see if there is a brace that falls
   // on a line that was split. If so on that line we make sure that
   // the spaces in front of the brace are enough.
-  Changes[CellIter->Index].NewlinesBefore = 0;
-  Changes[CellIter->Index].Spaces = 0;
-  for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
-   Next = Next->NextColumnElement) {
+  const auto *Next = CellIter;
+  do {
+const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
+if (Previous && Previous->isNot(TT_LineComment))
+  Changes[Next->Index].NewlinesBefore = 0;
 Changes[Next->Index].Spaces = 0;
-Changes[Next->Index].NewlinesBefore = 0;
-  }
+Next = Next->NextColumnElement;
+  } while (Next);
   // Unless the array is empty, we need the position of all the
   // immediately adjacent cells
   if (CellIter != Cells.begin()) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121455: [clang][dataflow] Add support for nested composite bool expressions

2022-03-14 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev updated this revision to Diff 415021.
sgatev marked an inline comment as done.
sgatev added a comment.

Address reviewers' comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121455

Files:
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2060,86 +2060,109 @@
   });
 }
 
-TEST_F(TransferTest, AssignFromBoolConjunction) {
-  std::string Code = R"(
-void target(bool Foo, bool Bar) {
-  bool Baz = (Foo) && (Bar);
+TEST_F(TransferTest, AssignFromCompositeBoolExpression) {
+  {
+std::string Code = R"(
+void target(bool Foo, bool Bar, bool Qux) {
+  bool Baz = (Foo) && (Bar || Qux);
   // [[p]]
 }
   )";
-  runDataflow(
-  Code, [](llvm::ArrayRef<
-   std::pair>>
-   Results,
-   ASTContext &ASTCtx) {
-ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
-const Environment &Env = Results[0].second.Env;
+runDataflow(
+Code, [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+  ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+  const Environment &Env = Results[0].second.Env;
 
-const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
-ASSERT_THAT(FooDecl, NotNull());
+  const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+  ASSERT_THAT(FooDecl, NotNull());
 
-const auto *FooVal =
-dyn_cast_or_null(Env.getValue(*FooDecl, SkipPast::None));
-ASSERT_THAT(FooVal, NotNull());
+  const auto *FooVal = dyn_cast_or_null(
+  Env.getValue(*FooDecl, SkipPast::None));
+  ASSERT_THAT(FooVal, NotNull());
 
-const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
-ASSERT_THAT(BarDecl, NotNull());
+  const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+  ASSERT_THAT(BarDecl, NotNull());
 
-const auto *BarVal =
-dyn_cast_or_null(Env.getValue(*BarDecl, SkipPast::None));
-ASSERT_THAT(BarVal, NotNull());
+  const auto *BarVal = dyn_cast_or_null(
+  Env.getValue(*BarDecl, SkipPast::None));
+  ASSERT_THAT(BarVal, NotNull());
 
-const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
-ASSERT_THAT(BazDecl, NotNull());
+  const ValueDecl *QuxDecl = findValueDecl(ASTCtx, "Qux");
+  ASSERT_THAT(QuxDecl, NotNull());
 
-const auto *BazVal = dyn_cast_or_null(
-Env.getValue(*BazDecl, SkipPast::None));
-ASSERT_THAT(BazVal, NotNull());
+  const auto *QuxVal = dyn_cast_or_null(
+  Env.getValue(*QuxDecl, SkipPast::None));
+  ASSERT_THAT(QuxVal, NotNull());
 
-EXPECT_EQ(&BazVal->getLeftSubValue(), FooVal);
-EXPECT_EQ(&BazVal->getRightSubValue(), BarVal);
-  });
-}
+  const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+  ASSERT_THAT(BazDecl, NotNull());
 
-TEST_F(TransferTest, AssignFromBoolDisjunction) {
-  std::string Code = R"(
-void target(bool Foo, bool Bar) {
-  bool Baz = (Foo) || (Bar);
+  const auto *BazVal = dyn_cast_or_null(
+  Env.getValue(*BazDecl, SkipPast::None));
+  ASSERT_THAT(BazVal, NotNull());
+  EXPECT_EQ(&BazVal->getLeftSubValue(), FooVal);
+
+  const auto *BazRightSubValVal =
+  cast(&BazVal->getRightSubValue());
+  EXPECT_EQ(&BazRightSubValVal->getLeftSubValue(), BarVal);
+  EXPECT_EQ(&BazRightSubValVal->getRightSubValue(), QuxVal);
+});
+  }
+
+  {
+std::string Code = R"(
+void target(bool Foo, bool Bar, bool Qux) {
+  bool Baz = (Foo && Qux) || (Bar);
   // [[p]]
 }
   )";
-  runDataflow(
-  Code, [](llvm::ArrayRef<
-   std::pair>>
-   Results,
-   ASTContext &ASTCtx) {
-ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
-const Environment &Env = Results[0].second.Env;
+runDataflow(
+Code, [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+  ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+  const Environment &Env = Results[0].second.Env;
 
-const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
-ASSERT_THAT(FooDecl, NotNull());
+  const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+  ASSERT_THAT(FooDecl, NotNull());
 
-const auto *FooVal =
-dyn_cast_or_null(Env.getValue(*FooDecl, SkipP

[PATCH] D121549: Define ABI breaking class members correctly

2022-03-14 Thread Daniil Kovalev via Phabricator via cfe-commits
kovdan01 updated this revision to Diff 415022.
kovdan01 added a comment.

Keep private headers untouched


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

https://reviews.llvm.org/D121549

Files:
  llvm/include/llvm/CodeGen/GlobalISel/GISelWorkList.h
  llvm/include/llvm/CodeGen/MachineScheduler.h
  llvm/include/llvm/CodeGen/PBQP/ReductionRules.h
  llvm/include/llvm/CodeGen/RegAllocPBQP.h
  llvm/include/llvm/CodeGen/SelectionDAG.h
  llvm/lib/CodeGen/MachineScheduler.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp

Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
+++ llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
@@ -181,11 +181,11 @@
 /// clearGraphAttrs - Clear all previously defined node graph attributes.
 /// Intended to be used from a debugging tool (eg. gdb).
 void SelectionDAG::clearGraphAttrs() {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs.clear();
 #else
-  errs() << "SelectionDAG::clearGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::clearGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
@@ -193,11 +193,11 @@
 /// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
 ///
 void SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs[N] = Attrs;
 #else
-  errs() << "SelectionDAG::setGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::setGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
@@ -205,7 +205,7 @@
 /// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
 /// Used from getNodeAttributes.
 std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   std::map::const_iterator I =
 NodeGraphAttrs.find(N);
 
@@ -214,8 +214,8 @@
   else
 return "";
 #else
-  errs() << "SelectionDAG::getGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::getGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
   return std::string();
 #endif
 }
@@ -223,11 +223,11 @@
 /// setGraphColor - Convenience for setting node color attribute.
 ///
 void SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs[N] = std::string("color=") + Color;
 #else
-  errs() << "SelectionDAG::setGraphColor is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::setGraphColor is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
Index: llvm/lib/CodeGen/MachineScheduler.cpp
===
--- llvm/lib/CodeGen/MachineScheduler.cpp
+++ llvm/lib/CodeGen/MachineScheduler.cpp
@@ -752,7 +752,7 @@
 }
 
 bool ScheduleDAGMI::checkSchedLimit() {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
 CurrentTop = CurrentBottom;
 return false;
@@ -2006,7 +2006,7 @@
   ReservedCycles.clear();
   ReservedCyclesIndex.clear();
   ResourceGroupSubUnitMasks.clear();
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   // Track the maximum number of stall cycles that could arise either from the
   // latency of a DAG edge or the number of cycles that a processor resource is
   // reserved (SchedBoundary::ReservedCycles).
@@ -2194,7 +2194,7 @@
   unsigned NRCycle, InstanceIdx;
   std::tie(NRCycle, InstanceIdx) = getNextResourceCycle(SC, ResIdx, Cycles);
   if (NRCycle > CurrCycle) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
 MaxObservedStall = std::max(Cycles, MaxObservedStall);
 #endif
 LLVM_DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") "
@@ -2261,7 +2261,7 @@
 unsigned Idx) {
   assert(SU->getInstr() && "Scheduled SUnit must have instr");
 
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   // ReadyCycle was been bumped up to the CurrCycle when this node was
   // scheduled, but CurrCycle may have been eagerly advanced immediately after
   // scheduling, so may now be greater than ReadyCycle.
Index: llvm/include/llvm/CodeGen/SelectionDAG.h
===
--- llvm/include/llvm/CodeGen/SelectionDAG.h
+++ llvm/include/llvm/CodeGen/SelectionDAG.h
@@ -467,7 +467,7 @@
   

[PATCH] D121455: [clang][dataflow] Add support for nested composite bool expressions

2022-03-14 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:516
+// assigned to it.
+Visit(&SubExpr);
+if (auto *Val = dyn_cast_or_null(

xazax.hun wrote:
> Could you elaborate on when would this happen? I'd expect the traversal to 
> always visit the predecessor basic blocks first and within a basic block 
> always visit subexpressions first. So I'd be quite surprised if there is a 
> subexpression we did not visit.
From what I've seen, logic operators influence the structure of the CFG through 
additional basic blocks and terminators, but their sub-expression operators are 
not added directly in the basic blocks.

For example:
```
void test(bool a, bool b, bool c) {
bool d = a && (b || c);
}
```

results in:
```

void test(bool a, bool b, bool c)
 [B5 (ENTRY)]
   Succs (1): B4

 [B1]
   1: [B4.2] && ([B3.2] || [B2.2])
   2: bool d = a && (b || c);
   Preds (3): B2 B3 B4
   Succs (1): B0

 [B2]
   1: c
   2: [B2.1] (ImplicitCastExpr, LValueToRValue, _Bool)
   Preds (1): B3
   Succs (1): B1

 [B3]
   1: b
   2: [B3.1] (ImplicitCastExpr, LValueToRValue, _Bool)
   T: [B3.2] || ...
   Preds (1): B4
   Succs (2): B1 B2

 [B4]
   1: a
   2: [B4.1] (ImplicitCastExpr, LValueToRValue, _Bool)
   T: [B4.2] && ...
   Preds (1): B5
   Succs (2): B3 B1

 [B0 (EXIT)]
   Preds (1): B1
```

So, when we evaluate `a && (b || c)` in `B1`, the sub-expression `b || c` has 
not been evaluated yet. I updated the comment in the code to make that more 
clear.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121455

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


[PATCH] D121549: Define ABI breaking class members correctly

2022-03-14 Thread Daniil Kovalev via Phabricator via cfe-commits
kovdan01 marked an inline comment as done.
kovdan01 added inline comments.



Comment at: mlir/lib/Target/SPIRV/Deserialization/Deserializer.h:601
 
+  // TODO: place logger under #if LLVM_ENABLE_ABI_BREAKING_CHECKS
 #ifndef NDEBUG

mehdi_amini wrote:
> This is a private header (you're in the `lib` directory and not in the 
> `include` directory)
> 
> Same for the SystemZ one above I believe.
Makes sense, fixed, thanks!


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

https://reviews.llvm.org/D121549

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


[PATCH] D121576: [clang-format] Don't unwrap lines preceded by line comments

2022-03-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121576

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


[PATCH] D121549: Define ABI breaking class members correctly

2022-03-14 Thread Mehdi AMINI via Phabricator via cfe-commits
mehdi_amini accepted this revision.
mehdi_amini added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D121549

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


[PATCH] D121578: [RISCV][NFC] Add tests to address invalid arch dependencies.

2022-03-14 Thread Zakk Chen via Phabricator via cfe-commits
khchen created this revision.
khchen added reviewers: craig.topper, kito-cheng.
Herald added subscribers: VincentWu, luke957, achieveartificialintelligence, 
vkmr, frasercrmck, evandro, luismarques, apazos, sameer.abuasal, s.egerton, 
Jim, benna, psnobl, jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, 
edward-jones, zzheng, jrtc27, niosHD, sabuasal, simoncook, johnrusso, rbar, asb.
Herald added a project: All.
khchen requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, eopXD.
Herald added a project: clang.

Improve test converage.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121578

Files:
  clang/test/Driver/riscv-arch.c


Index: clang/test/Driver/riscv-arch.c
===
--- clang/test/Driver/riscv-arch.c
+++ clang/test/Driver/riscv-arch.c
@@ -224,6 +224,31 @@
 // RV32-ORDER: error: invalid arch name 'rv32imcq',
 // RV32-ORDER: standard user-level extension not given in canonical order 'q'
 
+// RUN: %clang -target riscv32-unknown-elf -march=rv64e -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV64-EER %s
+// RV64-EER: error: invalid arch name 'rv64e',
+// RV64-EER: standard user-level extension 'e' requires 'rv32'
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32id -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-DER %s
+// RV32-DER: error: invalid arch name 'rv32id',
+// RV32-DER: d requires f extension to also be specified
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32izve32f -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZVE32F-ER %s
+// RV32-ZVE32F-ER: error: invalid arch name 'rv32izve32f',
+// RV32-ZVE32F-ER: zve32f requires f or zfinx extension to also be specified
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32ifzve64d -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZVE64D-ER %s
+// RV32-ZVE64D-ER: error: invalid arch name 'rv32ifzve64d',
+// RV32-ZVE64D-ER: zve64d requires d or zdinx extension to also be specified
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32izvl64b -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZVL64B-ER %s
+// RV32-ZVL64B-ER: error: invalid arch name 'rv32izvl64b',
+// RV32-ZVL64B-ER: zvl*b requires v or zve* extension to also be specified
+
 // RUN: %clang -target riscv32-unknown-elf -march=rv32imw -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-STD-INVAL %s
 // RV32-STD-INVAL: error: invalid arch name 'rv32imw',
@@ -376,6 +401,18 @@
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV64-TARGET %s
 // RV64-TARGET: "-triple" "riscv64-unknown-unknown-elf"
 
+// RUN: %clang -target riscv32-unknown-elf -march=rv32ifzfh01p0 -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZFH %s
+// RUN: %clang -target riscv32-unknown-elf -march=rv32ifzfh -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZFH %s
+// RV32-ZFH: "-target-feature" "+zfh"
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32ifzfhmin01p0 -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZFHMIN %s
+// RUN: %clang -target riscv32-unknown-elf -march=rv32ifzfhmin -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZFHMIN %s
+// RV32-ZFHMIN: "-target-feature" "+zfhmin"
+
 // RUN: %clang -target riscv32-unknown-elf -march=rv32izbb1p0 -### %s \
 // RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZBB %s
 // RUN: %clang -target riscv32-unknown-elf -march=rv32izbb -### %s \


Index: clang/test/Driver/riscv-arch.c
===
--- clang/test/Driver/riscv-arch.c
+++ clang/test/Driver/riscv-arch.c
@@ -224,6 +224,31 @@
 // RV32-ORDER: error: invalid arch name 'rv32imcq',
 // RV32-ORDER: standard user-level extension not given in canonical order 'q'
 
+// RUN: %clang -target riscv32-unknown-elf -march=rv64e -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV64-EER %s
+// RV64-EER: error: invalid arch name 'rv64e',
+// RV64-EER: standard user-level extension 'e' requires 'rv32'
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32id -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-DER %s
+// RV32-DER: error: invalid arch name 'rv32id',
+// RV32-DER: d requires f extension to also be specified
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32izve32f -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZVE32F-ER %s
+// RV32-ZVE32F-ER: error: invalid arch name 'rv32izve32f',
+// RV32-ZVE32F-ER: zve32f requires f or zfinx extension to also be specified
+
+// RUN: %clang -target riscv32-unknown-elf -march=rv32ifzve64d -### %s \
+// RUN: -fsyntax-only 2>&1 | FileCheck -check-prefix=RV32-ZVE64D-ER %s
+// RV32-ZVE64D-ER: error: invalid arch name 'rv32ifzve64d',
+// RV32-ZVE64D-ER: zve64d requires d or zdinx extension to also be specified
+
+// RUN: %clang -

[PATCH] D121475: [Clang][Sema] Avoid crashing for `__builtin_memcpy_inline` with an array argument

2022-03-14 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet accepted this revision.
gchatelet added a comment.
This revision is now accepted and ready to land.

Thx for the patch, please address the comment before submitting.




Comment at: clang/lib/Sema/SemaChecking.cpp:1946-1953
+auto ArgArrayConversion = [&](unsigned Arg) {
+  ExprResult ArgExpr =
+  DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg));
+  if (ArgExpr.isInvalid())
+return true;
+  TheCall->setArg(Arg, ArgExpr.get());
+  return false;

[nit] It's unclear looking at the function name that it's failing when 
returning `true` - one has to read the code to understand. It may be fine now 
but could become messy with time and refactoring.
Either change the lambda's name `FailArgArrayConversion` or negate everything.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121475

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


[PATCH] D121576: [clang-format] Don't unwrap lines preceded by line comments

2022-03-14 Thread Owen Pan via Phabricator via cfe-commits
owenpan updated this revision to Diff 415031.
owenpan added a comment.

Reset the `Spaces` of the closing brace only if it can be unwrapped.


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

https://reviews.llvm.org/D121576

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


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -19058,6 +19058,14 @@
" {init1, init2, init3, init4}}\n"
"};",
Style);
+  // TODO: Fix the indentations below when this option is fully functional.
+  verifyFormat("int a[][] = {\n"
+   "{\n"
+   " {0, 2}, //\n"
+   " {1, 2}  //\n"
+   "}\n"
+   "};",
+   Style);
   Style.ColumnLimit = 100;
   EXPECT_EQ(
   "test demo[] = {\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -1048,13 +1048,15 @@
   // So in here we want to see if there is a brace that falls
   // on a line that was split. If so on that line we make sure that
   // the spaces in front of the brace are enough.
-  Changes[CellIter->Index].NewlinesBefore = 0;
-  Changes[CellIter->Index].Spaces = 0;
-  for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
-   Next = Next->NextColumnElement) {
-Changes[Next->Index].Spaces = 0;
-Changes[Next->Index].NewlinesBefore = 0;
-  }
+  const auto *Next = CellIter;
+  do {
+const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
+if (Previous && Previous->isNot(TT_LineComment)) {
+  Changes[Next->Index].Spaces = 0;
+  Changes[Next->Index].NewlinesBefore = 0;
+}
+Next = Next->NextColumnElement;
+  } while (Next);
   // Unless the array is empty, we need the position of all the
   // immediately adjacent cells
   if (CellIter != Cells.begin()) {


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -19058,6 +19058,14 @@
" {init1, init2, init3, init4}}\n"
"};",
Style);
+  // TODO: Fix the indentations below when this option is fully functional.
+  verifyFormat("int a[][] = {\n"
+   "{\n"
+   " {0, 2}, //\n"
+   " {1, 2}  //\n"
+   "}\n"
+   "};",
+   Style);
   Style.ColumnLimit = 100;
   EXPECT_EQ(
   "test demo[] = {\n"
Index: clang/lib/Format/WhitespaceManager.cpp
===
--- clang/lib/Format/WhitespaceManager.cpp
+++ clang/lib/Format/WhitespaceManager.cpp
@@ -1048,13 +1048,15 @@
   // So in here we want to see if there is a brace that falls
   // on a line that was split. If so on that line we make sure that
   // the spaces in front of the brace are enough.
-  Changes[CellIter->Index].NewlinesBefore = 0;
-  Changes[CellIter->Index].Spaces = 0;
-  for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
-   Next = Next->NextColumnElement) {
-Changes[Next->Index].Spaces = 0;
-Changes[Next->Index].NewlinesBefore = 0;
-  }
+  const auto *Next = CellIter;
+  do {
+const FormatToken *Previous = Changes[Next->Index].Tok->Previous;
+if (Previous && Previous->isNot(TT_LineComment)) {
+  Changes[Next->Index].Spaces = 0;
+  Changes[Next->Index].NewlinesBefore = 0;
+}
+Next = Next->NextColumnElement;
+  } while (Next);
   // Unless the array is empty, we need the position of all the
   // immediately adjacent cells
   if (CellIter != Cells.begin()) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D111400: [Clang] Implement P2242R3

2022-03-14 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin updated this revision to Diff 415041.
cor3ntin marked 2 inline comments as done.
cor3ntin added a comment.

Address Hubert's feedback

- Add a diagnostic during constant evaluation when evaluating the declaration 
of a variable with non-automatic storage duration
- Add more tests
- Restore incorrect removed test (not sure what happened there!)
- Fix some tests
- Reorganize some tests to be in the correct file


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111400

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Frontend/InitPreprocessor.cpp
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/dtor.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3-2b.cpp
  clang/test/CXX/dcl.dcl/dcl.spec/dcl.constexpr/p3.cpp
  clang/test/Lexer/cxx-features.cpp
  clang/test/SemaCXX/constant-expression-cxx14.cpp
  clang/test/SemaCXX/constant-expression-cxx2b.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1361,7 +1361,7 @@
 
   Non-literal variables (and labels and gotos) in constexpr functions
   https://wg21.link/P2242R3";>P2242R3
-  No
+  Clang 15
 
 
   Character encoding of diagnostic text
Index: clang/test/SemaCXX/constant-expression-cxx2b.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/constant-expression-cxx2b.cpp
@@ -0,0 +1,84 @@
+// RUN: %clang_cc1 -std=c++2b -fsyntax-only -verify %s -fcxx-exceptions -triple=x86_64-linux-gnu -Wpre-c++2b-compat
+
+constexpr int f(int n) {  // expected-error {{constexpr function never produces a constant expression}}
+  static const int m = n; // expected-warning {{definition of a static variable in a constexpr function is incompatible with C++ standards before C++2b}} \
+  // expected-note {{control flows through the declaration of a static variable}}
+  return m;
+
+}
+constexpr int g(int n) {//  expected-error {{constexpr function never produces a constant expression}}
+  thread_local const int m = n; //  expected-warning {{definition of a thread_local variable in a constexpr function is incompatible with C++ standards before C++2b}} \
+// expected-note {{control flows through the declaration of a thread_local variable}}
+  return m;
+}
+
+constexpr int h(int n) {  // expected-error {{constexpr function never produces a constant expression}}
+  static const int m = n; // expected-warning {{definition of a static variable in a constexpr function is incompatible with C++ standards before C++2b}} \
+  // expected-note {{control flows through the declaration of a static variable}}
+  return &m-&m;
+
+}
+constexpr int i(int n) {//  expected-error {{constexpr function never produces a constant expression}}
+  thread_local const int m = n; //  expected-warning {{definition of a thread_local variable in a constexpr function is incompatible with C++ standards before C++2b}} \
+// expected-note {{control flows through the declaration of a thread_local variable}}
+  return &m-&m;
+}
+
+
+
+constexpr int j(int n) {
+  if (!n)
+return 0;
+  static const int m = n; // expected-warning{{definition of a static variable in a constexpr function is incompatible with C++ standards before C++2b}}
+  return m;
+}
+
+constexpr int k(int n) {
+  if (!n)
+return 0;
+  thread_local const int m = n; // expected-warning{{definition of a thread_local variable in a constexpr function is incompatible with C++ standards before C++2b}} \
+
+  return m;
+}
+
+constexpr int j_evaluated(int n) {
+  if (!n)
+return 0;
+  static const int m = n; // expected-warning{{definition of a static variable in a constexpr function is incompatible with C++ standards before C++2b}} \
+  // expected-note {{control flows through the declaration of a static variable}}
+  return m;
+}
+
+constexpr int je = j_evaluated(1); // expected-error {{constexpr variable 'je' must be initialized by a constant expression}}  \
+   // expected-note {{in call}}
+
+constexpr int k_evaluated(int n) {
+  if (!n)
+return 0;
+  thread_local const int m = n; // expected-warning{{definition of a thread_local variable in a constexpr function is incompatible with C++ standards before C++2b}} \
+// expected-note {{control flows through the declaration of a thread_local variable}}
+
+  return m;
+}
+
+constexpr int ke = k_evaluated(1); //expected-error {{constexpr variable 'ke' must be initialized by a constant expression}} \
+ 

[PATCH] D121427: [lit] add lit_config.substitute to interpolate lit_config.params

2022-03-14 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.

This patch is definitely an improvement.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121427

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


[PATCH] D88905: [Clang] Allow "ext_vector_type" applied to Booleans

2022-03-14 Thread Simon Moll via Phabricator via cfe-commits
simoll added a comment.

In D88905#3375676 , @aaron.ballman 
wrote:

> In D88905#3362347 , @kaz7 wrote:
>
>> At the beginning, this implementation extends `vector_type` attribute which 
>> is GCC's attribute.  So, this may cause future conflicts with GCC when they 
>> extend it.  But, now this patch uses it's own `ext_vector_type` attribute.  
>> So, basically this modification is safe against to the C/C++ future 
>> extension and the GCC future extension, in my honest opinion.
>>
>> Is it OK to accept this patch?  Or is there anything we need to consider?  I 
>> understand that this is a language extension, so it not easy to say OK...  
>> But, this patch spent 1 year and a half almost.
>
> At a minimum, I think the patch needs to be rebased onto the current trunk. 
> However, I don't know of a reason why this patch cannot proceed.

It's great to get feedback on this patch! I am rebasing right now.

> I'd be curious whether the codegen for ext_vector_type of N bools is the same 
> as for N `unsigned _BitInt(1)` (naively, I'd expect them to be equivalent).

bool vectors are for ``-typed masks in predicated SIMD code - _BitInt 
is for `iN` integer arithmetic.
For either type, the memory representation is packed bits with possible 
differences in alignment, padding.
So, the difference is in the intended usage and what kind of execution 
units/operands we expect to live the data near by.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88905

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


[PATCH] D121576: [clang-format] Don't unwrap lines preceded by line comments

2022-03-14 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay accepted this revision.
MyDeveloperDay added a comment.

I'm wondering if the presence of the comment would impact the CellCount, I 
might go back and add some more unit tests for the "non rectangular" change I 
made.

So this fixes the "}" going up onto the comment line, but not the indentation 
right?


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

https://reviews.llvm.org/D121576

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


[clang] 2507e0a - [clang-format] Clean up UnwrappedLineParser::parseRecord. NFC.

2022-03-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-14T11:59:52+01:00
New Revision: 2507e0a257991fd46bd847c8fa0964bc70891add

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

LOG: [clang-format] Clean up UnwrappedLineParser::parseRecord. NFC.

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 47e794c7b1ca6..b03296c7e02d9 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3511,7 +3511,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   // (this would still leave us with an ambiguity between template function
   // and class declarations).
   if (FormatTok->isOneOf(tok::colon, tok::less)) {
-while (!eof()) {
+do {
   if (FormatTok->is(tok::l_brace)) {
 calculateBraceTypes(/*ExpectClassBody=*/true);
 if (!tryToParseBracedList())
@@ -3525,6 +3525,9 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   // it was probably a pointer to an array: int (*)[].
   if (!tryToParseLambda())
 break;
+} else {
+  parseSquare();
+  continue;
 }
   }
   if (FormatTok->is(tok::semi))
@@ -3536,7 +3539,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 break;
   }
   nextToken();
-}
+} while (!eof());
   }
 
   auto GetBraceType = [](const FormatToken &RecordTok) {



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


[PATCH] D121549: Define ABI breaking class members correctly

2022-03-14 Thread Daniil Kovalev via Phabricator via cfe-commits
kovdan01 updated this revision to Diff 415049.
kovdan01 marked an inline comment as done.
kovdan01 removed projects: MLIR, clang.
kovdan01 added a comment.

Fix formatting problems found on pre-merge checks


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

https://reviews.llvm.org/D121549

Files:
  llvm/include/llvm/CodeGen/GlobalISel/GISelWorkList.h
  llvm/include/llvm/CodeGen/MachineScheduler.h
  llvm/include/llvm/CodeGen/PBQP/ReductionRules.h
  llvm/include/llvm/CodeGen/RegAllocPBQP.h
  llvm/include/llvm/CodeGen/SelectionDAG.h
  llvm/lib/CodeGen/MachineScheduler.cpp
  llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp

Index: llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
+++ llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp
@@ -181,11 +181,11 @@
 /// clearGraphAttrs - Clear all previously defined node graph attributes.
 /// Intended to be used from a debugging tool (eg. gdb).
 void SelectionDAG::clearGraphAttrs() {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs.clear();
 #else
-  errs() << "SelectionDAG::clearGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::clearGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
@@ -193,11 +193,11 @@
 /// setGraphAttrs - Set graph attributes for a node. (eg. "color=red".)
 ///
 void SelectionDAG::setGraphAttrs(const SDNode *N, const char *Attrs) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs[N] = Attrs;
 #else
-  errs() << "SelectionDAG::setGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::setGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
@@ -205,7 +205,7 @@
 /// getGraphAttrs - Get graph attributes for a node. (eg. "color=red".)
 /// Used from getNodeAttributes.
 std::string SelectionDAG::getGraphAttrs(const SDNode *N) const {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   std::map::const_iterator I =
 NodeGraphAttrs.find(N);
 
@@ -214,8 +214,8 @@
   else
 return "";
 #else
-  errs() << "SelectionDAG::getGraphAttrs is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::getGraphAttrs is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
   return std::string();
 #endif
 }
@@ -223,11 +223,11 @@
 /// setGraphColor - Convenience for setting node color attribute.
 ///
 void SelectionDAG::setGraphColor(const SDNode *N, const char *Color) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   NodeGraphAttrs[N] = std::string("color=") + Color;
 #else
-  errs() << "SelectionDAG::setGraphColor is only available in debug builds"
- << " on systems with Graphviz or gv!\n";
+  errs() << "SelectionDAG::setGraphColor is only available in builds with "
+ << "ABI breaking checks enabled on systems with Graphviz or gv!\n";
 #endif
 }
 
Index: llvm/lib/CodeGen/MachineScheduler.cpp
===
--- llvm/lib/CodeGen/MachineScheduler.cpp
+++ llvm/lib/CodeGen/MachineScheduler.cpp
@@ -752,7 +752,7 @@
 }
 
 bool ScheduleDAGMI::checkSchedLimit() {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
 CurrentTop = CurrentBottom;
 return false;
@@ -2006,7 +2006,7 @@
   ReservedCycles.clear();
   ReservedCyclesIndex.clear();
   ResourceGroupSubUnitMasks.clear();
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   // Track the maximum number of stall cycles that could arise either from the
   // latency of a DAG edge or the number of cycles that a processor resource is
   // reserved (SchedBoundary::ReservedCycles).
@@ -2194,7 +2194,7 @@
   unsigned NRCycle, InstanceIdx;
   std::tie(NRCycle, InstanceIdx) = getNextResourceCycle(SC, ResIdx, Cycles);
   if (NRCycle > CurrCycle) {
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
 MaxObservedStall = std::max(Cycles, MaxObservedStall);
 #endif
 LLVM_DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") "
@@ -2261,7 +2261,7 @@
 unsigned Idx) {
   assert(SU->getInstr() && "Scheduled SUnit must have instr");
 
-#ifndef NDEBUG
+#if LLVM_ENABLE_ABI_BREAKING_CHECKS
   // ReadyCycle was been bumped up to the CurrCycle when this node was
   // scheduled, but CurrCycle may have been eagerly advanced immediately after
   // scheduling, so may now be greater than ReadyCycle.
Index: llvm/include/llvm/CodeGen/SelectionDAG.h
===
--- llvm/in

[PATCH] D121584: [clang-format] Correctly recognize arrays in template parameter list.

2022-03-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius created this revision.
curdeius added reviewers: MyDeveloperDay, HazardyKnusperkeks, owenpan.
Herald added a project: All.
curdeius requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121584

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -98,6 +98,20 @@
   auto Tokens = annotate("struct S {};");
   EXPECT_EQ(Tokens.size(), 6u) << Tokens;
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S {};");
+  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S {};");
+  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUnions) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1935,6 +1935,11 @@
   if (!tryToParseLambdaIntroducer())
 return false;
 
+  // `[something] >` is not a lambda, but an array type in a template parameter
+  // list.
+  if (FormatTok->is(tok::greater))
+return false;
+
   bool SeenArrow = false;
   bool InTemplateParameterList = false;
 
@@ -3524,7 +3529,7 @@
   // Don't try parsing a lambda if we had a closing parenthesis before,
   // it was probably a pointer to an array: int (*)[].
   if (!tryToParseLambda())
-break;
+continue;
 } else {
   parseSquare();
   continue;


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -98,6 +98,20 @@
   auto Tokens = annotate("struct S {};");
   EXPECT_EQ(Tokens.size(), 6u) << Tokens;
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S {};");
+  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
+
+  Tokens = annotate("template  struct S {};");
+  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
+  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUnions) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1935,6 +1935,11 @@
   if (!tryToParseLambdaIntroducer())
 return false;
 
+  // `[something] >` is not a lambda, but an array type in a template parameter
+  // list.
+  if (FormatTok->is(tok::greater))
+return false;
+
   bool SeenArrow = false;
   bool InTemplateParameterList = false;
 
@@ -3524,7 +3529,7 @@
   // Don't try parsing a lambda if we had a closing parenthesis before,
   // it was probably a pointer to an array: int (*)[].
   if (!tryToParseLambda())
-break;
+continue;
 } else {
   parseSquare();
   continue;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121592: [clangd] Expose include cleaner interface in clangd

2022-03-14 Thread serge via Phabricator via cfe-commits
serge-sans-paille created this revision.
serge-sans-paille added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
Herald added a project: All.
serge-sans-paille requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

This gives it the same status as other pieces of clangd and paves the way for
other usage.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121592

Files:
  clang-tools-extra/clangd/ClangdServer.cpp
  clang-tools-extra/clangd/ClangdServer.h


Index: clang-tools-extra/clangd/ClangdServer.h
===
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -243,6 +243,10 @@
   void findHover(PathRef File, Position Pos,
  Callback> CB);
 
+  /// Get information about unused includes.
+  void findUnusedIncludes(PathRef File,
+  Callback> CB);
+
   /// Get information about type hierarchy for a given position.
   void typeHierarchy(PathRef File, Position Pos, int Resolve,
  TypeHierarchyDirection Direction,
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -14,6 +14,7 @@
 #include "FindSymbols.h"
 #include "Format.h"
 #include "HeaderSourceSwitch.h"
+#include "IncludeCleaner.h"
 #include "InlayHints.h"
 #include "ParsedAST.h"
 #include "Preamble.h"
@@ -715,6 +716,19 @@
   WorkScheduler->runWithAST("Hover", File, std::move(Action), Transient);
 }
 
+void ClangdServer::findUnusedIncludes(
+PathRef File, Callback> CB) {
+  auto Action = [File = File.str(), CB = std::move(CB)](
+llvm::Expected InpAST) mutable {
+if (!InpAST)
+  return CB(InpAST.takeError());
+CB(clangd::computeUnusedIncludes(InpAST->AST));
+  };
+
+  WorkScheduler->runWithAST("UnusedIncludes", File, std::move(Action),
+Transient);
+}
+
 void ClangdServer::typeHierarchy(PathRef File, Position Pos, int Resolve,
  TypeHierarchyDirection Direction,
  Callback> CB) {


Index: clang-tools-extra/clangd/ClangdServer.h
===
--- clang-tools-extra/clangd/ClangdServer.h
+++ clang-tools-extra/clangd/ClangdServer.h
@@ -243,6 +243,10 @@
   void findHover(PathRef File, Position Pos,
  Callback> CB);
 
+  /// Get information about unused includes.
+  void findUnusedIncludes(PathRef File,
+  Callback> CB);
+
   /// Get information about type hierarchy for a given position.
   void typeHierarchy(PathRef File, Position Pos, int Resolve,
  TypeHierarchyDirection Direction,
Index: clang-tools-extra/clangd/ClangdServer.cpp
===
--- clang-tools-extra/clangd/ClangdServer.cpp
+++ clang-tools-extra/clangd/ClangdServer.cpp
@@ -14,6 +14,7 @@
 #include "FindSymbols.h"
 #include "Format.h"
 #include "HeaderSourceSwitch.h"
+#include "IncludeCleaner.h"
 #include "InlayHints.h"
 #include "ParsedAST.h"
 #include "Preamble.h"
@@ -715,6 +716,19 @@
   WorkScheduler->runWithAST("Hover", File, std::move(Action), Transient);
 }
 
+void ClangdServer::findUnusedIncludes(
+PathRef File, Callback> CB) {
+  auto Action = [File = File.str(), CB = std::move(CB)](
+llvm::Expected InpAST) mutable {
+if (!InpAST)
+  return CB(InpAST.takeError());
+CB(clangd::computeUnusedIncludes(InpAST->AST));
+  };
+
+  WorkScheduler->runWithAST("UnusedIncludes", File, std::move(Action),
+Transient);
+}
+
 void ClangdServer::typeHierarchy(PathRef File, Position Pos, int Resolve,
  TypeHierarchyDirection Direction,
  Callback> CB) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121593: [clangd][WIP] Provide clang-include-cleaner

2022-03-14 Thread serge via Phabricator via cfe-commits
serge-sans-paille created this revision.
serge-sans-paille added reviewers: kbobyrev, sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman, mgorny.
Herald added a project: All.
serge-sans-paille requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

This is just a wrapper around clangd include cleaner's capability to be used in 
CLI mode.

I'm not sure why include-cleaner wasn't integrated in clang-tidy, but I suspect 
there's a good reason.
This revision is a support for discussing a potential tool that would leverage 
on include cleaner from clangd: it would be great to be able to run such a tool 
on LLVM database and make sure we don't regress.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121593

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang-tools-extra/clangd/include-cleaner/CMakeLists.txt
  clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp

Index: clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp
@@ -0,0 +1,69 @@
+#include "ClangdServer.h"
+#include "support/Logger.h"
+#include "llvm/Support/Path.h"
+
+using namespace clang::clangd;
+
+struct report {
+  PathRef File;
+  void operator()(llvm::Expected> C) {
+if (C) {
+  auto &Added = C.get();
+  if (Added.empty())
+return;
+  llvm::errs() << "Found " << Added.size() << " unused include"
+   << (Added.size() == 1 ? " " : "s ") << "in: " << File
+   << "\n";
+  for (auto const *I : Added) {
+llvm::outs() << "- " << I->Resolved << "\n";
+  }
+} else
+  llvm::errs() << C.takeError();
+  }
+};
+
+class NullLogger : public Logger {
+  void log(Level, const char *Fmt,
+   const llvm::formatv_object_base &Message) final {}
+};
+
+int main(int argc, char **argv) {
+  if (argc < 2) {
+llvm::errs()
+<< "usage: clang-include-cleaner compile_commands_dir files...\n";
+return 1;
+  }
+  RealThreadsafeFS TFS;
+  DirectoryBasedGlobalCompilationDatabase::Options CDBOpts(TFS);
+  llvm::SmallString<64> CCD;
+  auto errc = llvm::sys::fs::real_path(argv[1], CCD);
+  if (errc) {
+llvm::errs() << argv[1] << ": " << errc.message() << "\n";
+return 2;
+  }
+  CDBOpts.CompileCommandsDir = CCD.str().str();
+  DirectoryBasedGlobalCompilationDatabase CDB(CDBOpts);
+
+  StreamLogger SLog(llvm::errs(), Logger::Error);
+  clang::clangd::LoggingSession LoggingSession(SLog);
+
+  ClangdServer::Options CSOpts;
+  ClangdServer CS(CDB, TFS, CSOpts);
+
+  for (int i = 2; i < argc; ++i) {
+PathRef File = argv[i];
+auto MB = llvm::MemoryBuffer::getFile(File);
+if (!MB) {
+  llvm::errs() << "failed to open " << File;
+  return 1;
+}
+CS.addDocument(File, MB.get()->getBuffer());
+CS.findUnusedIncludes(File, report{File});
+
+// We're using clangd in synchronous mode
+while (CS.blockUntilIdleForTest(.1))
+  ;
+  }
+
+  return 0;
+}
Index: clang-tools-extra/clangd/include-cleaner/CMakeLists.txt
===
--- /dev/null
+++ clang-tools-extra/clangd/include-cleaner/CMakeLists.txt
@@ -0,0 +1,29 @@
+add_clang_tool(clang-include-cleaner
+  ClangIncludeCleanerMain.cpp
+  )
+
+set(LLVM_LINK_COMPONENTS
+  support
+  )
+
+clang_target_link_libraries(clang-include-cleaner
+  PRIVATE
+  clangAST
+  clangBasic
+  clangFormat
+  clangFrontend
+  clangLex
+  clangSema
+  clangTooling
+  clangToolingCore
+  clangToolingRefactoring
+  clangToolingSyntax
+  )
+
+target_link_libraries(clang-include-cleaner
+  PRIVATE
+
+  clangDaemon
+  clangdRemoteIndex
+  clangdSupport
+  )
Index: clang-tools-extra/clangd/CMakeLists.txt
===
--- clang-tools-extra/clangd/CMakeLists.txt
+++ clang-tools-extra/clangd/CMakeLists.txt
@@ -180,6 +180,7 @@
   add_subdirectory(fuzzer)
 endif()
 add_subdirectory(tool)
+add_subdirectory(include-cleaner)
 add_subdirectory(indexer)
 
 if (LLVM_INCLUDE_BENCHMARKS)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121588: [C++20][Modules][Driver][HU 1/N] Initial handling for -xc++-{system,user}-header.

2022-03-14 Thread Iain Sandoe via Phabricator via cfe-commits
iains created this revision.
Herald added a project: All.
iains added reviewers: rsmith, urnathan, ChuanqiXu.
iains added a subscriber: clang-modules.
iains published this revision for review.
iains added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is a set of 4 patches that adds the driver-side support for C++20 header 
modules.

We use the same user-facing options as the existing implementation in GCC 
(there seems no engineering reason to deviate from this and it makes things 
easier for users and build system alike).

1/4 - this patch introduces file types for header unit headers to be searched 
for in the user or system paths (or to be given an absolute pathname).
2/4 - adds the -fmoduke-header{.=} command line options
3/4 - is a user-convenience change that allows "foo.h" without complaining 
about C code used in C++ compilations (since we know that the user has already 
specified the intent).
4/4 - adds the -fdirectives-only command that produces pre-processor output 
which retains the macro definitions/undefs that will be present in the built 
header unit.


This adds file types and handling for three input types, representing a C++20
header unit source:

1. When provided with a complete pathname for the header.
2. For a header to be looked up (by the frontend) in the user search paths
3. For a header to be looked up in the system search paths.

We also add a pre-processed file type (although that is a single type, 
regardless
of the original input type).

These types may be specified with -xc++-{user,system,header-unit}-header .

These types allow us to disambiguate header unit jobs from PCH ones, and thus
we handle these differently from other header jobs in two ways:

1. The job construction is altered to build a C++20 header unit (rather than a 
PCH file, as would be the case for other headers).
2. When the type is "user" or "system" we defer checking for the file until the 
front end is run, since we need to look up the header in the relevant paths 
which are not known at this point.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121588

Files:
  clang/include/clang/Driver/Types.def
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/Types.cpp
  clang/lib/Frontend/FrontendOptions.cpp
  clang/test/Driver/Inputs/header-unit-01.hh
  clang/test/Driver/cxx20-header-units-01.cpp

Index: clang/test/Driver/cxx20-header-units-01.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-01.cpp
@@ -0,0 +1,18 @@
+// RUN: %clang++ -### -std=c++20 -xc++-user-header foo.h 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang++ -### -std=c++20 -xc++-system-header vector 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYSTEM %s
+
+// RUN: %clang++ -### -std=c++20 -xc++-header-unit-header %S/Inputs/header-unit-01.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.h"
+// CHECK-SYSTEM: "-emit-header-unit"
+// CHECK-SYSTEM-SAME: "-o" "vector.pcm"
+// CHECK-SYSTEM-SAME: "-x" "c++-system-header" "vector"
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
Index: clang/lib/Frontend/FrontendOptions.cpp
===
--- clang/lib/Frontend/FrontendOptions.cpp
+++ clang/lib/Frontend/FrontendOptions.cpp
@@ -27,6 +27,7 @@
   .Cases("C", "cc", "cp", Language::CXX)
   .Cases("cpp", "CPP", "c++", "cxx", "hpp", "hxx", Language::CXX)
   .Case("cppm", Language::CXX)
+  .Case("iih", InputKind(Language::CXX).getPreprocessed())
   .Case("iim", InputKind(Language::CXX).getPreprocessed())
   .Case("cl", Language::OpenCL)
   .Case("clcpp", Language::OpenCLCXX)
Index: clang/lib/Driver/Types.cpp
===
--- clang/lib/Driver/Types.cpp
+++ clang/lib/Driver/Types.cpp
@@ -65,9 +65,16 @@
   return Id == TY_CXXModule || Id == TY_PP_CXXModule;
 }
 
+static bool isPreprocessedHeaderUnitType(ID Id) {
+  return Id == TY_CXXSHeader || Id == TY_CXXUHeader || Id == TY_CXXHUHeader ||
+ Id == TY_PP_CXXHeaderUnit;
+}
+
 types::ID types::getPrecompiledType(ID Id) {
   if (isPreprocessedModuleType(Id))
 return TY_ModuleFile;
+  if (isPreprocessedHeaderUnitType(Id))
+return TY_HeaderUnit;
   if (onlyPrecompileType(Id))
 return TY_PCH;
   return TY_INVALID;
@@ -139,6 +146,10 @@
   case TY_CLHeader:
   case TY_ObjCHeader: case TY_PP_ObjCHeader:
   case TY_CXXHeader: case TY_PP_CXXHeader:
+  case TY_CXXSHeader:
+  case TY_CXXUHeader:
+  case TY_CXXHUHeader:
+  case TY_PP_CXXHeaderUnit:
   case TY_ObjCXXHeader: case TY_PP_ObjCXXHeader:
   case TY_CXXMod

[PATCH] D121589: [C++20][Modules][Driver][HU 2/N] Add fmodule-header, fmodule-header=

2022-03-14 Thread Iain Sandoe via Phabricator via cfe-commits
iains created this revision.
Herald added a subscriber: dang.
Herald added a project: All.
iains added reviewers: rsmith, urnathan, ChuanqiXu.
iains published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

These command-line flags are alternates to providing the -x
c++-*-header indicators that we are building a header unit.

Act on fmodule-header= for headers on the c/l:

If we have x.hh -fmodule-header, then we should treat that header
as a header unit input (equivalent to -xc++-header-unit-header x.hh).

Likewise, for fmodule-header={user,system} the source should be now
recognised as a header unit input (since this can affect the job list
that we need).

It's not practical to recognise a header without any suffix so
-fmodule-header=system foo isn't going to happen. Although
-fmodule-header=system foo.hh will work OK.  However we can make it
work if the user indicates that the item without a suffix is a valid
header. (so -fmodule-header=system -xc++-header vector)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121589

Files:
  clang/include/clang/Driver/Driver.h
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-02.cpp

Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -0,0 +1,32 @@
+// Test user-facing command line options to generate C++20 header units.
+
+// RUN: %clang++ -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER %s
+
+// RUN: %clang++ -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
+
+// RUN: %clang++ -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-system-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang++ -### -std=c++20 -fmodule-header=system \
+// RUN: -xc++-header vector 2>&1 | FileCheck -check-prefix=CHECK-SYS2 %s
+
+// RUN: %clang++ -### -std=c++20 -fmodule-header %S/Inputs/header-unit-01.hh \
+// RUN: 2>&1 | FileCheck -check-prefix=CHECK-ABS %s -DTDIR=%S/Inputs
+
+// CHECK-USER: "-emit-header-unit"
+// CHECK-USER-SAME: "-o" "foo.pcm"
+// CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
+
+// CHECK-SYS1: "-emit-header-unit"
+// CHECK-SYS1-SAME: "-o" "foo.pcm"
+// CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
+
+// CHECK-SYS2: "-emit-header-unit"
+// CHECK-SYS2-SAME: "-o" "vector.pcm"
+// CHECK-SYS2-SAME: "-x" "c++-system-header" "vector"
+
+// CHECK-ABS: "-emit-header-unit"
+// CHECK-ABS-SAME: "-o" "header-unit-01.pcm"
+// CHECK-ABS-SAME: "-x" "c++-header-unit-header" "[[TDIR]]/header-unit-01.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -188,7 +188,8 @@
DiagnosticsEngine &Diags, std::string Title,
IntrusiveRefCntPtr VFS)
 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
-  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
+  SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
+  CXX20HeaderType(HeaderMode_None), LTOMode(LTOK_None),
   ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
   DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
   CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
@@ -1241,6 +1242,37 @@
   BitcodeEmbed = static_cast(Model);
   }
 
+  // Setting up the jobs for some precompile cases depends on whether we are
+  // treating them as PCH, implicit modules or C++20 ones.
+  // TODO: inferring the mode like this seems fragile (it meets the objective
+  // of not requiring anything new for operation, however).
+  const Arg *Std = Args.getLastArg(options::OPT_std_EQ);
+  ModulesModeCXX20 =
+  !Args.hasArg(options::OPT_fmodules) && Std &&
+  (Std->containsValue("c++20") || Std->containsValue("c++2b") ||
+   Std->containsValue("c++2a") || Std->containsValue("c++latest"));
+
+  // Process -fmodule-header{=} flags.
+  if (Arg *A = Args.getLastArg(options::OPT_fmodule_header_EQ,
+   options::OPT_fmodule_header)) {
+// These flags force C++20 handling of headers.
+ModulesModeCXX20 = true;
+if (A->getOption().matches(options::OPT_fmodule_header))
+  CXX20HeaderType = HeaderMode_Default;
+else {
+  StringRef ArgName = A->getValue();
+  unsigned Kind = llvm::StringSwitch(ArgName)
+  .Case("user", HeaderMode_User)
+  .Case("system", HeaderMode_System)
+  .Default(~0U);
+  if (Kind == ~0U) {
+Diags.Report(diag::err_drv_invalid_value)
+<< A->getAsString(Args) << ArgName;
+  } else
+CXX20HeaderType = static_cast(Kind);
+}
+  }
+
   std::unique_

[PATCH] D121590: [C++20][Modules][Driver][HU 3/N] Handle foo.h with -fmodule-header and/or C++ invocation.

2022-03-14 Thread Iain Sandoe via Phabricator via cfe-commits
iains created this revision.
Herald added a project: All.
iains added reviewers: rsmith, urnathan, ChuanqiXu.
iains published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Allow an invocation like clang -fmodule-header bar.h (which will be a C++
compilation, but using a header which will be recognised as a C one).

Also  we do not want to produce:
 "treating 'c-header' input as 'c++-header' when in C++ mode"
diagnostics when the user has been specific about the intent.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121590

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/cxx20-header-units-02.cpp


Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- clang/test/Driver/cxx20-header-units-02.cpp
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -3,6 +3,9 @@
 // RUN: %clang++ -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-USER %s
 
+// RUN: %clang++ -### -std=c++20 -fmodule-header=user foo.h  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER1 %s
+
 // RUN: %clang++ -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
 
@@ -19,6 +22,10 @@
 // CHECK-USER-SAME: "-o" "foo.pcm"
 // CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
 
+// CHECK-USER1: "-emit-header-unit"
+// CHECK-USER1-SAME: "-o" "foo.pcm"
+// CHECK-USER1-SAME: "-x" "c++-user-header" "foo.h"
+
 // CHECK-SYS1: "-emit-header-unit"
 // CHECK-SYS1-SAME: "-o" "foo.pcm"
 // CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2415,7 +2415,9 @@
 types::ID OldTy = Ty;
 Ty = types::lookupCXXTypeForCType(Ty);
 
-if (Ty != OldTy)
+// Do not complain about foo.h, when we are known to be processing
+// it as a C++20 header unit.
+if (Ty != OldTy && !(OldTy == types::TY_CHeader && 
hasHeaderMode()))
   Diag(clang::diag::warn_drv_treating_input_as_cxx)
   << getTypeName(OldTy) << getTypeName(Ty);
   }
@@ -2440,8 +2442,11 @@
 }
 
 // Disambiguate headers that are meant to be header units from those
-// intended to be PCH.
-if (Ty == types::TY_CXXHeader && hasHeaderMode())
+// intended to be PCH.  Avoid missing '.h' cases that are  counted as
+// C headers by default - we know we are in C++ mode and we do not
+// want to issue a complaint about compiling things in the wrong mode.
+if ((Ty == types::TY_CXXHeader || Ty == types::TY_CHeader) &&
+hasHeaderMode())
   Ty = CXXHeaderUnitType(CXX20HeaderType);
   } else {
 assert(InputTypeArg && "InputType set w/o InputTypeArg");


Index: clang/test/Driver/cxx20-header-units-02.cpp
===
--- clang/test/Driver/cxx20-header-units-02.cpp
+++ clang/test/Driver/cxx20-header-units-02.cpp
@@ -3,6 +3,9 @@
 // RUN: %clang++ -### -std=c++20 -fmodule-header=user foo.hh  2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-USER %s
 
+// RUN: %clang++ -### -std=c++20 -fmodule-header=user foo.h  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-USER1 %s
+
 // RUN: %clang++ -### -std=c++20 -fmodule-header=system foo.hh 2>&1 | \
 // RUN:   FileCheck -check-prefix=CHECK-SYS1 %s
 
@@ -19,6 +22,10 @@
 // CHECK-USER-SAME: "-o" "foo.pcm"
 // CHECK-USER-SAME: "-x" "c++-user-header" "foo.hh"
 
+// CHECK-USER1: "-emit-header-unit"
+// CHECK-USER1-SAME: "-o" "foo.pcm"
+// CHECK-USER1-SAME: "-x" "c++-user-header" "foo.h"
+
 // CHECK-SYS1: "-emit-header-unit"
 // CHECK-SYS1-SAME: "-o" "foo.pcm"
 // CHECK-SYS1-SAME: "-x" "c++-system-header" "foo.hh"
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -2415,7 +2415,9 @@
 types::ID OldTy = Ty;
 Ty = types::lookupCXXTypeForCType(Ty);
 
-if (Ty != OldTy)
+// Do not complain about foo.h, when we are known to be processing
+// it as a C++20 header unit.
+if (Ty != OldTy && !(OldTy == types::TY_CHeader && hasHeaderMode()))
   Diag(clang::diag::warn_drv_treating_input_as_cxx)
   << getTypeName(OldTy) << getTypeName(Ty);
   }
@@ -2440,8 +2442,11 @@
 }
 
 // Disambiguate headers that are meant to be header units from those
-// intended to be PCH.
-if (Ty == types::TY_CXXHeader && hasHeaderMode())
+// intended to be PCH.  Avoid missing '.h' cases that are  counted as
+// C headers by default - we know we are in C++ mode and we do not
+// want to issue a complain

[PATCH] D121591: [C++20][Modules][Driver][HU 4/N] Add fdirectives-only mode for preprocessing output.

2022-03-14 Thread Iain Sandoe via Phabricator via cfe-commits
iains created this revision.
Herald added a project: All.
iains added reviewers: rsmith, urnathan, ChuanqiXu.
iains published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

When the -fdirectives-only option is used together with -E, the preprocessor
output reflects evaluation of if/then/else directives.

Thus it preserves macros that are still live after such processing.
This output can be consumed by a second compilation to produce a header unit.

We automatically invoke this (with -E) when we know that the job produces a
header unit so that the preprocessed output reflects the macros that will be
defined when the binary HU is emitted.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121591

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/Driver/cxx20-fdirectives-only.cpp


Index: clang/test/Driver/cxx20-fdirectives-only.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-fdirectives-only.cpp
@@ -0,0 +1,20 @@
+// Test -fdirectives-only cases.
+
+// We can manullay specify fdirectives-only, for any pre-processor job.
+// RUN: %clang++ -### -std=c++20 -E -fdirectives-only foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-NON-HU %s
+
+// Check that we automatically append -fdirectives-only for header-unit
+// preprocessor jobs.
+// RUN: %clang++ -### -std=c++20 -E -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-HU %s
+
+// CHECK-NON-HU: "-E"
+// CHECK-NON-HU-SAME: "-fdirectives-only"
+// CHECK-NON-HU-SAME: "-o" "-"
+// CHECK-NON-HU-SAME: "-x" "c++-header" "foo.hh"
+
+// CHECK-HU: "-E"
+// CHECK-HU-SAME: "-fdirectives-only"
+// CHECK-HU-SAME: "-o" "-"
+// CHECK-HU-SAME: "-x" "c++-user-header" "foo.hh"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4592,6 +4592,8 @@
   if (Args.hasArg(options::OPT_rewrite_objc) &&
   !Args.hasArg(options::OPT_g_Group))
 CmdArgs.push_back("-P");
+  else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
+CmdArgs.push_back("-fdirectives-only");
 }
   } else if (isa(JA)) {
 CmdArgs.push_back("-emit-obj");
@@ -6739,6 +6741,10 @@
   if (RewriteImports)
 CmdArgs.push_back("-frewrite-imports");
 
+  if (Args.hasFlag(options::OPT_fdirectives_only,
+   options::OPT_fno_directives_only, false))
+CmdArgs.push_back("-fdirectives-only");
+
   // Enable rewrite includes if the user's asked for it or if we're generating
   // diagnostics.
   // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -4251,10 +4251,14 @@
   OutputTy = types::TY_Dependencies;
 } else {
   OutputTy = Input->getType();
+  // For these cases, the preprocessor is only translating forms, the 
Output
+  // still needs preprocessing.
   if (!Args.hasFlag(options::OPT_frewrite_includes,
 options::OPT_fno_rewrite_includes, false) &&
   !Args.hasFlag(options::OPT_frewrite_imports,
 options::OPT_fno_rewrite_imports, false) &&
+  !Args.hasFlag(options::OPT_fdirectives_only,
+options::OPT_fno_directives_only, false) &&
   !CCGenDiagnostics)
 OutputTy = types::getPreprocessedType(OutputTy);
   assert(OutputTy != types::TY_INVALID &&


Index: clang/test/Driver/cxx20-fdirectives-only.cpp
===
--- /dev/null
+++ clang/test/Driver/cxx20-fdirectives-only.cpp
@@ -0,0 +1,20 @@
+// Test -fdirectives-only cases.
+
+// We can manullay specify fdirectives-only, for any pre-processor job.
+// RUN: %clang++ -### -std=c++20 -E -fdirectives-only foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-NON-HU %s
+
+// Check that we automatically append -fdirectives-only for header-unit
+// preprocessor jobs.
+// RUN: %clang++ -### -std=c++20 -E -fmodule-header=user foo.hh  2>&1 | \
+// RUN:   FileCheck -check-prefix=CHECK-HU %s
+
+// CHECK-NON-HU: "-E"
+// CHECK-NON-HU-SAME: "-fdirectives-only"
+// CHECK-NON-HU-SAME: "-o" "-"
+// CHECK-NON-HU-SAME: "-x" "c++-header" "foo.hh"
+
+// CHECK-HU: "-E"
+// CHECK-HU-SAME: "-fdirectives-only"
+// CHECK-HU-SAME: "-o" "-"
+// CHECK-HU-SAME: "-x" "c++-user-header" "foo.hh"
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4592,6 +4592,8 @@
   if (Args.hasArg(options::OPT_rewrite_objc) &&
   !Args.hasArg(options::OPT_g_Group))
 CmdArgs.push_b

[clang] 2d8e907 - [clang-format][NFC] Rename Left to OpeningParen...

2022-03-14 Thread Björn Schäpers via cfe-commits

Author: Björn Schäpers
Date: 2022-03-14T12:44:45+01:00
New Revision: 2d8e907016ef323ed1a9e2e70c558eb9c3568b06

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

LOG: [clang-format][NFC] Rename Left to OpeningParen...

in TokenAnnotator::parseParens(). Left is misleading since we have a
loop and Left is not adjusted.

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 77ef54e0e2d59..120100b14 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -211,32 +211,34 @@ class AnnotatingParser {
   bool parseParens(bool LookForDecls = false) {
 if (!CurrentToken)
   return false;
-FormatToken *Left = CurrentToken->Previous;
-assert(Left && "Unknown previous token");
-FormatToken *PrevNonComment = Left->getPreviousNonComment();
-Left->ParentBracket = Contexts.back().ContextKind;
+assert(CurrentToken->Previous && "Unknown previous token");
+FormatToken &OpeningParen = *CurrentToken->Previous;
+assert(OpeningParen.is(tok::l_paren));
+FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment();
+OpeningParen.ParentBracket = Contexts.back().ContextKind;
 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
 
 // FIXME: This is a bit of a hack. Do better.
 Contexts.back().ColonIsForRangeExpr =
 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
 
-if (Left->Previous && Left->Previous->is(TT_UntouchableMacroFunc)) {
-  Left->Finalized = true;
+if (OpeningParen.Previous &&
+OpeningParen.Previous->is(TT_UntouchableMacroFunc)) {
+  OpeningParen.Finalized = true;
   return parseUntouchableParens();
 }
 
 bool StartsObjCMethodExpr = false;
-if (FormatToken *MaybeSel = Left->Previous) {
+if (FormatToken *MaybeSel = OpeningParen.Previous) {
   // @selector( starts a selector.
   if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous 
&&
   MaybeSel->Previous->is(tok::at))
 StartsObjCMethodExpr = true;
 }
 
-if (Left->is(TT_OverloadedOperatorLParen)) {
+if (OpeningParen.is(TT_OverloadedOperatorLParen)) {
   // Find the previous kw_operator token.
-  FormatToken *Prev = Left;
+  FormatToken *Prev = &OpeningParen;
   while (!Prev->is(tok::kw_operator)) {
 Prev = Prev->Previous;
 assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
@@ -255,54 +257,58 @@ class AnnotatingParser {
   // type X = (...);
   // export type X = (...);
   Contexts.back().IsExpression = false;
-} else if (Left->Previous &&
-   (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_while,
-tok::l_paren, tok::comma) ||
-Left->Previous->isIf() ||
-Left->Previous->is(TT_BinaryOperator))) {
+} else if (OpeningParen.Previous &&
+   (OpeningParen.Previous->isOneOf(tok::kw_static_assert,
+   tok::kw_while, tok::l_paren,
+   tok::comma) ||
+OpeningParen.Previous->isIf() ||
+OpeningParen.Previous->is(TT_BinaryOperator))) {
   // static_assert, if and while usually contain expressions.
   Contexts.back().IsExpression = true;
-} else if (Style.isJavaScript() && Left->Previous &&
-   (Left->Previous->is(Keywords.kw_function) ||
-(Left->Previous->endsSequence(tok::identifier,
-  Keywords.kw_function {
+} else if (Style.isJavaScript() && OpeningParen.Previous &&
+   (OpeningParen.Previous->is(Keywords.kw_function) ||
+(OpeningParen.Previous->endsSequence(tok::identifier,
+ Keywords.kw_function {
   // function(...) or function f(...)
   Contexts.back().IsExpression = false;
-} else if (Style.isJavaScript() && Left->Previous &&
-   Left->Previous->is(TT_JsTypeColon)) {
+} else if (Style.isJavaScript() && OpeningParen.Previous &&
+   OpeningParen.Previous->is(TT_JsTypeColon)) {
   // let x: (SomeType);
   Contexts.back().IsExpression = false;
-} else if (isLambdaParameterList(Left)) {
+} else if (isLambdaParameterList(&OpeningParen)) {
   // This is a parameter list of a lambda expression.
   Contexts.back().IsExpression = false;
 } else if (Line.InPPDirective &&
-   (!Left->Previous || !Left->Previous->is(tok::identifier)))

[clang] acd17a2 - [clang-format] Fix crash on invalid requires expression

2022-03-14 Thread Björn Schäpers via cfe-commits

Author: Björn Schäpers
Date: 2022-03-14T12:44:46+01:00
New Revision: acd17a2be81a33abf4350e31ae1747dcb0f12332

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

LOG: [clang-format] Fix crash on invalid requires expression

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

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 120100b14..a918c0e7ab4da 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -421,8 +421,8 @@ class AnnotatingParser {
   if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
 return false;
 
-  if (CurrentToken->is(tok::l_brace))
-OpeningParen.setType(TT_Unknown); // Not TT_ObjCBlockLParen
+  if (CurrentToken->is(tok::l_brace) && 
OpeningParen.is(TT_ObjCBlockLParen))
+OpeningParen.setType(TT_Unknown);
   if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
   !CurrentToken->Next->HasUnescapedNewline &&
   !CurrentToken->Next->isTrailingComment())

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 5ca6f6244c40c..aadd24a0d6ca6 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -24041,9 +24041,9 @@ TEST_F(FormatTest, Concepts) {
   verifyFormat(
   "template  concept C = decltype([]() -> std::true_type {\n"
   "return {};\n"
-  "  }())::value\n"
-  "  && requires(T t) { t.bar(); } &&\n"
-  "  sizeof(T) <= 8;",
+  "  }())::value &&\n"
+  "  requires(T t) { t.bar(); } && "
+  "sizeof(T) <= 8;",
   Style);
 
   verifyFormat("template  concept Semiregular =\n"

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 7e753bc5a34d5..05cf000eadb71 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -356,6 +356,14 @@ TEST_F(TokenAnnotatorTest, UnderstandsRequiresExpressions) 
{
   EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_RequiresExpressionLBrace);
   EXPECT_TOKEN(Tokens[29], tok::kw_requires,
TT_RequiresClauseInARequiresExpression);
+
+  // Invalid Code, but we don't want to crash. See http://llvm.org/PR54350.
+  Tokens = annotate("bool r10 = requires (struct new_struct { int x; } s) { "
+"requires true; };");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_RequiresExpressionLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, RequiresDoesNotChangeParsingOfTheRest) {



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


[clang] b7494a1 - [clang-format][NFC] Left renamed to OpeningBrace...

2022-03-14 Thread Björn Schäpers via cfe-commits

Author: Björn Schäpers
Date: 2022-03-14T12:44:47+01:00
New Revision: b7494a1d72c16a4d1f9cc8d4b3eba36934c35664

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

LOG: [clang-format][NFC] Left renamed to OpeningBrace...

in TokenAnnotator::parseBrace. Left is misleading, because we have a
loop and Left does not move.

Also return early.

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index a918c0e7ab4da..8f433d78b7f74 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -774,63 +774,66 @@ class AnnotatingParser {
   }
 
   bool parseBrace() {
-if (CurrentToken) {
-  FormatToken *Left = CurrentToken->Previous;
-  Left->ParentBracket = Contexts.back().ContextKind;
+if (!CurrentToken)
+  return true;
 
-  if (Contexts.back().CaretFound)
-Left->setType(TT_ObjCBlockLBrace);
-  Contexts.back().CaretFound = false;
+assert(CurrentToken->Previous);
+FormatToken &OpeningBrace = *CurrentToken->Previous;
+assert(OpeningBrace.is(tok::l_brace));
+OpeningBrace.ParentBracket = Contexts.back().ContextKind;
 
-  ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
-  Contexts.back().ColonIsDictLiteral = true;
-  if (Left->is(BK_BracedInit))
-Contexts.back().IsExpression = true;
-  if (Style.isJavaScript() && Left->Previous &&
-  Left->Previous->is(TT_JsTypeColon))
-Contexts.back().IsExpression = false;
+if (Contexts.back().CaretFound)
+  OpeningBrace.setType(TT_ObjCBlockLBrace);
+Contexts.back().CaretFound = false;
 
-  unsigned CommaCount = 0;
-  while (CurrentToken) {
-if (CurrentToken->is(tok::r_brace)) {
-  assert(Left->Optional == CurrentToken->Optional);
-  Left->MatchingParen = CurrentToken;
-  CurrentToken->MatchingParen = Left;
-  if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
-if (Left->ParentBracket == tok::l_brace &&
-couldBeInStructArrayInitializer() && CommaCount > 0)
-  Contexts.back().InStructArrayInitializer = true;
-  }
-  next();
-  return true;
-}
-if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
-  return false;
-updateParameterCount(Left, CurrentToken);
-if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
-  FormatToken *Previous = CurrentToken->getPreviousNonComment();
-  if (Previous->is(TT_JsTypeOptionalQuestion))
-Previous = Previous->getPreviousNonComment();
-  if ((CurrentToken->is(tok::colon) &&
-   (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
-  Style.Language == FormatStyle::LK_Proto ||
-  Style.Language == FormatStyle::LK_TextProto) {
-Left->setType(TT_DictLiteral);
-if (Previous->Tok.getIdentifierInfo() ||
-Previous->is(tok::string_literal))
-  Previous->setType(TT_SelectorName);
-  }
-  if (CurrentToken->is(tok::colon) || Style.isJavaScript())
-Left->setType(TT_DictLiteral);
+ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
+Contexts.back().ColonIsDictLiteral = true;
+if (OpeningBrace.is(BK_BracedInit))
+  Contexts.back().IsExpression = true;
+if (Style.isJavaScript() && OpeningBrace.Previous &&
+OpeningBrace.Previous->is(TT_JsTypeColon))
+  Contexts.back().IsExpression = false;
+
+unsigned CommaCount = 0;
+while (CurrentToken) {
+  if (CurrentToken->is(tok::r_brace)) {
+assert(OpeningBrace.Optional == CurrentToken->Optional);
+OpeningBrace.MatchingParen = CurrentToken;
+CurrentToken->MatchingParen = &OpeningBrace;
+if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
+  if (OpeningBrace.ParentBracket == tok::l_brace &&
+  couldBeInStructArrayInitializer() && CommaCount > 0)
+Contexts.back().InStructArrayInitializer = true;
 }
-if (CurrentToken->is(tok::comma)) {
-  if (Style.isJavaScript())
-Left->overwriteFixedType(TT_DictLiteral);
-  ++CommaCount;
+next();
+return true;
+  }
+  if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
+return false;
+  updateParameterCount(&OpeningBrace, CurrentToken);
+  if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
+FormatToken *Previous = CurrentToken->getPreviousNonComment();
+if (Previous->is(TT_JsTypeOptionalQuesti

[clang] 35abbf1 - [clang-format] Fix crash on asm block with label

2022-03-14 Thread Björn Schäpers via cfe-commits

Author: Björn Schäpers
Date: 2022-03-14T12:44:48+01:00
New Revision: 35abbf166d4ad13e4a89095307bb6e4b2e96e0b3

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

LOG: [clang-format] Fix crash on asm block with label

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

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 8f433d78b7f74..6cf3681cdd9d5 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -824,8 +824,10 @@ class AnnotatingParser {
   Previous->is(tok::string_literal))
 Previous->setType(TT_SelectorName);
 }
-if (CurrentToken->is(tok::colon) || Style.isJavaScript())
+if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown))
   OpeningBrace.setType(TT_DictLiteral);
+else if (Style.isJavaScript())
+  OpeningBrace.overwriteFixedType(TT_DictLiteral);
   }
   if (CurrentToken->is(tok::comma)) {
 if (Style.isJavaScript())

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 05cf000eadb71..dd868be99f45e 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -602,6 +602,16 @@ TEST_F(TokenAnnotatorTest, 
RequiresDoesNotChangeParsingOfTheRest) {
   << I;
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsAsm) {
+  auto Tokens = annotate("__asm{\n"
+ "a:\n"
+ "};");
+  ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::kw_asm, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_brace, TT_InlineASMBrace);
+  EXPECT_TOKEN(Tokens[4], tok::r_brace, TT_InlineASMBrace);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang



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


[PATCH] D121557: [clang-format][NFC] Rename Left to OpeningParen...

2022-03-14 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2d8e907016ef: [clang-format][NFC] Rename Left to 
OpeningParen... (authored by HazardyKnusperkeks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121557

Files:
  clang/lib/Format/TokenAnnotator.cpp

Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -211,32 +211,34 @@
   bool parseParens(bool LookForDecls = false) {
 if (!CurrentToken)
   return false;
-FormatToken *Left = CurrentToken->Previous;
-assert(Left && "Unknown previous token");
-FormatToken *PrevNonComment = Left->getPreviousNonComment();
-Left->ParentBracket = Contexts.back().ContextKind;
+assert(CurrentToken->Previous && "Unknown previous token");
+FormatToken &OpeningParen = *CurrentToken->Previous;
+assert(OpeningParen.is(tok::l_paren));
+FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment();
+OpeningParen.ParentBracket = Contexts.back().ContextKind;
 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
 
 // FIXME: This is a bit of a hack. Do better.
 Contexts.back().ColonIsForRangeExpr =
 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
 
-if (Left->Previous && Left->Previous->is(TT_UntouchableMacroFunc)) {
-  Left->Finalized = true;
+if (OpeningParen.Previous &&
+OpeningParen.Previous->is(TT_UntouchableMacroFunc)) {
+  OpeningParen.Finalized = true;
   return parseUntouchableParens();
 }
 
 bool StartsObjCMethodExpr = false;
-if (FormatToken *MaybeSel = Left->Previous) {
+if (FormatToken *MaybeSel = OpeningParen.Previous) {
   // @selector( starts a selector.
   if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
   MaybeSel->Previous->is(tok::at))
 StartsObjCMethodExpr = true;
 }
 
-if (Left->is(TT_OverloadedOperatorLParen)) {
+if (OpeningParen.is(TT_OverloadedOperatorLParen)) {
   // Find the previous kw_operator token.
-  FormatToken *Prev = Left;
+  FormatToken *Prev = &OpeningParen;
   while (!Prev->is(tok::kw_operator)) {
 Prev = Prev->Previous;
 assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
@@ -255,54 +257,58 @@
   // type X = (...);
   // export type X = (...);
   Contexts.back().IsExpression = false;
-} else if (Left->Previous &&
-   (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_while,
-tok::l_paren, tok::comma) ||
-Left->Previous->isIf() ||
-Left->Previous->is(TT_BinaryOperator))) {
+} else if (OpeningParen.Previous &&
+   (OpeningParen.Previous->isOneOf(tok::kw_static_assert,
+   tok::kw_while, tok::l_paren,
+   tok::comma) ||
+OpeningParen.Previous->isIf() ||
+OpeningParen.Previous->is(TT_BinaryOperator))) {
   // static_assert, if and while usually contain expressions.
   Contexts.back().IsExpression = true;
-} else if (Style.isJavaScript() && Left->Previous &&
-   (Left->Previous->is(Keywords.kw_function) ||
-(Left->Previous->endsSequence(tok::identifier,
-  Keywords.kw_function {
+} else if (Style.isJavaScript() && OpeningParen.Previous &&
+   (OpeningParen.Previous->is(Keywords.kw_function) ||
+(OpeningParen.Previous->endsSequence(tok::identifier,
+ Keywords.kw_function {
   // function(...) or function f(...)
   Contexts.back().IsExpression = false;
-} else if (Style.isJavaScript() && Left->Previous &&
-   Left->Previous->is(TT_JsTypeColon)) {
+} else if (Style.isJavaScript() && OpeningParen.Previous &&
+   OpeningParen.Previous->is(TT_JsTypeColon)) {
   // let x: (SomeType);
   Contexts.back().IsExpression = false;
-} else if (isLambdaParameterList(Left)) {
+} else if (isLambdaParameterList(&OpeningParen)) {
   // This is a parameter list of a lambda expression.
   Contexts.back().IsExpression = false;
 } else if (Line.InPPDirective &&
-   (!Left->Previous || !Left->Previous->is(tok::identifier))) {
+   (!OpeningParen.Previous ||
+!OpeningParen.Previous->is(tok::identifier))) {
   Contexts.back().IsExpression = true;
 } else if (Contexts[Contexts.size() - 2].CaretFound) {
   // This is the parameter list of an ObjC block.
   Contexts.back().IsExpression = false;
-} else if (Left->Previous && Left->Previous->is(TT_ForE

[PATCH] D121550: [clang-format] Fix crash on invalid requires expression

2022-03-14 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGacd17a2be81a: [clang-format] Fix crash on invalid requires 
expression (authored by HazardyKnusperkeks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121550

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -356,6 +356,14 @@
   EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_RequiresExpressionLBrace);
   EXPECT_TOKEN(Tokens[29], tok::kw_requires,
TT_RequiresClauseInARequiresExpression);
+
+  // Invalid Code, but we don't want to crash. See http://llvm.org/PR54350.
+  Tokens = annotate("bool r10 = requires (struct new_struct { int x; } s) { "
+"requires true; };");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_RequiresExpressionLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, RequiresDoesNotChangeParsingOfTheRest) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -24041,9 +24041,9 @@
   verifyFormat(
   "template  concept C = decltype([]() -> std::true_type {\n"
   "return {};\n"
-  "  }())::value\n"
-  "  && requires(T t) { t.bar(); } &&\n"
-  "  sizeof(T) <= 8;",
+  "  }())::value &&\n"
+  "  requires(T t) { t.bar(); } && "
+  "sizeof(T) <= 8;",
   Style);
 
   verifyFormat("template  concept Semiregular =\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -421,8 +421,8 @@
   if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
 return false;
 
-  if (CurrentToken->is(tok::l_brace))
-OpeningParen.setType(TT_Unknown); // Not TT_ObjCBlockLParen
+  if (CurrentToken->is(tok::l_brace) && 
OpeningParen.is(TT_ObjCBlockLParen))
+OpeningParen.setType(TT_Unknown);
   if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
   !CurrentToken->Next->HasUnescapedNewline &&
   !CurrentToken->Next->isTrailingComment())


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -356,6 +356,14 @@
   EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_RequiresExpressionLBrace);
   EXPECT_TOKEN(Tokens[29], tok::kw_requires,
TT_RequiresClauseInARequiresExpression);
+
+  // Invalid Code, but we don't want to crash. See http://llvm.org/PR54350.
+  Tokens = annotate("bool r10 = requires (struct new_struct { int x; } s) { "
+"requires true; };");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_RequiresExpressionLParen);
+  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_RequiresExpressionLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, RequiresDoesNotChangeParsingOfTheRest) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -24041,9 +24041,9 @@
   verifyFormat(
   "template  concept C = decltype([]() -> std::true_type {\n"
   "return {};\n"
-  "  }())::value\n"
-  "  && requires(T t) { t.bar(); } &&\n"
-  "  sizeof(T) <= 8;",
+  "  }())::value &&\n"
+  "  requires(T t) { t.bar(); } && "
+  "sizeof(T) <= 8;",
   Style);
 
   verifyFormat("template  concept Semiregular =\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -421,8 +421,8 @@
   if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
 return false;
 
-  if (CurrentToken->is(tok::l_brace))
-

[PATCH] D121558: [clang-format][NFC] Left renamed to OpeningBrace...

2022-03-14 Thread Björn Schäpers via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb7494a1d72c1: [clang-format][NFC] Left renamed to 
OpeningBrace... (authored by HazardyKnusperkeks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121558

Files:
  clang/lib/Format/TokenAnnotator.cpp

Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -774,63 +774,66 @@
   }
 
   bool parseBrace() {
-if (CurrentToken) {
-  FormatToken *Left = CurrentToken->Previous;
-  Left->ParentBracket = Contexts.back().ContextKind;
+if (!CurrentToken)
+  return true;
 
-  if (Contexts.back().CaretFound)
-Left->setType(TT_ObjCBlockLBrace);
-  Contexts.back().CaretFound = false;
+assert(CurrentToken->Previous);
+FormatToken &OpeningBrace = *CurrentToken->Previous;
+assert(OpeningBrace.is(tok::l_brace));
+OpeningBrace.ParentBracket = Contexts.back().ContextKind;
 
-  ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
-  Contexts.back().ColonIsDictLiteral = true;
-  if (Left->is(BK_BracedInit))
-Contexts.back().IsExpression = true;
-  if (Style.isJavaScript() && Left->Previous &&
-  Left->Previous->is(TT_JsTypeColon))
-Contexts.back().IsExpression = false;
+if (Contexts.back().CaretFound)
+  OpeningBrace.setType(TT_ObjCBlockLBrace);
+Contexts.back().CaretFound = false;
 
-  unsigned CommaCount = 0;
-  while (CurrentToken) {
-if (CurrentToken->is(tok::r_brace)) {
-  assert(Left->Optional == CurrentToken->Optional);
-  Left->MatchingParen = CurrentToken;
-  CurrentToken->MatchingParen = Left;
-  if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
-if (Left->ParentBracket == tok::l_brace &&
-couldBeInStructArrayInitializer() && CommaCount > 0)
-  Contexts.back().InStructArrayInitializer = true;
-  }
-  next();
-  return true;
-}
-if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
-  return false;
-updateParameterCount(Left, CurrentToken);
-if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
-  FormatToken *Previous = CurrentToken->getPreviousNonComment();
-  if (Previous->is(TT_JsTypeOptionalQuestion))
-Previous = Previous->getPreviousNonComment();
-  if ((CurrentToken->is(tok::colon) &&
-   (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
-  Style.Language == FormatStyle::LK_Proto ||
-  Style.Language == FormatStyle::LK_TextProto) {
-Left->setType(TT_DictLiteral);
-if (Previous->Tok.getIdentifierInfo() ||
-Previous->is(tok::string_literal))
-  Previous->setType(TT_SelectorName);
-  }
-  if (CurrentToken->is(tok::colon) || Style.isJavaScript())
-Left->setType(TT_DictLiteral);
+ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
+Contexts.back().ColonIsDictLiteral = true;
+if (OpeningBrace.is(BK_BracedInit))
+  Contexts.back().IsExpression = true;
+if (Style.isJavaScript() && OpeningBrace.Previous &&
+OpeningBrace.Previous->is(TT_JsTypeColon))
+  Contexts.back().IsExpression = false;
+
+unsigned CommaCount = 0;
+while (CurrentToken) {
+  if (CurrentToken->is(tok::r_brace)) {
+assert(OpeningBrace.Optional == CurrentToken->Optional);
+OpeningBrace.MatchingParen = CurrentToken;
+CurrentToken->MatchingParen = &OpeningBrace;
+if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
+  if (OpeningBrace.ParentBracket == tok::l_brace &&
+  couldBeInStructArrayInitializer() && CommaCount > 0)
+Contexts.back().InStructArrayInitializer = true;
 }
-if (CurrentToken->is(tok::comma)) {
-  if (Style.isJavaScript())
-Left->overwriteFixedType(TT_DictLiteral);
-  ++CommaCount;
+next();
+return true;
+  }
+  if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
+return false;
+  updateParameterCount(&OpeningBrace, CurrentToken);
+  if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
+FormatToken *Previous = CurrentToken->getPreviousNonComment();
+if (Previous->is(TT_JsTypeOptionalQuestion))
+  Previous = Previous->getPreviousNonComment();
+if ((CurrentToken->is(tok::colon) &&
+ (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
+Style.Language == FormatStyle::LK_Proto ||
+Style.Language == FormatStyle::LK_TextProto) {
+  OpeningBrace.setType(TT_DictLiteral);
+  if (Previ

[PATCH] D121559: [clang-format] Fix crash on asm block with label

2022-03-14 Thread Björn Schäpers 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 rG35abbf166d4a: [clang-format] Fix crash on asm block with 
label (authored by HazardyKnusperkeks).

Changed prior to commit:
  https://reviews.llvm.org/D121559?vs=414958&id=415068#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121559

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -602,6 +602,16 @@
   << I;
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsAsm) {
+  auto Tokens = annotate("__asm{\n"
+ "a:\n"
+ "};");
+  ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::kw_asm, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_brace, TT_InlineASMBrace);
+  EXPECT_TOKEN(Tokens[4], tok::r_brace, TT_InlineASMBrace);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -824,8 +824,10 @@
   Previous->is(tok::string_literal))
 Previous->setType(TT_SelectorName);
 }
-if (CurrentToken->is(tok::colon) || Style.isJavaScript())
+if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown))
   OpeningBrace.setType(TT_DictLiteral);
+else if (Style.isJavaScript())
+  OpeningBrace.overwriteFixedType(TT_DictLiteral);
   }
   if (CurrentToken->is(tok::comma)) {
 if (Style.isJavaScript())


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -602,6 +602,16 @@
   << I;
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsAsm) {
+  auto Tokens = annotate("__asm{\n"
+ "a:\n"
+ "};");
+  ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::kw_asm, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_brace, TT_InlineASMBrace);
+  EXPECT_TOKEN(Tokens[4], tok::r_brace, TT_InlineASMBrace);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -824,8 +824,10 @@
   Previous->is(tok::string_literal))
 Previous->setType(TT_SelectorName);
 }
-if (CurrentToken->is(tok::colon) || Style.isJavaScript())
+if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown))
   OpeningBrace.setType(TT_DictLiteral);
+else if (Style.isJavaScript())
+  OpeningBrace.overwriteFixedType(TT_DictLiteral);
   }
   if (CurrentToken->is(tok::comma)) {
 if (Style.isJavaScript())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121475: [Clang][Sema] Avoid crashing for `__builtin_memcpy_inline` with an array argument

2022-03-14 Thread Egor Zhdan via Phabricator via cfe-commits
egorzhdan updated this revision to Diff 415069.
egorzhdan added a comment.

Rename a lambda to improve readability


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121475

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/builtins-memcpy-inline.cpp


Index: clang/test/Sema/builtins-memcpy-inline.cpp
===
--- clang/test/Sema/builtins-memcpy-inline.cpp
+++ clang/test/Sema/builtins-memcpy-inline.cpp
@@ -36,3 +36,9 @@
   // we do not try to evaluate size in non intantiated templates.
   __builtin_memcpy_inline(dst, src, size);
 }
+
+void test_memcpy_inline_implicit_conversion(void *ptr) {
+  char a[5];
+  __builtin_memcpy_inline(ptr, a, 5);
+  __builtin_memcpy_inline(a, ptr, 5);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1943,6 +1943,17 @@
   case Builtin::BI__builtin_nontemporal_store:
 return SemaBuiltinNontemporalOverloaded(TheCallResult);
   case Builtin::BI__builtin_memcpy_inline: {
+auto ArgArrayConversionFailed = [&](unsigned Arg) {
+  ExprResult ArgExpr =
+  DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg));
+  if (ArgExpr.isInvalid())
+return true;
+  TheCall->setArg(Arg, ArgExpr.get());
+  return false;
+};
+
+if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1))
+  return true;
 clang::Expr *SizeOp = TheCall->getArg(2);
 // We warn about copying to or from `nullptr` pointers when `size` is
 // greater than 0. When `size` is value dependent we cannot evaluate its


Index: clang/test/Sema/builtins-memcpy-inline.cpp
===
--- clang/test/Sema/builtins-memcpy-inline.cpp
+++ clang/test/Sema/builtins-memcpy-inline.cpp
@@ -36,3 +36,9 @@
   // we do not try to evaluate size in non intantiated templates.
   __builtin_memcpy_inline(dst, src, size);
 }
+
+void test_memcpy_inline_implicit_conversion(void *ptr) {
+  char a[5];
+  __builtin_memcpy_inline(ptr, a, 5);
+  __builtin_memcpy_inline(a, ptr, 5);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1943,6 +1943,17 @@
   case Builtin::BI__builtin_nontemporal_store:
 return SemaBuiltinNontemporalOverloaded(TheCallResult);
   case Builtin::BI__builtin_memcpy_inline: {
+auto ArgArrayConversionFailed = [&](unsigned Arg) {
+  ExprResult ArgExpr =
+  DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg));
+  if (ArgExpr.isInvalid())
+return true;
+  TheCall->setArg(Arg, ArgExpr.get());
+  return false;
+};
+
+if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1))
+  return true;
 clang::Expr *SizeOp = TheCall->getArg(2);
 // We warn about copying to or from `nullptr` pointers when `size` is
 // greater than 0. When `size` is value dependent we cannot evaluate its
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121122: Set FLT_EVAL_METHOD to -1 when fast-math is enabled.

2022-03-14 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.

Please fix the clang format issue as well. Other than that and a nit, this LGTM.




Comment at: clang/lib/Lex/PPMacroExpansion.cpp:1587
+  // The `minus` operator is the next token we read from the stream.
+  auto Toks = std::make_unique(2);
+  OS << "-";

Pretty sure `2` can be `1` so that we only create an array of one token, right?


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

https://reviews.llvm.org/D121122

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


[PATCH] D88905: [Clang] Allow "ext_vector_type" applied to Booleans

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

In D88905#3378933 , @simoll wrote:

> In D88905#3375676 , @aaron.ballman 
> wrote:
>
>> In D88905#3362347 , @kaz7 wrote:
>>
>>> At the beginning, this implementation extends `vector_type` attribute which 
>>> is GCC's attribute.  So, this may cause future conflicts with GCC when they 
>>> extend it.  But, now this patch uses it's own `ext_vector_type` attribute.  
>>> So, basically this modification is safe against to the C/C++ future 
>>> extension and the GCC future extension, in my honest opinion.
>>>
>>> Is it OK to accept this patch?  Or is there anything we need to consider?  
>>> I understand that this is a language extension, so it not easy to say OK... 
>>>  But, this patch spent 1 year and a half almost.
>>
>> At a minimum, I think the patch needs to be rebased onto the current trunk. 
>> However, I don't know of a reason why this patch cannot proceed.
>
> It's great to get feedback on this patch! I am rebasing right now.
>
>> I'd be curious whether the codegen for ext_vector_type of N bools is the 
>> same as for N `unsigned _BitInt(1)` (naively, I'd expect them to be 
>> equivalent).
>
> bool vectors are for ``-typed masks in predicated SIMD code - _BitInt 
> is for `iN` integer arithmetic.
> For either type, the memory representation is packed bits with possible 
> differences in alignment, padding.
> So, the difference is in the intended usage and what kind of execution 
> units/operands we expect to live the data near by.

Okay, that sounds like what I'd hoped for, thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88905

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


[PATCH] D121596: [clang-format] Fix crash with ObjC Blocks

2022-03-14 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks created this revision.
HazardyKnusperkeks added reviewers: owenpan, MyDeveloperDay, curdeius.
HazardyKnusperkeks added a project: clang-format.
Herald added a project: All.
HazardyKnusperkeks requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Fixes https://github.com/llvm/llvm-project/issues/54367
Fixes https://github.com/llvm/llvm-project/issues/54368


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121596

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -612,6 +612,22 @@
   EXPECT_TOKEN(Tokens[4], tok::r_brace, TT_InlineASMBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsObjCBlock) {
+  auto Tokens = annotate("int (^)() = ^ ()\n"
+ "  external_source_symbol() { //\n"
+ "  return 1;\n"
+ "};");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_ObjCBlockLParen);
+  EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_ObjCBlockLBrace);
+
+  Tokens = annotate("int *p = ^int*(){ //\n"
+"  return nullptr;\n"
+"}();");
+  ASSERT_EQ(Tokens.size(), 19u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::l_brace, TT_ObjCBlockLBrace);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -783,7 +783,7 @@
 OpeningBrace.ParentBracket = Contexts.back().ContextKind;
 
 if (Contexts.back().CaretFound)
-  OpeningBrace.setType(TT_ObjCBlockLBrace);
+  OpeningBrace.overwriteFixedType(TT_ObjCBlockLBrace);
 Contexts.back().CaretFound = false;
 
 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);


Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -612,6 +612,22 @@
   EXPECT_TOKEN(Tokens[4], tok::r_brace, TT_InlineASMBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsObjCBlock) {
+  auto Tokens = annotate("int (^)() = ^ ()\n"
+ "  external_source_symbol() { //\n"
+ "  return 1;\n"
+ "};");
+  ASSERT_EQ(Tokens.size(), 21u) << Tokens;
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_ObjCBlockLParen);
+  EXPECT_TOKEN(Tokens[13], tok::l_brace, TT_ObjCBlockLBrace);
+
+  Tokens = annotate("int *p = ^int*(){ //\n"
+"  return nullptr;\n"
+"}();");
+  ASSERT_EQ(Tokens.size(), 19u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::l_brace, TT_ObjCBlockLBrace);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -783,7 +783,7 @@
 OpeningBrace.ParentBracket = Contexts.back().ContextKind;
 
 if (Contexts.back().CaretFound)
-  OpeningBrace.setType(TT_ObjCBlockLBrace);
+  OpeningBrace.overwriteFixedType(TT_ObjCBlockLBrace);
 Contexts.back().CaretFound = false;
 
 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121532: [Clang][WIP] Fix Unevaluated Lambdas

2022-03-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a reviewer: erichkeane.
aaron.ballman added a comment.

Adding Erich to look at this WIP for early feedback as he's recently been 
looking at template instantiation guts rather deeply, but I added some 
questions.




Comment at: clang/include/clang/AST/DeclCXX.h:280-282
+LDKUnknown = 0,
+LDKAlwaysDependent,
+LDKNeverDependent,

(Matches the naming style used just above.)



Comment at: clang/lib/Sema/TreeTransform.h:12934
+  // substituting an unevaluated lambda inside of a function's parameter's type
+  // - as parameter type are not instanciated from within a function's DC. We
+  // use isUnevaluatedContext() to distinguish the function parameter case.





Comment at: clang/lib/Sema/TreeTransform.h:12948
+
+  if (OldClass->isDependentContext())
+getDerived().transformedLocalDecl(OldClass, {Class});

Can you explain why you only do these transformations when the old class is a 
dependent context? Also, should this be looking at 
`getDerived().AlwaysRebuild()`? I'm not certain -- we're not calling any 
`Rebuild*` functions here because lambdas are not rebuilt but generated 
entirely from scratch. So I'm guessing we don't need to look at 
`AlwaysRebuild`, but it's a bit unclear.



Comment at: clang/lib/Sema/TreeTransform.h:12968-12971
+  if (E->getCallOperator()->isDependentContext()) {
+getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
+getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
+  }

Are these changes necessary as part of this patch? I'm a bit worried that only 
doing this in dependent contexts may change behavior for code like this: 
https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp#L769



Comment at: clang/lib/Sema/TreeTransform.h:13040
 
-  getDerived().transformedLocalDecl(OldVD, NewVDs);
+  if (OldVD->isTemplated())
+getDerived().transformedLocalDecl(OldVD, NewVDs);

This also seems a bit surprising -- can't the variable declaration be 
non-templated but still dependent (e.g., an `auto` variable whose 
initialization is dependent?)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121532

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


[PATCH] D121475: [Clang][Sema] Avoid crashing for `__builtin_memcpy_inline` with an array argument

2022-03-14 Thread Guillaume Chatelet via Phabricator via cfe-commits
gchatelet accepted this revision.
gchatelet added a comment.

Much better, thank you.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121475

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


[clang] 6ca2f19 - [Clang][Sema] Avoid crashing for `__builtin_memcpy_inline` with an array argument

2022-03-14 Thread Egor Zhdan via cfe-commits

Author: Egor Zhdan
Date: 2022-03-14T12:47:30Z
New Revision: 6ca2f1938f96a71abdecdd96508f48e4d20a5694

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

LOG: [Clang][Sema] Avoid crashing for `__builtin_memcpy_inline` with an array 
argument

This change teaches the Sema logic for `__builtin_memcpy_inline` to implicitly 
convert arrays passed as arguments to pointers, similarly to regular `memcpy`.

This code will no longer cause a compiler crash:
```
void f(char *p) {
char s[1] = {0};
__builtin_memcpy_inline(p, s, 1);
}
```

rdar://88147527

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

Added: 


Modified: 
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/builtins-memcpy-inline.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 2bd0d113fc992..2d14019cdbf18 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -1943,6 +1943,17 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, 
unsigned BuiltinID,
   case Builtin::BI__builtin_nontemporal_store:
 return SemaBuiltinNontemporalOverloaded(TheCallResult);
   case Builtin::BI__builtin_memcpy_inline: {
+auto ArgArrayConversionFailed = [&](unsigned Arg) {
+  ExprResult ArgExpr =
+  DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg));
+  if (ArgExpr.isInvalid())
+return true;
+  TheCall->setArg(Arg, ArgExpr.get());
+  return false;
+};
+
+if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1))
+  return true;
 clang::Expr *SizeOp = TheCall->getArg(2);
 // We warn about copying to or from `nullptr` pointers when `size` is
 // greater than 0. When `size` is value dependent we cannot evaluate its

diff  --git a/clang/test/Sema/builtins-memcpy-inline.cpp 
b/clang/test/Sema/builtins-memcpy-inline.cpp
index 81b11fc021fff..30bc636c78393 100644
--- a/clang/test/Sema/builtins-memcpy-inline.cpp
+++ b/clang/test/Sema/builtins-memcpy-inline.cpp
@@ -36,3 +36,9 @@ void test_memcpy_inline_template(void *dst, const void *src) {
   // we do not try to evaluate size in non intantiated templates.
   __builtin_memcpy_inline(dst, src, size);
 }
+
+void test_memcpy_inline_implicit_conversion(void *ptr) {
+  char a[5];
+  __builtin_memcpy_inline(ptr, a, 5);
+  __builtin_memcpy_inline(a, ptr, 5);
+}



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


[PATCH] D121475: [Clang][Sema] Avoid crashing for `__builtin_memcpy_inline` with an array argument

2022-03-14 Thread Egor Zhdan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6ca2f1938f96: [Clang][Sema] Avoid crashing for 
`__builtin_memcpy_inline` with an array… (authored by egorzhdan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121475

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/builtins-memcpy-inline.cpp


Index: clang/test/Sema/builtins-memcpy-inline.cpp
===
--- clang/test/Sema/builtins-memcpy-inline.cpp
+++ clang/test/Sema/builtins-memcpy-inline.cpp
@@ -36,3 +36,9 @@
   // we do not try to evaluate size in non intantiated templates.
   __builtin_memcpy_inline(dst, src, size);
 }
+
+void test_memcpy_inline_implicit_conversion(void *ptr) {
+  char a[5];
+  __builtin_memcpy_inline(ptr, a, 5);
+  __builtin_memcpy_inline(a, ptr, 5);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1943,6 +1943,17 @@
   case Builtin::BI__builtin_nontemporal_store:
 return SemaBuiltinNontemporalOverloaded(TheCallResult);
   case Builtin::BI__builtin_memcpy_inline: {
+auto ArgArrayConversionFailed = [&](unsigned Arg) {
+  ExprResult ArgExpr =
+  DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg));
+  if (ArgExpr.isInvalid())
+return true;
+  TheCall->setArg(Arg, ArgExpr.get());
+  return false;
+};
+
+if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1))
+  return true;
 clang::Expr *SizeOp = TheCall->getArg(2);
 // We warn about copying to or from `nullptr` pointers when `size` is
 // greater than 0. When `size` is value dependent we cannot evaluate its


Index: clang/test/Sema/builtins-memcpy-inline.cpp
===
--- clang/test/Sema/builtins-memcpy-inline.cpp
+++ clang/test/Sema/builtins-memcpy-inline.cpp
@@ -36,3 +36,9 @@
   // we do not try to evaluate size in non intantiated templates.
   __builtin_memcpy_inline(dst, src, size);
 }
+
+void test_memcpy_inline_implicit_conversion(void *ptr) {
+  char a[5];
+  __builtin_memcpy_inline(ptr, a, 5);
+  __builtin_memcpy_inline(a, ptr, 5);
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -1943,6 +1943,17 @@
   case Builtin::BI__builtin_nontemporal_store:
 return SemaBuiltinNontemporalOverloaded(TheCallResult);
   case Builtin::BI__builtin_memcpy_inline: {
+auto ArgArrayConversionFailed = [&](unsigned Arg) {
+  ExprResult ArgExpr =
+  DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg));
+  if (ArgExpr.isInvalid())
+return true;
+  TheCall->setArg(Arg, ArgExpr.get());
+  return false;
+};
+
+if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1))
+  return true;
 clang::Expr *SizeOp = TheCall->getArg(2);
 // We warn about copying to or from `nullptr` pointers when `size` is
 // greater than 0. When `size` is value dependent we cannot evaluate its
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121498: let EST_Uninstantiated in FunctionProtoType::canThrow return CT_Dependent

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

This seems reasonable to me, but can you please add a lit test and fix the 
format of the code in your commit message?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121498

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


[PATCH] D121283: [Clang] Support multiple attributes in a single pragma

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

In D121283#3375806 , @egorzhdan wrote:

> In D121283#3373560 , @aaron.ballman 
> wrote:
>
>> why do we support multiple attribute *specifiers* in the same pragma? I 
>> would not expect to be able to mix attribute styles in the same pragma given 
>> that all of the individual styles allow you to specify multiple attributes 
>> within a single specifier
>
> I don't think I have a strong use case for this. It seemed consistent with 
> the way multiple attributes can be added for individual declarations, e.g. 
> `__attribute__((cdecl)) __declspec(dllexport) [[noreturn]] void f()`. But we 
> can prohibit multiple specifiers within a single pragma if you think that 
> this is not a good construct to support.

I don't yet think it's a *bad* construct to support...

> In D121283#3373560 , @aaron.ballman 
> wrote:
>
>> why is whitespace the correct separator as opposed to a comma-delimited list?
>
> My motivation for this was also consistency with the syntax for attributes in 
> individual declarations. Given that attribute specifiers are delimited by 
> space for individual declarations (`__attribute__((cdecl)) 
> __attribute__((noreturn)) void f()`), I think it would be unintuitive to 
> require commas for attribute specifiers in pragmas when we could instead 
> reuse the existing syntax of space-delimited attribute specifiers.

Thanks, that makes some sense to me, but at the same time, I can't think of 
another pragma that behaves similarly off the top of my head (usually, lists of 
things have a delimiter other than whitespace), so it's kind of unintuitive 
either way.

As a thought experiment, would it make sense to lift the restriction on the 
number of attributes allowed in a pragma, but not allow multiple attribute 
specifiers? e.g.,

  // These are fine
  #pragma clang attribute push ([[clang::disable_tail_calls, noreturn]], 
apply_to = function)
  #pragma clang attribute pop
  
  #pragma clang attribute push (__attribute__((noreturn, noinline)), apply_to = 
function)
  #pragma clang attribute pop
  
  // These are not allowed
  #pragma clang attribute push ([[clang::disable_tail_calls]] [[noreturn]], 
apply_to = function)
  #pragma clang attribute pop
  
  #pragma clang attribute push (__attribute__((noreturn)) 
__attribute__((noinline)), apply_to = function)
  #pragma clang attribute pop
  
  #pragma clang attribute push ([[clang::disable_tail_calls]] 
__attribute__((noreturn)), apply_to = function)
  #pragma clang attribute pop

This still allows you to specify more than one attribute in the pragma, but 
removes the concerns about how to separate the syntaxes (whitespace or another 
delimiter) while still leaving that design open in the future if there's a 
strong need to mix syntaxes.

The pragma attribute feature has a lot of power to it, but it also comes with a 
lot of risk to users, so it's a feature that I think we should be cautious 
about extending (in general). I think what you propose here could very well be 
reasonable, but I'm a bit worried that there's not a clear need for that amount 
of flexibility, which is why I'm sort of leaning towards being more restrictive 
here. However, this isn't exposing any functionality that users can't already 
do the long way with multiple pragmas, so I don't see a blocking concern with 
the current patch either.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121283

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


[PATCH] D121586: [Clang][VE] Add the rest of intrinsics to clang

2022-03-14 Thread Simon Moll via Phabricator via cfe-commits
simoll added inline comments.



Comment at: clang/include/clang/Basic/BuiltinsVEVL.gen.def:1242
+#if 0
+BUILTIN(__builtin_ve_vl_andm_mmm, "V256bV256bV256b", "n")
+BUILTIN(__builtin_ve_vl_andm_MMM, "V512bV512bV512b", "n")

Could you comment at the top of this file (i know, again) that the `#if 0`-ed 
and commented-out parts are because of the missing mask vector type?



Comment at: clang/lib/Headers/velintrin.h:65
+
+static inline unsigned long int _vel_pack_i32(int a, int b) {
+  return (((unsigned long int)a) << 32) | (unsigned int)b;

Is there any particular reason the parameters are signed?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121586

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


[PATCH] D121410: Have cpu-specific variants set 'tune-cpu' as an optimization hint

2022-03-14 Thread Erich Keane via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
erichkeane marked an inline comment as done.
Closed by commit rGdc152659b452: Have cpu-specific variants set 
'tune-cpu' as an optimization hint (authored by erichkeane).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D121410?vs=414709&id=415077#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121410

Files:
  clang/include/clang/Basic/TargetInfo.h
  clang/lib/Basic/Targets/X86.cpp
  clang/lib/Basic/Targets/X86.h
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGen/attr-cpuspecific-avx-abi.c
  clang/test/CodeGen/attr-cpuspecific.c
  llvm/include/llvm/Support/X86TargetParser.def

Index: llvm/include/llvm/Support/X86TargetParser.def
===
--- llvm/include/llvm/Support/X86TargetParser.def
+++ llvm/include/llvm/Support/X86TargetParser.def
@@ -211,47 +211,47 @@
 #undef X86_FEATURE
 
 #ifndef CPU_SPECIFIC
-#define CPU_SPECIFIC(NAME, MANGLING, FEATURES)
+#define CPU_SPECIFIC(NAME, TUNE_NAME, MANGLING, FEATURES)
 #endif
 
 #ifndef CPU_SPECIFIC_ALIAS
-#define CPU_SPECIFIC_ALIAS(NEW_NAME, NAME)
+#define CPU_SPECIFIC_ALIAS(NEW_NAME, TUNE_NAME, NAME)
 #endif
 
-CPU_SPECIFIC("generic", 'A', "")
-CPU_SPECIFIC("pentium", 'B', "")
-CPU_SPECIFIC("pentium_pro", 'C', "+cmov")
-CPU_SPECIFIC("pentium_mmx", 'D', "+mmx")
-CPU_SPECIFIC("pentium_ii", 'E', "+cmov,+mmx")
-CPU_SPECIFIC("pentium_iii", 'H', "+cmov,+mmx,+sse")
-CPU_SPECIFIC_ALIAS("pentium_iii_no_xmm_regs", "pentium_iii")
-CPU_SPECIFIC("pentium_4", 'J', "+cmov,+mmx,+sse,+sse2")
-CPU_SPECIFIC("pentium_m", 'K', "+cmov,+mmx,+sse,+sse2")
-CPU_SPECIFIC("pentium_4_sse3", 'L', "+cmov,+mmx,+sse,+sse2,+sse3")
-CPU_SPECIFIC("core_2_duo_ssse3", 'M', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3")
-CPU_SPECIFIC("core_2_duo_sse4_1", 'N', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1")
-CPU_SPECIFIC("atom", 'O', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+movbe")
-CPU_SPECIFIC("atom_sse4_2", 'c', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt")
-CPU_SPECIFIC("core_i7_sse4_2", 'P', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt")
-CPU_SPECIFIC("core_aes_pclmulqdq", 'Q', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt")
-CPU_SPECIFIC("atom_sse4_2_movbe", 'd', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt")
-CPU_SPECIFIC("goldmont", 'i', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt")
-CPU_SPECIFIC("sandybridge", 'R', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt,+avx")
-CPU_SPECIFIC_ALIAS("core_2nd_gen_avx", "sandybridge")
-CPU_SPECIFIC("ivybridge", 'S', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+popcnt,+f16c,+avx")
-CPU_SPECIFIC_ALIAS("core_3rd_gen_avx", "ivybridge")
-CPU_SPECIFIC("haswell", 'V', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt,+f16c,+avx,+fma,+bmi,+lzcnt,+avx2")
-CPU_SPECIFIC_ALIAS("core_4th_gen_avx", "haswell")
-CPU_SPECIFIC("core_4th_gen_avx_tsx", 'W', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt,+f16c,+avx,+fma,+bmi,+lzcnt,+avx2")
-CPU_SPECIFIC("broadwell", 'X', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt,+f16c,+avx,+fma,+bmi,+lzcnt,+avx2,+adx")
-CPU_SPECIFIC_ALIAS("core_5th_gen_avx", "broadwell")
-CPU_SPECIFIC("core_5th_gen_avx_tsx", 'Y', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt,+f16c,+avx,+fma,+bmi,+lzcnt,+avx2,+adx")
-CPU_SPECIFIC("knl", 'Z', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt,+f16c,+avx,+fma,+bmi,+lzcnt,+avx2,+avx512f,+adx,+avx512er,+avx512pf,+avx512cd")
-CPU_SPECIFIC_ALIAS("mic_avx512", "knl")
-CPU_SPECIFIC("skylake", 'b', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt,+f16c,+avx,+fma,+bmi,+lzcnt,+avx2,+adx,+mpx")
-CPU_SPECIFIC( "skylake_avx512", 'a', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt,+f16c,+avx,+fma,+bmi,+lzcnt,+avx2,+avx512dq,+avx512f,+adx,+avx512cd,+avx512bw,+avx512vl,+clwb")
-CPU_SPECIFIC("cannonlake", 'e', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt,+f16c,+avx,+fma,+bmi,+lzcnt,+avx2,+avx512dq,+avx512f,+adx,+avx512ifma,+avx512cd,+avx512bw,+avx512vl,+avx512vbmi")
-CPU_SPECIFIC("knm", 'j', "+cmov,+mmx,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2,+movbe,+popcnt,+f16c,+avx,+fma,+bmi,+lzcnt,+avx2,+avx512f,+adx,+avx512er,+avx512pf,+avx512cd,+avx5124fmaps,+avx5124vnniw,+avx512vpopcntdq")
+CPU_SPECIFIC("generic", "generic", 'A', "")
+CPU_SPECIFIC("pentium", "pentium", 'B', "")
+CPU_SPECIFIC("pentium_pro", "pentiumpro", 'C', "+cmov")
+CPU_SPECIFIC("pentium_mmx", "pentium-mmx", 'D', "+mmx")
+CPU_SPECIFIC("pentium_ii", "pentium2", 'E', "+cmov,+mmx")
+CPU_SPECIFIC("pentium_iii", "pentium3", 'H', "+cmov,+mmx,+sse")
+CPU_SPECIFIC_ALIAS("pentium_iii_no_xmm_regs", "pentium3", "pentiu

[clang] dc15265 - Have cpu-specific variants set 'tune-cpu' as an optimization hint

2022-03-14 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-03-14T06:14:30-07:00
New Revision: dc152659b4527cc2e5f75cc33f36df67c7d5db26

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

LOG: Have cpu-specific variants set 'tune-cpu' as an optimization hint

Due to various implementation constraints, despite the programmer
choosing a 'processor' cpu_dispatch/cpu_specific needs to use the
'feature' list of a processor to identify it. This results in the
identified processor in source-code not being propogated to the
optimizer, and thus, not able to be tuned for.

This patch changes to use the actual cpu as written for tune-cpu so that
opt can make decisions based on the cpu-as-spelled, which should better
match the behavior expected by the programmer.

Note that the 'valid' list of processors for x86 is in
llvm/include/llvm/Support/X86TargetParser.def. At the moment, this list
contains only Intel processors, but other vendors may wish to add their
own entries as 'alias'es (or with different feature lists!).

If this is not done, there is two potential performance issues with the
patch, but I believe them to be worth it in light of the improvements to
behavior and performance.

1- In the event that the user spelled "ProcessorB", but we only have the
features available to test for "ProcessorA" (where A is B minus
features),
AND there is an optimization opportunity for "B" that negatively affects
"A", the optimizer will likely choose to do so.

2- In the event that the user spelled VendorI's processor, and the
feature
list allows it to run on VendorA's processor of similar features, AND
there
is an optimization opportunity for VendorIs that negatively affects
"A"s,
the optimizer will likely choose to do so. This can be fixed by adding
an
alias to X86TargetParser.def.

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

Added: 


Modified: 
clang/include/clang/Basic/TargetInfo.h
clang/lib/Basic/Targets/X86.cpp
clang/lib/Basic/Targets/X86.h
clang/lib/CodeGen/CodeGenModule.cpp
clang/test/CodeGen/attr-cpuspecific-avx-abi.c
clang/test/CodeGen/attr-cpuspecific.c
llvm/include/llvm/Support/X86TargetParser.def

Removed: 




diff  --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 34884f621e770..94da7ac593a07 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -1375,6 +1375,13 @@ class TargetInfo : public virtual 
TransferrableTargetInfo,
 "cpu_specific Multiversioning not implemented on this target");
   }
 
+  // Get the value for the 'tune-cpu' flag for a cpu_specific variant with the
+  // programmer-specified 'Name'.
+  virtual StringRef getCPUSpecificTuneName(StringRef Name) const {
+llvm_unreachable(
+"cpu_specific Multiversioning not implemented on this target");
+  }
+
   // Get a list of the features that make up the CPU option for
   // cpu_specific/cpu_dispatch so that it can be passed to llvm as optimization
   // options.

diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index 5c4bd364b06a3..1ec2bb9c249f0 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -1095,22 +1095,22 @@ unsigned 
X86TargetInfo::multiVersionSortPriority(StringRef Name) const {
 
 bool X86TargetInfo::validateCPUSpecificCPUDispatch(StringRef Name) const {
   return llvm::StringSwitch(Name)
-#define CPU_SPECIFIC(NAME, MANGLING, FEATURES) .Case(NAME, true)
-#define CPU_SPECIFIC_ALIAS(NEW_NAME, NAME) .Case(NEW_NAME, true)
+#define CPU_SPECIFIC(NAME, TUNE_NAME, MANGLING, FEATURES) .Case(NAME, true)
+#define CPU_SPECIFIC_ALIAS(NEW_NAME, TUNE_NAME, NAME) .Case(NEW_NAME, true)
 #include "llvm/Support/X86TargetParser.def"
   .Default(false);
 }
 
 static StringRef CPUSpecificCPUDispatchNameDealias(StringRef Name) {
   return llvm::StringSwitch(Name)
-#define CPU_SPECIFIC_ALIAS(NEW_NAME, NAME) .Case(NEW_NAME, NAME)
+#define CPU_SPECIFIC_ALIAS(NEW_NAME, TUNE_NAME, NAME) .Case(NEW_NAME, NAME)
 #include "llvm/Support/X86TargetParser.def"
   .Default(Name);
 }
 
 char X86TargetInfo::CPUSpecificManglingCharacter(StringRef Name) const {
   return llvm::StringSwitch(CPUSpecificCPUDispatchNameDealias(Name))
-#define CPU_SPECIFIC(NAME, MANGLING, FEATURES) .Case(NAME, MANGLING)
+#define CPU_SPECIFIC(NAME, TUNE_NAME, MANGLING, FEATURES) .Case(NAME, MANGLING)
 #include "llvm/Support/X86TargetParser.def"
   .Default(0);
 }
@@ -1119,12 +1119,20 @@ void X86TargetInfo::getCPUSpecificCPUDispatchFeatures(
 StringRef Name, llvm::SmallVectorImpl &Features) const {
   StringRef WholeList =
   llvm::StringSwitch(CPUSpecificCPUDispatchNameDealias(Name))
-#define CPU_SPECIFIC(NAME, MANGLING, FEATURES) .Case(NAME, FEATURES)
+#define CPU_SPECIFIC(N

[PATCH] D121599: [AST] Better recovery on an expression refers to an invalid decl.

2022-03-14 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added a project: All.
hokein requested review of this revision.
Herald added a project: clang.

Prior to the patch, we didn't build a DeclRefExpr if the Decl being
referred to is invalid, because many clang downstream AST consumers
assume it, violating it will cause many diagnostic regressions.

With this patch, we build a DeclRefExpr enven for an invalid decl (when the
AcceptInvalidDecl is true), and wrap it with a dependent-type
RecoveryExpr (to prevent follow-up semantic analysis, and diagnostic
regressions).

This is a revised version of https://reviews.llvm.org/D76831


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121599

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/AST/ast-dump-recovery.cpp
  clang/test/SemaTemplate/constraints.cpp
  clang/test/SemaTemplate/cxx2a-constraint-exprs.cpp
  clang/test/SemaTemplate/instantiate-var-template.cpp

Index: clang/test/SemaTemplate/instantiate-var-template.cpp
===
--- clang/test/SemaTemplate/instantiate-var-template.cpp
+++ clang/test/SemaTemplate/instantiate-var-template.cpp
@@ -28,7 +28,7 @@
   template constexpr T b = a; // expected-error {{invalid application of 'sizeof' to an incomplete type 'void'}}
 
   static_assert(b == 1, "");
-  static_assert(b == 1, ""); // expected-note {{in instantiation of}} expected-error {{not an integral constant}}
+  static_assert(b == 1, ""); // expected-note {{in instantiation of}}
 
   template void f() {
 static_assert(a == 0, ""); // expected-error {{static_assert failed due to requirement 'a == 0'}}
Index: clang/test/SemaTemplate/cxx2a-constraint-exprs.cpp
===
--- clang/test/SemaTemplate/cxx2a-constraint-exprs.cpp
+++ clang/test/SemaTemplate/cxx2a-constraint-exprs.cpp
@@ -26,28 +26,22 @@
 
 namespace constant_evaluated {
   template requires f struct S {};
-  // expected-note@-1{{in instantiation of}} expected-note@-1{{while substituting}} \
- expected-error@-1{{substitution into constraint expression resulted in a non-constant expression}} \
- expected-note@-1{{subexpression not valid}}
+  // expected-note@-1{{in instantiation of}} expected-note@-1{{while substituting}}
   using s = S;
-  // expected-note@-1 2{{while checking}}
+  // expected-note@-1 {{while checking}}
   template void foo() requires f { };
   // expected-note@-1{{in instantiation}} expected-note@-1{{while substituting}} \
- expected-note@-1{{candidate template ignored}} expected-note@-1{{subexpression not valid}} \
- expected-error@-1{{substitution into constraint expression resulted in a non-constant expression}}
+ expected-note@-1{{candidate template ignored}}
   int a = (foo(), 0);
-  // expected-note@-1 2{{while checking}} expected-error@-1{{no matching function}} \
- expected-note@-1 2{{in instantiation}}
+  // expected-note@-1 {{while checking}} expected-error@-1{{no matching function}} \
+ expected-note@-1 {{in instantiation}}
   template void bar() requires requires { requires f; } { };
-  // expected-note@-1{{in instantiation}} expected-note@-1{{subexpression not valid}} \
+  // expected-note@-1{{in instantiation}} \
  expected-note@-1{{while substituting}} \
- expected-error@-1{{substitution into constraint expression resulted in a non-constant expression}} \
- expected-note@-1 2{{while checking the satisfaction of nested requirement}}
+ expected-note@-1 {{while checking the satisfaction of nested requirement}}
   int b = (bar(), 0);
   template struct M { static void foo() requires f { }; };
-  // expected-note@-1{{in instantiation}} expected-note@-1{{subexpression not valid}} \
- expected-note@-1{{while substituting}} \
- expected-error@-1{{substitution into constraint expression resulted in a non-constant expression}}
+  // expected-note@-1{{in instantiation}} expected-note@-1{{while substituting}}
   int c = (M::foo(), 0);
-  // expected-note@-1 2{{while checking}}
+  // expected-note@-1 {{while checking}}
 }
Index: clang/test/SemaTemplate/constraints.cpp
===
--- clang/test/SemaTemplate/constraints.cpp
+++ clang/test/SemaTemplate/constraints.cpp
@@ -15,12 +15,11 @@
 
   template constexpr int test = 0;
   template requires C constexpr int test = 1;
-  template requires (B && C) || (X::value && C) constexpr int test = 2; // expected-error {{non-constant expression}} expected-note {{subexpression}} expected-note {{instantiation of}} expected-note {{while substituting}}
+  template requires (B && C) || (X::value && C) constexpr int test = 2; // expected-note {{instantiation of}} expected-note {{while substituting}}
   static_assert(test == 2);
   static_assert(test == 2);
   static_assert(test == 2); // satisfaction of second term of || not considered
   static_assert(test 

[PATCH] D88905: [Clang] Allow "ext_vector_type" applied to Booleans

2022-03-14 Thread Simon Moll via Phabricator via cfe-commits
simoll updated this revision to Diff 415079.
simoll added a comment.

Rebased


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88905

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/AST/Type.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaExprMember.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/AST/ast-print-vector-size-bool.c
  clang/test/CodeGen/debug-info-vector-bool.c
  clang/test/CodeGen/vector-alignment.c
  clang/test/Sema/ext_vector_casts.c
  clang/test/SemaCXX/constexpr-vectors.cpp
  clang/test/SemaCXX/vector-bool.cpp
  clang/test/SemaCXX/vector-size-conditional.cpp
  clang/test/SemaOpenCL/ext_vectors.cl

Index: clang/test/SemaOpenCL/ext_vectors.cl
===
--- clang/test/SemaOpenCL/ext_vectors.cl
+++ clang/test/SemaOpenCL/ext_vectors.cl
@@ -5,6 +5,7 @@
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=clc++2021
 
 typedef float float4 __attribute__((ext_vector_type(4)));
+typedef __attribute__((ext_vector_type(8))) bool BoolVector; // expected-error {{invalid vector element type 'bool'}}
 
 void test_ext_vector_accessors(float4 V) {
   V = V.wzyx;
Index: clang/test/SemaCXX/vector-size-conditional.cpp
===
--- clang/test/SemaCXX/vector-size-conditional.cpp
+++ clang/test/SemaCXX/vector-size-conditional.cpp
@@ -13,6 +13,7 @@
 using FourFloats = float __attribute__((__vector_size__(16)));
 using TwoDoubles = double __attribute__((__vector_size__(16)));
 using FourDoubles = double __attribute__((__vector_size__(32)));
+using EightBools = bool __attribute__((ext_vector_type(8)));
 
 FourShorts four_shorts;
 TwoInts two_ints;
@@ -25,6 +26,8 @@
 FourFloats four_floats;
 TwoDoubles two_doubles;
 FourDoubles four_doubles;
+EightBools eight_bools;
+EightBools other_eight_bools;
 
 enum E {};
 enum class SE {};
@@ -95,6 +98,9 @@
   (void)(four_ints ? four_uints : 3.0f);
   (void)(four_ints ? four_ints : 3.0f);
 
+  // Allow conditional select on bool vectors.
+  (void)(eight_bools ? eight_bools : other_eight_bools);
+
   // When there is a vector and a scalar, conversions must be legal.
   (void)(four_ints ? four_floats : 3); // should work, ints can convert to floats.
   (void)(four_ints ? four_uints : e);  // expected-error {{cannot convert between scalar type 'E' and vector type 'FourUInts'}}
@@ -163,10 +169,10 @@
 void Templates() {
   dependent_cond(two_ints);
   dependent_operand(two_floats);
-  // expected-error@159 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(4 * sizeof(double double' (vector of 4 'double' values))}}}
+  // expected-error@165 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(4 * sizeof(double double' (vector of 4 'double' values))}}}
   all_dependent(four_ints, four_uints, four_doubles); // expected-note {{in instantiation of}}
 
-  // expected-error@159 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(2 * sizeof(unsigned int unsigned int' (vector of 2 'unsigned int' values))}}}
+  // expected-error@165 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(2 * sizeof(unsigned int unsigned int' (vector of 2 'unsigned int' values))}}}
   all_dependent(four_ints, four_uints, two_uints); // expected-note {{in instantiation of}}
   all_dependent(four_ints, four_uints, four_uints);
 }
Index: clang/test/SemaCXX/vector-bool.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/vector-bool.cpp
@@ -0,0 +1,92 @@
+// RUN: %clang_cc1 -triple x86_64-linux-pc -fsyntax-only -verify -fexceptions -fcxx-exceptions %s -std=c++17
+// Note that this test depends on the size of long-long to be different from
+// int, so it specifies a triple.
+
+using FourShorts = short __attribute__((__vector_size__(8)));
+using TwoInts = int __attribute__((__vector_size__(8)));
+using EightInts = int __attribute__((__vector_size__(32)));
+using TwoUInts = unsign

[clang] 8cba721 - Implement literal suffixes for _BitInt

2022-03-14 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-03-14T09:24:19-04:00
New Revision: 8cba72177dcd8de5d37177dbaf2347e5c1f0f1e8

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

LOG: Implement literal suffixes for _BitInt

WG14 adopted N2775 (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2775.pdf)
at our Feb 2022 meeting. This paper adds a literal suffix for
bit-precise types that automatically sizes the bit-precise type to be
the smallest possible legal _BitInt type that can represent the literal
value. The suffix chosen is wb (for a signed bit-precise type) which
can be combined with the u suffix (for an unsigned bit-precise type).

The preprocessor continues to operate as-if all integer types were
intmax_t/uintmax_t, including bit-precise integer types. It is a
constraint violation if the bit-precise literal is too large to fit
within that type in the context of the preprocessor (when still using
a pp-number preprocessing token), but it is not a constraint violation
in other circumstances. This allows you to make bit-precise integer
literals that are wider than what the preprocessor currently supports
in order to initialize variables, etc.

Added: 
clang/test/AST/bitint-suffix.c
clang/test/Lexer/bitint-constants-compat.c
clang/test/Lexer/bitint-constants.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticCommonKinds.td
clang/include/clang/Lex/LiteralSupport.h
clang/lib/AST/StmtPrinter.cpp
clang/lib/Lex/LiteralSupport.cpp
clang/lib/Lex/PPExpressions.cpp
clang/lib/Sema/SemaExpr.cpp
llvm/include/llvm/ADT/APInt.h
llvm/lib/Support/APInt.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 53d07c03af0f9..2422c8f2cba7a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -111,6 +111,8 @@ C2x Feature Support
 
 - Implemented `WG14 N2674 The noreturn attribute 
`_.
 - Implemented `WG14 N2935 Make false and true first-class language features 
`_.
+- Implemented `WG14 N2763 Adding a fundamental type for N-bit integers 
`_.
+- Implemented `WG14 N2775 Literal suffixes for bit-precise integers 
`_.
 
 C++ Language Changes in Clang
 -

diff  --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td 
b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index 421527827a4bd..66defc1d8ca5f 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -207,6 +207,12 @@ def err_cxx2b_size_t_suffix: Error<
 def err_size_t_literal_too_large: Error<
   "%select{signed |}0'size_t' literal is out of range of possible "
   "%select{signed |}0'size_t' values">;
+def ext_c2x_bitint_suffix : ExtWarn<
+  "'_BitInt' suffix for literals is a C2x extension">,
+  InGroup;
+def warn_c2x_compat_bitint_suffix : Warning<
+  "'_BitInt' suffix for literals is incompatible with C standards before C2x">,
+  InGroup, DefaultIgnore;
 def err_integer_literal_too_large : Error<
   "integer literal is too large to be represented in any %select{signed |}0"
   "integer type">;

diff  --git a/clang/include/clang/Lex/LiteralSupport.h 
b/clang/include/clang/Lex/LiteralSupport.h
index 32471969f5967..977963dcbbba0 100644
--- a/clang/include/clang/Lex/LiteralSupport.h
+++ b/clang/include/clang/Lex/LiteralSupport.h
@@ -69,10 +69,11 @@ class NumericLiteralParser {
   bool isImaginary : 1; // 1.0i
   bool isFloat16 : 1;   // 1.0f16
   bool isFloat128 : 1;  // 1.0q
-  uint8_t MicrosoftInteger; // Microsoft suffix extension i8, i16, i32, or i64.
-
   bool isFract : 1; // 1.0hr/r/lr/uhr/ur/ulr
   bool isAccum : 1; // 1.0hk/k/lk/uhk/uk/ulk
+  bool isBitInt : 1;// 1wb, 1uwb (C2x)
+  uint8_t MicrosoftInteger; // Microsoft suffix extension i8, i16, i32, or i64.
+
 
   bool isFixedPointLiteral() const {
 return (saw_period || saw_exponent) && saw_fixed_point_suffix;
@@ -120,6 +121,13 @@ class NumericLiteralParser {
   /// calculating the digit sequence of the exponent.
   bool GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale);
 
+  /// Get the digits that comprise the literal. This excludes any prefix or
+  /// suffix associated with the literal.
+  StringRef getLiteralDigits() const {
+assert(!hadError && "cannot reliably get the literal digits with an 
error");
+return StringRef(DigitsBegin, SuffixBegin - DigitsBegin);
+  }
+
 private:
 
   void ParseNumberStartingWithZero(SourceLocation TokLoc);

diff  --git a/clang/lib/AST/StmtPrinter.cpp b/cl

[PATCH] D120770: [C2x] Implement literal suffixes for _BitInt

2022-03-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman closed this revision.
aaron.ballman added a comment.

Thanks for the reviews! I've commit in 8cba72177dcd8de5d37177dbaf2347e5c1f0f1e8 
 (LLVM 
bits) and 8cba72177dcd8de5d37177dbaf2347e5c1f0f1e8 
 (Clang 
bits)


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

https://reviews.llvm.org/D120770

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


[PATCH] D121586: [Clang][VE] Add the rest of intrinsics to clang

2022-03-14 Thread Kazushi Marukawa via Phabricator via cfe-commits
kaz7 added inline comments.



Comment at: clang/include/clang/Basic/BuiltinsVEVL.gen.def:1242
+#if 0
+BUILTIN(__builtin_ve_vl_andm_mmm, "V256bV256bV256b", "n")
+BUILTIN(__builtin_ve_vl_andm_MMM, "V512bV512bV512b", "n")

simoll wrote:
> Could you comment at the top of this file (i know, again) that the `#if 0`-ed 
> and commented-out parts are because of the missing mask vector type?
I don't want to add at the top of this file bacause this file is automatically 
generated and I don't want to use any structured comments.  But, I added 
comments at the each point of `#if 0` and added comments at the place where 
include this file.



Comment at: clang/lib/Headers/velintrin.h:65
+
+static inline unsigned long int _vel_pack_i32(int a, int b) {
+  return (((unsigned long int)a) << 32) | (unsigned int)b;

simoll wrote:
> Is there any particular reason the parameters are signed?
I guess no.  So, I changed the code following your suggestion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121586

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


[PATCH] D121586: [Clang][VE] Add the rest of intrinsics to clang

2022-03-14 Thread Simon Moll via Phabricator via cfe-commits
simoll accepted this revision.
simoll added a comment.
This revision is now accepted and ready to land.

Thx


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121586

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


[PATCH] D121498: let EST_Uninstantiated in FunctionProtoType::canThrow return CT_Dependent

2022-03-14 Thread zhouyizhou via Phabricator via cfe-commits
zhouyizhou added a comment.

In D121498#3379222 , @erichkeane 
wrote:

> This seems reasonable to me, but can you please add a lit test and fix the 
> format of the code in your commit message?

Thank you for reviewing the patch for me ;-)  I am a beginner, please give me a 
couple of days to add the lit test and fix the format of the code in my commit 
message and make my patch better.

Thanks again
Zhouyi


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121498

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


[PATCH] D121206: [AARCH64] ssbs should be enabled by default for cortex-x1, cortex-x1c, cortex-a77

2022-03-14 Thread Amilendra Kodithuwakku via Phabricator via cfe-commits
amilendra accepted this revision.
amilendra added inline comments.
This revision is now accepted and ready to land.



Comment at: llvm/lib/Target/AArch64/AArch64.td:978
  FeatureNEON, FeatureRCPC, FeaturePerfMon,
  FeatureSPE, FeatureFullFP16, FeatureDotProd];
   list X1C  = [HasV8_2aOps, FeatureCrypto, FeatureFPARMv8,

stuij wrote:
> dmgreen wrote:
> > X1 and A77 missing SSBS too. Should they be added at the same time?
> Yes they should. Thanks!
Maybe add unit tests for X1 and A77 too?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121206

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


[PATCH] D121596: [clang-format] Fix crash with ObjC Blocks

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



Comment at: clang/unittests/Format/TokenAnnotatorTest.cpp:615
 
+TEST_F(TokenAnnotatorTest, UnderstandsObjCBlock) {
+  auto Tokens = annotate("int (^)() = ^ ()\n"

I hope the name is appropriate, I don't know shit about objective c.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121596

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


[PATCH] D121586: [Clang][VE] Add the rest of intrinsics to clang

2022-03-14 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added inline comments.



Comment at: clang/include/clang/Basic/BuiltinsVEVL.gen.def:35
+// TODO: Vector mask registers
+// Depend on https://reviews.llvm.org/D88905
+// BUILTIN(__builtin_ve_vl_vst_vssml, "vV256dLUiv*V256bUi", "n")

Why leave dead code under comments? Bad habit, remove it please.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121586

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


[clang] 9e3e85a - Silence -Wlogical-op-parentheses and fix a logic bug while doing so

2022-03-14 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-03-14T10:13:39-04:00
New Revision: 9e3e85ac6efeb948647810dae93f3ba0cc8a4314

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

LOG: Silence -Wlogical-op-parentheses and fix a logic bug while doing so

Added: 


Modified: 
clang/lib/Lex/LiteralSupport.cpp

Removed: 




diff  --git a/clang/lib/Lex/LiteralSupport.cpp 
b/clang/lib/Lex/LiteralSupport.cpp
index 6bab51250adb1..6e6fd361ebf94 100644
--- a/clang/lib/Lex/LiteralSupport.cpp
+++ b/clang/lib/Lex/LiteralSupport.cpp
@@ -907,8 +907,8 @@ NumericLiteralParser::NumericLiteralParser(StringRef 
TokSpelling,
   // explicitly do not support the suffix in C++ as an extension because a
   // library-based UDL that resolves to a library type may be more
   // appropriate there.
-  if (!LangOpts.CPlusPlus && (s[0] == 'w' && s[1] == 'b') ||
-  (s[0] == 'W' && s[1] == 'B')) {
+  if (!LangOpts.CPlusPlus && ((s[0] == 'w' && s[1] == 'b') ||
+  (s[0] == 'W' && s[1] == 'B'))) {
 isBitInt = true;
 HasSize = true;
 ++s; // Skip both characters (2nd char skipped on continue).



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


[PATCH] D121206: [AARCH64] ssbs should be enabled by default for cortex-x1, cortex-x1c, cortex-a77

2022-03-14 Thread Ties Stuij via Phabricator via cfe-commits
stuij marked 2 inline comments as done.
stuij added inline comments.



Comment at: llvm/lib/Target/AArch64/AArch64.td:978
  FeatureNEON, FeatureRCPC, FeaturePerfMon,
  FeatureSPE, FeatureFullFP16, FeatureDotProd];
   list X1C  = [HasV8_2aOps, FeatureCrypto, FeatureFPARMv8,

amilendra wrote:
> stuij wrote:
> > dmgreen wrote:
> > > X1 and A77 missing SSBS too. Should they be added at the same time?
> > Yes they should. Thanks!
> Maybe add unit tests for X1 and A77 too?
I did. See the top file.

In general it'd be good to have better testing for individual cores. This will 
happen more structurally in future changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121206

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


[PATCH] D121532: [Clang][WIP] Fix Unevaluated Lambdas

2022-03-14 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/TreeTransform.h:12948
+
+  if (OldClass->isDependentContext())
+getDerived().transformedLocalDecl(OldClass, {Class});

aaron.ballman wrote:
> Can you explain why you only do these transformations when the old class is a 
> dependent context? Also, should this be looking at 
> `getDerived().AlwaysRebuild()`? I'm not certain -- we're not calling any 
> `Rebuild*` functions here because lambdas are not rebuilt but generated 
> entirely from scratch. So I'm guessing we don't need to look at 
> `AlwaysRebuild`, but it's a bit unclear.
I was trying to fix some crashes at some point, Not sure that's still needed 
anymore, I have to check. I suspect you might be right.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121532

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


[PATCH] D120271: [Clang] Add offload kind to embedded offload object

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

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120271

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


[PATCH] D121586: [Clang][VE] Add the rest of intrinsics to clang

2022-03-14 Thread Kazushi Marukawa via Phabricator via cfe-commits
kaz7 added inline comments.



Comment at: clang/include/clang/Basic/BuiltinsVEVL.gen.def:35
+// TODO: Vector mask registers
+// Depend on https://reviews.llvm.org/D88905
+// BUILTIN(__builtin_ve_vl_vst_vssml, "vV256dLUiv*V256bUi", "n")

xbolva00 wrote:
> Why leave dead code under comments? Bad habit, remove it please.
Thank you for the comments.  What is the best way to leave a list of functions 
need to be supported in near future?  Should I just make a list of function 
names using vector mask registers instead of writing them down with "BUILTIN" 
for future reference?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121586

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


[PATCH] D121602: [clang][dataflow] Model the behavior of non-standard optional constructors

2022-03-14 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev created this revision.
sgatev added reviewers: ymandel, xazax.hun, gribozavr2.
Herald added subscribers: tschuett, steakhal, rnkovacs.
Herald added a project: All.
sgatev requested review of this revision.
Herald added a project: clang.

Model nullopt, inplace, value, and conversion constructors.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121602

Files:
  clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
  clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp
@@ -31,8 +31,8 @@
 
 // FIXME: Move header definitions in separate file(s).
 static constexpr char StdTypeTraitsHeader[] = R"(
-#ifndef TYPE_TRAITS_H
-#define TYPE_TRAITS_H
+#ifndef STD_TYPE_TRAITS_H
+#define STD_TYPE_TRAITS_H
 
 namespace std {
 
@@ -127,6 +127,9 @@
   typedef T type;
 };
 
+template 
+using remove_cv_t = typename remove_cv::type;
+
 template 
 struct decay {
  private:
@@ -139,9 +142,196 @@
typename remove_cv::type>::type>::type type;
 };
 
+template 
+struct enable_if {};
+
+template 
+struct enable_if {
+  typedef T type;
+};
+
+template 
+using enable_if_t = typename enable_if::type;
+
+template 
+struct is_same : false_type {};
+
+template 
+struct is_same : true_type {};
+
+template 
+struct is_void : is_same::type> {};
+
+namespace detail {
+
+template 
+auto try_add_rvalue_reference(int) -> type_identity;
+template 
+auto try_add_rvalue_reference(...) -> type_identity;
+
+}  // namespace detail
+
+template 
+struct add_rvalue_reference : decltype(detail::try_add_rvalue_reference(0)) {
+};
+
+template 
+typename add_rvalue_reference::type declval() noexcept;
+
+namespace detail {
+
+template 
+auto test_returnable(int)
+-> decltype(void(static_cast(nullptr)), true_type{});
+template 
+auto test_returnable(...) -> false_type;
+
+template 
+auto test_implicitly_convertible(int)
+-> decltype(void(declval()(declval())), true_type{});
+template 
+auto test_implicitly_convertible(...) -> false_type;
+
+}  // namespace detail
+
+template 
+struct is_convertible
+: integral_constant(0))::value &&
+ decltype(detail::test_implicitly_convertible(
+ 0))::value) ||
+(is_void::value && is_void::value)> {};
+
+template 
+inline constexpr bool is_convertible_v = is_convertible::value;
+
+template 
+using void_t = void;
+
+template 
+struct is_constructible_ : false_type {};
+
+template 
+struct is_constructible_()...))>, T, Args...>
+: true_type {};
+
+template 
+using is_constructible = is_constructible_, T, Args...>;
+
+template 
+inline constexpr bool is_constructible_v = is_constructible::value;
+
+template 
+struct __uncvref {
+  typedef typename remove_cv::type>::type type;
+};
+
+template 
+using __uncvref_t = typename __uncvref<_Tp>::type;
+
+template 
+using _BoolConstant = integral_constant;
+
+template 
+using _IsSame = _BoolConstant<__is_same(_Tp, _Up)>;
+
+template 
+using _IsNotSame = _BoolConstant;
+
+template 
+struct _MetaBase;
+template <>
+struct _MetaBase {
+  template 
+  using _SelectImpl = _Tp;
+  template  class _FirstFn, template  class,
+class... _Args>
+  using _SelectApplyImpl = _FirstFn<_Args...>;
+  template 
+  using _FirstImpl = _First;
+  template 
+  using _SecondImpl = _Second;
+  template 
+  using _OrImpl =
+  typename _MetaBase<_First::value != true && sizeof...(_Rest) != 0>::
+  template _OrImpl<_First, _Rest...>;
+};
+
+template <>
+struct _MetaBase {
+  template 
+  using _SelectImpl = _Up;
+  template  class, template  class _SecondFn,
+class... _Args>
+  using _SelectApplyImpl = _SecondFn<_Args...>;
+  template 
+  using _OrImpl = _Result;
+};
+
+template 
+using _If = typename _MetaBase<_Cond>::template _SelectImpl<_IfRes, _ElseRes>;
+
+template 
+using _Or = typename _MetaBase::template _OrImpl;
+
+template 
+using __enable_if_t = typename enable_if<_Bp, _Tp>::type;
+
+template 
+using __expand_to_true = true_type;
+template 
+__expand_to_true<__enable_if_t<_Pred::value>...> __and_helper(int);
+template 
+false_type __and_helper(...);
+template 
+using _And = decltype(__and_helper<_Pred...>(0));
+
+struct __check_tuple_constructor_fail {
+  static constexpr bool __enable_explicit_default() { return false; }
+  static constexpr bool __enable_implicit_default() { return false; }
+  template 
+  static constexpr bool __enable_explicit() {
+return false;
+  }
+  template 
+  static constexpr bool

[clang] a6b2f50 - Revert "[clang-format] Correctly format variable templates."

2022-03-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-14T16:04:09+01:00
New Revision: a6b2f50fb47da3baeee10b1906da6e30ac5d26ec

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

LOG: Revert "[clang-format] Correctly format variable templates."

This reverts commit a140b7104fdae0d9eff5b18efbc784754e0ca274.

It provoked the bug https://github.com/llvm/llvm-project/issues/54374.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 6cf3681cdd9d5..0c760b5b2811d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1526,30 +1526,8 @@ class AnnotatingParser {
   if (Current.getPrecedence() != prec::Assignment)
 return false;
 
-  if (Line.First->isOneOf(tok::kw_using, tok::kw_return))
+  if (Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return))
 return false;
-  if (Line.First->is(tok::kw_template)) {
-// `template` keyword can start a variable template.
-const FormatToken *Tok = Line.First->getNextNonComment();
-assert(Tok); // Current token is on the same line.
-if (Tok->isNot(TT_TemplateOpener)) {
-  // Explicit template instantiations do not have `<>`.
-  return false;
-}
-
-Tok = Tok->MatchingParen;
-if (!Tok)
-  return false;
-Tok = Tok->getNextNonComment();
-if (!Tok)
-  return false;
-
-if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept,
- tok::kw_struct, tok::kw_using))
-  return false;
-
-return true;
-  }
 
   // Type aliases use `type X = ...;` in TypeScript and can be exported
   // using `export type ...`.

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index aadd24a0d6ca6..05427c6249749 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25625,12 +25625,6 @@ TEST_F(FormatTest, 
AlignArrayOfStructuresRightAlignmentNonSquare) {
Style);
 }
 
-TEST_F(FormatTest, FormatsVariableTemplates) {
-  verifyFormat("inline bool var = is_integral_v && is_signed_v;");
-  verifyFormat("template  "
-   "inline bool var = is_integral_v && is_signed_v;");
-}
-
 } // namespace
 } // namespace format
 } // namespace clang

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index dd868be99f45e..dff8c04662601 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -117,31 +117,6 @@ TEST_F(TokenAnnotatorTest, UnderstandsEnums) {
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_EnumLBrace);
 }
 
-TEST_F(TokenAnnotatorTest, UnderstandsDefaultedAndDeletedFunctions) {
-  auto Tokens = annotate("auto operator<=>(const T &) const & = default;");
-  EXPECT_EQ(Tokens.size(), 14u) << Tokens;
-  EXPECT_TOKEN(Tokens[9], tok::amp, TT_PointerOrReference);
-
-  Tokens = annotate("template  void F(T) && = delete;");
-  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
-  EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_PointerOrReference);
-}
-
-TEST_F(TokenAnnotatorTest, UnderstandsVariables) {
-  auto Tokens =
-  annotate("inline bool var = is_integral_v && is_signed_v;");
-  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
-  EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
-}
-
-TEST_F(TokenAnnotatorTest, UnderstandsVariableTemplates) {
-  auto Tokens =
-  annotate("template  "
-   "inline bool var = is_integral_v && is_signed_v;");
-  EXPECT_EQ(Tokens.size(), 20u) << Tokens;
-  EXPECT_TOKEN(Tokens[13], tok::ampamp, TT_BinaryOperator);
-}
-
 TEST_F(TokenAnnotatorTest, UnderstandsLBracesInMacroDefinition) {
   auto Tokens = annotate("#define BEGIN NS {");
   EXPECT_EQ(Tokens.size(), 6u) << Tokens;



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


[PATCH] D121456: [clang-format] Correctly format variable templates.

2022-03-14 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius reopened this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

Reverting as it provoked bug https://github.com/llvm/llvm-project/issues/54374.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121456

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


[PATCH] D121455: [clang][dataflow] Add support for nested composite bool expressions

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



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:516
+// assigned to it.
+Visit(&SubExpr);
+if (auto *Val = dyn_cast_or_null(

sgatev wrote:
> xazax.hun wrote:
> > Could you elaborate on when would this happen? I'd expect the traversal to 
> > always visit the predecessor basic blocks first and within a basic block 
> > always visit subexpressions first. So I'd be quite surprised if there is a 
> > subexpression we did not visit.
> From what I've seen, logic operators influence the structure of the CFG 
> through additional basic blocks and terminators, but their sub-expression 
> operators are not added directly in the basic blocks.
> 
> For example:
> ```
> void test(bool a, bool b, bool c) {
> bool d = a && (b || c);
> }
> ```
> 
> results in:
> ```
> 
> void test(bool a, bool b, bool c)
>  [B5 (ENTRY)]
>Succs (1): B4
> 
>  [B1]
>1: [B4.2] && ([B3.2] || [B2.2])
>2: bool d = a && (b || c);
>Preds (3): B2 B3 B4
>Succs (1): B0
> 
>  [B2]
>1: c
>2: [B2.1] (ImplicitCastExpr, LValueToRValue, _Bool)
>Preds (1): B3
>Succs (1): B1
> 
>  [B3]
>1: b
>2: [B3.1] (ImplicitCastExpr, LValueToRValue, _Bool)
>T: [B3.2] || ...
>Preds (1): B4
>Succs (2): B1 B2
> 
>  [B4]
>1: a
>2: [B4.1] (ImplicitCastExpr, LValueToRValue, _Bool)
>T: [B4.2] && ...
>Preds (1): B5
>Succs (2): B3 B1
> 
>  [B0 (EXIT)]
>Preds (1): B1
> ```
> 
> So, when we evaluate `a && (b || c)` in `B1`, the sub-expression `b || c` has 
> not been evaluated yet. I updated the comment in the code to make that more 
> clear.
I understand the structure of the CFG and also understand that certain 
subexpressions are in different basic blocks. But I still don't understand why 
would `b || c` be not evaluated when we evaluate `a && (b || c)`.

The operator `&&` in your example is evaluated in `B1`. The operator `||` is 
evaluated in `B3`. `B3` is a predecessor of `B1`, so if we process the CFG in 
reverse-post order, we should visit `B3` before `B1`. 

I am pretty sure if the traversal is well-written we should have the `||` 
evaluated before we visit `B1`.

I suspect that something different might be going on. Is it possible that you 
want to evaluate the `&&` in `B4`?

Note that `&&` is a terminator there because of the short-circuiting. So at 
that point we should NOT ask for the value of `||`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121455

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


[PATCH] D121455: [clang][dataflow] Add support for nested composite bool expressions

2022-03-14 Thread Stanislav Gatev via Phabricator via cfe-commits
sgatev added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:516
+// assigned to it.
+Visit(&SubExpr);
+if (auto *Val = dyn_cast_or_null(

xazax.hun wrote:
> sgatev wrote:
> > xazax.hun wrote:
> > > Could you elaborate on when would this happen? I'd expect the traversal 
> > > to always visit the predecessor basic blocks first and within a basic 
> > > block always visit subexpressions first. So I'd be quite surprised if 
> > > there is a subexpression we did not visit.
> > From what I've seen, logic operators influence the structure of the CFG 
> > through additional basic blocks and terminators, but their sub-expression 
> > operators are not added directly in the basic blocks.
> > 
> > For example:
> > ```
> > void test(bool a, bool b, bool c) {
> > bool d = a && (b || c);
> > }
> > ```
> > 
> > results in:
> > ```
> > 
> > void test(bool a, bool b, bool c)
> >  [B5 (ENTRY)]
> >Succs (1): B4
> > 
> >  [B1]
> >1: [B4.2] && ([B3.2] || [B2.2])
> >2: bool d = a && (b || c);
> >Preds (3): B2 B3 B4
> >Succs (1): B0
> > 
> >  [B2]
> >1: c
> >2: [B2.1] (ImplicitCastExpr, LValueToRValue, _Bool)
> >Preds (1): B3
> >Succs (1): B1
> > 
> >  [B3]
> >1: b
> >2: [B3.1] (ImplicitCastExpr, LValueToRValue, _Bool)
> >T: [B3.2] || ...
> >Preds (1): B4
> >Succs (2): B1 B2
> > 
> >  [B4]
> >1: a
> >2: [B4.1] (ImplicitCastExpr, LValueToRValue, _Bool)
> >T: [B4.2] && ...
> >Preds (1): B5
> >Succs (2): B3 B1
> > 
> >  [B0 (EXIT)]
> >Preds (1): B1
> > ```
> > 
> > So, when we evaluate `a && (b || c)` in `B1`, the sub-expression `b || c` 
> > has not been evaluated yet. I updated the comment in the code to make that 
> > more clear.
> I understand the structure of the CFG and also understand that certain 
> subexpressions are in different basic blocks. But I still don't understand 
> why would `b || c` be not evaluated when we evaluate `a && (b || c)`.
> 
> The operator `&&` in your example is evaluated in `B1`. The operator `||` is 
> evaluated in `B3`. `B3` is a predecessor of `B1`, so if we process the CFG in 
> reverse-post order, we should visit `B3` before `B1`. 
> 
> I am pretty sure if the traversal is well-written we should have the `||` 
> evaluated before we visit `B1`.
> 
> I suspect that something different might be going on. Is it possible that you 
> want to evaluate the `&&` in `B4`?
> 
> Note that `&&` is a terminator there because of the short-circuiting. So at 
> that point we should NOT ask for the value of `||`.
> The operator `||` is evaluated in `B3`.

I don't think that's the case.  Similar to your observation about `&&` being a 
terminator in `B4`, I believe that `||` is a terminator in `B3`.

I interpret `B3` as the "`a` is true" branch. It still doesn't contain 
information about `b` and `c` which might be subject to short-circuiting.

Does that make sense?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121455

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


[PATCH] D121455: [clang][dataflow] Add support for nested composite bool expressions

2022-03-14 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun accepted this revision.
xazax.hun added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/Transfer.cpp:516
+// assigned to it.
+Visit(&SubExpr);
+if (auto *Val = dyn_cast_or_null(

sgatev wrote:
> xazax.hun wrote:
> > sgatev wrote:
> > > xazax.hun wrote:
> > > > Could you elaborate on when would this happen? I'd expect the traversal 
> > > > to always visit the predecessor basic blocks first and within a basic 
> > > > block always visit subexpressions first. So I'd be quite surprised if 
> > > > there is a subexpression we did not visit.
> > > From what I've seen, logic operators influence the structure of the CFG 
> > > through additional basic blocks and terminators, but their sub-expression 
> > > operators are not added directly in the basic blocks.
> > > 
> > > For example:
> > > ```
> > > void test(bool a, bool b, bool c) {
> > > bool d = a && (b || c);
> > > }
> > > ```
> > > 
> > > results in:
> > > ```
> > > 
> > > void test(bool a, bool b, bool c)
> > >  [B5 (ENTRY)]
> > >Succs (1): B4
> > > 
> > >  [B1]
> > >1: [B4.2] && ([B3.2] || [B2.2])
> > >2: bool d = a && (b || c);
> > >Preds (3): B2 B3 B4
> > >Succs (1): B0
> > > 
> > >  [B2]
> > >1: c
> > >2: [B2.1] (ImplicitCastExpr, LValueToRValue, _Bool)
> > >Preds (1): B3
> > >Succs (1): B1
> > > 
> > >  [B3]
> > >1: b
> > >2: [B3.1] (ImplicitCastExpr, LValueToRValue, _Bool)
> > >T: [B3.2] || ...
> > >Preds (1): B4
> > >Succs (2): B1 B2
> > > 
> > >  [B4]
> > >1: a
> > >2: [B4.1] (ImplicitCastExpr, LValueToRValue, _Bool)
> > >T: [B4.2] && ...
> > >Preds (1): B5
> > >Succs (2): B3 B1
> > > 
> > >  [B0 (EXIT)]
> > >Preds (1): B1
> > > ```
> > > 
> > > So, when we evaluate `a && (b || c)` in `B1`, the sub-expression `b || c` 
> > > has not been evaluated yet. I updated the comment in the code to make 
> > > that more clear.
> > I understand the structure of the CFG and also understand that certain 
> > subexpressions are in different basic blocks. But I still don't understand 
> > why would `b || c` be not evaluated when we evaluate `a && (b || c)`.
> > 
> > The operator `&&` in your example is evaluated in `B1`. The operator `||` 
> > is evaluated in `B3`. `B3` is a predecessor of `B1`, so if we process the 
> > CFG in reverse-post order, we should visit `B3` before `B1`. 
> > 
> > I am pretty sure if the traversal is well-written we should have the `||` 
> > evaluated before we visit `B1`.
> > 
> > I suspect that something different might be going on. Is it possible that 
> > you want to evaluate the `&&` in `B4`?
> > 
> > Note that `&&` is a terminator there because of the short-circuiting. So at 
> > that point we should NOT ask for the value of `||`.
> > The operator `||` is evaluated in `B3`.
> 
> I don't think that's the case.  Similar to your observation about `&&` being 
> a terminator in `B4`, I believe that `||` is a terminator in `B3`.
> 
> I interpret `B3` as the "`a` is true" branch. It still doesn't contain 
> information about `b` and `c` which might be subject to short-circuiting.
> 
> Does that make sense?
Oh, I see now! Sorry, I somehow assumed `Visit` is recursive. But you only 
visit the top level operator not the whole subexpression. Yeah, I understand 
now, thanks! This looks good to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121455

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


[PATCH] D121602: [clang][dataflow] Model the behavior of non-standard optional constructors

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



Comment at: clang/include/clang/Analysis/FlowSensitive/MatchSwitch.h:42
 
-  /// Current lattice element.
+  ASTContext &ASTCtx;
   LatticeT &Lattice;

This shouldn't be needed, since we now pass the `MatchFinder::MatchResult` in 
`Action`, which includes the `ASTContext`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121602

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


[PATCH] D111579: [clang] Fix DIFile directory root on Windows

2022-03-14 Thread Keith Smiley via Phabricator via cfe-commits
keith added a comment.

Ping, all green here, I just had to mess with the test regex a bit


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D111579

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


[PATCH] D121332: Cleanup includes: DebugInfo & CodeGen

2022-03-14 Thread Steven Wu via Phabricator via cfe-commits
steven_wu added a comment.

This breaks implicit module on macOS bots: 
https://green.lab.llvm.org/green/job/lldb-cmake/42098/console

Error message:

  
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/llvm/include/llvm/CodeGen/MachinePipeliner.h:136:3:
 error: missing '#include "llvm/ADT/SetVector.h"'; 'SetVector' must be declared 
before it is used
SetVector NodeOrder;
^
  
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/llvm/include/llvm/ADT/SetVector.h:40:7:
 note: declaration here is not visible
  class SetVector {
^
  
/Users/buildslave/jenkins/workspace/lldb-cmake/llvm-project/llvm/lib/CodeGen/AtomicExpandPass.cpp:21:10:
 fatal error: could not build module 'LLVM_Backend'
  #include "llvm/CodeGen/AtomicExpandUtils.h"
   ^~
  2 errors generated.

This can be fixed by adding `ADT/SetVector.h` to 
`include/llvm/CodeGen/MachinePipeliner.h`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121332

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


[clang-tools-extra] 5da83ee - clang-tidy: discover binaries in build dir

2022-03-14 Thread Keith Smiley via cfe-commits

Author: Keith Smiley
Date: 2022-03-14T09:04:36-07:00
New Revision: 5da83eeb91bab848a096db7521c6d8be29231665

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

LOG: clang-tidy: discover binaries in build dir

This changes the clang-tidy script to discover binaries you've built
locally without having to pass them.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/tool/run-clang-tidy.py

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index fa98c217e2381..73edef494ab1f 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- run-clang-tidy.py - Parallel clang-tidy runner *- python -*--===#
 #
@@ -41,6 +41,7 @@
 import json
 import multiprocessing
 import os
+import queue
 import re
 import shutil
 import subprocess
@@ -54,13 +55,6 @@
 except ImportError:
   yaml = None
 
-is_py2 = sys.version[0] == '2'
-
-if is_py2:
-import Queue as queue
-else:
-import queue as queue
-
 
 def strtobool(val):
   """Convert a string representation of truth to a bool following LLVM's CLI 
argument parsing."""
@@ -158,20 +152,29 @@ def merge_replacement_files(tmpdir, mergefile):
 open(mergefile, 'w').close()
 
 
-def check_clang_apply_replacements_binary(args):
-  """Checks if invoking supplied clang-apply-replacements binary works."""
-  try:
-subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
-  except:
-print('Unable to run clang-apply-replacements. Is clang-apply-replacements 
'
-  'binary correctly specified?', file=sys.stderr)
-traceback.print_exc()
-sys.exit(1)
+def find_binary(arg, name, build_path):
+  """Get the path for a binary or exit"""
+  if arg:
+if shutil.which(arg):
+  return arg
+else:
+  raise SystemExit(
+"error: passed binary '{}' was not found or is not executable"
+.format(arg))
+
+  built_path = os.path.join(build_path, "bin", name)
+  binary = shutil.which(name) or shutil.which(built_path)
+  if binary:
+return binary
+  else:
+raise SystemExit(
+  "error: failed to find {} in $PATH or at {}"
+  .format(name, built_path))
 
 
-def apply_fixes(args, tmpdir):
+def apply_fixes(args, clang_apply_replacements_binary, tmpdir):
   """Calls clang-apply-fixes on a given directory."""
-  invocation = [args.clang_apply_replacements_binary]
+  invocation = [clang_apply_replacements_binary]
   if args.format:
 invocation.append('-format')
   if args.style:
@@ -180,11 +183,12 @@ def apply_fixes(args, tmpdir):
   subprocess.call(invocation)
 
 
-def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
+def run_tidy(args, clang_tidy_binary, tmpdir, build_path, queue, lock,
+ failed_files):
   """Takes filenames out of queue and runs clang-tidy on them."""
   while True:
 name = queue.get()
-invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
+invocation = get_tidy_invocation(name, clang_tidy_binary, args.checks,
  tmpdir, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
@@ -210,15 +214,13 @@ def main():
   parser = argparse.ArgumentParser(description='Runs clang-tidy over all files 
'
'in a compilation database. Requires '
'clang-tidy and clang-apply-replacements in 
'
-   '$PATH.')
+   '$PATH or in your build directory.')
   parser.add_argument('-allow-enabling-alpha-checkers',
   action='store_true', help='allow alpha checkers from '
 'clang-analyzer.')
   parser.add_argument('-clang-tidy-binary', metavar='PATH',
-  default='clang-tidy',
   help='path to clang-tidy binary')
   parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
-  default='clang-apply-replacements',
   help='path to clang-apply-replacements binary')
   parser.add_argument('-checks', default=None,
   help='checks filter, when not specified, use clang-tidy '
@@ -278,8 +280,18 @@ def main():
 # Find our database
 build_path = find_compilation_database(db_path)
 
+  clang_tidy_binary = find_binary(args.clang_tidy_binary, "clang-tidy",
+  build_path)

[PATCH] D100692: clang-tidy: discover binaries in build dir

2022-03-14 Thread Keith Smiley via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5da83eeb91ba: clang-tidy: discover binaries in build dir 
(authored by keith).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D100692

Files:
  clang-tools-extra/clang-tidy/tool/run-clang-tidy.py

Index: clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
===
--- clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- run-clang-tidy.py - Parallel clang-tidy runner *- python -*--===#
 #
@@ -41,6 +41,7 @@
 import json
 import multiprocessing
 import os
+import queue
 import re
 import shutil
 import subprocess
@@ -54,13 +55,6 @@
 except ImportError:
   yaml = None
 
-is_py2 = sys.version[0] == '2'
-
-if is_py2:
-import Queue as queue
-else:
-import queue as queue
-
 
 def strtobool(val):
   """Convert a string representation of truth to a bool following LLVM's CLI argument parsing."""
@@ -158,20 +152,29 @@
 open(mergefile, 'w').close()
 
 
-def check_clang_apply_replacements_binary(args):
-  """Checks if invoking supplied clang-apply-replacements binary works."""
-  try:
-subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
-  except:
-print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
-  'binary correctly specified?', file=sys.stderr)
-traceback.print_exc()
-sys.exit(1)
+def find_binary(arg, name, build_path):
+  """Get the path for a binary or exit"""
+  if arg:
+if shutil.which(arg):
+  return arg
+else:
+  raise SystemExit(
+"error: passed binary '{}' was not found or is not executable"
+.format(arg))
+
+  built_path = os.path.join(build_path, "bin", name)
+  binary = shutil.which(name) or shutil.which(built_path)
+  if binary:
+return binary
+  else:
+raise SystemExit(
+  "error: failed to find {} in $PATH or at {}"
+  .format(name, built_path))
 
 
-def apply_fixes(args, tmpdir):
+def apply_fixes(args, clang_apply_replacements_binary, tmpdir):
   """Calls clang-apply-fixes on a given directory."""
-  invocation = [args.clang_apply_replacements_binary]
+  invocation = [clang_apply_replacements_binary]
   if args.format:
 invocation.append('-format')
   if args.style:
@@ -180,11 +183,12 @@
   subprocess.call(invocation)
 
 
-def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
+def run_tidy(args, clang_tidy_binary, tmpdir, build_path, queue, lock,
+ failed_files):
   """Takes filenames out of queue and runs clang-tidy on them."""
   while True:
 name = queue.get()
-invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
+invocation = get_tidy_invocation(name, clang_tidy_binary, args.checks,
  tmpdir, build_path, args.header_filter,
  args.allow_enabling_alpha_checkers,
  args.extra_arg, args.extra_arg_before,
@@ -210,15 +214,13 @@
   parser = argparse.ArgumentParser(description='Runs clang-tidy over all files '
'in a compilation database. Requires '
'clang-tidy and clang-apply-replacements in '
-   '$PATH.')
+   '$PATH or in your build directory.')
   parser.add_argument('-allow-enabling-alpha-checkers',
   action='store_true', help='allow alpha checkers from '
 'clang-analyzer.')
   parser.add_argument('-clang-tidy-binary', metavar='PATH',
-  default='clang-tidy',
   help='path to clang-tidy binary')
   parser.add_argument('-clang-apply-replacements-binary', metavar='PATH',
-  default='clang-apply-replacements',
   help='path to clang-apply-replacements binary')
   parser.add_argument('-checks', default=None,
   help='checks filter, when not specified, use clang-tidy '
@@ -278,8 +280,18 @@
 # Find our database
 build_path = find_compilation_database(db_path)
 
+  clang_tidy_binary = find_binary(args.clang_tidy_binary, "clang-tidy",
+  build_path)
+
+  tmpdir = None
+  if args.fix or (yaml and args.export_fixes):
+clang_apply_replacements_binary = find_binary(
+  args.clang_apply_replacements_binary, "clang-apply-replacements",
+  build_path)
+tmpdir = tempfile.mkdtemp()
+
   try:
-invocation = get_tidy_invocation("", args.clang_tidy_binary, args.checks,
+invocation = get_tidy_invocation("", clang_tidy_binary, args.checks,
  None, build_path, a

[PATCH] D88905: [Clang] Allow "ext_vector_type" applied to Booleans

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

Sema bits look pretty reasonable to me (I don't feel qualified to review the 
codegen bits).




Comment at: clang/lib/Sema/SemaExpr.cpp:10244-10245
+  // This operation may not be performed on boolean vectors.
+  if (!AllowBoolOperation && (isBoolOrExtVectorBoolType(LHSType) &&
+  isBoolOrExtVectorBoolType(RHSType)))
+return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();

No need for the parens, but should that `&&` have been `||`?



Comment at: clang/lib/Sema/SemaExprCXX.cpp:6099
+  assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
+  return EltTy->isIntegralType(Ctx) || EltTy->isBooleanType();
 }

`bool` is already covered by `isIntegralType()`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88905

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


[PATCH] D121602: [clang][dataflow] Model the behavior of non-standard optional constructors

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



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:55
+  return hasType(
+  recordDecl(anyOf(hasName("std::nullopt_t"), hasName("absl::nullopt_t"),
+   hasName("base::nullopt_t";

Did you consider `hasAnyName`? Or would that not work in this context?



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:75
+
+auto isOptionalNonStandardConstructor() {
+  return cxxConstructExpr(

What is a `non-standard` constructor? This might be a well-known term I'm not 
aware of. If that is not the case I'd prefer a comment or a more descriptive 
name.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:263
+  isOptionalMemberCallWithName("emplace"),
+  +[](const CXXMemberCallExpr *E, LatticeTransferState &State) {
+assignOptionalValue(*E->getImplicitObjectArgument(), State,

Do we need this `+` to force conversion to function pointer? Is it possible to 
fix `CaseOf` so it works with lambdas or is that not desirable?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121602

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


[PATCH] D121593: [clangd][WIP] Provide clang-include-cleaner

2022-03-14 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added a comment.

Hi! I'm glad you're excited about IncludeCleaner and having a tool to try it 
out seems like a cool idea!

> I'm not sure why include-cleaner wasn't integrated in clang-tidy, but I 
> suspect there's a good reason.

The problem with IncludeCleaner as of right now is that it depends on some 
clangd internals. I've started reducing the dependency recently but there's 
still some way to go before it can really be used in Clang-Tidy or in external 
tooling. Detaching the most important primitives from clangd is also some work 
that is often orthogonal to just getting the feature done but I would agree 
that it is a good idea and a promising venue for future implementation efforts.

Here's what I did so far:

- 
https://github.com/llvm/llvm-project/commit/089d9c50b29e8e0eb18884edf17451e11a84a80f
- 
https://github.com/llvm/llvm-project/commit/46a6f5ae148ae2044f13cddf1bb1498a8bcfb372

Apart from what I've mentioned, Clang-Tidy and clangd have different 
performance trade-offs and policies. In clangd we need to make everything 
really fast to keep the editor responsive; in Clang-Tidy we can allow expensive 
checks and disable them by default/provide guidance on how to do large-scale 
analysis. It's most likely possible to keep a large chunk of the implementation 
common and implement adapters for both clangd and Clang-Tidy, each of which 
will target the specific use-case; but that would require some thought, design 
and effort on making existing infrastructure commonly available (most likely 
under `clang/Tooling` where I moved `stdlib` handlers).

I've seen the discussion you have started 
(https://discourse.llvm.org/t/include-what-you-use-include-cleanup/5831). I'd 
like to read it thorough-fully and reply but I don't think that would happen 
until next week (at the earliest).

I left some comments but it's really a quasi-review, not a real one. 
Unfortunately, I'm mostly not working over the last three weeks for personal 
reasons, so I'm not as useful or up-to-date as I would usually be. @sammccall 
is a great person to talk to about these changes until I'm back but I'm 
expecting to start doing _some_ work reasonably soon and getting back to your 
discussion and this patch is one of the first things I'd like to do.




Comment at: clang-tools-extra/clangd/CMakeLists.txt:183
 add_subdirectory(tool)
+add_subdirectory(include-cleaner)
 add_subdirectory(indexer)

I think it would be better to just put it into `tool/`.



Comment at: clang-tools-extra/clangd/include-cleaner/CMakeLists.txt:6
+set(LLVM_LINK_COMPONENTS
+  support
+  )

nit: 



Comment at: 
clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp:1
+#include "ClangdServer.h"
+#include "support/Logger.h"

Please use the LLVM style heading and explain what this file & tooling is about.



Comment at: 
clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp:7
+
+struct report {
+  PathRef File;

nit: naming should be `Report`; Clang-Tidy should catch this.



Comment at: 
clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp:9
+  PathRef File;
+  void operator()(llvm::Expected> C) {
+if (C) {

nit: here and elsewhere there are one-to-three letter variable names and it's 
hard to read the code without going to the definition; it should probably be 
documented and expanded for clarity.



Comment at: 
clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp:14
+return;
+  llvm::errs() << "Found " << Added.size() << " unused include"
+   << (Added.size() == 1 ? " " : "s ") << "in: " << File

Nit: I had a similar tool and it printed both used and unused includes which I 
found rather useful; maybe it would be good to include/add an option to report 
both for clarity.

You don't have to do this but maybe add a FIXME/mention it somewhere.



Comment at: 
clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp:25
+
+class NullLogger : public Logger {
+  void log(Level, const char *Fmt,

This seems to be unused.



Comment at: 
clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp:31
+int main(int argc, char **argv) {
+  if (argc < 2) {
+llvm::errs()

Normally, we don't use plain `argc` and `argv`. LLVM has a nice [[ 
https://llvm.org/docs/CommandLine.html | Command Line library ]] (`llvm::cl`), 
please use it instead. It provides a nice abstraction over the primitives and 
offers useful diagnostics.

Also, please provide a useful `--help` message through this library, this will 
be super nice for those without access to sources.



Comment at: 
clang-tools-extra/clangd/include-cleaner/ClangIncludeCleanerMain.cpp:68
+
+  return 0;
+}

nit

[clang] f51d7e4 - Fix the implicit module build

2022-03-14 Thread Jonas Devlieghere via cfe-commits

Author: Jonas Devlieghere
Date: 2022-03-14T09:24:17-07:00
New Revision: f51d7e4bae9e861e711ad9711599456fc2f1bbca

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

LOG: Fix the implicit module build

This fixes the implicit module build after b1b4b6f36695 broke the LLDB
build: https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/42084/

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsVE.def
llvm/include/llvm/CodeGen/MachinePipeliner.h

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsVE.def 
b/clang/include/clang/Basic/BuiltinsVE.def
index 1cb5250893819..29b2bd203ef0f 100644
--- a/clang/include/clang/Basic/BuiltinsVE.def
+++ b/clang/include/clang/Basic/BuiltinsVE.def
@@ -11,7 +11,12 @@
 //
 
//===--===//
 
+#if defined(BUILTIN) && !defined(TARGET_BUILTIN)
+#   define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE) BUILTIN(ID, TYPE, ATTRS)
+#endif
+
 // Use generated BUILTIN definitions
 #include "clang/Basic/BuiltinsVEVL.gen.def"
 
 #undef BUILTIN
+#undef TARGET_BUILTIN

diff  --git a/llvm/include/llvm/CodeGen/MachinePipeliner.h 
b/llvm/include/llvm/CodeGen/MachinePipeliner.h
index 7e7fa57d80da6..63024562bd2d3 100644
--- a/llvm/include/llvm/CodeGen/MachinePipeliner.h
+++ b/llvm/include/llvm/CodeGen/MachinePipeliner.h
@@ -40,6 +40,7 @@
 #ifndef LLVM_CODEGEN_MACHINEPIPELINER_H
 #define LLVM_CODEGEN_MACHINEPIPELINER_H
 
+#include "llvm/ADT/SetVector.h"
 #include "llvm/CodeGen/MachineDominators.h"
 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
 #include "llvm/CodeGen/RegisterClassInfo.h"



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


[clang] 4fc7c55 - [NewPM] Actually recompute GlobalsAA before module optimization pipeline

2022-03-14 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2022-03-14T09:42:34-07:00
New Revision: 4fc7c551bb2b23fc022331b82b086d4b03b4

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

LOG: [NewPM] Actually recompute GlobalsAA before module optimization pipeline

RequireAnalysis doesn't actually recompute GlobalsAA.
GlobalsAA isn't invalidated (unless specifically invalidated) because
it's self-updating via ValueHandles, but can be imprecise during the
self-updates.

Rather than invalidating GlobalsAA, which would invalidate AAManager and
any analyses that use AAManager, create a new pass that recomputes
GlobalsAA.

Fixes #53131.

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

Added: 


Modified: 
clang/test/CodeGen/thinlto-distributed-newpm.ll
llvm/include/llvm/Analysis/GlobalsModRef.h
llvm/lib/Analysis/GlobalsModRef.cpp
llvm/lib/Passes/PassBuilderPipelines.cpp
llvm/lib/Passes/PassRegistry.def
llvm/test/Other/new-pm-defaults.ll
llvm/test/Other/new-pm-thinlto-defaults.ll
llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
llvm/test/Transforms/PhaseOrdering/recompute-globalsaa.ll

Removed: 




diff  --git a/clang/test/CodeGen/thinlto-distributed-newpm.ll 
b/clang/test/CodeGen/thinlto-distributed-newpm.ll
index 177d0375c53b1..708c288eeb530 100644
--- a/clang/test/CodeGen/thinlto-distributed-newpm.ll
+++ b/clang/test/CodeGen/thinlto-distributed-newpm.ll
@@ -78,7 +78,7 @@
 ; CHECK-O: Running pass: GlobalDCEPass
 ; CHECK-O: Running pass: EliminateAvailableExternallyPass
 ; CHECK-O: Running pass: ReversePostOrderFunctionAttrsPass
-; CHECK-O: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
+; CHECK-O: Running pass: RecomputeGlobalsAAPass
 ; CHECK-O: Running pass: Float2IntPass on main
 ; CHECK-O: Running pass: LowerConstantIntrinsicsPass on main
 ; CHECK-O: Running pass: LoopSimplifyPass on main

diff  --git a/llvm/include/llvm/Analysis/GlobalsModRef.h 
b/llvm/include/llvm/Analysis/GlobalsModRef.h
index 2f88e8d697a81..4d8ed10bb18ea 100644
--- a/llvm/include/llvm/Analysis/GlobalsModRef.h
+++ b/llvm/include/llvm/Analysis/GlobalsModRef.h
@@ -14,6 +14,7 @@
 #define LLVM_ANALYSIS_GLOBALSMODREF_H
 
 #include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/IR/PassManager.h"
 #include "llvm/IR/ValueHandle.h"
 #include "llvm/Pass.h"
 #include 
@@ -77,6 +78,8 @@ class GlobalsAAResult : public AAResultBase {
   const DataLayout &DL,
   std::function GetTLI);
 
+  friend struct RecomputeGlobalsAAPass;
+
 public:
   GlobalsAAResult(GlobalsAAResult &&Arg);
   ~GlobalsAAResult();
@@ -137,6 +140,10 @@ class GlobalsAA : public AnalysisInfoMixin {
   GlobalsAAResult run(Module &M, ModuleAnalysisManager &AM);
 };
 
+struct RecomputeGlobalsAAPass : PassInfoMixin {
+  PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
+};
+
 /// Legacy wrapper pass to provide the GlobalsAAResult object.
 class GlobalsAAWrapperPass : public ModulePass {
   std::unique_ptr Result;

diff  --git a/llvm/lib/Analysis/GlobalsModRef.cpp 
b/llvm/lib/Analysis/GlobalsModRef.cpp
index 14a191ec2529c..80989c2c66715 100644
--- a/llvm/lib/Analysis/GlobalsModRef.cpp
+++ b/llvm/lib/Analysis/GlobalsModRef.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/Instructions.h"
 #include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Module.h"
+#include "llvm/IR/PassManager.h"
 #include "llvm/InitializePasses.h"
 #include "llvm/Pass.h"
 #include "llvm/Support/CommandLine.h"
@@ -1009,6 +1010,24 @@ GlobalsAAResult GlobalsAA::run(Module &M, 
ModuleAnalysisManager &AM) {
 AM.getResult(M));
 }
 
+PreservedAnalyses RecomputeGlobalsAAPass::run(Module &M,
+  ModuleAnalysisManager &AM) {
+  if (auto *G = AM.getCachedResult(M)) {
+auto &CG = AM.getResult(M);
+G->NonAddressTakenGlobals.clear();
+G->UnknownFunctionsWithLocalLinkage = false;
+G->IndirectGlobals.clear();
+G->AllocsForIndirectGlobals.clear();
+G->FunctionInfos.clear();
+G->FunctionToSCCMap.clear();
+G->Handles.clear();
+G->CollectSCCMembership(CG);
+G->AnalyzeGlobals(M);
+G->AnalyzeCallGraph(CG, M);
+  }
+  return PreservedAnalyses::all();
+}
+
 char GlobalsAAWrapperPass::ID = 0;
 INITIALIZE_PASS_BEGIN(GlobalsAAWrapperPass, "globals-aa",
   "Globals Alias Analysis", false, true)

diff  --git a/llvm/lib/Passes/PassBuilderPipelines.cpp 
b/llvm/lib/Passes/PassBuilderPipelines.cpp
index 8c532367f1654..b875ddc861544 100644
--- a/llvm/lib/Passes/PassBuilderPipelines.cpp
+++ b/llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -1159,14 +1159,14 @@ 
PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
 PGOOpt->ProfileRemappingFile

[PATCH] D121167: [NewPM] Actually recompute GlobalsAA before module optimization pipeline

2022-03-14 Thread Arthur Eubanks 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 rG4fc7c551: [NewPM] Actually recompute GlobalsAA before 
module optimization pipeline (authored by aeubanks).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D121167?vs=413643&id=415124#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121167

Files:
  clang/test/CodeGen/thinlto-distributed-newpm.ll
  llvm/include/llvm/Analysis/GlobalsModRef.h
  llvm/lib/Analysis/GlobalsModRef.cpp
  llvm/lib/Passes/PassBuilderPipelines.cpp
  llvm/lib/Passes/PassRegistry.def
  llvm/test/Other/new-pm-defaults.ll
  llvm/test/Other/new-pm-thinlto-defaults.ll
  llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
  llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
  llvm/test/Transforms/PhaseOrdering/recompute-globalsaa.ll

Index: llvm/test/Transforms/PhaseOrdering/recompute-globalsaa.ll
===
--- llvm/test/Transforms/PhaseOrdering/recompute-globalsaa.ll
+++ llvm/test/Transforms/PhaseOrdering/recompute-globalsaa.ll
@@ -12,12 +12,6 @@
 ; CHECK-NEXT:store i1 true, i1* @a, align 4
 ; CHECK-NEXT:[[TMP0:%.*]] = load i32*, i32** @e, align 8
 ; CHECK-NEXT:store i32 0, i32* [[TMP0]], align 4
-; CHECK-NEXT:[[DOTB:%.*]] = load i1, i1* @a, align 4
-; CHECK-NEXT:br i1 [[DOTB]], label [[BAR_EXIT:%.*]], label [[IF_THEN_I:%.*]]
-; CHECK:   if.then.i:
-; CHECK-NEXT:tail call void @foo()
-; CHECK-NEXT:br label [[BAR_EXIT]]
-; CHECK:   bar.exit:
 ; CHECK-NEXT:store i32* null, i32** @e, align 8
 ; CHECK-NEXT:ret i32 0
 ;
Index: llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
===
--- llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
+++ llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
@@ -172,7 +172,7 @@
 ; CHECK-O-NEXT: Running pass: GlobalDCEPass
 ; CHECK-O-NEXT: Running pass: EliminateAvailableExternallyPass
 ; CHECK-O-NEXT: Running pass: ReversePostOrderFunctionAttrsPass
-; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
+; CHECK-O-NEXT: Running pass: RecomputeGlobalsAAPass
 ; CHECK-O-NEXT: Running pass: Float2IntPass
 ; CHECK-O-NEXT: Running pass: LowerConstantIntrinsicsPass
 ; CHECK-EXT: Running pass: {{.*}}::Bye
Index: llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
===
--- llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
+++ llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
@@ -160,7 +160,7 @@
 ; CHECK-O-NEXT: Running pass: GlobalDCEPass
 ; CHECK-O-NEXT: Running pass: EliminateAvailableExternallyPass
 ; CHECK-O-NEXT: Running pass: ReversePostOrderFunctionAttrsPass
-; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
+; CHECK-O-NEXT: Running pass: RecomputeGlobalsAAPass
 ; CHECK-O-NEXT: Running pass: Float2IntPass
 ; CHECK-O-NEXT: Running pass: LowerConstantIntrinsicsPass
 ; CHECK-EXT: Running pass: {{.*}}::Bye
Index: llvm/test/Other/new-pm-thinlto-defaults.ll
===
--- llvm/test/Other/new-pm-thinlto-defaults.ll
+++ llvm/test/Other/new-pm-thinlto-defaults.ll
@@ -189,7 +189,7 @@
 ; CHECK-POSTLINK-O-NEXT: Running pass: GlobalDCEPass
 ; CHECK-POSTLINK-O-NEXT: Running pass: EliminateAvailableExternallyPass
 ; CHECK-POSTLINK-O-NEXT: Running pass: ReversePostOrderFunctionAttrsPass
-; CHECK-POSTLINK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
+; CHECK-POSTLINK-O-NEXT: Running pass: RecomputeGlobalsAAPass
 ; CHECK-POSTLINK-O-NEXT: Running pass: Float2IntPass
 ; CHECK-POSTLINK-O-NEXT: Running pass: LowerConstantIntrinsicsPass
 ; CHECK-EXT: Running pass: {{.*}}::Bye
Index: llvm/test/Other/new-pm-defaults.ll
===
--- llvm/test/Other/new-pm-defaults.ll
+++ llvm/test/Other/new-pm-defaults.ll
@@ -217,7 +217,7 @@
 ; CHECK-DEFAULT-NEXT: Running pass: EliminateAvailableExternallyPass
 ; CHECK-LTO-NOT: Running pass: EliminateAvailableExternallyPass
 ; CHECK-O-NEXT: Running pass: ReversePostOrderFunctionAttrsPass
-; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
+; CHECK-O-NEXT: Running pass: RecomputeGlobalsAAPass
 ; CHECK-O-NEXT: Running pass: Float2IntPass
 ; CHECK-O-NEXT: Running pass: LowerConstantIntrinsicsPass on foo
 ; CHECK-MATRIX: Running pass: LowerMatrixIntrinsicsPass on f
Index: llvm/lib/Passes/PassRegistry.def
===
--- llvm/lib/Passes/PassRegistry.def
+++ llvm/lib/Passes/PassRegistry.def
@@ -94,6 +94,7 @@
 MODULE_PASS("print-must-be-executed-contexts", MustBeExecutedContextPrinterPass(dbgs(

[clang] df6fcef - Fix the implicit module build (2/2)

2022-03-14 Thread Jonas Devlieghere via cfe-commits

Author: Jonas Devlieghere
Date: 2022-03-14T09:43:13-07:00
New Revision: df6fcef2b8330afd08a3c76e6a01cb5ada6b1aa9

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

LOG: Fix the implicit module build (2/2)

This fixes the implicit module build after b1b4b6f36695 broke the LLDB
build: https://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/42084/

My previous commit didn't have the modulemap change staged.

Added: 


Modified: 
clang/include/clang/module.modulemap

Removed: 




diff  --git a/clang/include/clang/module.modulemap 
b/clang/include/clang/module.modulemap
index 981f32aa25a10..aca4d5ab919a0 100644
--- a/clang/include/clang/module.modulemap
+++ b/clang/include/clang/module.modulemap
@@ -51,6 +51,7 @@ module Clang_Basic {
   textual header "Basic/BuiltinsSVE.def"
   textual header "Basic/BuiltinsSystemZ.def"
   textual header "Basic/BuiltinsVE.def"
+  textual header "Basic/BuiltinsVEVL.gen.def"
   textual header "Basic/BuiltinsWebAssembly.def"
   textual header "Basic/BuiltinsX86.def"
   textual header "Basic/BuiltinsX86_64.def"



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


[PATCH] D121412: Complete the list of single-underscore keywords for MSVC compat.

2022-03-14 Thread Eli Friedman via Phabricator via cfe-commits
efriedma updated this revision to Diff 415136.
efriedma added a comment.

Use KEYMSCOMPAT


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121412

Files:
  clang/include/clang/Basic/TokenKinds.def


Index: clang/include/clang/Basic/TokenKinds.def
===
--- clang/include/clang/Basic/TokenKinds.def
+++ clang/include/clang/Basic/TokenKinds.def
@@ -676,24 +676,39 @@
 KEYWORD(__virtual_inheritance , KEYMS)
 KEYWORD(__interface   , KEYMS)
 ALIAS("__int8"   , char   , KEYMS)
-ALIAS("_int8", char   , KEYMS)
 ALIAS("__int16"  , short  , KEYMS)
-ALIAS("_int16"   , short  , KEYMS)
 ALIAS("__int32"  , int, KEYMS)
-ALIAS("_int32"   , int, KEYMS)
-ALIAS("_int64"   , __int64, KEYMS)
 ALIAS("__wchar_t", wchar_t, KEYMS)
-ALIAS("_asm" , asm, KEYMS)
-ALIAS("_alignof" , __alignof  , KEYMS)
 ALIAS("__builtin_alignof", __alignof  , KEYMS)
-ALIAS("_cdecl"   , __cdecl, KEYMS | KEYBORLAND)
-ALIAS("_fastcall", __fastcall , KEYMS | KEYBORLAND)
-ALIAS("_stdcall" , __stdcall  , KEYMS | KEYBORLAND)
-ALIAS("_thiscall", __thiscall , KEYMS)
-ALIAS("_vectorcall"  , __vectorcall, KEYMS)
-ALIAS("_uuidof"  , __uuidof   , KEYMS | KEYBORLAND)
-ALIAS("_inline"  , inline , KEYMS)
-ALIAS("_declspec", __declspec , KEYMS)
+
+// Microsoft single-underscore prefixed aliases for double-underscore prefixed
+// keywords.
+ALIAS("_asm" , asm  , KEYMS)
+ALIAS("_alignof" , __alignof, KEYMS)
+ALIAS("_cdecl"   , __cdecl  , KEYMS | KEYBORLAND)
+ALIAS("_declspec", __declspec   , KEYMS)
+ALIAS("_fastcall", __fastcall   , KEYMS | KEYBORLAND)
+ALIAS("_finally" , __finally, KEYMSCOMPAT)
+ALIAS("_forceinline" , __forceinline, KEYMSCOMPAT)
+ALIAS("_inline"  , inline   , KEYMS)
+ALIAS("_int8", char , KEYMS)
+ALIAS("_int16"   , short, KEYMS)
+ALIAS("_int32"   , int  , KEYMS)
+ALIAS("_int64"   , __int64  , KEYMS)
+ALIAS("_leave"   , __leave  , KEYMSCOMPAT)
+ALIAS("_multiple_inheritance", __multiple_inheritance, KEYMSCOMPAT)
+ALIAS("_ptr32"   , __ptr32  , KEYMSCOMPAT)
+ALIAS("_ptr64"   , __ptr64  , KEYMSCOMPAT)
+ALIAS("_restrict", restrict , KEYMSCOMPAT)
+ALIAS("_stdcall" , __stdcall, KEYMS | KEYBORLAND)
+ALIAS("_thiscall", __thiscall   , KEYMS)
+ALIAS("_try" , __try, KEYMSCOMPAT)
+ALIAS("_vectorcall"  , __vectorcall , KEYMS)
+ALIAS("_unaligned"   , __unaligned  , KEYMSCOMPAT)
+ALIAS("_uptr", __uptr   , KEYMSCOMPAT)
+ALIAS("_uuidof"  , __uuidof , KEYMS | KEYBORLAND)
+ALIAS("_virtual_inheritance", __virtual_inheritance, KEYMSCOMPAT)
+ALIAS("_w64" , __w64, KEYMSCOMPAT)
 
 // Borland Extensions which should be disabled in strict conformance mode.
 ALIAS("_pascal"  , __pascal   , KEYBORLAND)


Index: clang/include/clang/Basic/TokenKinds.def
===
--- clang/include/clang/Basic/TokenKinds.def
+++ clang/include/clang/Basic/TokenKinds.def
@@ -676,24 +676,39 @@
 KEYWORD(__virtual_inheritance , KEYMS)
 KEYWORD(__interface   , KEYMS)
 ALIAS("__int8"   , char   , KEYMS)
-ALIAS("_int8", char   , KEYMS)
 ALIAS("__int16"  , short  , KEYMS)
-ALIAS("_int16"   , short  , KEYMS)
 ALIAS("__int32"  , int, KEYMS)
-ALIAS("_int32"   , int, KEYMS)
-ALIAS("_int64"   , __int64, KEYMS)
 ALIAS("__wchar_t", wchar_t, KEYMS)
-ALIAS("_asm" , asm, KEYMS)
-ALIAS("_alignof" , __alignof  , KEYMS)
 ALIAS("__builtin_alignof", __alignof  , KEYMS)
-ALIAS("_cdecl"   , __cdecl, KEYMS | KEYBORLAND)
-ALIAS("_fastcall", __fastcall , KEYMS | KEYBORLAND)
-ALIAS("_stdcall" , __stdcall  , KEYMS | KEYBORLAND)
-ALIAS("_thiscall", __thiscall , KEYMS)
-ALIAS("_vectorcall"  , __vectorcall, KEYMS)
-ALIAS("_uuidof"  , __uuidof   , KEYMS | KEYBORLAND)
-ALIAS("_inline"  , inline , KEYMS)
-ALIAS("_declspec", __declspec , KEYMS)
+
+// Microsoft single-underscore prefixed aliases for double-underscore prefixed
+// keywords.
+ALIAS("_asm" , asm  , KEYMS)
+ALIAS("_alignof" , __alignof, KEYMS)
+ALIAS("_cdecl"   , __cdecl  , KEYMS | KEYBORLAND)
+ALIAS("_declspec", __declspec   , KEYMS)
+ALIAS("_fastcall", __fastcall   , KEYMS | KEYBORLAND)
+ALIAS("_finally" , __finally, KEYMSCOMPAT)
+ALIAS("_forceinline" , __forcei

[PATCH] D120527: [OpaquePtr][AArch64] Use elementtype on ldxr/stxr

2022-03-14 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks updated this revision to Diff 415137.
aeubanks added a comment.

update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120527

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/arm_acle.c
  clang/test/CodeGen/builtins-arm-exclusive.c
  clang/test/CodeGenCXX/builtins-arm-exclusive.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
  llvm/test/Bitcode/upgrade-aarch64-ldstxr.bc
  llvm/test/Bitcode/upgrade-aarch64-ldstxr.ll
  llvm/test/CodeGen/AArch64/GlobalISel/arm64-irtranslator.ll
  llvm/test/CodeGen/AArch64/arm64-ldxr-stxr.ll
  llvm/test/CodeGen/AArch64/arm64_32-atomics.ll
  llvm/test/Transforms/AtomicExpand/AArch64/expand-atomicrmw-xchg-fp.ll
  llvm/test/Transforms/ConstantHoisting/AArch64/const-hoist-intrinsics.ll
  llvm/test/Verifier/aarch64-ldstxr.ll

Index: llvm/test/Verifier/aarch64-ldstxr.ll
===
--- /dev/null
+++ llvm/test/Verifier/aarch64-ldstxr.ll
@@ -0,0 +1,19 @@
+; RUN: not opt -passes=verify -S < %s 2>&1 | FileCheck %s
+
+define void @f(i32* %p) {
+; CHECK: Intrinsic requires elementtype attribute on first argument
+  %a = call i64 @llvm.aarch64.ldxr.p0i32(i32* %p)
+; CHECK: Intrinsic requires elementtype attribute on second argument
+  %c = call i32 @llvm.aarch64.stxr.p0i32(i64 0, i32* %p)
+
+; CHECK: Intrinsic requires elementtype attribute on first argument
+  %a2 = call i64 @llvm.aarch64.ldaxr.p0i32(i32* %p)
+; CHECK: Intrinsic requires elementtype attribute on second argument
+  %c2 = call i32 @llvm.aarch64.stlxr.p0i32(i64 0, i32* %p)
+  ret void
+}
+
+declare i64 @llvm.aarch64.ldxr.p0i32(i32*)
+declare i64 @llvm.aarch64.ldaxr.p0i32(i32*)
+declare i32 @llvm.aarch64.stxr.p0i32(i64, i32*)
+declare i32 @llvm.aarch64.stlxr.p0i32(i64, i32*)
Index: llvm/test/Transforms/ConstantHoisting/AArch64/const-hoist-intrinsics.ll
===
--- llvm/test/Transforms/ConstantHoisting/AArch64/const-hoist-intrinsics.ll
+++ llvm/test/Transforms/ConstantHoisting/AArch64/const-hoist-intrinsics.ll
@@ -9,26 +9,26 @@
 ; CHECK-NEXT:[[CONST:%.*]] = bitcast i64 -9223372036317904832 to i64
 ; CHECK-NEXT:[[PTR_0:%.*]] = getelementptr i64, i64* [[PTR:%.*]], i64 0
 ; CHECK-NEXT:[[CONST_MAT:%.*]] = add i64 [[CONST]], -64
-; CHECK-NEXT:[[BAR_0:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT]], i64* [[PTR_0]])
+; CHECK-NEXT:[[BAR_0:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT]], i64* elementtype(i64) [[PTR_0]])
 ; CHECK-NEXT:[[PTR_1:%.*]] = getelementptr i64, i64* [[PTR]], i64 1
-; CHECK-NEXT:[[BAR_1:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST]], i64* [[PTR_1]])
+; CHECK-NEXT:[[BAR_1:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST]], i64* elementtype(i64) [[PTR_1]])
 ; CHECK-NEXT:[[PTR_2:%.*]] = getelementptr i64, i64* [[PTR]], i64 2
 ; CHECK-NEXT:[[CONST_MAT1:%.*]] = add i64 [[CONST]], 64
-; CHECK-NEXT:[[BAR_2:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT1]], i64* [[PTR_2]])
+; CHECK-NEXT:[[BAR_2:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT1]], i64* elementtype(i64) [[PTR_2]])
 ; CHECK-NEXT:[[PTR_3:%.*]] = getelementptr i64, i64* [[PTR]], i64 3
 ; CHECK-NEXT:[[CONST_MAT2:%.*]] = add i64 [[CONST]], 128
-; CHECK-NEXT:[[BAR_3:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT2]], i64* [[PTR_3]])
+; CHECK-NEXT:[[BAR_3:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT2]], i64* elementtype(i64) [[PTR_3]])
 ; CHECK-NEXT:ret void
 ;
 entry:
   %ptr.0 = getelementptr i64, i64* %ptr, i64 0
-  %bar.0 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904896, i64* %ptr.0)
+  %bar.0 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904896, i64* elementtype(i64) %ptr.0)
   %ptr.1 = getelementptr i64, i64* %ptr, i64 1
-  %bar.1 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904832,  i64* %ptr.1)
+  %bar.1 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904832,  i64* elementtype(i64) %ptr.1)
   %ptr.2 = getelementptr i64, i64* %ptr, i64 2
-  %bar.2 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904768, i64* %ptr.2)
+  %bar.2 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904768, i64* elementtype(i64) %ptr.2)
   %ptr.3 = getelementptr i64, i64* %ptr, i64 3
-  %bar.3 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904704, i64* %ptr.3)
+  %bar.3 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904704, i64* elementtype(i64) %ptr.3)
   ret void
 }
 
Index: llvm/test/Transforms/AtomicExpand/AArch64/expand-atomicrmw-xchg-fp.ll
===
--- llvm/test/Transforms/AtomicExpand/AArch64/expand-atomicrmw-xchg-fp.ll
+++ llvm/test/Transforms/AtomicExpand/AArch64/expand-atomicrmw-xchg-fp.ll
@@ -8,10 +8,10 @@
 ; CH

[PATCH] D120527: [OpaquePtr][AArch64] Use elementtype on ldxr/stxr

2022-03-14 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks added a comment.

In D120527#3372092 , @dmgreen wrote:

> Seems OK. Thanks for the patch.
>
> Do opaque pointer variants (like `i32 @llvm.aarch64.stxr.p0(i64 1, ptr 
> elementtype(i64) %ptr.0)`) get tested automatically from the existing tests 
> once -opaque-pointers is the default?

yup

In D120527#3371927 , @nikic wrote:

> LGTM. You probably want to add these intrinsics to the auto-upgrade code in 
> `BitcodeReader::propagateAttributeTypes()` as well.

done


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120527

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


[clang] 250620f - [OpaquePtr][AArch64] Use elementtype on ldxr/stxr

2022-03-14 Thread Arthur Eubanks via cfe-commits

Author: Arthur Eubanks
Date: 2022-03-14T10:09:59-07:00
New Revision: 250620f76e070cbbd4e8511f751f577b6e1633ac

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

LOG: [OpaquePtr][AArch64] Use elementtype on ldxr/stxr

Includes verifier changes checking the elementtype, clang codegen
changes to emit the elementtype, and ISel changes using the elementtype.

Reviewed By: #opaque-pointers, nikic

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

Added: 
llvm/test/Bitcode/upgrade-aarch64-ldstxr.bc
llvm/test/Bitcode/upgrade-aarch64-ldstxr.ll
llvm/test/Verifier/aarch64-ldstxr.ll

Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/arm_acle.c
clang/test/CodeGen/builtins-arm-exclusive.c
clang/test/CodeGenCXX/builtins-arm-exclusive.cpp
llvm/lib/Bitcode/Reader/BitcodeReader.cpp
llvm/lib/IR/Verifier.cpp
llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
llvm/test/CodeGen/AArch64/GlobalISel/arm64-irtranslator.ll
llvm/test/CodeGen/AArch64/arm64-ldxr-stxr.ll
llvm/test/CodeGen/AArch64/arm64_32-atomics.ll
llvm/test/Transforms/AtomicExpand/AArch64/expand-atomicrmw-xchg-fp.ll
llvm/test/Transforms/ConstantHoisting/AArch64/const-hoist-intrinsics.ll

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index a2699f5b3ea1e..6383dfdd89508 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -9684,23 +9684,26 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned 
BuiltinID,
 
 QualType Ty = E->getType();
 llvm::Type *RealResTy = ConvertType(Ty);
-llvm::Type *PtrTy = llvm::IntegerType::get(
-getLLVMContext(), getContext().getTypeSize(Ty))->getPointerTo();
+llvm::Type *IntTy =
+llvm::IntegerType::get(getLLVMContext(), getContext().getTypeSize(Ty));
+llvm::Type *PtrTy = IntTy->getPointerTo();
 LoadAddr = Builder.CreateBitCast(LoadAddr, PtrTy);
 
 Function *F = CGM.getIntrinsic(BuiltinID == AArch64::BI__builtin_arm_ldaex
? Intrinsic::aarch64_ldaxr
: Intrinsic::aarch64_ldxr,
PtrTy);
-Value *Val = Builder.CreateCall(F, LoadAddr, "ldxr");
+CallInst *Val = Builder.CreateCall(F, LoadAddr, "ldxr");
+Val->addParamAttr(
+0, Attribute::get(getLLVMContext(), Attribute::ElementType, IntTy));
 
 if (RealResTy->isPointerTy())
   return Builder.CreateIntToPtr(Val, RealResTy);
 
 llvm::Type *IntResTy = llvm::IntegerType::get(
 getLLVMContext(), CGM.getDataLayout().getTypeSizeInBits(RealResTy));
-Val = Builder.CreateTruncOrBitCast(Val, IntResTy);
-return Builder.CreateBitCast(Val, RealResTy);
+return Builder.CreateBitCast(Builder.CreateTruncOrBitCast(Val, IntResTy),
+ RealResTy);
   }
 
   if ((BuiltinID == AArch64::BI__builtin_arm_strex ||
@@ -9748,7 +9751,10 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned 
BuiltinID,
? Intrinsic::aarch64_stlxr
: Intrinsic::aarch64_stxr,
StoreAddr->getType());
-return Builder.CreateCall(F, {StoreVal, StoreAddr}, "stxr");
+CallInst *CI = Builder.CreateCall(F, {StoreVal, StoreAddr}, "stxr");
+CI->addParamAttr(
+1, Attribute::get(getLLVMContext(), Attribute::ElementType, StoreTy));
+return CI;
   }
 
   if (BuiltinID == AArch64::BI__getReg) {

diff  --git a/clang/test/CodeGen/arm_acle.c b/clang/test/CodeGen/arm_acle.c
index 99c281633fc3b..350aff5814644 100644
--- a/clang/test/CodeGen/arm_acle.c
+++ b/clang/test/CodeGen/arm_acle.c
@@ -153,10 +153,10 @@ void test_dbg(void) {
 // AArch64-NEXT:[[TMP0:%.*]] = bitcast i8* [[P:%.*]] to i32*
 // AArch64-NEXT:br label [[DO_BODY_I:%.*]]
 // AArch64:   do.body.i:
-// AArch64-NEXT:[[LDXR_I:%.*]] = call i64 @llvm.aarch64.ldxr.p0i32(i32* 
[[TMP0]]) [[ATTR3]]
+// AArch64-NEXT:[[LDXR_I:%.*]] = call i64 @llvm.aarch64.ldxr.p0i32(i32* 
elementtype(i32) [[TMP0]]) [[ATTR3]]
 // AArch64-NEXT:[[TMP1:%.*]] = trunc i64 [[LDXR_I]] to i32
 // AArch64-NEXT:[[TMP2:%.*]] = zext i32 [[X:%.*]] to i64
-// AArch64-NEXT:[[STXR_I:%.*]] = call i32 @llvm.aarch64.stxr.p0i32(i64 
[[TMP2]], i32* [[TMP0]]) [[ATTR3]]
+// AArch64-NEXT:[[STXR_I:%.*]] = call i32 @llvm.aarch64.stxr.p0i32(i64 
[[TMP2]], i32* elementtype(i32) [[TMP0]]) [[ATTR3]]
 // AArch64-NEXT:[[TOBOOL_I:%.*]] = icmp ne i32 [[STXR_I]], 0
 // AArch64-NEXT:br i1 [[TOBOOL_I]], label [[DO_BODY_I]], label 
[[__SWP_EXIT:%.*]], [[LOOP6:!llvm.loop !.*]]
 // AArch64:   __swp.exit:

diff  --git a/clang/test/CodeGen/builtins-arm-exclusive.c 
b/clang/test/C

[PATCH] D120527: [OpaquePtr][AArch64] Use elementtype on ldxr/stxr

2022-03-14 Thread Arthur Eubanks 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 rG250620f76e07: [OpaquePtr][AArch64] Use elementtype on 
ldxr/stxr (authored by aeubanks).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D120527

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/arm_acle.c
  clang/test/CodeGen/builtins-arm-exclusive.c
  clang/test/CodeGenCXX/builtins-arm-exclusive.cpp
  llvm/lib/Bitcode/Reader/BitcodeReader.cpp
  llvm/lib/IR/Verifier.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
  llvm/test/Bitcode/upgrade-aarch64-ldstxr.bc
  llvm/test/Bitcode/upgrade-aarch64-ldstxr.ll
  llvm/test/CodeGen/AArch64/GlobalISel/arm64-irtranslator.ll
  llvm/test/CodeGen/AArch64/arm64-ldxr-stxr.ll
  llvm/test/CodeGen/AArch64/arm64_32-atomics.ll
  llvm/test/Transforms/AtomicExpand/AArch64/expand-atomicrmw-xchg-fp.ll
  llvm/test/Transforms/ConstantHoisting/AArch64/const-hoist-intrinsics.ll
  llvm/test/Verifier/aarch64-ldstxr.ll

Index: llvm/test/Verifier/aarch64-ldstxr.ll
===
--- /dev/null
+++ llvm/test/Verifier/aarch64-ldstxr.ll
@@ -0,0 +1,19 @@
+; RUN: not opt -passes=verify -S < %s 2>&1 | FileCheck %s
+
+define void @f(i32* %p) {
+; CHECK: Intrinsic requires elementtype attribute on first argument
+  %a = call i64 @llvm.aarch64.ldxr.p0i32(i32* %p)
+; CHECK: Intrinsic requires elementtype attribute on second argument
+  %c = call i32 @llvm.aarch64.stxr.p0i32(i64 0, i32* %p)
+
+; CHECK: Intrinsic requires elementtype attribute on first argument
+  %a2 = call i64 @llvm.aarch64.ldaxr.p0i32(i32* %p)
+; CHECK: Intrinsic requires elementtype attribute on second argument
+  %c2 = call i32 @llvm.aarch64.stlxr.p0i32(i64 0, i32* %p)
+  ret void
+}
+
+declare i64 @llvm.aarch64.ldxr.p0i32(i32*)
+declare i64 @llvm.aarch64.ldaxr.p0i32(i32*)
+declare i32 @llvm.aarch64.stxr.p0i32(i64, i32*)
+declare i32 @llvm.aarch64.stlxr.p0i32(i64, i32*)
Index: llvm/test/Transforms/ConstantHoisting/AArch64/const-hoist-intrinsics.ll
===
--- llvm/test/Transforms/ConstantHoisting/AArch64/const-hoist-intrinsics.ll
+++ llvm/test/Transforms/ConstantHoisting/AArch64/const-hoist-intrinsics.ll
@@ -9,26 +9,26 @@
 ; CHECK-NEXT:[[CONST:%.*]] = bitcast i64 -9223372036317904832 to i64
 ; CHECK-NEXT:[[PTR_0:%.*]] = getelementptr i64, i64* [[PTR:%.*]], i64 0
 ; CHECK-NEXT:[[CONST_MAT:%.*]] = add i64 [[CONST]], -64
-; CHECK-NEXT:[[BAR_0:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT]], i64* [[PTR_0]])
+; CHECK-NEXT:[[BAR_0:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT]], i64* elementtype(i64) [[PTR_0]])
 ; CHECK-NEXT:[[PTR_1:%.*]] = getelementptr i64, i64* [[PTR]], i64 1
-; CHECK-NEXT:[[BAR_1:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST]], i64* [[PTR_1]])
+; CHECK-NEXT:[[BAR_1:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST]], i64* elementtype(i64) [[PTR_1]])
 ; CHECK-NEXT:[[PTR_2:%.*]] = getelementptr i64, i64* [[PTR]], i64 2
 ; CHECK-NEXT:[[CONST_MAT1:%.*]] = add i64 [[CONST]], 64
-; CHECK-NEXT:[[BAR_2:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT1]], i64* [[PTR_2]])
+; CHECK-NEXT:[[BAR_2:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT1]], i64* elementtype(i64) [[PTR_2]])
 ; CHECK-NEXT:[[PTR_3:%.*]] = getelementptr i64, i64* [[PTR]], i64 3
 ; CHECK-NEXT:[[CONST_MAT2:%.*]] = add i64 [[CONST]], 128
-; CHECK-NEXT:[[BAR_3:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT2]], i64* [[PTR_3]])
+; CHECK-NEXT:[[BAR_3:%.*]] = call i32 @llvm.aarch64.stxr.p0i64(i64 [[CONST_MAT2]], i64* elementtype(i64) [[PTR_3]])
 ; CHECK-NEXT:ret void
 ;
 entry:
   %ptr.0 = getelementptr i64, i64* %ptr, i64 0
-  %bar.0 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904896, i64* %ptr.0)
+  %bar.0 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904896, i64* elementtype(i64) %ptr.0)
   %ptr.1 = getelementptr i64, i64* %ptr, i64 1
-  %bar.1 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904832,  i64* %ptr.1)
+  %bar.1 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904832,  i64* elementtype(i64) %ptr.1)
   %ptr.2 = getelementptr i64, i64* %ptr, i64 2
-  %bar.2 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904768, i64* %ptr.2)
+  %bar.2 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904768, i64* elementtype(i64) %ptr.2)
   %ptr.3 = getelementptr i64, i64* %ptr, i64 3
-  %bar.3 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904704, i64* %ptr.3)
+  %bar.3 = call i32 @llvm.aarch64.stxr.p0i64(i64 -9223372036317904704, i64* elementtype(i64) %ptr.3)
   ret void
 }
 
Index: llvm/test/Transforms/AtomicExpand/AArch64/expand-atomicrmw-xchg-fp.ll
===
--- llvm/test/T

[clang] cf63e9d - [clang][dataflow] Add support for nested composite bool expressions

2022-03-14 Thread Stanislav Gatev via cfe-commits

Author: Stanislav Gatev
Date: 2022-03-14T17:18:30Z
New Revision: cf63e9d4caccbd540df083c63a5217ac50b5e1f9

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

LOG: [clang][dataflow] Add support for nested composite bool expressions

This is part of the implementation of the dataflow analysis framework.
See "[RFC] A dataflow analysis framework for Clang AST" on cfe-dev.

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

Added: 


Modified: 
clang/lib/Analysis/FlowSensitive/Transfer.cpp
clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Removed: 




diff  --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index df4d919b6006a..0430bc3c6eb18 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -43,25 +43,23 @@ class TransferVisitor : public 
ConstStmtVisitor {
   : StmtToEnv(StmtToEnv), Env(Env) {}
 
   void VisitBinaryOperator(const BinaryOperator *S) {
+// The CFG does not contain `ParenExpr` as top-level statements in basic
+// blocks, however sub-expressions can still be of that type.
+assert(S->getLHS() != nullptr);
+const Expr *LHS = S->getLHS()->IgnoreParens();
+assert(LHS != nullptr);
+
+assert(S->getRHS() != nullptr);
+const Expr *RHS = S->getRHS()->IgnoreParens();
+assert(RHS != nullptr);
+
 switch (S->getOpcode()) {
 case BO_Assign: {
-  // The CFG does not contain `ParenExpr` as top-level statements in basic
-  // blocks, however sub-expressions can still be of that type.
-  assert(S->getLHS() != nullptr);
-  const Expr *LHS = S->getLHS()->IgnoreParens();
-
-  assert(LHS != nullptr);
   auto *LHSLoc = Env.getStorageLocation(*LHS, SkipPast::Reference);
   if (LHSLoc == nullptr)
 break;
 
-  // The CFG does not contain `ParenExpr` as top-level statements in basic
-  // blocks, however sub-expressions can still be of that type.
-  assert(S->getRHS() != nullptr);
-  const Expr *RHS = S->getRHS()->IgnoreParens();
-
-  assert(RHS != nullptr);
-  Value *RHSVal = Env.getValue(*RHS, SkipPast::Reference);
+  auto *RHSVal = Env.getValue(*RHS, SkipPast::Reference);
   if (RHSVal == nullptr)
 break;
 
@@ -74,38 +72,15 @@ class TransferVisitor : public 
ConstStmtVisitor {
 }
 case BO_LAnd:
 case BO_LOr: {
-  const Expr *LHS = S->getLHS();
-  assert(LHS != nullptr);
-
-  const Expr *RHS = S->getRHS();
-  assert(RHS != nullptr);
-
-  BoolValue *LHSVal =
-  dyn_cast_or_null(Env.getValue(*LHS, SkipPast::Reference));
-
-  // `RHS` and `S` might be part of 
diff erent basic blocks. We need to
-  // access their values from the corresponding environments.
-  BoolValue *RHSVal = nullptr;
-  const Environment *RHSEnv = StmtToEnv.getEnvironment(*RHS);
-  if (RHSEnv != nullptr)
-RHSVal = dyn_cast_or_null(
-RHSEnv->getValue(*RHS, SkipPast::Reference));
-
-  // Create fresh values for unknown boolean expressions.
-  // FIXME: Consider providing a `GetOrCreateFresh` util in case this style
-  // is expected to be common or make sure that all expressions are 
assigned
-  // values and drop this.
-  if (LHSVal == nullptr)
-LHSVal = &Env.takeOwnership(std::make_unique());
-  if (RHSVal == nullptr)
-RHSVal = &Env.takeOwnership(std::make_unique());
+  BoolValue &LHSVal = getLogicOperatorSubExprValue(*LHS);
+  BoolValue &RHSVal = getLogicOperatorSubExprValue(*RHS);
 
   auto &Loc = Env.createStorageLocation(*S);
   Env.setStorageLocation(*S, Loc);
   if (S->getOpcode() == BO_LAnd)
-Env.setValue(Loc, Env.makeAnd(*LHSVal, *RHSVal));
+Env.setValue(Loc, Env.makeAnd(LHSVal, RHSVal));
   else
-Env.setValue(Loc, Env.makeOr(*LHSVal, *RHSVal));
+Env.setValue(Loc, Env.makeOr(LHSVal, RHSVal));
   break;
 }
 default:
@@ -525,6 +500,31 @@ class TransferVisitor : public 
ConstStmtVisitor {
   }
 
 private:
+  BoolValue &getLogicOperatorSubExprValue(const Expr &SubExpr) {
+// `SubExpr` and its parent logic operator might be part of 
diff erent basic
+// blocks. We try to access the value that is assigned to `SubExpr` in the
+// corresponding environment.
+if (const Environment *SubExprEnv = StmtToEnv.getEnvironment(SubExpr)) {
+  if (auto *Val = dyn_cast_or_null(
+  SubExprEnv->getValue(SubExpr, SkipPast::Reference)))
+return *Val;
+}
+
+// Sub-expressions that are logic operators are not added in basic blocks
+// (e.g. see CFG for `bool d = a && (b || c);`). If `SubExpr` is a logic
+// operator, it isn't evaluated and assigned a value

[PATCH] D121455: [clang][dataflow] Add support for nested composite bool expressions

2022-03-14 Thread Stanislav Gatev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGcf63e9d4cacc: [clang][dataflow] Add support for nested 
composite bool expressions (authored by sgatev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121455

Files:
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/unittests/Analysis/FlowSensitive/TransferTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
@@ -2060,86 +2060,109 @@
   });
 }
 
-TEST_F(TransferTest, AssignFromBoolConjunction) {
-  std::string Code = R"(
-void target(bool Foo, bool Bar) {
-  bool Baz = (Foo) && (Bar);
+TEST_F(TransferTest, AssignFromCompositeBoolExpression) {
+  {
+std::string Code = R"(
+void target(bool Foo, bool Bar, bool Qux) {
+  bool Baz = (Foo) && (Bar || Qux);
   // [[p]]
 }
   )";
-  runDataflow(
-  Code, [](llvm::ArrayRef<
-   std::pair>>
-   Results,
-   ASTContext &ASTCtx) {
-ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
-const Environment &Env = Results[0].second.Env;
+runDataflow(
+Code, [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+  ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+  const Environment &Env = Results[0].second.Env;
 
-const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
-ASSERT_THAT(FooDecl, NotNull());
+  const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+  ASSERT_THAT(FooDecl, NotNull());
 
-const auto *FooVal =
-dyn_cast_or_null(Env.getValue(*FooDecl, SkipPast::None));
-ASSERT_THAT(FooVal, NotNull());
+  const auto *FooVal = dyn_cast_or_null(
+  Env.getValue(*FooDecl, SkipPast::None));
+  ASSERT_THAT(FooVal, NotNull());
 
-const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
-ASSERT_THAT(BarDecl, NotNull());
+  const ValueDecl *BarDecl = findValueDecl(ASTCtx, "Bar");
+  ASSERT_THAT(BarDecl, NotNull());
 
-const auto *BarVal =
-dyn_cast_or_null(Env.getValue(*BarDecl, SkipPast::None));
-ASSERT_THAT(BarVal, NotNull());
+  const auto *BarVal = dyn_cast_or_null(
+  Env.getValue(*BarDecl, SkipPast::None));
+  ASSERT_THAT(BarVal, NotNull());
 
-const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
-ASSERT_THAT(BazDecl, NotNull());
+  const ValueDecl *QuxDecl = findValueDecl(ASTCtx, "Qux");
+  ASSERT_THAT(QuxDecl, NotNull());
 
-const auto *BazVal = dyn_cast_or_null(
-Env.getValue(*BazDecl, SkipPast::None));
-ASSERT_THAT(BazVal, NotNull());
+  const auto *QuxVal = dyn_cast_or_null(
+  Env.getValue(*QuxDecl, SkipPast::None));
+  ASSERT_THAT(QuxVal, NotNull());
 
-EXPECT_EQ(&BazVal->getLeftSubValue(), FooVal);
-EXPECT_EQ(&BazVal->getRightSubValue(), BarVal);
-  });
-}
+  const ValueDecl *BazDecl = findValueDecl(ASTCtx, "Baz");
+  ASSERT_THAT(BazDecl, NotNull());
 
-TEST_F(TransferTest, AssignFromBoolDisjunction) {
-  std::string Code = R"(
-void target(bool Foo, bool Bar) {
-  bool Baz = (Foo) || (Bar);
+  const auto *BazVal = dyn_cast_or_null(
+  Env.getValue(*BazDecl, SkipPast::None));
+  ASSERT_THAT(BazVal, NotNull());
+  EXPECT_EQ(&BazVal->getLeftSubValue(), FooVal);
+
+  const auto *BazRightSubValVal =
+  cast(&BazVal->getRightSubValue());
+  EXPECT_EQ(&BazRightSubValVal->getLeftSubValue(), BarVal);
+  EXPECT_EQ(&BazRightSubValVal->getRightSubValue(), QuxVal);
+});
+  }
+
+  {
+std::string Code = R"(
+void target(bool Foo, bool Bar, bool Qux) {
+  bool Baz = (Foo && Qux) || (Bar);
   // [[p]]
 }
   )";
-  runDataflow(
-  Code, [](llvm::ArrayRef<
-   std::pair>>
-   Results,
-   ASTContext &ASTCtx) {
-ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
-const Environment &Env = Results[0].second.Env;
+runDataflow(
+Code, [](llvm::ArrayRef<
+ std::pair>>
+ Results,
+ ASTContext &ASTCtx) {
+  ASSERT_THAT(Results, ElementsAre(Pair("p", _)));
+  const Environment &Env = Results[0].second.Env;
 
-const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
-ASSERT_THAT(FooDecl, NotNull());
+  const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo");
+  ASSERT_THAT(FooDecl, NotNull());
 
-const auto *FooVal =
-

[PATCH] D121412: Complete the list of single-underscore keywords for MSVC compat.

2022-03-14 Thread Reid Kleckner via Phabricator via cfe-commits
rnk accepted this revision.
rnk added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121412

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


[PATCH] D88905: [Clang] Allow "ext_vector_type" applied to Booleans

2022-03-14 Thread Simon Moll via Phabricator via cfe-commits
simoll updated this revision to Diff 415153.
simoll marked an inline comment as done.
simoll added a comment.

Simplify following comments. Thx :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88905

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/AST/Type.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaExprMember.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/AST/ast-print-vector-size-bool.c
  clang/test/CodeGen/debug-info-vector-bool.c
  clang/test/CodeGen/vector-alignment.c
  clang/test/Sema/ext_vector_casts.c
  clang/test/SemaCXX/constexpr-vectors.cpp
  clang/test/SemaCXX/vector-bool.cpp
  clang/test/SemaCXX/vector-size-conditional.cpp
  clang/test/SemaOpenCL/ext_vectors.cl

Index: clang/test/SemaOpenCL/ext_vectors.cl
===
--- clang/test/SemaOpenCL/ext_vectors.cl
+++ clang/test/SemaOpenCL/ext_vectors.cl
@@ -5,6 +5,7 @@
 // RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -cl-std=clc++2021
 
 typedef float float4 __attribute__((ext_vector_type(4)));
+typedef __attribute__((ext_vector_type(8))) bool BoolVector; // expected-error {{invalid vector element type 'bool'}}
 
 void test_ext_vector_accessors(float4 V) {
   V = V.wzyx;
Index: clang/test/SemaCXX/vector-size-conditional.cpp
===
--- clang/test/SemaCXX/vector-size-conditional.cpp
+++ clang/test/SemaCXX/vector-size-conditional.cpp
@@ -13,6 +13,7 @@
 using FourFloats = float __attribute__((__vector_size__(16)));
 using TwoDoubles = double __attribute__((__vector_size__(16)));
 using FourDoubles = double __attribute__((__vector_size__(32)));
+using EightBools = bool __attribute__((ext_vector_type(8)));
 
 FourShorts four_shorts;
 TwoInts two_ints;
@@ -25,6 +26,8 @@
 FourFloats four_floats;
 TwoDoubles two_doubles;
 FourDoubles four_doubles;
+EightBools eight_bools;
+EightBools other_eight_bools;
 
 enum E {};
 enum class SE {};
@@ -95,6 +98,9 @@
   (void)(four_ints ? four_uints : 3.0f);
   (void)(four_ints ? four_ints : 3.0f);
 
+  // Allow conditional select on bool vectors.
+  (void)(eight_bools ? eight_bools : other_eight_bools);
+
   // When there is a vector and a scalar, conversions must be legal.
   (void)(four_ints ? four_floats : 3); // should work, ints can convert to floats.
   (void)(four_ints ? four_uints : e);  // expected-error {{cannot convert between scalar type 'E' and vector type 'FourUInts'}}
@@ -163,10 +169,10 @@
 void Templates() {
   dependent_cond(two_ints);
   dependent_operand(two_floats);
-  // expected-error@159 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(4 * sizeof(double double' (vector of 4 'double' values))}}}
+  // expected-error@165 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(4 * sizeof(double double' (vector of 4 'double' values))}}}
   all_dependent(four_ints, four_uints, four_doubles); // expected-note {{in instantiation of}}
 
-  // expected-error@159 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(2 * sizeof(unsigned int unsigned int' (vector of 2 'unsigned int' values))}}}
+  // expected-error@165 {{vector operands to the vector conditional must be the same type ('__attribute__((__vector_size__(4 * sizeof(unsigned int unsigned int' (vector of 4 'unsigned int' values) and '__attribute__((__vector_size__(2 * sizeof(unsigned int unsigned int' (vector of 2 'unsigned int' values))}}}
   all_dependent(four_ints, four_uints, two_uints); // expected-note {{in instantiation of}}
   all_dependent(four_ints, four_uints, four_uints);
 }
Index: clang/test/SemaCXX/vector-bool.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/vector-bool.cpp
@@ -0,0 +1,92 @@
+// RUN: %clang_cc1 -triple x86_64-linux-pc -fsyntax-only -verify -fexceptions -fcxx-exceptions %s -std=c++17
+// Note that this test depends on the size of long-long to be different from
+// int, so it specifies a triple.
+
+using FourShorts = short __attribute__((__vector_size__(8)));
+using TwoInts = int __attribute__((__vector_size__(8)));
+using EightInts

[PATCH] D88905: [Clang] Allow "ext_vector_type" applied to Booleans

2022-03-14 Thread Simon Moll via Phabricator via cfe-commits
simoll added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:10244-10245
+  // This operation may not be performed on boolean vectors.
+  if (!AllowBoolOperation && (isBoolOrExtVectorBoolType(LHSType) &&
+  isBoolOrExtVectorBoolType(RHSType)))
+return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();

aaron.ballman wrote:
> No need for the parens, but should that `&&` have been `||`?
The `&&` is intentional. We cannot step into this if `AllowBoolOperation` is 
true.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88905

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


[PATCH] D121533: [clang][deps] Fix traversal of precompiled dependencies

2022-03-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

I'm not a big fan of moving to the recursive call. Creating a separate 
`StringMap` for each iteration seems awfully wasteful.

I'd prefer fixing the iterative algorithm so that it's correct and easy to 
verify. This can be done with a stack that points at the stable pointers into 
the StringMap:

  StringMap Imports;
  SmallVector *> Worklist;
  PrebuiltModuleListener Listener(Imports, Worklist, InputFiles, 
VisitInputFiles);
  
  while (!Worklist.empty()) {
StringMapEntry *Import = Worklist.pop_back_val();
// Deal with "Import".
  }

and in `PrebuiltModuleListener` only push to the worklist for newly-discovered 
imports:

  void visitImport(StringRef ModuleName, StringRef Filename) override {
auto I = PrebuiltModuleFiles.insert({ModuleName, Filename.str()});
if (I.second)
  Worklist.push_back(&*I.first);
  }

Also, is it possible to add a test to exercise the (fixed) the dangling 
iterator bug?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121533

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


[PATCH] D121295: [clang][deps] Modules don't contribute to search path usage

2022-03-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added inline comments.



Comment at: clang/lib/Lex/HeaderSearch.cpp:305
   // maps, searching for a module map that describes this module.
-  for (It = search_dir_begin(); It != search_dir_end(); ++It) {
-if (It->isFramework()) {
+  for (DirectoryLookup Dir : search_dir_range()) {
+if (Dir.isFramework()) {

This triggers a bunch of noise in this patch. Is it possible to make this 
change either before or after, to avoid the noise, giving that there's a 
functional change hiding here?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121295

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


[PATCH] D121206: [AARCH64] ssbs should be enabled by default for cortex-x1, cortex-x1c, cortex-a77

2022-03-14 Thread Amilendra Kodithuwakku via Phabricator via cfe-commits
amilendra added inline comments.



Comment at: llvm/lib/Target/AArch64/AArch64.td:978
  FeatureNEON, FeatureRCPC, FeaturePerfMon,
  FeatureSPE, FeatureFullFP16, FeatureDotProd];
   list X1C  = [HasV8_2aOps, FeatureCrypto, FeatureFPARMv8,

stuij wrote:
> amilendra wrote:
> > stuij wrote:
> > > dmgreen wrote:
> > > > X1 and A77 missing SSBS too. Should they be added at the same time?
> > > Yes they should. Thanks!
> > Maybe add unit tests for X1 and A77 too?
> I did. See the top file.
> 
> In general it'd be good to have better testing for individual cores. This 
> will happen more structurally in future changes.
Ah yes, I was expecting tests similar to that for `R82` in 
aarch64-target-features.c. Anyway what you have already is good for `ssbs`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121206

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


[PATCH] D121206: [AARCH64] ssbs should be enabled by default for cortex-x1, cortex-x1c, cortex-a77

2022-03-14 Thread Amilendra Kodithuwakku via Phabricator via cfe-commits
amilendra added a comment.

LGTM.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121206

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


[PATCH] D121303: [clang][deps] Don't prune search paths used by dependencies

2022-03-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.
This revision is now accepted and ready to land.

LGTM.




Comment at: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp:31
+  [&](const serialization::ModuleFile *MF) -> void {
+SearchPathUsage |= MF->SearchPathUsage;
+Visited.insert(MF);

Note that `clang-format` wants you to do something here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121303

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


[PATCH] D121512: [Support] Change zlib::compress to return void

2022-03-14 Thread Igor Kudrin via Phabricator via cfe-commits
ikudrin added inline comments.



Comment at: llvm/lib/ObjCopy/ELF/ELFObject.cpp:568
  DebugCompressionType CompressionType,
  Error &OutErr)
 : SectionBase(Sec), CompressionType(CompressionType),

`OutErr` can now be removed to further simplify the calling code.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121512

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


[PATCH] D121627: [IROutliner][NFC] Fix typo in doc of findOrCreatePHIInBlock

2022-03-14 Thread Hirochika Matsumoto via Phabricator via cfe-commits
hkmatsumoto created this revision.
Herald added subscribers: ormris, hiraditya.
Herald added a project: All.
hkmatsumoto requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121627

Files:
  llvm/lib/Transforms/IPO/IROutliner.cpp


Index: llvm/lib/Transforms/IPO/IROutliner.cpp
===
--- llvm/lib/Transforms/IPO/IROutliner.cpp
+++ llvm/lib/Transforms/IPO/IROutliner.cpp
@@ -1559,7 +1559,7 @@
 /// \p PN in.
 /// \param OutputMappings [in] - The mapping of output values from outlined
 /// region to their original values.
-/// \param UsedPhis [in, out] - The PHINodes in the block that have already 
been
+/// \param UsedPHIs [in, out] - The PHINodes in the block that have already 
been
 /// matched.
 /// \return the newly found or created PHINode in \p OverallPhiBlock.
 static PHINode*


Index: llvm/lib/Transforms/IPO/IROutliner.cpp
===
--- llvm/lib/Transforms/IPO/IROutliner.cpp
+++ llvm/lib/Transforms/IPO/IROutliner.cpp
@@ -1559,7 +1559,7 @@
 /// \p PN in.
 /// \param OutputMappings [in] - The mapping of output values from outlined
 /// region to their original values.
-/// \param UsedPhis [in, out] - The PHINodes in the block that have already been
+/// \param UsedPHIs [in, out] - The PHINodes in the block that have already been
 /// matched.
 /// \return the newly found or created PHINode in \p OverallPhiBlock.
 static PHINode*
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121549: Define ABI breaking class members correctly

2022-03-14 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith accepted this revision.
dexonsmith added a comment.

LGTM too; thanks!


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

https://reviews.llvm.org/D121549

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


[PATCH] D121628: Only run this test for x86 registed targets.

2022-03-14 Thread Abhina Sree via Phabricator via cfe-commits
abhina.sreeskantharajan created this revision.
Herald added a project: All.
abhina.sreeskantharajan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121628

Files:
  clang/test/CodeGen/sanitize-coverage-old-pm.c


Index: clang/test/CodeGen/sanitize-coverage-old-pm.c
===
--- clang/test/CodeGen/sanitize-coverage-old-pm.c
+++ clang/test/CodeGen/sanitize-coverage-old-pm.c
@@ -1,3 +1,4 @@
+// REQUIRES: x86-registered-target
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S   
-fsanitize-coverage=trace-pc,trace-cmp -o - -flegacy-pass-manager | 
FileCheck %s --check-prefixes=CHECK
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=address-fsanitize-coverage=trace-pc,trace-cmp -o - 
-flegacy-pass-manager | FileCheck %s --check-prefixes=CHECK,ASAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S 
-fsanitize=bounds -fsanitize-coverage=trace-pc,trace-cmp -o - 
-flegacy-pass-manager | FileCheck %s --check-prefixes=CHECK,BOUNDS


Index: clang/test/CodeGen/sanitize-coverage-old-pm.c
===
--- clang/test/CodeGen/sanitize-coverage-old-pm.c
+++ clang/test/CodeGen/sanitize-coverage-old-pm.c
@@ -1,3 +1,4 @@
+// REQUIRES: x86-registered-target
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S   -fsanitize-coverage=trace-pc,trace-cmp -o - -flegacy-pass-manager | FileCheck %s --check-prefixes=CHECK
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=address-fsanitize-coverage=trace-pc,trace-cmp -o - -flegacy-pass-manager | FileCheck %s --check-prefixes=CHECK,ASAN
 // RUN: %clang %s -target x86_64-unknown-linux-gnu -emit-llvm -S -fsanitize=bounds -fsanitize-coverage=trace-pc,trace-cmp -o - -flegacy-pass-manager | FileCheck %s --check-prefixes=CHECK,BOUNDS
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D121602: [clang][dataflow] Model the behavior of non-standard optional constructors

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



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:110
+return false;
+  auto TypeName = Type->getAsCXXRecordDecl()->getQualifiedNameAsString();
+  return TypeName == "std::optional" || TypeName == "absl::optional" ||

This could get expensive. Maybe add a FIXME to optimize this by avoiding 
`getQualifiedNameAsString`?



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:264
+  +[](const CXXMemberCallExpr *E, LatticeTransferState &State) {
+assignOptionalValue(*E->getImplicitObjectArgument(), State,
+State.Env.getBoolLiteralValue(true));

I realize this is consistent with the previous version, but just noticed this 
issue. By using `assignOptionalValue` for `emplace` (and `reset`), does that 
break the following case?

```
optional opt;
if (p) opt.emplace(3);
someCode();
if (p) use(*opt);
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121602

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


[PATCH] D121512: [Support] Change zlib::compress to return void

2022-03-14 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay updated this revision to Diff 415167.
MaskRay marked an inline comment as done.
MaskRay added a comment.

Simplify CompressedSection::CompressedSection in llvm-objcopy.

CompressedSection::create can be further simplified, but I'll leave that as a 
future change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121512

Files:
  clang-tools-extra/clangd/index/Serialization.cpp
  clang/lib/Serialization/ASTWriter.cpp
  llvm/include/llvm/ProfileData/SampleProf.h
  llvm/include/llvm/Support/Compression.h
  llvm/lib/MC/ELFObjectWriter.cpp
  llvm/lib/ObjCopy/ELF/ELFObject.cpp
  llvm/lib/ObjCopy/ELF/ELFObject.h
  llvm/lib/ProfileData/Coverage/CoverageMappingWriter.cpp
  llvm/lib/ProfileData/InstrProf.cpp
  llvm/lib/ProfileData/SampleProf.cpp
  llvm/lib/ProfileData/SampleProfWriter.cpp
  llvm/lib/Support/Compression.cpp
  llvm/unittests/Support/CompressionTest.cpp

Index: llvm/unittests/Support/CompressionTest.cpp
===
--- llvm/unittests/Support/CompressionTest.cpp
+++ llvm/unittests/Support/CompressionTest.cpp
@@ -27,13 +27,10 @@
   SmallString<32> Compressed;
   SmallString<32> Uncompressed;
 
-  Error E = zlib::compress(Input, Compressed, Level);
-  EXPECT_FALSE(E);
-  consumeError(std::move(E));
+  zlib::compress(Input, Compressed, Level);
 
   // Check that uncompressed buffer is the same as original.
-  E = zlib::uncompress(Compressed, Uncompressed, Input.size());
-  EXPECT_FALSE(E);
+  Error E = zlib::uncompress(Compressed, Uncompressed, Input.size());
   consumeError(std::move(E));
 
   EXPECT_EQ(Input, Uncompressed);
Index: llvm/lib/Support/Compression.cpp
===
--- llvm/lib/Support/Compression.cpp
+++ llvm/lib/Support/Compression.cpp
@@ -46,18 +46,20 @@
 
 bool zlib::isAvailable() { return true; }
 
-Error zlib::compress(StringRef InputBuffer,
- SmallVectorImpl &CompressedBuffer, int Level) {
+void zlib::compress(StringRef InputBuffer,
+SmallVectorImpl &CompressedBuffer, int Level) {
   unsigned long CompressedSize = ::compressBound(InputBuffer.size());
   CompressedBuffer.resize_for_overwrite(CompressedSize);
   int Res =
   ::compress2((Bytef *)CompressedBuffer.data(), &CompressedSize,
   (const Bytef *)InputBuffer.data(), InputBuffer.size(), Level);
+  if (Res == Z_MEM_ERROR)
+report_bad_alloc_error("Allocation failed");
+  assert(Res == Z_OK);
   // Tell MemorySanitizer that zlib output buffer is fully initialized.
   // This avoids a false report when running LLVM with uninstrumented ZLib.
   __msan_unpoison(CompressedBuffer.data(), CompressedSize);
   CompressedBuffer.truncate(CompressedSize);
-  return Res ? createError(convertZlibCodeToString(Res)) : Error::success();
 }
 
 Error zlib::uncompress(StringRef InputBuffer, char *UncompressedBuffer,
@@ -87,8 +89,8 @@
 
 #else
 bool zlib::isAvailable() { return false; }
-Error zlib::compress(StringRef InputBuffer,
- SmallVectorImpl &CompressedBuffer, int Level) {
+void zlib::compress(StringRef InputBuffer,
+SmallVectorImpl &CompressedBuffer, int Level) {
   llvm_unreachable("zlib::compress is unavailable");
 }
 Error zlib::uncompress(StringRef InputBuffer, char *UncompressedBuffer,
Index: llvm/lib/ProfileData/SampleProfWriter.cpp
===
--- llvm/lib/ProfileData/SampleProfWriter.cpp
+++ llvm/lib/ProfileData/SampleProfWriter.cpp
@@ -86,10 +86,8 @@
 return sampleprof_error::success;
   auto &OS = *OutputStream;
   SmallString<128> CompressedStrings;
-  llvm::Error E = zlib::compress(UncompressedStrings, CompressedStrings,
- zlib::BestSizeCompression);
-  if (E)
-return sampleprof_error::compress_failed;
+  zlib::compress(UncompressedStrings, CompressedStrings,
+ zlib::BestSizeCompression);
   encodeULEB128(UncompressedStrings.size(), OS);
   encodeULEB128(CompressedStrings.size(), OS);
   OS << CompressedStrings.str();
Index: llvm/lib/ProfileData/SampleProf.cpp
===
--- llvm/lib/ProfileData/SampleProf.cpp
+++ llvm/lib/ProfileData/SampleProf.cpp
@@ -85,8 +85,6 @@
   return "Counter overflow";
 case sampleprof_error::ostream_seek_unsupported:
   return "Ostream does not support seek";
-case sampleprof_error::compress_failed:
-  return "Compress failure";
 case sampleprof_error::uncompress_failed:
   return "Uncompress failure";
 case sampleprof_error::zlib_unavailable:
Index: llvm/lib/ProfileData/InstrProf.cpp
===
--- llvm/lib/ProfileData/InstrProf.cpp
+++ llvm/lib/ProfileData/InstrProf.cpp
@@ -467,12 +467,8 @@
   }
 
   SmallString<128> CompressedNameStrings;
-  Error E

[PATCH] D121629: clang: also check alloc_alignment claims in return

2022-03-14 Thread Augie Fackler via Phabricator via cfe-commits
durin42 created this revision.
Herald added a project: All.
durin42 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Prior to this patch, we only check alloc_alignment claims in the caller.
I'm about to add some extra logic that threads alloc_alignment
information down into LLVM, which would then have a chance to defeat the
sanitizer checks by performing optimizations. To avoid that, we also
check alignment claims in the called function prior to return.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D121629

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  
clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function-variable.cpp
  
clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function.cpp

Index: clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function.cpp
===
--- clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function.cpp
+++ clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function.cpp
@@ -8,15 +8,38 @@
 
 char **__attribute__((alloc_align(2)))
 passthrough(char **x, unsigned long alignment) {
-  // CHECK:  define{{.*}} i8** @[[PASSTHROUGH:.*]](i8** noundef %[[X:.*]], i64 noundef %[[ALIGNMENT:.*]])
-  // CHECK-NEXT: entry:
-  // CHECK-NEXT:   %[[X_ADDR:.*]] = alloca i8**, align 8
-  // CHECK-NEXT:   %[[ALIGNMENT_ADDR:.*]] = alloca i64, align 8
-  // CHECK-NEXT:   store i8** %[[X]], i8*** %[[X_ADDR]], align 8
-  // CHECK-NEXT:   store i64 %[[ALIGNMENT]], i64* %[[ALIGNMENT_ADDR]], align 8
-  // CHECK-NEXT:   %[[X_RELOADED:.*]] = load i8**, i8*** %[[X_ADDR]], align 8
-  // CHECK-NEXT:   ret i8** %[[X_RELOADED]]
-  // CHECK-NEXT: }
+  // CHECK:define{{.*}} i8** @[[PASSTHROUGH:.*]](i8** noundef %[[X:.*]], i64 noundef %[[ALIGNMENT:.*]])
+  // CHECK-NEXT:   entry:
+  // CHECK-SANITIZE-NEXT:%return.sloc.ptr = alloca i8*, align 8
+  // CHECK-NEXT: %[[X_ADDR:.*]] = alloca i8**, align 8
+  // CHECK-NEXT: %[[ALIGNMENT_ADDR:.*]] = alloca i64, align 8
+  // CHECK-SANITIZE-NEXT:store i8* null, i8** %return.sloc.ptr, align 8
+  // CHECK-NEXT: store i8** %[[X]], i8*** %[[X_ADDR]], align 8
+  // CHECK-NEXT: store i64 %[[ALIGNMENT]], i64* %[[ALIGNMENT_ADDR]], align 8
+  // CHECK-SANITIZE-NEXT:store i8* bitcast ({ [151 x i8]*, i32, i32 }* @0 to i8*), i8** %return.sloc.ptr, align 8
+  // CHECK-NEXT: %[[X_RELOADED:.*]] = load i8**, i8*** %[[X_ADDR]], align 8
+  // CHECK-SANITIZE-NEXT:%ptrint = ptrtoint i8** %0 to i64
+  // CHECK-SANITIZE-NEXT:%1 = sub i64 %alignment, 1
+  // CHECK-SANITIZE-NEXT:%maskedptr = and i64 %ptrint, %1
+  // CHECK-SANITIZE-NEXT:%maskcond = icmp eq i64 %maskedptr, 0
+  // CHECK-SANITIZE-NEXT:%2 = ptrtoint i8** %0 to i64, !nosanitize !2
+  // CHECK-SANITIZE-ANYRECOVER-NEXT: br i1 %maskcond, label %cont, label %handler.alignment_assumption, !prof !3, !nosanitize !2
+  // CHECK-SANITIZE-TRAP-NEXT:   br i1 %maskcond, label %cont, label %trap, !nosanitize !2
+
+  // CHECK-SANITIZE-ANYRECOVER:handler.alignment_assumption:
+  // CHECK-SANITIZE-NORECOVER-NEXT:  call void @__ubsan_handle_alignment_assumption_abort(i8* bitcast ({ { [151 x i8]*, i32, i32 }, { [151 x i8]*, i32, i32 }, { i16, i16, [10 x i8] }* }* @2 to i8*), i64 %2, i64 %alignment, i64 0) #3, !nosanitize !2
+  // CHECK-SANITIZE-NORECOVER-NEXT:  unreachable, !nosanitize !2
+  // CHECK-SANITIZE-RECOVER-NEXT:call void @__ubsan_handle_alignment_assumption(i8* bitcast ({ { [151 x i8]*, i32, i32 }, { [151 x i8]*, i32, i32 }, { i16, i16, [10 x i8] }* }* @2 to i8*), i64 %2, i64 %alignment, i64 0) #3, !nosanitize !2
+  // CHECK-SANITIZE-RECOVER-NEXT:br label %cont, !nosanitize !2
+
+  // CHECK-SANITIZE-TRAP:  trap:
+  // CHECK-SANITIZE-TRAP-NEXT:   call void @llvm.ubsantrap(i8 23) #3, !nosanitize !2
+  // CHECK-SANITIZE-TRAP-NEXT:   unreachable, !nosanitize !2
+
+  // CHECK-SANITIZE:   cont:
+  // CHECK-SANITIZE-NEXT:call void @llvm.assume(i1 true) [ "align"(i8** %[[X_RELOADED]], i64 %[[ALIGNMENT]]) ]
+  // CHECK-NEXT: ret i8** %[[X_RELOADED]]
+  // CHECK-NEXT:   }
   return x;
 }
 
Index: clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function-variable.cpp
===
--- clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function-variable.cpp
+++ clang/test/CodeGen/catch-alignment-assumption-attribute-alloc_align-on-function-variable.cp

[PATCH] D88905: [Clang] Allow "ext_vector_type" applied to Booleans

2022-03-14 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:10244-10245
+  // This operation may not be performed on boolean vectors.
+  if (!AllowBoolOperation && (isBoolOrExtVectorBoolType(LHSType) &&
+  isBoolOrExtVectorBoolType(RHSType)))
+return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();

simoll wrote:
> aaron.ballman wrote:
> > No need for the parens, but should that `&&` have been `||`?
> The `&&` is intentional. We cannot step into this if `AllowBoolOperation` is 
> true.
Yes, but don't we want to step into it if *either* operand is a vector boolean 
type when bool operations are not allowed? (I'm confused by the 
`!AllowBoolOperations` but then allowing them anyway if only one operand is a 
vector bool.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88905

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


  1   2   3   >