[PATCH] D124151: [clang][HIP] Updating driver to enable archive/bitcode to bitcode linking when targeting HIPAMD toolchain

2022-04-21 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j created this revision.
lamb-j added reviewers: yaxunl, kzhuravl.
Herald added a project: All.
lamb-j requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1, MaskRay.
Herald added a reviewer: jdoerfert.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124151

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/lib/Driver/ToolChains/HIPAMD.h
  clang/test/Driver/hip-link-bc-to-bc.hip
  clang/test/Driver/hip-phases.hip

Index: clang/test/Driver/hip-phases.hip
===
--- clang/test/Driver/hip-phases.hip
+++ clang/test/Driver/hip-phases.hip
@@ -520,3 +520,25 @@
 // MIXED2-DAG: input, "{{.*}}empty.cpp", hip, (device-hip, gfx803)
 // MIXED2-DAG: input, "{{.*}}empty.cpp", hip, (device-hip, gfx900)
 // MIXED2-NEG-NOT: input, "{{.*}}empty.cpp", c++
+
+// Test HIP bitcode to bitcode linking. Input should be bundled or unbundled bitcode, and
+// output should be unbundled linked bitcode
+
+// RUN: touch %T/bitcodeA.bc
+// RUN: touch %T/bitcodeB.bc
+// RUN: %clang -ccc-print-phases --hip-link -emit-llvm --cuda-device-only \
+// RUN: --offload-arch=gfx906 %T/bitcodeA.bc %T/bitcodeB.bc 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK %s
+
+// CHECK: [[A0:[0-9]+]]: input, "{{.*}}bitcodeA.bc", ir
+// CHECK: [[A1:[0-9]+]]: clang-offload-unbundler, {[[A0]]}, ir
+// CHECK: [[A2:[0-9]+]]: compiler, {[[A1]]}, ir, (device-hip, [[ARCH:gfx906]])
+// CHECK: [[A3:[0-9]+]]: backend, {[[A2]]}, ir, (device-hip, [[ARCH]])
+
+// CHECK: [[B0:[0-9]+]]: input, "{{.*}}bitcodeB.bc", ir
+// CHECK: [[B1:[0-9]+]]: clang-offload-unbundler, {[[B0]]}, ir
+// CHECK: [[B2:[0-9]+]]: compiler, {[[B1]]}, ir, (device-hip, [[ARCH]])
+// CHECK: [[B3:[0-9]+]]: backend, {[[B2]]}, ir, (device-hip, [[ARCH]])
+
+// CHECK: [[L0:[0-9]+]]: linker, {[[A3]], [[B3]]}, ir, (device-hip, [[ARCH]])
+// CHECK: offload, "device-hip (amdgcn-amd-amdhsa:[[ARCH]])" {[[L0]]}, ir
Index: clang/test/Driver/hip-link-bc-to-bc.hip
===
--- /dev/null
+++ clang/test/Driver/hip-link-bc-to-bc.hip
@@ -0,0 +1,34 @@
+// REQUIRES: clang-driver, x86-registered-target, amdgpu-registered-target
+
+// Check that clang unbundles the two bitcodes and links via llvm-link
+// RUN: touch %T/bundle1.bc
+// RUN: touch %T/bundle2.bc
+
+// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
+// RUN:   %T/bundle1.bc %T/bundle2.bc \
+// RUN:   2>&1 | FileCheck -check-prefix=BITCODE %s
+
+// BITCODE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle1.bc" "-output=[[B1HOST:.*\.bc]]" "-output=[[B1DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// BITCODE: "{{.*}}clang-{{.*}}" "-o" "[[B1DEV2:.*bundle1-gfx906.bc]]" "-x" "ir" "[[B1DEV1]]"
+
+// BITCODE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle2.bc" "-output=[[B2HOST:.*\.bc]]" "-output=[[B2DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// BITCODE: "{{.*}}clang-{{.*}}" "-o" "[[B2DEV2:.*bundle2-gfx906.bc]]" "-x" "ir" "[[B2DEV1]]"
+
+// BITCODE: "{{.*}}llvm-link" "-o" "bundle1-hip-amdgcn-amd-amdhsa-gfx906.bc" "[[B1DEV2]]" "[[B2DEV2]]"
+
+// Check that clang unbundles the bitcode and archive and links via llvm-link
+// RUN: touch %T/libhipbundle.a
+// RUN: touch %T/bundle.bc
+
+// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
+// RUN:   %T/bundle.bc -L%T -lhipbundle \
+// RUN:   2>&1 | FileCheck -check-prefix=ARCHIVE %s
+
+// ARCHIVE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle.bc" "-output=[[HOST:.*\.bc]]" "-output=[[DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// ARCHIVE: "{{.*}}clang-{{.*}}" "-o" "[[DEV2:.*\.bc]]" "-x" "ir" "[[DEV1]]"
+
+// ARCHIVE: "{{.*}}clang-offload-bundler" "-unbundle" "-type=a" "-input={{.*}}libhipbundle.a" "-targets=hip-amdgcn-amd-amdhsa-gfx906" "-output=[[AR:.*\.a]]" "-allow-missing-bundles" "-hip-openmp-compatible"
+
+// ARCHIVE: "{{.*}}llvm-link" "-o" "bundle-hip-amdgcn-amd-amdhsa-gfx906.bc" "[[DEV2]]" "[[AR]]"
Index: clang/lib/Driver/ToolChains/HIPAMD.h
===
--- clang/lib/Driver/ToolChains/HIPAMD.h
+++ clang/lib/Driver/ToolChains/HIPAMD.h
@@ -36,6 +36,9 @@
   void constructLldCommand(Compilation &C, const JobAction &JA,
const InputInfoList &Inputs, const InputInfo &Output,
const llvm::opt::ArgList &Args) const;
+  void constructLlvmLinkCommand(Compilation &C, const JobAction &JA,
+   const InputInfoList &Inputs, const InputInfo &Output,
+   const llvm:

[PATCH] D124151: [clang][HIP] Updating driver to enable archive/bitcode to bitcode linking when targeting HIPAMD toolchain

2022-04-21 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j updated this revision to Diff 424110.
lamb-j added a comment.

Adding clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124151

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/lib/Driver/ToolChains/HIPAMD.h
  clang/test/Driver/hip-link-bc-to-bc.hip
  clang/test/Driver/hip-phases.hip

Index: clang/test/Driver/hip-phases.hip
===
--- clang/test/Driver/hip-phases.hip
+++ clang/test/Driver/hip-phases.hip
@@ -520,3 +520,25 @@
 // MIXED2-DAG: input, "{{.*}}empty.cpp", hip, (device-hip, gfx803)
 // MIXED2-DAG: input, "{{.*}}empty.cpp", hip, (device-hip, gfx900)
 // MIXED2-NEG-NOT: input, "{{.*}}empty.cpp", c++
+
+// Test HIP bitcode to bitcode linking. Input should be bundled or unbundled bitcode, and
+// output should be unbundled linked bitcode
+
+// RUN: touch %T/bitcodeA.bc
+// RUN: touch %T/bitcodeB.bc
+// RUN: %clang -ccc-print-phases --hip-link -emit-llvm --cuda-device-only \
+// RUN: --offload-arch=gfx906 %T/bitcodeA.bc %T/bitcodeB.bc 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK %s
+
+// CHECK: [[A0:[0-9]+]]: input, "{{.*}}bitcodeA.bc", ir
+// CHECK: [[A1:[0-9]+]]: clang-offload-unbundler, {[[A0]]}, ir
+// CHECK: [[A2:[0-9]+]]: compiler, {[[A1]]}, ir, (device-hip, [[ARCH:gfx906]])
+// CHECK: [[A3:[0-9]+]]: backend, {[[A2]]}, ir, (device-hip, [[ARCH]])
+
+// CHECK: [[B0:[0-9]+]]: input, "{{.*}}bitcodeB.bc", ir
+// CHECK: [[B1:[0-9]+]]: clang-offload-unbundler, {[[B0]]}, ir
+// CHECK: [[B2:[0-9]+]]: compiler, {[[B1]]}, ir, (device-hip, [[ARCH]])
+// CHECK: [[B3:[0-9]+]]: backend, {[[B2]]}, ir, (device-hip, [[ARCH]])
+
+// CHECK: [[L0:[0-9]+]]: linker, {[[A3]], [[B3]]}, ir, (device-hip, [[ARCH]])
+// CHECK: offload, "device-hip (amdgcn-amd-amdhsa:[[ARCH]])" {[[L0]]}, ir
Index: clang/test/Driver/hip-link-bc-to-bc.hip
===
--- /dev/null
+++ clang/test/Driver/hip-link-bc-to-bc.hip
@@ -0,0 +1,34 @@
+// REQUIRES: clang-driver, x86-registered-target, amdgpu-registered-target
+
+// Check that clang unbundles the two bitcodes and links via llvm-link
+// RUN: touch %T/bundle1.bc
+// RUN: touch %T/bundle2.bc
+
+// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
+// RUN:   %T/bundle1.bc %T/bundle2.bc \
+// RUN:   2>&1 | FileCheck -check-prefix=BITCODE %s
+
+// BITCODE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle1.bc" "-output=[[B1HOST:.*\.bc]]" "-output=[[B1DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// BITCODE: "{{.*}}clang-{{.*}}" "-o" "[[B1DEV2:.*bundle1-gfx906.bc]]" "-x" "ir" "[[B1DEV1]]"
+
+// BITCODE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle2.bc" "-output=[[B2HOST:.*\.bc]]" "-output=[[B2DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// BITCODE: "{{.*}}clang-{{.*}}" "-o" "[[B2DEV2:.*bundle2-gfx906.bc]]" "-x" "ir" "[[B2DEV1]]"
+
+// BITCODE: "{{.*}}llvm-link" "-o" "bundle1-hip-amdgcn-amd-amdhsa-gfx906.bc" "[[B1DEV2]]" "[[B2DEV2]]"
+
+// Check that clang unbundles the bitcode and archive and links via llvm-link
+// RUN: touch %T/libhipbundle.a
+// RUN: touch %T/bundle.bc
+
+// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
+// RUN:   %T/bundle.bc -L%T -lhipbundle \
+// RUN:   2>&1 | FileCheck -check-prefix=ARCHIVE %s
+
+// ARCHIVE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle.bc" "-output=[[HOST:.*\.bc]]" "-output=[[DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// ARCHIVE: "{{.*}}clang-{{.*}}" "-o" "[[DEV2:.*\.bc]]" "-x" "ir" "[[DEV1]]"
+
+// ARCHIVE: "{{.*}}clang-offload-bundler" "-unbundle" "-type=a" "-input={{.*}}libhipbundle.a" "-targets=hip-amdgcn-amd-amdhsa-gfx906" "-output=[[AR:.*\.a]]" "-allow-missing-bundles" "-hip-openmp-compatible"
+
+// ARCHIVE: "{{.*}}llvm-link" "-o" "bundle-hip-amdgcn-amd-amdhsa-gfx906.bc" "[[DEV2]]" "[[AR]]"
Index: clang/lib/Driver/ToolChains/HIPAMD.h
===
--- clang/lib/Driver/ToolChains/HIPAMD.h
+++ clang/lib/Driver/ToolChains/HIPAMD.h
@@ -36,6 +36,9 @@
   void constructLldCommand(Compilation &C, const JobAction &JA,
const InputInfoList &Inputs, const InputInfo &Output,
const llvm::opt::ArgList &Args) const;
+  void constructLlvmLinkCommand(Compilation &C, const JobAction &JA,
+   const InputInfoList &Inputs, const InputInfo &Output,
+   const llvm::opt::ArgList &Args) const;
 };
 
 } // end namespace AMDGCN
Index: clang/lib/Driver/ToolChains/HIPAMD.cpp
===

[PATCH] D124151: [clang][HIP] Updating driver to enable archive/bitcode to bitcode linking when targeting HIPAMD toolchain

2022-04-21 Thread Jacob Lambert via Phabricator via cfe-commits
lamb-j updated this revision to Diff 424111.
lamb-j added a comment.

Adding clang-format


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124151

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/lib/Driver/ToolChains/HIPAMD.h
  clang/test/Driver/hip-link-bc-to-bc.hip
  clang/test/Driver/hip-phases.hip

Index: clang/test/Driver/hip-phases.hip
===
--- clang/test/Driver/hip-phases.hip
+++ clang/test/Driver/hip-phases.hip
@@ -520,3 +520,25 @@
 // MIXED2-DAG: input, "{{.*}}empty.cpp", hip, (device-hip, gfx803)
 // MIXED2-DAG: input, "{{.*}}empty.cpp", hip, (device-hip, gfx900)
 // MIXED2-NEG-NOT: input, "{{.*}}empty.cpp", c++
+
+// Test HIP bitcode to bitcode linking. Input should be bundled or unbundled bitcode, and
+// output should be unbundled linked bitcode
+
+// RUN: touch %T/bitcodeA.bc
+// RUN: touch %T/bitcodeB.bc
+// RUN: %clang -ccc-print-phases --hip-link -emit-llvm --cuda-device-only \
+// RUN: --offload-arch=gfx906 %T/bitcodeA.bc %T/bitcodeB.bc 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK %s
+
+// CHECK: [[A0:[0-9]+]]: input, "{{.*}}bitcodeA.bc", ir
+// CHECK: [[A1:[0-9]+]]: clang-offload-unbundler, {[[A0]]}, ir
+// CHECK: [[A2:[0-9]+]]: compiler, {[[A1]]}, ir, (device-hip, [[ARCH:gfx906]])
+// CHECK: [[A3:[0-9]+]]: backend, {[[A2]]}, ir, (device-hip, [[ARCH]])
+
+// CHECK: [[B0:[0-9]+]]: input, "{{.*}}bitcodeB.bc", ir
+// CHECK: [[B1:[0-9]+]]: clang-offload-unbundler, {[[B0]]}, ir
+// CHECK: [[B2:[0-9]+]]: compiler, {[[B1]]}, ir, (device-hip, [[ARCH]])
+// CHECK: [[B3:[0-9]+]]: backend, {[[B2]]}, ir, (device-hip, [[ARCH]])
+
+// CHECK: [[L0:[0-9]+]]: linker, {[[A3]], [[B3]]}, ir, (device-hip, [[ARCH]])
+// CHECK: offload, "device-hip (amdgcn-amd-amdhsa:[[ARCH]])" {[[L0]]}, ir
Index: clang/test/Driver/hip-link-bc-to-bc.hip
===
--- /dev/null
+++ clang/test/Driver/hip-link-bc-to-bc.hip
@@ -0,0 +1,34 @@
+// REQUIRES: clang-driver, x86-registered-target, amdgpu-registered-target
+
+// Check that clang unbundles the two bitcodes and links via llvm-link
+// RUN: touch %T/bundle1.bc
+// RUN: touch %T/bundle2.bc
+
+// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
+// RUN:   %T/bundle1.bc %T/bundle2.bc \
+// RUN:   2>&1 | FileCheck -check-prefix=BITCODE %s
+
+// BITCODE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle1.bc" "-output=[[B1HOST:.*\.bc]]" "-output=[[B1DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// BITCODE: "{{.*}}clang-{{.*}}" "-o" "[[B1DEV2:.*bundle1-gfx906.bc]]" "-x" "ir" "[[B1DEV1]]"
+
+// BITCODE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle2.bc" "-output=[[B2HOST:.*\.bc]]" "-output=[[B2DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// BITCODE: "{{.*}}clang-{{.*}}" "-o" "[[B2DEV2:.*bundle2-gfx906.bc]]" "-x" "ir" "[[B2DEV1]]"
+
+// BITCODE: "{{.*}}llvm-link" "-o" "bundle1-hip-amdgcn-amd-amdhsa-gfx906.bc" "[[B1DEV2]]" "[[B2DEV2]]"
+
+// Check that clang unbundles the bitcode and archive and links via llvm-link
+// RUN: touch %T/libhipbundle.a
+// RUN: touch %T/bundle.bc
+
+// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
+// RUN:   %T/bundle.bc -L%T -lhipbundle \
+// RUN:   2>&1 | FileCheck -check-prefix=ARCHIVE %s
+
+// ARCHIVE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle.bc" "-output=[[HOST:.*\.bc]]" "-output=[[DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// ARCHIVE: "{{.*}}clang-{{.*}}" "-o" "[[DEV2:.*\.bc]]" "-x" "ir" "[[DEV1]]"
+
+// ARCHIVE: "{{.*}}clang-offload-bundler" "-unbundle" "-type=a" "-input={{.*}}libhipbundle.a" "-targets=hip-amdgcn-amd-amdhsa-gfx906" "-output=[[AR:.*\.a]]" "-allow-missing-bundles" "-hip-openmp-compatible"
+
+// ARCHIVE: "{{.*}}llvm-link" "-o" "bundle-hip-amdgcn-amd-amdhsa-gfx906.bc" "[[DEV2]]" "[[AR]]"
Index: clang/lib/Driver/ToolChains/HIPAMD.h
===
--- clang/lib/Driver/ToolChains/HIPAMD.h
+++ clang/lib/Driver/ToolChains/HIPAMD.h
@@ -36,6 +36,10 @@
   void constructLldCommand(Compilation &C, const JobAction &JA,
const InputInfoList &Inputs, const InputInfo &Output,
const llvm::opt::ArgList &Args) const;
+  void constructLlvmLinkCommand(Compilation &C, const JobAction &JA,
+const InputInfoList &Inputs,
+const InputInfo &Output,
+const llvm::opt::ArgList &Args) const;
 };
 
 } // end namespace AMDGCN
Index

[PATCH] D124152: [clang-format] Fix a crash on AllowShortFunctionsOnASingleLine

2022-04-21 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: aeubanks, curdeius, MyDeveloperDay, 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/55008.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124152

Files:
  clang/lib/Format/TokenAnnotator.h
  clang/lib/Format/UnwrappedLineFormatter.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -12773,6 +12773,14 @@
"};",
MergeInlineOnly);
 
+  verifyFormat("struct S {\n"
+   "// comment\n"
+   "#ifdef FOO\n"
+   "  int foo() { bar(); }\n"
+   "#endif\n"
+   "};",
+   MergeInlineOnly);
+
   // Also verify behavior when BraceWrapping.AfterFunction = true
   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
   MergeInlineOnly.BraceWrapping.AfterFunction = true;
Index: clang/lib/Format/UnwrappedLineFormatter.cpp
===
--- clang/lib/Format/UnwrappedLineFormatter.cpp
+++ clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -306,24 +306,26 @@
 
   // TODO: Use IndentTracker to avoid loop?
   // Find the last line with lower level.
-  auto J = I - 1;
-  if (!TheLine->InPPDirective) {
-for (; J != AnnotatedLines.begin(); --J) {
-  if (!(*J)->InPPDirective && (*J)->Level < TheLine->Level)
-break;
+  const AnnotatedLine *Line = nullptr;
+  for (auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
+assert(*J);
+if (!(*J)->InPPDirective && !(*J)->isComment() &&
+(*J)->Level < TheLine->Level) {
+  Line = *J;
+  break;
 }
   }
 
-  if ((*J)->Level >= TheLine->Level)
+  if (!Line)
 return false;
 
   // Check if the found line starts a record.
-  const FormatToken *LastNonComment = (*J)->Last;
+  const FormatToken *LastNonComment = Line->Last;
   assert(LastNonComment);
   if (LastNonComment->is(tok::comment)) {
 LastNonComment = LastNonComment->getPreviousNonComment();
 // There must be another token (usually `{`), because we chose a
-// line that has a smaller level.
+// non-PPDirective and non-comment line that has a smaller level.
 assert(LastNonComment);
   }
   return isRecordLBrace(*LastNonComment);
Index: clang/lib/Format/TokenAnnotator.h
===
--- clang/lib/Format/TokenAnnotator.h
+++ clang/lib/Format/TokenAnnotator.h
@@ -76,6 +76,10 @@
 }
   }
 
+  bool isComment() const {
+return First && First->is(tok::comment) && !First->getNextNonComment();
+  }
+
   /// \c true if this line starts with the given tokens in order, ignoring
   /// comments.
   template  bool startsWith(Ts... Tokens) const {


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -12773,6 +12773,14 @@
"};",
MergeInlineOnly);
 
+  verifyFormat("struct S {\n"
+   "// comment\n"
+   "#ifdef FOO\n"
+   "  int foo() { bar(); }\n"
+   "#endif\n"
+   "};",
+   MergeInlineOnly);
+
   // Also verify behavior when BraceWrapping.AfterFunction = true
   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
   MergeInlineOnly.BraceWrapping.AfterFunction = true;
Index: clang/lib/Format/UnwrappedLineFormatter.cpp
===
--- clang/lib/Format/UnwrappedLineFormatter.cpp
+++ clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -306,24 +306,26 @@
 
   // TODO: Use IndentTracker to avoid loop?
   // Find the last line with lower level.
-  auto J = I - 1;
-  if (!TheLine->InPPDirective) {
-for (; J != AnnotatedLines.begin(); --J) {
-  if (!(*J)->InPPDirective && (*J)->Level < TheLine->Level)
-break;
+  const AnnotatedLine *Line = nullptr;
+  for (auto J = I - 1; J >= AnnotatedLines.begin(); --J) {
+assert(*J);
+if (!(*J)->InPPDirective && !(*J)->isComment() &&
+(*J)->Level < TheLine->Level) {
+  Line = *J;
+  break;
 }
   }
 
-  if ((*J)->Level >= TheLine->Level)
+  if (!Line)
 

[PATCH] D124067: [x86] Support 3 builtin functions for 32-bits targets

2022-04-21 Thread Xiang Zhang via Phabricator via cfe-commits
xiangzhangllvm updated this revision to Diff 424113.

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

https://reviews.llvm.org/D124067

Files:
  clang/include/clang/Basic/BuiltinsX86.def
  clang/include/clang/Basic/BuiltinsX86_64.def
  clang/lib/Headers/emmintrin.h
  clang/lib/Headers/smmintrin.h
  clang/test/CodeGen/X86/sse2-builtins.c
  clang/test/CodeGen/X86/sse41-builtins.c

Index: clang/test/CodeGen/X86/sse41-builtins.c
===
--- clang/test/CodeGen/X86/sse41-builtins.c
+++ clang/test/CodeGen/X86/sse41-builtins.c
@@ -184,13 +184,11 @@
   return _mm_extract_epi32(x, 1);
 }
 
-#ifdef __x86_64__
 long long test_mm_extract_epi64(__m128i x) {
-  // X64-LABEL: test_mm_extract_epi64
-  // X64: extractelement <2 x i64> %{{.*}}, {{i32|i64}} 1
+  // CHECK-LABEL: test_mm_extract_epi64
+  // CHECK: extractelement <2 x i64> %{{.*}}, {{i32|i64}} 1
   return _mm_extract_epi64(x, 1);
 }
-#endif
 
 int test_mm_extract_ps(__m128 x) {
   // CHECK-LABEL: test_mm_extract_ps
Index: clang/test/CodeGen/X86/sse2-builtins.c
===
--- clang/test/CodeGen/X86/sse2-builtins.c
+++ clang/test/CodeGen/X86/sse2-builtins.c
@@ -510,13 +510,11 @@
   return _mm_cvtsi128_si32(A);
 }
 
-#ifdef __x86_64__
 long long test_mm_cvtsi128_si64(__m128i A) {
-  // X64-LABEL: test_mm_cvtsi128_si64
-  // X64: extractelement <2 x i64> %{{.*}}, i32 0
+  // CHECK-LABEL: test_mm_cvtsi128_si64
+  // CHECK: extractelement <2 x i64> %{{.*}}, i32 0
   return _mm_cvtsi128_si64(A);
 }
-#endif
 
 __m128d test_mm_cvtsi32_sd(__m128d A, int B) {
   // CHECK-LABEL: test_mm_cvtsi32_sd
@@ -541,14 +539,14 @@
   // X64: insertelement <2 x double> %{{.*}}, double %{{.*}}, i32 0
   return _mm_cvtsi64_sd(A, B);
 }
+#endif
 
 __m128i test_mm_cvtsi64_si128(long long A) {
-  // X64-LABEL: test_mm_cvtsi64_si128
-  // X64: insertelement <2 x i64> undef, i64 %{{.*}}, i32 0
-  // X64: insertelement <2 x i64> %{{.*}}, i64 0, i32 1
+  // CHECK-LABEL: test_mm_cvtsi64_si128
+  // CHECK: insertelement <2 x i64> undef, i64 %{{.*}}, i32 0
+  // CHECK: insertelement <2 x i64> %{{.*}}, i64 0, i32 1
   return _mm_cvtsi64_si128(A);
 }
-#endif
 
 __m128d test_mm_cvtss_sd(__m128d A, __m128 B) {
   // CHECK-LABEL: test_mm_cvtss_sd
Index: clang/lib/Headers/smmintrin.h
===
--- clang/lib/Headers/smmintrin.h
+++ clang/lib/Headers/smmintrin.h
@@ -1061,7 +1061,6 @@
 #define _mm_extract_epi32(X, N) \
   ((int)__builtin_ia32_vec_ext_v4si((__v4si)(__m128i)(X), (int)(N)))
 
-#ifdef __x86_64__
 /// Extracts a 64-bit element from the 128-bit integer vector of
 ///[2 x i64], using the immediate value parameter \a N as a selector.
 ///
@@ -1071,7 +1070,8 @@
 /// long long _mm_extract_epi64(__m128i X, const int N);
 /// \endcode
 ///
-/// This intrinsic corresponds to the  VPEXTRQ / PEXTRQ  instruction.
+/// This intrinsic corresponds to the  VPEXTRQ / PEXTRQ  instruction
+/// in 64-bit mode.
 ///
 /// \param X
 ///A 128-bit integer vector.
@@ -1083,7 +1083,6 @@
 /// \returns  A 64-bit integer.
 #define _mm_extract_epi64(X, N) \
   ((long long)__builtin_ia32_vec_ext_v2di((__v2di)(__m128i)(X), (int)(N)))
-#endif /* __x86_64 */
 
 /* SSE4 128-bit Packed Integer Comparisons.  */
 /// Tests whether the specified bits in a 128-bit integer vector are all
Index: clang/lib/Headers/emmintrin.h
===
--- clang/lib/Headers/emmintrin.h
+++ clang/lib/Headers/emmintrin.h
@@ -3467,13 +3467,13 @@
   return __extension__ (__m128i)(__v4si){ __a, 0, 0, 0 };
 }
 
-#ifdef __x86_64__
 /// Returns a vector of [2 x i64] where the lower element is the input
 ///operand and the upper element is zero.
 ///
 /// \headerfile 
 ///
-/// This intrinsic corresponds to the  VMOVQ / MOVQ  instruction.
+/// This intrinsic corresponds to the  VMOVQ / MOVQ  instruction
+/// in 64 bit mode.
 ///
 /// \param __a
 ///A 64-bit signed integer operand containing the value to be converted.
@@ -3483,7 +3483,6 @@
 {
   return __extension__ (__m128i)(__v2di){ __a, 0 };
 }
-#endif
 
 /// Moves the least significant 32 bits of a vector of [4 x i32] to a
 ///32-bit signed integer value.
@@ -3503,7 +3502,6 @@
   return __b[0];
 }
 
-#ifdef __x86_64__
 /// Moves the least significant 64 bits of a vector of [2 x i64] to a
 ///64-bit signed integer value.
 ///
@@ -3520,7 +3518,6 @@
 {
   return __a[0];
 }
-#endif
 
 /// Moves packed integer values from an aligned 128-bit memory location
 ///to elements in a 128-bit integer vector.
Index: clang/include/clang/Basic/BuiltinsX86_64.def
===
--- clang/include/clang/Basic/BuiltinsX86_64.def
+++ clang/include/clang/Basic/BuiltinsX86_64.def
@@ -42,7 +42,6 @@
 TARGET_BUILTIN(__builtin_ia32_cvtsd2si64, "OiV2d", "ncV:128:", "sse2")
 TARGET_BUILTIN(__builtin_ia32_cvttsd2

[PATCH] D124067: [x86] Support 3 builtin functions for 32-bits targets

2022-04-21 Thread Xiang Zhang via Phabricator via cfe-commits
xiangzhangllvm marked an inline comment as done.
xiangzhangllvm added inline comments.



Comment at: clang/lib/Headers/emmintrin.h:3476
+/// This intrinsic corresponds to the  VMOVQ / MOVQ  instruction
+/// in 64 bits.
 ///

craig.topper wrote:
> craig.topper wrote:
> > 64 bits -> 64-bit mode
> 64 bits -> 64-bit
Thank you!


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

https://reviews.llvm.org/D124067

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


[clang] 1234b1c - [AST] Support template declaration found through using-decl for QualifiedTemplateName.

2022-04-21 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-04-21T10:53:23+02:00
New Revision: 1234b1c6d8113d50beef5801be607ad1d502b2f7

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

LOG: [AST] Support template declaration found through using-decl for 
QualifiedTemplateName.

This is a followup of https://reviews.llvm.org/D123127, adding support
for the QualifiedTemplateName.

Reviewed By: sammccall

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

Added: 


Modified: 
clang/include/clang/AST/ASTContext.h
clang/include/clang/AST/PropertiesBase.td
clang/include/clang/AST/TemplateName.h
clang/lib/AST/ASTContext.cpp
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/QualTypeNames.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/lib/Sema/TreeTransform.h
clang/unittests/AST/TemplateNameTest.cpp

Removed: 




diff  --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 9e10571740de4..03d6a0fbe6eea 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2182,7 +2182,7 @@ class ASTContext : public RefCountedBase {
 
   TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
 bool TemplateKeyword,
-TemplateDecl *Template) const;
+TemplateName Template) const;
 
   TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
 const IdentifierInfo *Name) const;

diff  --git a/clang/include/clang/AST/PropertiesBase.td 
b/clang/include/clang/AST/PropertiesBase.td
index 0ab18b6d59c3d..559f29edcf0fe 100644
--- a/clang/include/clang/AST/PropertiesBase.td
+++ b/clang/include/clang/AST/PropertiesBase.td
@@ -663,12 +663,12 @@ let Class = PropertyTypeCase in {
   def : Property<"hasTemplateKeyword", Bool> {
 let Read = [{ qtn->hasTemplateKeyword() }];
   }
-  def : Property<"declaration", TemplateDeclRef> {
-let Read = [{ qtn->getTemplateDecl() }];
+  def : Property<"underlyingTemplateName", TemplateName> {
+let Read = [{ qtn->getUnderlyingTemplate() }];
   }
   def : Creator<[{
 return ctx.getQualifiedTemplateName(qualifier, hasTemplateKeyword,
-declaration);
+underlyingTemplateName);
   }]>;
 }
 let Class = PropertyTypeCase in {

diff  --git a/clang/include/clang/AST/TemplateName.h 
b/clang/include/clang/AST/TemplateName.h
index 1bd86b0bdcf11..b6f4332830c8f 100644
--- a/clang/include/clang/AST/TemplateName.h
+++ b/clang/include/clang/AST/TemplateName.h
@@ -414,13 +414,19 @@ class QualifiedTemplateName : public llvm::FoldingSetNode 
{
   /// this name with DependentTemplateName).
   llvm::PointerIntPair Qualifier;
 
-  /// The template declaration or set of overloaded function templates
-  /// that this qualified name refers to.
-  TemplateDecl *Template;
+  /// The underlying template name, it is either
+  ///  1) a Template -- a template declaration that this qualified name refers
+  /// to.
+  ///  2) or a UsingTemplate -- a template declaration introduced by a
+  /// using-shadow declaration.
+  TemplateName UnderlyingTemplate;
 
   QualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword,
-TemplateDecl *Template)
-  : Qualifier(NNS, TemplateKeyword? 1 : 0), Template(Template) {}
+TemplateName Template)
+  : Qualifier(NNS, TemplateKeyword ? 1 : 0), UnderlyingTemplate(Template) {
+assert(UnderlyingTemplate.getKind() == TemplateName::Template ||
+   UnderlyingTemplate.getKind() == TemplateName::UsingTemplate);
+  }
 
 public:
   /// Return the nested name specifier that qualifies this name.
@@ -430,19 +436,25 @@ class QualifiedTemplateName : public llvm::FoldingSetNode 
{
   /// keyword.
   bool hasTemplateKeyword() const { return Qualifier.getInt(); }
 
+  /// Return the underlying template name.
+  TemplateName getUnderlyingTemplate() const { return UnderlyingTemplate; }
+
   /// The template declaration to which this qualified name
   /// refers.
-  TemplateDecl *getTemplateDecl() const { return Template; }
+  /// FIXME: remove this and use getUnderlyingTemplate() instead.
+  TemplateDecl *getTemplateDecl() const {
+return UnderlyingTemplate.getAsTemplateDecl();
+  }
 
   void Profile(llvm::FoldingSetNodeID &ID) {
-Profile(ID, getQualifier(), hasTemplateKeyword(), getTemplateDecl());
+Profile(ID, getQualifier(), hasTemplateKeyword(), UnderlyingTemplate);
   }
 
   static void Profile(llvm::FoldingSetNodeID &ID, NestedNameSpecifier *NNS,
-  bool TemplateKeyword, TemplateDecl *Template) {
+ 

[PATCH] D123775: [AST] Support template declaration found through using-decl for QualifiedTemplateName.

2022-04-21 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1234b1c6d811: [AST] Support template declaration found 
through using-decl for… (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D123775?vs=423843&id=424128#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123775

Files:
  clang/include/clang/AST/ASTContext.h
  clang/include/clang/AST/PropertiesBase.td
  clang/include/clang/AST/TemplateName.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/QualTypeNames.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/TreeTransform.h
  clang/unittests/AST/TemplateNameTest.cpp

Index: clang/unittests/AST/TemplateNameTest.cpp
===
--- clang/unittests/AST/TemplateNameTest.cpp
+++ clang/unittests/AST/TemplateNameTest.cpp
@@ -58,5 +58,69 @@
 "vector");
 }
 
+TEST(TemplateName, QualifiedUsingTemplate) {
+  std::string Code = R"cpp(
+namespace std {
+  template  struct vector {};
+}
+namespace absl { using std::vector; }
+
+template class T> class X;
+
+using A = X; // QualifiedTemplateName in a template argument.
+  )cpp";
+  auto AST = tooling::buildASTFromCode(Code);
+  // Match the template argument absl::vector in X.
+  auto Matcher = templateArgumentLoc().bind("id");
+  auto MatchResults = match(Matcher, AST->getASTContext());
+  const auto *TAL = MatchResults.front().getNodeAs("id");
+  ASSERT_TRUE(TAL);
+  TemplateName TN = TAL->getArgument().getAsTemplate();
+  EXPECT_EQ(TN.getKind(), TemplateName::QualifiedTemplate);
+  const auto *QTN = TN.getAsQualifiedTemplateName();
+  // Verify that we have the Using template name in the QualifiedTemplateName.
+  const auto *USD = QTN->getUnderlyingTemplate().getAsUsingShadowDecl();
+  EXPECT_TRUE(USD);
+  EXPECT_EQ(USD->getTargetDecl(), TN.getAsTemplateDecl());
+}
+
+TEST(TemplateName, UsingTemplate) {
+  auto AST = tooling::buildASTFromCode(R"cpp(
+namespace std {
+  template  struct vector { vector(T); };
+}
+namespace absl { using std::vector; }
+// The "absl::vector" is an elaborated TemplateSpecializationType with
+// an inner Using TemplateName (not a Qualified TemplateName, the qualifiers
+// are rather part of the ElaboratedType)!
+absl::vector v(123);
+  )cpp");
+  auto Matcher = elaboratedTypeLoc(
+  hasNamedTypeLoc(loc(templateSpecializationType().bind("id";
+  auto MatchResults = match(Matcher, AST->getASTContext());
+  const auto *TST =
+  MatchResults.front().getNodeAs("id");
+  ASSERT_TRUE(TST);
+  EXPECT_EQ(TST->getTemplateName().getKind(), TemplateName::UsingTemplate);
+
+  AST = tooling::buildASTFromCodeWithArgs(R"cpp(
+namespace std {
+  template  struct vector { vector(T); };
+}
+namespace absl { using std::vector; }
+// Similiar to the TemplateSpecializationType, absl::vector is an elaborated
+// DeducedTemplateSpecializationType with an inner Using TemplateName!
+absl::vector DTST(123);
+)cpp",
+  {"-std=c++17"});
+  Matcher = elaboratedTypeLoc(
+  hasNamedTypeLoc(loc(deducedTemplateSpecializationType().bind("id";
+  MatchResults = match(Matcher, AST->getASTContext());
+  const auto *DTST =
+  MatchResults.front().getNodeAs("id");
+  ASSERT_TRUE(DTST);
+  EXPECT_EQ(DTST->getTemplateName().getKind(), TemplateName::UsingTemplate);
+}
+
 } // namespace
 } // namespace clang
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14714,7 +14714,7 @@
 bool TemplateKW,
 TemplateDecl *Template) {
   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
-  Template);
+  TemplateName(Template));
 }
 
 template
Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -284,17 +284,13 @@
 }
 
 TemplateDecl *TD = cast(D);
-
+Template =
+FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
+assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
 if (SS.isSet() && !SS.isInvalid()) {
   NestedNameSpecifier *Qualifier = SS.getScopeRep();
-  // FIXME: store the using TemplateName in QualifiedTemplateName if
-  // the TD is referred via a using-declaration.
-  Template =
-  Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword, TD);
-} else {
-  Template =
-  FoundUsingShadow ? Tem

[PATCH] D123676: [clang-format] Fix WhitespaceSensitiveMacros not being honoured when macro closing parenthesis is followed by a newline.

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



Comment at: clang/lib/Format/FormatTokenLexer.cpp:1031-1035
+  if (it->second.Finalized) {
+FormatTok->setFinalizedType(it->second.Type);
+  } else {
+FormatTok->setType(it->second.Type);
+  }

owenpan wrote:
> It seems we can simply do this and leave the rest of `FormatTokenLexer` alone.
+1



Comment at: clang/lib/Format/FormatTokenLexer.h:117-120
+  struct MacroTokenInfo {
+TokenType Type;
+bool Finalized;
+  };

ksyx wrote:
> curdeius wrote:
> > ksyx wrote:
> > > Would making constructor of `struct MacroTokenInfo` having default 
> > > parameter or overloading it help avoiding the change of adding `, 
> > > /*Finalized=*/false` to the existing initializer lists?
> > I've thought about it, but it would mean that we have a non-explicit 1-arg 
> > ctor. I'm not a big fan of these as they trigger implicit conversions.
> > I can do though:
> > ```
> >   struct MacroTokenInfo {
> > TokenType Type;
> > bool Finalized{false};
> >   };
> > ```
> > but we'd still need adding braces in:
> > ```
> > Macros.insert({Identifier, {TT_ForEachMacro}});
> > ```
> Yes they are both good point to consider and my start point is just that the 
> `finalized` property is less frequently be `true`.
I wouldn't add a CTor. And I also wouldn't add a default initializer. But the 
latter is better.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123676

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


[PATCH] D107668: [OpenMP]Fix PR50336: Remove temporary files in the offload bundler tool

2022-04-21 Thread Victor Lomuller via Phabricator via cfe-commits
Naghasan added a comment.
Herald added a subscriber: MaskRay.
Herald added a project: All.

Any rational for not calling `addTempFile` during the binding rather than the 
call setup ? I had a brief look there and it seems to me this is the root of 
the problem.

I got bitten by this patch in a downstream project where some of the files in 
the offload action are actual inputs and so got deleted.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107668

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


[PATCH] D124154: [clangd] Fix a declare-constructor tweak crash on incomplete fields.

2022-04-21 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
Herald added a project: All.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124154

Files:
  clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
  clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp


Index: clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
@@ -23,6 +23,8 @@
 
 TEST_F(MemberwiseConstructorTest, Availability) {
   EXPECT_AVAILABLE("^struct ^S ^{ int x, y; };");
+  // Verify no crashes on incomplete member fields.
+  EXPECT_UNAVAILABLE("/*error-ok*/class Forward; class ^A { Forward f;}");
   EXPECT_UNAVAILABLE("struct S { ^int ^x, y; }; struct ^S;");
   EXPECT_UNAVAILABLE("struct ^S {};");
   EXPECT_UNAVAILABLE("union ^S { int x; };");
Index: clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
@@ -178,6 +178,8 @@
 
   // Decide what to do with a field of type C.
   static FieldAction considerClassValue(const CXXRecordDecl &C) {
+if (!C.hasDefinition())
+  return Skip;
 // We can't always tell if C is copyable/movable without doing Sema work.
 // We assume operations are possible unless we can prove not.
 bool CanCopy = C.hasUserDeclaredCopyConstructor() ||


Index: clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
@@ -23,6 +23,8 @@
 
 TEST_F(MemberwiseConstructorTest, Availability) {
   EXPECT_AVAILABLE("^struct ^S ^{ int x, y; };");
+  // Verify no crashes on incomplete member fields.
+  EXPECT_UNAVAILABLE("/*error-ok*/class Forward; class ^A { Forward f;}");
   EXPECT_UNAVAILABLE("struct S { ^int ^x, y; }; struct ^S;");
   EXPECT_UNAVAILABLE("struct ^S {};");
   EXPECT_UNAVAILABLE("union ^S { int x; };");
Index: clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
@@ -178,6 +178,8 @@
 
   // Decide what to do with a field of type C.
   static FieldAction considerClassValue(const CXXRecordDecl &C) {
+if (!C.hasDefinition())
+  return Skip;
 // We can't always tell if C is copyable/movable without doing Sema work.
 // We assume operations are possible unless we can prove not.
 bool CanCopy = C.hasUserDeclaredCopyConstructor() ||
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 82cddb1 - [clangd] tweak tile should start with a capital letter.

2022-04-21 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-04-21T11:24:02+02:00
New Revision: 82cddb173f3781860814fedd86dc83f11ac12e02

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

LOG: [clangd] tweak tile should start with a capital letter.

to consistent with other tweaks.

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/SpecialMembers.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/SpecialMembers.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/SpecialMembers.cpp
index 70604c0c630cf..7d5b41abe5fc5 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/SpecialMembers.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/SpecialMembers.cpp
@@ -91,7 +91,7 @@ class DeclareCopyMove : public Tweak {
 return CodeAction::REFACTOR_KIND;
   }
   std::string title() const override {
-return llvm::formatv("declare implicit {0} members",
+return llvm::formatv("Declare implicit {0} members",
  NeedCopy ? NeedMove ? "copy/move" : "copy" : "move");
   }
 



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


[PATCH] D123450: [clang-format] Parse Verilog if statements

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



Comment at: clang/lib/Format/FormatToken.h:1572
+  bool isBlockBegin(const FormatToken &Tok, const FormatStyle &Style) const {
+return Style.isVerilog() ? isVerilogBegin(Tok) : Tok.is(tok::l_brace);
+  }

Shouldn't we add TT_MacroBlockBegin?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123450

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


[PATCH] D123896: [clang-format] fix nested angle brackets parse inside concept definition

2022-04-21 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

As this is still on my todo list: Have you considered

  concept X = Bar<5 < 4, 5 > 8>;
  concept X = Bar<5 < 4, false>;

Or stuff like that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123896

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


[PATCH] D124157: [clang][preprocessor] Add more macros to target AVR

2022-04-21 Thread Ben Shi via Phabricator via cfe-commits
benshi001 created this revision.
benshi001 added reviewers: aykevl, dylanmckay.
Herald added a subscriber: Jim.
Herald added a project: All.
benshi001 requested review of this revision.
Herald added subscribers: cfe-commits, jacquesguan.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124157

Files:
  clang/lib/Basic/Targets/AVR.cpp
  clang/test/Preprocessor/avr-common.c


Index: clang/test/Preprocessor/avr-common.c
===
--- clang/test/Preprocessor/avr-common.c
+++ clang/test/Preprocessor/avr-common.c
@@ -1,6 +1,10 @@
 // RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown /dev/null | FileCheck 
-match-full-lines %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny4 
/dev/null | FileCheck -match-full-lines %s --check-prefix TINY
 
 // CHECK: #define AVR 1
 // CHECK: #define __AVR 1
 // CHECK: #define __AVR__ 1
 // CHECK: #define __ELF__ 1
+// CHECK-NOT: __AVR_TINY__
+
+// TINY: #define __AVR_TINY__ 1
Index: clang/lib/Basic/Targets/AVR.cpp
===
--- clang/lib/Basic/Targets/AVR.cpp
+++ clang/lib/Basic/Targets/AVR.cpp
@@ -384,6 +384,9 @@
 auto It = llvm::find_if(
 AVRMcus, [&](const MCUInfo &Info) { return Info.Name == this->CPU; });
 
+if (It->IsTiny)
+  Builder.defineMacro("__AVR_TINY__", "1");
+
 if (It != std::end(AVRMcus)) {
   Builder.defineMacro(It->DefineName);
   if (It->NumFlashBanks >= 1)


Index: clang/test/Preprocessor/avr-common.c
===
--- clang/test/Preprocessor/avr-common.c
+++ clang/test/Preprocessor/avr-common.c
@@ -1,6 +1,10 @@
 // RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown /dev/null | FileCheck -match-full-lines %s
+// RUN: %clang_cc1 -E -dM -triple avr-unknown-unknown -target-cpu attiny4 /dev/null | FileCheck -match-full-lines %s --check-prefix TINY
 
 // CHECK: #define AVR 1
 // CHECK: #define __AVR 1
 // CHECK: #define __AVR__ 1
 // CHECK: #define __ELF__ 1
+// CHECK-NOT: __AVR_TINY__
+
+// TINY: #define __AVR_TINY__ 1
Index: clang/lib/Basic/Targets/AVR.cpp
===
--- clang/lib/Basic/Targets/AVR.cpp
+++ clang/lib/Basic/Targets/AVR.cpp
@@ -384,6 +384,9 @@
 auto It = llvm::find_if(
 AVRMcus, [&](const MCUInfo &Info) { return Info.Name == this->CPU; });
 
+if (It->IsTiny)
+  Builder.defineMacro("__AVR_TINY__", "1");
+
 if (It != std::end(AVRMcus)) {
   Builder.defineMacro(It->DefineName);
   if (It->NumFlashBanks >= 1)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D123896: [clang-format] fix nested angle brackets parse inside concept definition

2022-04-21 Thread Sergey Semushin via Phabricator via cfe-commits
predelnik added a comment.

In D123896#3464171 , 
@HazardyKnusperkeks wrote:

> As this is still on my todo list: Have you considered
>
>   concept X = Bar<5 < 4, 5 > 8>;
>   concept X = Bar<5 < 4, false>;
>
> Or stuff like that?

I think it would not work but would not make things much worse than before, 
have to check that though.
Looks like `parseBracedList` probably would not be enough for correct parsing 
of such expressions, is there any better approach?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123896

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


[clang] 87a2583 - [OpenCL] Guard read_write images with TypeExtension

2022-04-21 Thread Sven van Haastregt via cfe-commits

Author: Sven van Haastregt
Date: 2022-04-21T10:52:41+01:00
New Revision: 87a258366e5d4f3786c6c2b9fe5dbeb736def909

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

LOG: [OpenCL] Guard read_write images with TypeExtension

Ensure that any `read_write` image type carries the
`__opencl_c_read_write_images` upon construction of the `ImageType`.

Added: 


Modified: 
clang/lib/Sema/OpenCLBuiltins.td

Removed: 




diff  --git a/clang/lib/Sema/OpenCLBuiltins.td 
b/clang/lib/Sema/OpenCLBuiltins.td
index a7469d684bcc4..ece0b8866d942 100644
--- a/clang/lib/Sema/OpenCLBuiltins.td
+++ b/clang/lib/Sema/OpenCLBuiltins.td
@@ -99,10 +99,8 @@ def FuncExtKhrLocalInt32ExtendedAtomics  : 
FunctionExtension<"cl_khr_local_int32
 def FuncExtKhrInt64BaseAtomics   : 
FunctionExtension<"cl_khr_int64_base_atomics">;
 def FuncExtKhrInt64ExtendedAtomics   : 
FunctionExtension<"cl_khr_int64_extended_atomics">;
 def FuncExtKhrMipmapImage: 
FunctionExtension<"cl_khr_mipmap_image">;
-def FuncExtKhrMipmapImageReadWrite   : 
FunctionExtension<"cl_khr_mipmap_image __opencl_c_read_write_images">;
 def FuncExtKhrMipmapImageWrites  : 
FunctionExtension<"cl_khr_mipmap_image_writes">;
 def FuncExtKhrGlMsaaSharing  : 
FunctionExtension<"cl_khr_gl_msaa_sharing">;
-def FuncExtKhrGlMsaaSharingReadWrite : 
FunctionExtension<"cl_khr_gl_msaa_sharing __opencl_c_read_write_images">;
 
 def FuncExtOpenCLCDeviceEnqueue  : 
FunctionExtension<"__opencl_c_device_enqueue">;
 def FuncExtOpenCLCGenericAddressSpace: 
FunctionExtension<"__opencl_c_generic_address_space">;
@@ -244,9 +242,11 @@ class ImageType :
   let IsConst = _Ty.IsConst;
   let IsVolatile = _Ty.IsVolatile;
   let AddrSpace = _Ty.AddrSpace;
-  // Add TypeExtension for "write_only image3d_t".
+  // Add TypeExtensions for writable "image3d_t" and "read_write" image types.
   let Extension = !cond(
   !and(!eq(_Ty.Name, "image3d_t"), !eq(_AccessQualifier, "WO")) : 
TypeExtension<"cl_khr_3d_image_writes">,
+  !and(!eq(_Ty.Name, "image3d_t"), !eq(_AccessQualifier, "RW")) : 
TypeExtension<"cl_khr_3d_image_writes __opencl_c_read_write_images">,
+  !eq(_AccessQualifier, "RW") : 
TypeExtension<"__opencl_c_read_write_images">,
   true : _Ty.Extension);
 }
 
@@ -1594,9 +1594,6 @@ multiclass ImageQueryNumMipLevels {
 let Extension = FuncExtKhrMipmapImage in {
   defm : ImageQueryNumMipLevels<"RO">;
   defm : ImageQueryNumMipLevels<"WO">;
-}
-
-let Extension = FuncExtKhrMipmapImageReadWrite in {
   defm : ImageQueryNumMipLevels<"RW">;
 }
 
@@ -1673,9 +1670,6 @@ let Extension = FuncExtKhrGlMsaaSharing in {
   defm : ImageReadMsaa<"RO">;
   defm : ImageQueryMsaa<"RO">;
   defm : ImageQueryMsaa<"WO">;
-}
-
-let Extension = FuncExtKhrGlMsaaSharingReadWrite in {
   defm : ImageReadMsaa<"RW">;
   defm : ImageQueryMsaa<"RW">;
 }



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


[PATCH] D124158: [Clang][Attr] Skip adding noundef attribute to arguments when function has convergent attribute

2022-04-21 Thread krishna chaitanya sankisa via Phabricator via cfe-commits
skc7 created this revision.
skc7 added reviewers: sameerds, cdevadas, ronlieb.
Herald added subscribers: mattd, asavonic, ThomasRaoux, jdoerfert, kerbowa, 
kbarton, jvesely, nemanjai.
Herald added a project: All.
skc7 requested review of this revision.
Herald added a reviewer: jdoerfert.
Herald added subscribers: llvm-commits, cfe-commits, sstefan1.
Herald added projects: clang, LLVM.

Change https://reviews.llvm.org/D105169 enables noundef attribute by default. 
This is causing issue with functions tagged with convergent attribute.

For Ex: SimplifyCFG pass removes the branch leading to a BB which has an 
incoming value that will always trigger undefined behavior. This basically 
modifies the CFG and combines the basic blocks. This works for CPU execution. 
But on a GPU, there are intrinsics like "__shfl_sync(unsigned mask, T var, int 
srcLane, int width=warpSize)", Where the exchange of variable occurs 
simultaneously for all active threads within the warp. So, here in the cuda/hip 
kernel, variable var in shuffl_sync may not be initialised, and LLVM IR treats 
it as undef. Currently all the arguments are tagged with noundef attribute and 
the above mentioned optimization by SimplifyCFG gets applied and the kernel 
execution becomes ambiguous. So, the proposed change is to skip adding noundef 
attribute to arguments when a function has been tagged with convergent 
attribute.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124158

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/test/CodeGen/PowerPC/ppc64le-varargs-f128.c
  clang/test/CodeGenCUDA/address-spaces.cu
  clang/test/CodeGenCUDA/builtins-amdgcn.cu
  clang/test/CodeGenCUDA/cuda-builtin-vars.cu
  clang/test/CodeGenCUDA/kernel-args-alignment.cu
  clang/test/CodeGenCUDA/kernel-args.cu
  clang/test/CodeGenCUDA/redux-builtins.cu
  clang/test/CodeGenCUDA/usual-deallocators.cu
  clang/test/CodeGenCUDA/vtbl.cu
  clang/test/CodeGenCUDASPIRV/kernel-argument.cu
  clang/test/CodeGenOpenCL/addr-space-struct-arg.cl
  clang/test/CodeGenOpenCL/address-spaces.cl
  clang/test/CodeGenOpenCL/amdgcn-automatic-variable.cl
  clang/test/CodeGenOpenCL/amdgpu-abi-struct-coerce.cl
  clang/test/CodeGenOpenCL/amdgpu-call-kernel.cl
  clang/test/CodeGenOpenCL/amdgpu-printf.cl
  clang/test/CodeGenOpenCL/as_type.cl
  clang/test/CodeGenOpenCL/atomic-ops-libcall.cl
  clang/test/CodeGenOpenCL/blocks.cl
  clang/test/CodeGenOpenCL/byval.cl
  clang/test/CodeGenOpenCL/const-str-array-decay.cl
  clang/test/CodeGenOpenCL/constant-addr-space-globals.cl
  clang/test/CodeGenOpenCL/convergent.cl
  clang/test/CodeGenOpenCL/fpmath.cl
  clang/test/CodeGenOpenCL/half.cl
  clang/test/CodeGenOpenCL/kernel-param-alignment.cl
  clang/test/CodeGenOpenCL/kernels-have-spir-cc-by-default.cl
  clang/test/CodeGenOpenCL/no-half.cl
  clang/test/CodeGenOpenCL/overload.cl
  clang/test/CodeGenOpenCL/size_t.cl
  clang/test/CodeGenOpenCL/spir-calling-conv.cl
  clang/test/CodeGenOpenCLCXX/address-space-deduction.clcpp
  clang/test/CodeGenOpenCLCXX/addrspace-of-this.clcpp
  clang/test/CodeGenOpenCLCXX/addrspace-operators.clcpp
  clang/test/CodeGenOpenCLCXX/addrspace-references.clcpp
  clang/test/CodeGenOpenCLCXX/addrspace-with-class.clcpp
  clang/test/CodeGenSYCL/address-space-conversions.cpp
  clang/test/CodeGenSYCL/address-space-mangling.cpp
  clang/test/CodeGenSYCL/functionptr-addrspace.cpp
  clang/test/CodeGenSYCL/unique_stable_name.cpp
  clang/test/OpenMP/amdgcn-attributes.cpp
  clang/test/OpenMP/amdgcn_target_global_constructor.cpp
  clang/test/OpenMP/assumes_include_nvptx.cpp
  clang/test/OpenMP/declare_target_codegen.cpp
  clang/test/OpenMP/declare_target_codegen_globalization.cpp
  clang/test/OpenMP/declare_target_link_codegen.cpp
  clang/test/OpenMP/declare_variant_mixed_codegen.c
  clang/test/OpenMP/distribute_codegen.cpp
  clang/test/OpenMP/distribute_simd_codegen.cpp
  clang/test/OpenMP/nvptx_allocate_codegen.cpp
  clang/test/OpenMP/nvptx_data_sharing.cpp
  clang/test/OpenMP/nvptx_declare_target_var_ctor_dtor_codegen.cpp
  clang/test/OpenMP/nvptx_distribute_parallel_generic_mode_codegen.cpp
  clang/test/OpenMP/nvptx_multi_target_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_nested_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_parallel_for_codegen.cpp
  clang/test/OpenMP/nvptx_target_firstprivate_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_num_threads_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_reduction_codegen.cpp
  clang/test/OpenMP/nvptx_target_printf_codegen.c
  clang/test/OpenMP/nvptx_target_teams_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_parallel_for_codegen.cpp
  
clang/test/OpenMP/nvptx_target_teams_distribute_parallel_for_generic_mode_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_parallel_for_simd_codegen.cpp
  clang/test/OpenMP/nvptx_teams_codegen.cpp
  clang

[PATCH] D123896: [clang-format] fix nested angle brackets parse inside concept definition

2022-04-21 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Not yet: https://reviews.llvm.org/D120034


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123896

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


[PATCH] D123896: [clang-format] fix nested angle brackets parse inside concept definition

2022-04-21 Thread Sergey Semushin via Phabricator via cfe-commits
predelnik added a comment.

I see now, would certainly like to help but it sounds like I might not be 
competent enough for this. I guess this review could be closed unless it's an 
acceptable half-measure, not sure.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123896

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


[PATCH] D124067: [x86] Support 3 builtin functions for 32-bits targets

2022-04-21 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon accepted this revision.
RKSimon added a comment.
This revision is now accepted and ready to land.

LGTM with one minor typo




Comment at: clang/lib/Headers/emmintrin.h:3476
+/// This intrinsic corresponds to the  VMOVQ / MOVQ  instruction
+/// in 64 bits.
 ///

xiangzhangllvm wrote:
> craig.topper wrote:
> > craig.topper wrote:
> > > 64 bits -> 64-bit mode
> > 64 bits -> 64-bit
> Thank you!
64-bit (missing hypen)


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

https://reviews.llvm.org/D124067

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


[PATCH] D118409: [OpenMPIRBuilder] Remove ContinuationBB argument from Body callback.

2022-04-21 Thread Kiran Chandramohan via Phabricator via cfe-commits
kiranchandramohan added a comment.

Thanks @Meinersbur for this patch. Apologies for the delay in reviewing many of 
your patches.

The patch looks mostly LGTM.  A few nits. The patch probably needs a rebase 
since there are no dependencies now and a few more construct lowering has 
landed in MLIR (single, simdloop).




Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:5571-5579
+  {
+OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP,
+   *FiniBB);
+EmitStmt(CS->getCapturedStmt());
+  }
+
+  if (Builder.saveIP().isSet())

Why is it not possible to use `OMPBuilderCBHelpers::EmitOMPInlinedRegionBody` 
here?



Comment at: clang/lib/CodeGen/CodeGenFunction.h:1819
+/// Emit the body of an OMP region that will be outlined in
+/// OpenMPIRBuilder::finialize().
+/// \param CGF   The Codegen function this belongs to

Nit:finalize



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:26-58
+/// Move the instruction after an InsertPoint to the beginning of another
+/// BasicBlock.
+///
+/// The instructions after \p IP are moved to the beginning of \p New which 
must
+/// not have any PHINodes. If \p CreateBranch is true, a branch instruction to
+/// \p New will be added such that there is no semantic change. Otherwise, the
+/// \p IP insert block remains degenerate and it is up to the caller to insert 
a

I guess these are already in from your other patch 
(https://reviews.llvm.org/D114413).



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:138
+  /// BasicBlock after CodeGenIP including CodeGenIP itself are invalidated. If
+  /// such InsertPoints need to be preserved, it can split the block itseff
+  /// before calling the callback.

Nit:itself



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:1086
   auto FiniInfo = FinalizationStack.pop_back_val();
-  assert(FiniInfo.DK == OMPD_sections &&
- "Unexpected finalization stack state!");
-  Builder.SetInsertPoint(LoopAfterBB->getTerminator());
-  FiniInfo.FiniCB(Builder.saveIP());
-  Builder.SetInsertPoint(ExitBB);
+  assert(FiniInfo.DK == OMPD_sections && "Uxpected finalization stack state!");
+  if (FinalizeCallbackTy &CB = FiniInfo.FiniCB) {

Nit:Unexpected



Comment at: 
mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp:103
+  llvm::BasicBlock *continuationBlock =
+  splitBB(builder, true, "omp.region.cont");
+  llvm::BasicBlock *sourceBlock = builder.GetInsertBlock();

Would this "omp.region.cont" be a mostly empty block in most cases? I guess it 
is not a problem since llvm will remove these blocks.

The IR generated for 
```
  omp.parallel {
omp.barrier
omp.terminator
  }
```
is the following. Notice the empty (only a branch) `omp.region.cont` block. 
Previously we had this only at the source side `omp.par.region`.

```
omp.par.entry:
  %tid.addr.local = alloca i32, align 4
  %0 = load i32, i32* %tid.addr, align 4
  store i32 %0, i32* %tid.addr.local, align 4
  %tid = load i32, i32* %tid.addr.local, align 4
  br label %omp.par.region

omp.par.region:   ; preds = %omp.par.entry
  br label %omp.par.region1

omp.par.region1:  ; preds = %omp.par.region
  %omp_global_thread_num2 = call i32 @__kmpc_global_thread_num(%struct.ident_t* 
@4)
  call void @__kmpc_barrier(%struct.ident_t* @3, i32 %omp_global_thread_num2)
  br label %omp.region.cont, !dbg !12

omp.region.cont:  ; preds = %omp.par.region1
  br label %omp.par.pre_finalize

omp.par.pre_finalize: ; preds = %omp.region.cont
  br label %omp.par.outlined.exit.exitStub
```



Comment at: openmp/runtime/test/ompt/cancel/cancel_parallel.c:1
-// RUN: %libomp-compile && env OMP_CANCELLATION=true %libomp-run | 
%sort-threads | FileCheck %s
+// RUN: %libomp-compile && env OMP_CANCELLATION=true %libomp-run \
+//  | %sort-threads | FileCheck %s

Nit: unrelated change?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D118409

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


[PATCH] D124154: [clangd] Fix a declare-constructor tweak crash on incomplete fields.

2022-04-21 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp:182
+if (!C.hasDefinition())
+  return Skip;
 // We can't always tell if C is copyable/movable without doing Sema work.

Fail instead?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124154

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


[PATCH] D124057: [asan] Enable detect_stack_use_after_return=1 by default

2022-04-21 Thread Hans Wennborg via Phabricator via cfe-commits
hans accepted this revision.
hans added a comment.
This revision is now accepted and ready to land.

Sounds good to me.

Worth a release note maybe?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124057

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

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

In D122983#3463600 , @nemanjai wrote:

> In D122983#3463569 , @xbolva00 
> wrote:
>
>> But your link shows failures in compiler-rt/, not in llvm test-suite
>
> It shows both. But the `compiler-rt` ones have subsequently been fixed while 
> the `test-suite` ones are still failing as of 
> https://lab.llvm.org/buildbot/#/builders/105/builds/24314.

Thanks for pointing this out -- I'm baffled what's going on with that bot, 
because 1) other bots running the test suite are fine, and 2) the test suite 
was already fixed to disable the diagnostics (which is what fixed things for 
#1):

https://github.com/llvm/llvm-test-suite/blob/main/MultiSource/Benchmarks/Prolangs-C/archie-client/CMakeLists.txt#L2
https://github.com/llvm/llvm-test-suite/blob/main/MultiSource/Benchmarks/Prolangs-C/bison/CMakeLists.txt#L1

(and so on). It's almost as if something on that particular bot is overriding 
the cmake flags (or perhaps using CFLAGS instead of CPPFLAGS)... Here's the 
command line that's failing for bison's symtab.c:

RunSafely.sh detected a failure with these command-line arguments:  
--show-errors -t 
/home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/sandbox/build/tools/timeit
 500 /dev/null Output/symtab.llvm.o.compile 
/home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/stage1.install/bin/clang
 
-I/home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/sandbox/build/MultiSource/Benchmarks/Prolangs-C/bison
 
-I/home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/test-suite/MultiSource/Benchmarks/Prolangs-C/bison
 
-I/home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/test-suite/include
 -I../../../../include -D_GNU_SOURCE -D__STDC_LIMIT_MACROS -DNDEBUG -O3 
-ffp-contract=off -fomit-frame-pointer -c 
/home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/test-suite/MultiSource/Benchmarks/Prolangs-C/bison/symtab.c
 -o Output/symtab.llvm.o

Note how it's missing the warning flag from the CMakeLists.txt file.

So I have no idea what's going on (I can't even really run the tests; I'm on 
Windows and test-suite requires perl to run).

In D122983#3463561 , @MaskRay wrote:

> Adding a global `-Wno-implicit-function-declaration` looks good. @Meinersbur

+1 to this idea, but I'm worried it won't fix that particular bot.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D123667: [clang][AST] Fix crash getting name of a template decl

2022-04-21 Thread Tom Eccles via Phabricator via cfe-commits
tblah added a comment.

I'm not able to reproduce the test failure in CI. It looks spurious to me 
because I have not changed anything related to openmp. The only change in 
behaviour after my patch should be to avoid a null pointer dereference. In 
tests which did not hit that null pointer dereference before there should not 
be any change in behaviour.

What I tried:

  - Use a debian 11 x64 base image
- Install a minimum set of required packages from debian repos (including clang 
and lld from debian)
- Run the commands listed under "Reproduce build locally" on the CI failure 
report


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123667

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-21 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a subscriber: fhahn.
xbolva00 added a comment.

In D122983#3464315 , @aaron.ballman 
wrote:

> In D122983#3463600 , @nemanjai 
> wrote:
>
>> In D122983#3463569 , @xbolva00 
>> wrote:
>>
>>> But your link shows failures in compiler-rt/, not in llvm test-suite
>>
>> It shows both. But the `compiler-rt` ones have subsequently been fixed while 
>> the `test-suite` ones are still failing as of 
>> https://lab.llvm.org/buildbot/#/builders/105/builds/24314.
>
> Thanks for pointing this out -- I'm baffled what's going on with that bot, 
> because 1) other bots running the test suite are fine, and 2) the test suite 
> was already fixed to disable the diagnostics (which is what fixed things for 
> #1):
>
> https://github.com/llvm/llvm-test-suite/blob/main/MultiSource/Benchmarks/Prolangs-C/archie-client/CMakeLists.txt#L2
> https://github.com/llvm/llvm-test-suite/blob/main/MultiSource/Benchmarks/Prolangs-C/bison/CMakeLists.txt#L1
>
> (and so on). It's almost as if something on that particular bot is overriding 
> the cmake flags (or perhaps using CFLAGS instead of CPPFLAGS)... Here's the 
> command line that's failing for bison's symtab.c:
>
> RunSafely.sh detected a failure with these command-line arguments:  
> --show-errors -t 
> /home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/sandbox/build/tools/timeit
>  500 /dev/null Output/symtab.llvm.o.compile 
> /home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/stage1.install/bin/clang
>  
> -I/home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/sandbox/build/MultiSource/Benchmarks/Prolangs-C/bison
>  
> -I/home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/test-suite/MultiSource/Benchmarks/Prolangs-C/bison
>  
> -I/home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/test-suite/include
>  -I../../../../include -D_GNU_SOURCE -D__STDC_LIMIT_MACROS -DNDEBUG -O3 
> -ffp-contract=off -fomit-frame-pointer -c 
> /home/buildbots/ppc64le-clang-lnt-test/clang-ppc64le-lnt/test/test-suite/MultiSource/Benchmarks/Prolangs-C/bison/symtab.c
>  -o Output/symtab.llvm.o
>
> Note how it's missing the warning flag from the CMakeLists.txt file.
>
> So I have no idea what's going on (I can't even really run the tests; I'm on 
> Windows and test-suite requires perl to run).
>
> In D122983#3463561 , @MaskRay wrote:
>
>> Adding a global `-Wno-implicit-function-declaration` looks good. @Meinersbur
>
> +1 to this idea, but I'm worried it won't fix that particular bot.

You probably need to fix Makefiles as well. I believe there were similar 
mysterious errors with -ffp-contract changes. Try to look at history of llvm 
test-suite.

cc @fhahn if he can remember more


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


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

2022-04-21 Thread Gabor Marton via Phabricator via cfe-commits
martong accepted this revision.
martong added a comment.
This revision is now accepted and ready to land.

Ok, still looks good to me, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121176

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

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

In D122983#3464331 , @xbolva00 wrote:

> You probably need to fix Makefiles as well. I believe there were similar 
> mysterious errors with -ffp-contract changes. Try to look at history of llvm 
> test-suite.
>
> cc @fhahn if he can remember more

Good call on looking back through the commit history. It took a while to find 
anyone mucking about with warning flags, but I noticed: 
https://github.com/llvm/llvm-test-suite/commit/24550c3385e8e3703ed364e1ce20b06de97bbeee
 so it looks like CFLAGS is used. I'll push a speculative fix that tries that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-21 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

https://github.com/llvm/llvm-test-suite/commit/79f2b03c5111392d647fa542e120f70c8f39a991


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D107668: [OpenMP]Fix PR50336: Remove temporary files in the offload bundler tool

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

In D107668#3464124 , @Naghasan wrote:

> Any rational for not calling `addTempFile` during the binding rather than the 
> call setup ? I had a brief look there and it seems to me this is the root of 
> the problem.
>
> I got bitten by this patch in a downstream project where some of the files in 
> the offload action are actual inputs and so got deleted.

Sorry to hear that. If I recall the main problem was that the bindings always 
use the `.o` suffix while CUDA requires the `.cubin` suffix to work. There was 
a similar hack somewhere else so I just copied it here and didn't think too 
much about it. If you have a solution that solves your problem I could take a 
look at it. However, we're moving away from this tool anyway, upstream it's no 
longer used for OpenMP offloading and I'm currently working on making that true 
for HIP as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D107668

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

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

In D122983#3464342 , @xbolva00 wrote:

> https://github.com/llvm/llvm-test-suite/commit/79f2b03c5111392d647fa542e120f70c8f39a991

Awesome, parallel build systems to boot. I'll make that change at the same time 
as setting CFLAGS and hopefully the combination of changes will appease the 
bots.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D121868: [cc1as] Add support for emitting the build version load command for -darwin-target-variant

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

Xcode's clang seems to support this:

   % clang -target arm64-apple-macos -target-variant arm64-apple-ios13.1-macabi 
foo.s -c  
  % otool -l foo.o | rg -A2 BUILD   
 
cmd LC_BUILD_VERSION
cmdsize 24
   platform 1
  --
cmd LC_BUILD_VERSION
cmdsize 24
   platform 6

But normal clang doesn't:

  % out/gn/bin/clang -target arm64-apple-macos -darwin-target-variant 
arm64-apple-ios13.1-macabi foo.s -isysroot $(xcrun -show-sdk-path) -c
  % otool -l foo.o | rg -A2 BUILD   
   
cmd LC_BUILD_VERSION
cmdsize 24
   platform 1

So based on that, I agree it's good to land this.

You have commit permissions, right?




Comment at: clang/test/Misc/cc1as-darwin-target-variant-triple.s:2
+// Run cc1as using darwin-target-variant-triple
+// RUN: %clang -cc1as -triple x86_64-apple-macos10.9 
-darwin-target-variant-triple x86_64-apple-ios13.1-macabi -filetype obj %s -o - 
\
+// RUN: | llvm-readobj --file-headers --macho-version-min - \

bc-lee wrote:
> MaskRay wrote:
> > `-filetype obj` on the `%clang -cc1as` line seems weird.
> Without this, I cannot create object file and validate it using 
> `llvm-readobj`.
If you use `emit-obj` I think this test needs a `REQUIRES: 
x86-registered-target`.

I'm not sure if piping binary data works on Windows – it might have stdout in 
text mode, which will do some byte replacements.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121868

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-21 Thread Dávid Bolvanský via Phabricator via cfe-commits
xbolva00 added a comment.

In D122983#3464347 , @aaron.ballman 
wrote:

> In D122983#3464342 , @xbolva00 
> wrote:
>
>> https://github.com/llvm/llvm-test-suite/commit/79f2b03c5111392d647fa542e120f70c8f39a991
>
> Awesome, parallel build systems to boot. I'll make that change at the same 
> time as setting CFLAGS and hopefully the combination of changes will appease 
> the bots.

Anyway true pain to support both. Maybe time to open discussion to remove 
Makefile support as it is a maintenence hell.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

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

In D122983#3464347 , @aaron.ballman 
wrote:

> In D122983#3464342 , @xbolva00 
> wrote:
>
>> https://github.com/llvm/llvm-test-suite/commit/79f2b03c5111392d647fa542e120f70c8f39a991
>
> Awesome, parallel build systems to boot. I'll make that change at the same 
> time as setting CFLAGS and hopefully the combination of changes will appease 
> the bots.

Speculative fixes landed in 33a2cab37889f9599d71d27d48895d0992fe9735 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-21 Thread Florian Hahn via Phabricator via cfe-commits
fhahn added a comment.

In D122983#3464331 , @xbolva00 wrote:

> In D122983#3464315 , @aaron.ballman 
> wrote:
>
>> In D122983#3463561 , @MaskRay 
>> wrote:
>>
>>> Adding a global `-Wno-implicit-function-declaration` looks good. @Meinersbur
>>
>> +1 to this idea, but I'm worried it won't fix that particular bot.
>
> You probably need to fix Makefiles as well. I believe there were similar 
> mysterious errors with -ffp-contract changes. Try to look at history of llvm 
> test-suite.
>
> cc @fhahn if he can remember more

Depending on how many tests need updating in llvm-test-suite, I think it would 
be better to only disable the warning per-test, after verifying the warning 
works as expected.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D124039: [OpenMP] Add better testing for the linker wrapper

2022-04-21 Thread Zibi Sarbino via Phabricator via cfe-commits
zibi added inline comments.



Comment at: clang/test/Driver/linker-wrapper-image.c:8
+
+// OPENMP: @__start_omp_offloading_entries = external hidden constant 
%__tgt_offload_entry
+// OPENMP-NEXT: @__stop_omp_offloading_entries = external hidden constant 
%__tgt_offload_entry

jhuber6 wrote:
> jhuber6 wrote:
> > zibi wrote:
> > > On PowerPC I'm seeing the following error: pointing at `@` char:
> > > clang/test/Driver/linker-wrapper-image.c:10:12: error: OPENMP: expected 
> > > string not found in input
> > > // OPENMP: @__start_omp_offloading_entries = external hidden constant 
> > > %__tgt_offload_entry
> > > 
> > > Are you aware of this?
> > Do you have a link to a buildbot with the full error log? I'll try to test 
> > it locally by manually setting the triple.
> I tested this on a PPC64LE machine and couldn't reproduce, do you have any 
> more information?
Yes, those test cases do pass on external bots. At the time of reporting I did 
not know this affects only the internal builds. We will handle this internally.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124039

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


[PATCH] D124164: [include-cleaner] Include-cleaner library structure, and simplistic AST walking.

2022-04-21 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added reviewers: kbobyrev, CJ-Johnson.
Herald added subscribers: usaxena95, kadircet, mgrang, mgorny.
Herald added a project: All.
sammccall requested review of this revision.
Herald added subscribers: cfe-commits, ilya-biryukov.
Herald added projects: clang, clang-tools-extra.

Include-cleaner is a library that uses the clang AST and preprocessor to
determine which headers are used. It will be used in clang-tidy, in
clangd, in a standalone tool at least for testing, and in out-of-tree tools.

Roughly, it walks the AST, finds referenced decls, maps these to
used sourcelocations, then to FileEntrys, then matching these against #includes.
However there are many wrinkles: dealing with macros, standard library
symbols, umbrella headers, IWYU directives etc.

It is not built on the C++20 modules concept of usage, to allow:

- use with existing non-modules codebases
- a flexible API embeddable in clang-tidy, clangd, and other tools
- avoiding a chicken-and-egg problem where include cleanups are needed before 
modules can be adopted

This library is based on existing functionality in clangd that provides
an unused-include warning. However it has design changes:

- it accommodates diagnosing missing includes too (this means tracking where 
references come from, not just the set of targets)
- it more clearly separates the different mappings (symbol => location => 
header => include) for better testing
- it handles special cases like standard library symbols and IWYU directives 
more elegantly by adding unified Location and Header types instead of 
side-tables
- it will support some customization of policy where necessary (e.g. for style 
questions of what constitutes a use, or to allow both missing-include and 
unused-include modes to be conservative)

This patch adds the basic directory structure under clang-tools-extra
and a skeleton version of the AST traversal, which will be the central
piece.
A more end-to-end prototype is in https://reviews.llvm.org/D122677

RFC: 
https://discourse.llvm.org/t/rfc-lifting-include-cleaner-missing-unused-include-detection-out-of-clangd/61228


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124164

Files:
  clang-tools-extra/CMakeLists.txt
  clang-tools-extra/include-cleaner/CMakeLists.txt
  clang-tools-extra/include-cleaner/README.md
  clang-tools-extra/include-cleaner/lib/AnalysisInternal.h
  clang-tools-extra/include-cleaner/lib/CMakeLists.txt
  clang-tools-extra/include-cleaner/lib/WalkAST.cpp
  clang-tools-extra/include-cleaner/test/CMakeLists.txt
  clang-tools-extra/include-cleaner/test/Unit/lit.cfg.py
  clang-tools-extra/include-cleaner/test/Unit/lit.site.cfg.py.in
  clang-tools-extra/include-cleaner/test/lit.cfg.py
  clang-tools-extra/include-cleaner/test/lit.site.cfg.py.in
  clang-tools-extra/include-cleaner/unittests/CMakeLists.txt
  clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
  clang/include/clang/Testing/TestAST.h
  clang/lib/Testing/TestAST.cpp

Index: clang/lib/Testing/TestAST.cpp
===
--- clang/lib/Testing/TestAST.cpp
+++ clang/lib/Testing/TestAST.cpp
@@ -106,6 +106,10 @@
   auto VFS = llvm::makeIntrusiveRefCnt();
   VFS->addFile(Filename, /*ModificationTime=*/0,
llvm::MemoryBuffer::getMemBufferCopy(In.Code, Filename));
+  for (const auto &Extra : In.ExtraFiles)
+VFS->addFile(
+Extra.getKey(), /*ModificationTime=*/0,
+llvm::MemoryBuffer::getMemBufferCopy(Extra.getValue(), Extra.getKey()));
   Clang->createFileManager(VFS);
 
   // Running the FrontendAction creates the other components: SourceManager,
Index: clang/include/clang/Testing/TestAST.h
===
--- clang/include/clang/Testing/TestAST.h
+++ clang/include/clang/Testing/TestAST.h
@@ -45,6 +45,10 @@
   /// Extra argv to pass to clang -cc1.
   std::vector ExtraArgs = {};
 
+  /// Extra virtual files that are available to be #included.
+  /// Keys are plain filenames ("foo.h"), values are file content.
+  llvm::StringMap ExtraFiles = {};
+
   /// By default, error diagnostics during parsing are reported as gtest errors.
   /// To suppress this, set ErrorOK or include "error-ok" in a comment in Code.
   /// In either case, all diagnostics appear in TestAST::diagnostics().
Index: clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
===
--- /dev/null
+++ clang-tools-extra/include-cleaner/unittests/WalkASTTest.cpp
@@ -0,0 +1,109 @@
+#include "AnalysisInternal.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Frontend/TextDiagnostic.h"
+#include "clang/Testing/TestAST.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Testing/Support/Annotations.h"
+#include "gtest/gtest.h"
+
+namespace clang {
+namespace include_cleaner {
+namespace {
+
+// Specifies a test of which symbo

[clang] 408226f - Fix Sphinx build

2022-04-21 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2022-04-21T08:52:29-04:00
New Revision: 408226f20ab51508350b2e683c39e1710ea73491

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

LOG: Fix Sphinx build

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 818b39933f5d0..00d6b035ff3cf 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -6383,19 +6383,21 @@ The full documentation is available here: 
https://docs.microsoft.com/en-us/windo
 def HLSLSV_ShaderTypeAttrDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
-The ``shader`` type attribute applies to HLSL shader entry functions to 
+The ``shader`` type attribute applies to HLSL shader entry functions to
 identify the shader type for the entry function.
 The syntax is:
+
+.. code-block:: text
+
   ``[shader(string-literal)]``
+
 where the string literal is one of: "pixel", "vertex", "geometry", "hull",
- "domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
- "miss", "callable", "mesh", "amplification".
-Normally the shader type is set by shader target with the ``-T`` option like
-``-Tps_6_1``.
-When compiling to a library target like ``lib_6_3``, the shader type attribute
- can help the compiler to identify the shader type.
-It is mostly used by Raytracing shaders where shaders must be compiled into a
-library and linked at runtime.
+"domain", "compute", "raygeneration", "intersection", "anyhit", "closesthit",
+"miss", "callable", "mesh", "amplification". Normally the shader type is set
+by shader target with the ``-T`` option like ``-Tps_6_1``. When compiling to a
+library target like ``lib_6_3``, the shader type attribute can help the
+compiler to identify the shader type. It is mostly used by Raytracing shaders
+where shaders must be compiled into a library and linked at runtime.
   }];
 }
 



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


[clang-tools-extra] 95d7738 - [clang-tidy] Fix behavior of `modernize-use-using` with nested structs/unions

2022-04-21 Thread Fabian Wolff via cfe-commits

Author: Fabian Wolff
Date: 2022-04-21T15:18:31+02:00
New Revision: 95d77383f2ba8d3136856b52520d3f73f9bc89e7

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

LOG: [clang-tidy] Fix behavior of `modernize-use-using` with nested 
structs/unions

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

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
clang-tools-extra/clang-tidy/modernize/UseUsingCheck.h
clang-tools-extra/test/clang-tidy/checkers/modernize-use-using.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
index a12a056f13ea1..fa3cfa5e9cfca 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -16,6 +16,10 @@ namespace clang {
 namespace tidy {
 namespace modernize {
 
+static constexpr llvm::StringLiteral ParentDeclName = "parent-decl";
+static constexpr llvm::StringLiteral TagDeclName = "tag-decl";
+static constexpr llvm::StringLiteral TypedefName = "typedef";
+
 UseUsingCheck::UseUsingCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)) {}
@@ -25,23 +29,45 @@ void 
UseUsingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
 }
 
 void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(typedefDecl(unless(isInstantiated())).bind("typedef"),
+  Finder->addMatcher(typedefDecl(unless(isInstantiated()),
+ hasParent(decl().bind(ParentDeclName)))
+ .bind(TypedefName),
  this);
-  // This matcher used to find tag declarations in source code within typedefs.
-  // They appear in the AST just *prior* to the typedefs.
-  Finder->addMatcher(tagDecl(unless(isImplicit())).bind("tagdecl"), this);
+
+  // This matcher is used to find tag declarations in source code within
+  // typedefs. They appear in the AST just *prior* to the typedefs.
+  Finder->addMatcher(
+  tagDecl(
+  anyOf(allOf(unless(anyOf(isImplicit(),
+   classTemplateSpecializationDecl())),
+  hasParent(decl().bind(ParentDeclName))),
+// We want the parent of the ClassTemplateDecl, not the parent
+// of the specialization.
+classTemplateSpecializationDecl(hasAncestor(classTemplateDecl(
+hasParent(decl().bind(ParentDeclName)))
+  .bind(TagDeclName),
+  this);
 }
 
 void UseUsingCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *ParentDecl = Result.Nodes.getNodeAs(ParentDeclName);
+  if (!ParentDecl)
+return;
+
   // Match CXXRecordDecl only to store the range of the last non-implicit full
   // declaration, to later check whether it's within the typdef itself.
-  const auto *MatchedTagDecl = Result.Nodes.getNodeAs("tagdecl");
+  const auto *MatchedTagDecl = Result.Nodes.getNodeAs(TagDeclName);
   if (MatchedTagDecl) {
-LastTagDeclRange = MatchedTagDecl->getSourceRange();
+// It is not sufficient to just track the last TagDecl that we've seen,
+// because if one struct or union is nested inside another, the last 
TagDecl
+// before the typedef will be the nested one (PR#50990). Therefore, we also
+// keep track of the parent declaration, so that we can look up the last
+// TagDecl that is a sibling of the typedef in the AST.
+LastTagDeclRanges[ParentDecl] = MatchedTagDecl->getSourceRange();
 return;
   }
 
-  const auto *MatchedDecl = Result.Nodes.getNodeAs("typedef");
+  const auto *MatchedDecl = Result.Nodes.getNodeAs(TypedefName);
   if (MatchedDecl->getLocation().isInvalid())
 return;
 
@@ -102,13 +128,14 @@ void UseUsingCheck::check(const MatchFinder::MatchResult 
&Result) {
   auto Diag = diag(ReplaceRange.getBegin(), UseUsingWarning);
 
   // If typedef contains a full tag declaration, extract its full text.
-  if (LastTagDeclRange.isValid() &&
-  ReplaceRange.fullyContains(LastTagDeclRange)) {
-bool Invalid;
-Type = std::string(
-Lexer::getSourceText(CharSourceRange::getTokenRange(LastTagDeclRange),
- *Result.SourceManager, getLangOpts(), &Invalid));
-if (Invalid)
+  auto LastTagDeclRange = LastTagDeclRanges.find(ParentDecl);
+  if (LastTagDeclRange != LastTagDeclRanges.end() &&
+  LastTagDeclRange->second.isValid() &&
+  ReplaceRange.fullyContains(LastTagDeclRange->second)) {
+Type = std::string(Lexer::getSourceText(
+CharSourceRange::ge

[PATCH] D113804: [clang-tidy] Fix behavior of `modernize-use-using` with nested structs/unions

2022-04-21 Thread Fabian Wolff via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG95d77383f2ba: [clang-tidy] Fix behavior of 
`modernize-use-using` with nested structs/unions (authored by fwolff).

Changed prior to commit:
  https://reviews.llvm.org/D113804?vs=400677&id=424172#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113804

Files:
  clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
  clang-tools-extra/clang-tidy/modernize/UseUsingCheck.h
  clang-tools-extra/test/clang-tidy/checkers/modernize-use-using.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-using.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-use-using.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-using.cpp
@@ -302,3 +302,15 @@
   // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use 'using' instead of 'typedef'
   // CHECK-FIXES: using b = InjectedClassNameWithUnnamedArgument;
 };
+
+typedef struct { int a; union { int b; }; } PR50990;
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: use 'using' instead of 'typedef'
+// CHECK-FIXES: using PR50990 = struct { int a; union { int b; }; };
+
+typedef struct { struct { int a; struct { struct { int b; } c; int d; } e; } f; int g; } PR50990_nested;
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: use 'using' instead of 'typedef'
+// CHECK-FIXES: using PR50990_nested = struct { struct { int a; struct { struct { int b; } c; int d; } e; } f; int g; };
+
+typedef struct { struct { int a; } b; union { int c; float d; struct { int e; }; }; struct { double f; } g; } PR50990_siblings;
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: use 'using' instead of 'typedef'
+// CHECK-FIXES: using PR50990_siblings = struct { struct { int a; } b; union { int c; float d; struct { int e; }; }; struct { double f; } g; };
Index: clang-tools-extra/clang-tidy/modernize/UseUsingCheck.h
===
--- clang-tools-extra/clang-tidy/modernize/UseUsingCheck.h
+++ clang-tools-extra/clang-tidy/modernize/UseUsingCheck.h
@@ -23,7 +23,8 @@
 
   const bool IgnoreMacros;
   SourceLocation LastReplacementEnd;
-  SourceRange LastTagDeclRange;
+  llvm::DenseMap LastTagDeclRanges;
+
   std::string FirstTypedefType;
   std::string FirstTypedefName;
 
Index: clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -16,6 +16,10 @@
 namespace tidy {
 namespace modernize {
 
+static constexpr llvm::StringLiteral ParentDeclName = "parent-decl";
+static constexpr llvm::StringLiteral TagDeclName = "tag-decl";
+static constexpr llvm::StringLiteral TypedefName = "typedef";
+
 UseUsingCheck::UseUsingCheck(StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)) {}
@@ -25,23 +29,45 @@
 }
 
 void UseUsingCheck::registerMatchers(MatchFinder *Finder) {
-  Finder->addMatcher(typedefDecl(unless(isInstantiated())).bind("typedef"),
+  Finder->addMatcher(typedefDecl(unless(isInstantiated()),
+ hasParent(decl().bind(ParentDeclName)))
+ .bind(TypedefName),
  this);
-  // This matcher used to find tag declarations in source code within typedefs.
-  // They appear in the AST just *prior* to the typedefs.
-  Finder->addMatcher(tagDecl(unless(isImplicit())).bind("tagdecl"), this);
+
+  // This matcher is used to find tag declarations in source code within
+  // typedefs. They appear in the AST just *prior* to the typedefs.
+  Finder->addMatcher(
+  tagDecl(
+  anyOf(allOf(unless(anyOf(isImplicit(),
+   classTemplateSpecializationDecl())),
+  hasParent(decl().bind(ParentDeclName))),
+// We want the parent of the ClassTemplateDecl, not the parent
+// of the specialization.
+classTemplateSpecializationDecl(hasAncestor(classTemplateDecl(
+hasParent(decl().bind(ParentDeclName)))
+  .bind(TagDeclName),
+  this);
 }
 
 void UseUsingCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *ParentDecl = Result.Nodes.getNodeAs(ParentDeclName);
+  if (!ParentDecl)
+return;
+
   // Match CXXRecordDecl only to store the range of the last non-implicit full
   // declaration, to later check whether it's within the typdef itself.
-  const auto *MatchedTagDecl = Result.Nodes.getNodeAs("tagdecl");
+  const auto *MatchedTagDecl = Result.Nodes.getNodeAs(TagDeclName);
   if (MatchedTagDecl) {
-LastTagDeclRange = MatchedTagDecl->getSourceRange();
+// It is not sufficient to just track the last TagDec

[PATCH] D124166: [clangd] Correctly identify self-contained headers included rercursively

2022-04-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
Herald added a project: All.
kbobyrev requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Right now when exiting the file Headers.cpp will identify the recursive
inclusion (with a new FileID) as non self-contained and will add it to the set
from which it will never be removed. As a result, we get incorrect results in
the IncludeStructure and Include Cleaner. This patch is a fix.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124166

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -538,6 +538,38 @@
   EXPECT_THAT(Unused, IsEmpty());
 }
 
+TEST(IncludeCleaner, RecursiveInclusion) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+
+void baz() {
+  foo();
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+void foo() {}
+
+#include "bar.h"
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+#include "foo.h"
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  auto Unused = computeUnusedIncludes(AST);
+  EXPECT_THAT(Unused, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -383,6 +383,7 @@
 #include "nonguarded.h"
 #include "pp_depend.h"
 #include "pragmaguarded.h"
+#include "recursive.h"
 )cpp";
   FS.Files["pragmaguarded.h"] = R"cpp(
 #pragma once
@@ -400,10 +401,19 @@
   # error You have to have PP directive set to include this one!
   #endif
 )cpp";
+  FS.Files["recursive.h"] = R"cpp(
+  #ifndef RECURSIVE_H
+  #define RECURSIVE_H
+
+  #include "recursive.h"
+  
+  #endif // RECURSIVE_H
+)cpp";
 
   auto Includes = collectIncludes();
   EXPECT_TRUE(Includes.isSelfContained(getID("pragmaguarded.h", Includes)));
   EXPECT_TRUE(Includes.isSelfContained(getID("includeguarded.h", Includes)));
+  EXPECT_TRUE(Includes.isSelfContained(getID("recursive.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("nonguarded.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("pp_depend.h", Includes)));
 }
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -9,6 +9,7 @@
 #include "Headers.h"
 #include "Preamble.h"
 #include "SourceCode.h"
+#include "support/Logger.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Frontend/CompilerInstance.h"
@@ -106,10 +107,19 @@
 InBuiltinFile = false;
   // At file exit time HeaderSearchInfo is valid and can be used to
   // determine whether the file was a self-contained header or not.
-  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID))
+  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID)) {
+// If a self-contained header is included recursively it will get
+// different FileIDs each time. Only the last result of
+// isSelfContainedHeader is reliable, so we should remove the header
+// from a set of non self-contanied ones if at some point we realze it
+// wasn't one.
 if (!isSelfContainedHeader(FE, PrevFID, SM, HeaderInfo))
   Out->NonSelfContained.insert(
   *Out->getID(SM.getFileEntryForID(PrevFID)));
+else
+  Out->NonSelfContained.erase(
+  *Out->getID(SM.getFileEntryForID(PrevFID)));
+  }
   break;
 }
 case PPCallbacks::RenameFile:
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D124166: [clangd] Correctly identify self-contained headers included rercursively

2022-04-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 424176.
kbobyrev added a comment.

Remove unused include.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124166

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -538,6 +538,38 @@
   EXPECT_THAT(Unused, IsEmpty());
 }
 
+TEST(IncludeCleaner, RecursiveInclusion) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+
+void baz() {
+  foo();
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+void foo() {}
+
+#include "bar.h"
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+#include "foo.h"
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  auto Unused = computeUnusedIncludes(AST);
+  EXPECT_THAT(Unused, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -383,6 +383,7 @@
 #include "nonguarded.h"
 #include "pp_depend.h"
 #include "pragmaguarded.h"
+#include "recursive.h"
 )cpp";
   FS.Files["pragmaguarded.h"] = R"cpp(
 #pragma once
@@ -400,10 +401,19 @@
   # error You have to have PP directive set to include this one!
   #endif
 )cpp";
+  FS.Files["recursive.h"] = R"cpp(
+  #ifndef RECURSIVE_H
+  #define RECURSIVE_H
+
+  #include "recursive.h"
+  
+  #endif // RECURSIVE_H
+)cpp";
 
   auto Includes = collectIncludes();
   EXPECT_TRUE(Includes.isSelfContained(getID("pragmaguarded.h", Includes)));
   EXPECT_TRUE(Includes.isSelfContained(getID("includeguarded.h", Includes)));
+  EXPECT_TRUE(Includes.isSelfContained(getID("recursive.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("nonguarded.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("pp_depend.h", Includes)));
 }
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -106,10 +106,19 @@
 InBuiltinFile = false;
   // At file exit time HeaderSearchInfo is valid and can be used to
   // determine whether the file was a self-contained header or not.
-  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID))
+  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID)) {
+// If a self-contained header is included recursively it will get
+// different FileIDs each time. Only the last result of
+// isSelfContainedHeader is reliable, so we should remove the header
+// from a set of non self-contanied ones if at some point we realze it
+// wasn't one.
 if (!isSelfContainedHeader(FE, PrevFID, SM, HeaderInfo))
   Out->NonSelfContained.insert(
   *Out->getID(SM.getFileEntryForID(PrevFID)));
+else
+  Out->NonSelfContained.erase(
+  *Out->getID(SM.getFileEntryForID(PrevFID)));
+  }
   break;
 }
 case PPCallbacks::RenameFile:


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -538,6 +538,38 @@
   EXPECT_THAT(Unused, IsEmpty());
 }
 
+TEST(IncludeCleaner, RecursiveInclusion) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+
+void baz() {
+  foo();
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+void foo() {}
+
+#include "bar.h"
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+#include "foo.h"
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  auto Unused = computeUnusedIncludes(AST);
+  EXPECT_THAT(Unused, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp

[PATCH] D124166: [clangd] Correctly identify self-contained headers included rercursively

2022-04-21 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/Headers.cpp:111
+// If a self-contained header is included recursively it will get
+// different FileIDs each time. Only the last result of
+// isSelfContainedHeader is reliable, so we should remove the header

second sentence just echoes the code: say why, not what

isSelfContainedHeader only returns true once the full header-guard structure 
has been seen, i.e. when exiting the *outer* copy of the file. So last result 
wins.



Comment at: clang-tools-extra/clangd/Headers.cpp:115
+// wasn't one.
 if (!isSelfContainedHeader(FE, PrevFID, SM, HeaderInfo))
   Out->NonSelfContained.insert(

nit: reverse the if condition to avoid double-negative.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124166

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


[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-04-21 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 424183.
erichkeane added a comment.
This revision is now accepted and ready to land.

Added the tests that still fail to 'concepts.cpp', I still need to figure those 
out.

However, I switched our 'skipping of instantiation' over to use 
`RebuildExprInCurrentInstantiation`, which LOOKS like it is doing the right 
thing in a couple of cases. I thought perhaps this would be useful progress for 
anyone who has ideas/time to poke around to help.


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

https://reviews.llvm.org/D119544

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/Template.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp
  clang/test/SemaTemplate/concepts.cpp
  clang/test/SemaTemplate/cxx2a-constraint-exprs.cpp
  clang/test/SemaTemplate/deferred-concept-inst.cpp
  clang/test/SemaTemplate/instantiate-requires-clause.cpp
  clang/test/SemaTemplate/trailing-return-short-circuit.cpp

Index: clang/test/SemaTemplate/trailing-return-short-circuit.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/trailing-return-short-circuit.cpp
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+  requires(sizeof(T) > 2) || T::value // #FOO_REQ
+void Foo(T){};// #FOO
+
+template 
+void TrailingReturn(T)   // #TRAILING
+  requires(sizeof(T) > 2) || // #TRAILING_REQ
+  T::value   // #TRAILING_REQ_VAL
+{};
+template 
+struct HasValue {
+  static constexpr bool value = B;
+};
+static_assert(sizeof(HasValue) <= 2);
+
+template 
+struct HasValueLarge {
+  static constexpr bool value = B;
+  int I;
+};
+static_assert(sizeof(HasValueLarge) > 2);
+
+void usage() {
+  // Passes the 1st check, short-circuit so the 2nd ::value is not evaluated.
+  Foo(1.0);
+  TrailingReturn(1.0);
+
+  // Fails the 1st check, but has a ::value, so the check happens correctly.
+  Foo(HasValue{});
+  TrailingReturn(HasValue{});
+
+  // Passes the 1st check, but would have passed the 2nd one.
+  Foo(HasValueLarge{});
+  TrailingReturn(HasValueLarge{});
+
+  // Fails the 1st check, fails 2nd because there is no ::value.
+  Foo(true);
+  // expected-error@-1{{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  TrailingReturn(true);
+  // expected-error@-1{{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  // Fails the 1st check, fails 2nd because ::value is false.
+  Foo(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{and 'HasValue::value' evaluated to false}}
+  TrailingReturn(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{and 'HasValue::value' evaluated to false}}
+}
Index: clang/test/SemaTemplate/instantiate-requires-clause.cpp
===
--- clang/test/SemaTemplate/instantiate-requires-clause.cpp
+++ clang/test/SemaTemplate/instantiate-requires-clause.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++2a -x c++ %s -verify
+// RUN: %clang_cc1 -std=c++2a -x c++ %s -Wno-unused-value -verify
 
 template  requires ((sizeof(Args) == 1), ...)
 // expected-note@-1 {{because '(sizeof(int) == 1) , (sizeof(cha

[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-04-21 Thread Erich Keane via Phabricator via cfe-commits
erichkeane planned changes to this revision.
erichkeane added inline comments.



Comment at: clang/test/SemaTemplate/concepts.cpp:391
+
+  CausesFriendConstraint CFC;
+  FriendFunc(CFC, 1);

A bunch of the tests below this all fail.


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

https://reviews.llvm.org/D119544

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


[PATCH] D124170: [clangd] Include Cleaner: suppress unused warnings for IWYU pragma: export

2022-04-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev created this revision.
kbobyrev added a reviewer: sammccall.
Herald added subscribers: usaxena95, kadircet, arphaman.
Herald added a project: All.
kbobyrev requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Add limited support for "IWYU pragma: export" - for now it just supresses the
warning similar to "IWYU pragma: keep".


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124170

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -511,11 +511,13 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "exported.h" // IWYU pragma: export
 #include "public.h"
 
 void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["exported.h"] = guard("");
   TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
   TU.AdditionalFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "public.h"
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -22,6 +22,7 @@
 namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -129,15 +130,21 @@
   // 2. HandleComment("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // HandleComment will store the last location of "IWYU pragma: keep" comment
-  // in the main file, so that when InclusionDirective is called, it will know
-  // that the next inclusion is behind the IWYU pragma.
+  // HandleComment will store the last location of "IWYU pragma: keep" (or
+  // export) comment in the main file, so that when InclusionDirective is
+  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 if (!inMainFile() || Range.getBegin().isMacroID())
   return false;
 bool Err = false;
 llvm::StringRef Text = SM.getCharacterData(Range.getBegin(), &Err);
-if (Err || !Text.consume_front(IWYUPragmaKeep))
+if (Err)
+  return false;
+if (Text.startswith(IWYUPragmaKeep))
+  Text.consume_front(IWYUPragmaKeep);
+else if (Text.startswith(IWYUPragmaExport))
+  Text.consume_front(IWYUPragmaExport);
+else
   return false;
 unsigned Offset = SM.getFileOffset(Range.getBegin());
 LastPragmaKeepInMainFileLine =


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -511,11 +511,13 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "exported.h" // IWYU pragma: export
 #include "public.h"
 
 void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["exported.h"] = guard("");
   TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
   TU.AdditionalFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "public.h"
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -22,6 +22,7 @@
 namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -129,15 +130,21 @@
   // 2. HandleComment("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // HandleComment will store the last location of "IWYU pragma: keep" comment
-  // in the main file, so that when InclusionDirective is called, it will know
-  // that the next inclusion is behind the IWYU pragma.
+  // HandleComment will store the last location of "IWYU pragma: keep" (or
+  // export) comment in the main file, so that when InclusionDirective is
+  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 if (!inMainFile() || Range.getBegin().isMacroID())
   return false;
 bool Err = false;
 llvm:

[PATCH] D124151: [clang][HIP] Updating driver to enable archive/bitcode to bitcode linking when targeting HIPAMD toolchain

2022-04-21 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124151

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


[PATCH] D124170: [clangd] Include Cleaner: suppress unused warnings for IWYU pragma: export

2022-04-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 424189.
kbobyrev added a comment.

Use strlen for performance.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124170

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -511,11 +511,13 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "exported.h" // IWYU pragma: export
 #include "public.h"
 
 void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["exported.h"] = guard("");
   TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
   TU.AdditionalFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "public.h"
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -17,11 +17,13 @@
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -129,15 +131,21 @@
   // 2. HandleComment("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // HandleComment will store the last location of "IWYU pragma: keep" comment
-  // in the main file, so that when InclusionDirective is called, it will know
-  // that the next inclusion is behind the IWYU pragma.
+  // HandleComment will store the last location of "IWYU pragma: keep" (or
+  // export) comment in the main file, so that when InclusionDirective is
+  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 if (!inMainFile() || Range.getBegin().isMacroID())
   return false;
 bool Err = false;
 llvm::StringRef Text = SM.getCharacterData(Range.getBegin(), &Err);
-if (Err || !Text.consume_front(IWYUPragmaKeep))
+if (Err)
+  return false;
+if (Text.startswith(IWYUPragmaKeep))
+  Text = Text.drop_front(std::strlen(IWYUPragmaKeep));
+else if (Text.startswith(IWYUPragmaExport))
+  Text = Text.drop_front(std::strlen(IWYUPragmaExport));
+else
   return false;
 unsigned Offset = SM.getFileOffset(Range.getBegin());
 LastPragmaKeepInMainFileLine =


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -511,11 +511,13 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "exported.h" // IWYU pragma: export
 #include "public.h"
 
 void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["exported.h"] = guard("");
   TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
   TU.AdditionalFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "public.h"
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -17,11 +17,13 @@
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -129,15 +131,21 @@
   // 2. HandleComment("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // HandleComment will store the last location of "IWYU pragma: keep" comment
-  // in the main file, so that when InclusionDirective is called, it will know
-  // that the next inclusion is behind the IWYU pragma.
+  // HandleComment will store the last location of "IWYU pragma: keep" (or
+  // export) comment in the main file, so that when InclusionDirective is
+  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 if (!inMainFile() || Range.getBegin().isMacroID())

[PATCH] D123831: [POC][WIP] Use relative include in extract-api

2022-04-21 Thread Daniel Grumberg via Phabricator via cfe-commits
dang added a comment.

In D123831#3459368 , @ributzka wrote:

> In D123831#3458774 , @dang wrote:
>
>> In D123831#3455048 , @cishida 
>> wrote:
>>
 we might not always want to transform an absolute path because the 
 resulting relative include name might get remapped in a headermap, for 
 example in test known_files_only_hmap.c. But how does it work with modules 
 where we need relative includes? Is the setup in known_files_only_hmap 
 even valid?
>>>
>>> I think, in most cases, this shouldn't matter because if the header path 
>>> input doesn't match the location stored in the header map, they should 
>>> still have the same source content. The same should be true with header 
>>> search resolution with modules & vfsoverlay
>>
>> Agreed, I think it would be classified as a user error to remap to different 
>> source content via headermap.
>
> This is happening today in Xcode. Headers that are mapped from the DSTROOT 
> back to the SRCROOT can be different, because they are not simply copied. 
> Xcode also runs unifdef on them.

What do you mean? The headers in the DSTROOT don't have the ifdef? Either way, 
this shouldn't matter because the declarations we are processing would be the 
same across both versions of the header?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123831

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


[PATCH] D124166: [clangd] Correctly identify self-contained headers included rercursively

2022-04-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 424192.
kbobyrev marked 2 inline comments as done.
kbobyrev added a comment.

Resolve the comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124166

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -538,6 +538,38 @@
   EXPECT_THAT(Unused, IsEmpty());
 }
 
+TEST(IncludeCleaner, RecursiveInclusion) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+
+void baz() {
+  foo();
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+void foo() {}
+
+#include "bar.h"
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+#include "foo.h"
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  auto Unused = computeUnusedIncludes(AST);
+  EXPECT_THAT(Unused, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -383,6 +383,7 @@
 #include "nonguarded.h"
 #include "pp_depend.h"
 #include "pragmaguarded.h"
+#include "recursive.h"
 )cpp";
   FS.Files["pragmaguarded.h"] = R"cpp(
 #pragma once
@@ -400,10 +401,19 @@
   # error You have to have PP directive set to include this one!
   #endif
 )cpp";
+  FS.Files["recursive.h"] = R"cpp(
+  #ifndef RECURSIVE_H
+  #define RECURSIVE_H
+
+  #include "recursive.h"
+  
+  #endif // RECURSIVE_H
+)cpp";
 
   auto Includes = collectIncludes();
   EXPECT_TRUE(Includes.isSelfContained(getID("pragmaguarded.h", Includes)));
   EXPECT_TRUE(Includes.isSelfContained(getID("includeguarded.h", Includes)));
+  EXPECT_TRUE(Includes.isSelfContained(getID("recursive.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("nonguarded.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("pp_depend.h", Includes)));
 }
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -106,10 +106,17 @@
 InBuiltinFile = false;
   // At file exit time HeaderSearchInfo is valid and can be used to
   // determine whether the file was a self-contained header or not.
-  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID))
-if (!isSelfContainedHeader(FE, PrevFID, SM, HeaderInfo))
+  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID)) {
+// isSelfContainedHeader only returns true once the full header-guard
+// structure has been seen, i.e. when exiting the *outer* copy of the
+// file. So last result wins.
+if (isSelfContainedHeader(FE, PrevFID, SM, HeaderInfo))
+  Out->NonSelfContained.erase(
+  *Out->getID(SM.getFileEntryForID(PrevFID)));
+else
   Out->NonSelfContained.insert(
   *Out->getID(SM.getFileEntryForID(PrevFID)));
+  }
   break;
 }
 case PPCallbacks::RenameFile:


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -538,6 +538,38 @@
   EXPECT_THAT(Unused, IsEmpty());
 }
 
+TEST(IncludeCleaner, RecursiveInclusion) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+
+void baz() {
+  foo();
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+void foo() {}
+
+#include "bar.h"
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+#include "foo.h"
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  auto Unused = computeUnusedIncludes(AST);
+  EXPECT_THAT(Unused, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
==

[PATCH] D124091: [clang][AArch64][SVE] Implement conditional operator for SVE vectors

2022-04-21 Thread David Truby via Phabricator via cfe-commits
DavidTruby updated this revision to Diff 424193.
DavidTruby added a comment.

Add additional tests for vector splats


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124091

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/CodeGenCXX/aarch64-sve-vector-conditional-op.cpp
  clang/test/SemaCXX/aarch64-sve-vector-conditional-op.cpp

Index: clang/test/SemaCXX/aarch64-sve-vector-conditional-op.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/aarch64-sve-vector-conditional-op.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -verify -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -fsyntax-only %s
+
+// REQUIRES: aarch64-registered-target
+
+#include 
+
+void cond(svint8_t i8, svint16_t i16, svint32_t i32, svint64_t i64,
+  svuint8_t u8, svuint16_t u16, svuint32_t u32, svuint64_t u64,
+  svfloat16_t f16, svfloat32_t f32, svfloat64_t f64,
+  svbool_t b) {
+  (void) i8 < i8 ? i16 : i16; // expected-error{{invalid operands to binary expression}}
+  (void) i8 < i8 ? i32 : i32; // expected-error{{invalid operands to binary expression}}
+  (void) i8 < i8 ? i64 : i64; // expected-error{{invalid operands to binary expression}}
+
+  (void) i16 < i16 ? i16 : i8; // expected-error{{invalid operands to binary expression}}
+  (void) i16 < i16 ? i16 : i32; // expected-error{{invalid operands to binary expression}}
+  (void) i16 < i16 ? i16 : i64; // expected-error{{invalid operands to binary expression}}
+
+  (void) i16 < i16 ? i8 : i16; // expected-error{{invalid operands to binary expression}}
+  (void) i16 < i16 ? i32 : i16; // expected-error{{invalid operands to binary expression}}
+  (void) i16 < i16 ? i64 : i16; // expected-error{{invalid operands to binary expression}}
+}
\ No newline at end of file
Index: clang/test/CodeGenCXX/aarch64-sve-vector-conditional-op.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/aarch64-sve-vector-conditional-op.cpp
@@ -0,0 +1,224 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve \
+// RUN: -fallow-half-arguments-and-returns -disable-O0-optnone \
+// RUN:  -emit-llvm -o - %s | opt -S -sroa | FileCheck %s
+
+// REQUIRES: aarch64-registered-target
+
+#include 
+
+// CHECK-LABEL: @_Z9cond_boolu10__SVBool_tu10__SVBool_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CMP]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [[A]],  [[B]]
+// CHECK-NEXT:ret  [[VECTOR_SELECT]]
+//
+svbool_t cond_bool(svbool_t a, svbool_t b) {
+return a < b ? a : b;
+}
+
+// CHECK-LABEL: @_Z7cond_i8u10__SVInt8_tu10__SVInt8_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[CONV:%.*]] = zext  [[CMP]] to 
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CONV]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [[A]],  [[B]]
+// CHECK-NEXT:ret  [[VECTOR_SELECT]]
+//
+svint8_t cond_i8(svint8_t a, svint8_t b) {
+return a < b ? a : b;
+}
+
+// CHECK-LABEL: @_Z7cond_u8u11__SVUint8_tu11__SVUint8_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[CONV:%.*]] = zext  [[CMP]] to 
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CONV]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [[A]],  [[B]]
+// CHECK-NEXT:ret  [[VECTOR_SELECT]]
+//
+svuint8_t cond_u8(svuint8_t a, svuint8_t b) {
+return a < b ? a : b;
+}
+
+// CHECK-LABEL: @_Z8cond_i16u11__SVInt16_tu11__SVInt16_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[CONV:%.*]] = zext  [[CMP]] to 
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CONV]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [[A]],  [[B]]
+// CHECK-NEXT:ret  [[VECTOR_SELECT]]
+//
+svint16_t cond_i16(svint16_t a, svint16_t b) {
+return a < b ? a : b;
+}
+
+// CHECK-LABEL: @_Z8cond_u16u12__SVUint16_tu12__SVUint16_t(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[CMP:%.*]] = icmp ult  [[A:%.*]], [[B:%.*]]
+// CHECK-NEXT:[[CONV:%.*]] = zext  [[CMP]] to 
+// CHECK-NEXT:[[VECTOR_COND:%.*]] = icmp ne  [[CONV]], zeroinitializer
+// CHECK-NEXT:[[VECTOR_SELECT:%.*]] = select  [[VECTOR_COND]],  [[A]],  [[B]]
+// CHECK-NEXT:ret  [[VECTOR_SELECT]]
+//
+svuint16_t cond_u16(svuint16_t a, svuint16_t b) {
+return a < b ? a : b;
+}
+
+// CHECK-LABEL: @_Z8cond_i32u11__SVInt32_tu11__SVInt32_t(
+// CHECK-NEXT:  entry:
+

[PATCH] D124170: [clangd] Include Cleaner: suppress unused warnings for IWYU pragma: export

2022-04-21 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/Headers.cpp:26
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 

or just drop to IWYUPragma and hardcode "keep" and "export" at the sites? up to 
you



Comment at: clang-tools-extra/clangd/Headers.cpp:144
+  return false;
+if (Text.startswith(IWYUPragmaKeep))
+  Text = Text.drop_front(std::strlen(IWYUPragmaKeep));

why not just `if (!Text.consume_front(IWYUPragmaKeep) && 
!Text.consume_front(IWYUPragmaExport))`?

strlen makes me wary and also seems more verbose


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124170

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-21 Thread Jake Egan via Phabricator via cfe-commits
Jake-Egan added a comment.

Hi, we also have a failure on AIX with test-suite `call to undeclared library 
function '%0' with type %1; ISO C99 and later`  
https://lab.llvm.org/buildbot/#/builders/214/builds/825/steps/9/logs/stdio


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

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

In D122983#3464724 , @Jake-Egan wrote:

> Hi, we also have a failure on AIX with test-suite `call to undeclared library 
> function '%0' with type %1; ISO C99 and later`  
> https://lab.llvm.org/buildbot/#/builders/214/builds/825/steps/9/logs/stdio

Thanks for letting me know, this should now be fixed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D124176: [clangd] Add beforeExecute() callback to FeatureModules.

2022-04-21 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz created this revision.
adamcz added a reviewer: kadircet.
Herald added subscribers: usaxena95, arphaman.
Herald added a project: All.
adamcz requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

It runs immediatelly before FrontendAction::Execute() with a mutable
CompilerInstance, allowing FeatureModules to register callbacks, remap
files, etc.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124176

Files:
  clang-tools-extra/clangd/FeatureModule.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp

Index: clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
===
--- clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
+++ clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
@@ -12,6 +12,7 @@
 #include "TestTU.h"
 #include "refactor/Tweak.h"
 #include "support/Logger.h"
+#include "clang/Lex/PreprocessorOptions.h"
 #include "llvm/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -85,6 +86,41 @@
   }
 }
 
+TEST(FeatureModulesTest, BeforeExecute) {
+  struct BeforeExecuteModule final : public FeatureModule {
+struct Listener : public FeatureModule::ASTListener {
+  void beforeExecute(CompilerInstance &CI) override {
+CI.getPreprocessor().SetSuppressIncludeNotFoundError(true);
+  }
+};
+std::unique_ptr astListeners() override {
+  return std::make_unique();
+};
+  };
+  FeatureModuleSet FMS;
+  FMS.add(std::make_unique());
+
+  TestTU TU = TestTU::withCode(R"cpp(
+/*error-ok*/
+#include "not_found.h"
+
+void foo() {
+  #include "not_found_not_preamble.h"
+}
+  )cpp");
+
+  {
+auto AST = TU.build();
+EXPECT_THAT(*AST.getDiagnostics(), testing::Not(testing::IsEmpty()));
+  }
+
+  TU.FeatureModules = &FMS;
+  {
+auto AST = TU.build();
+EXPECT_THAT(*AST.getDiagnostics(), testing::IsEmpty());
+  }
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -64,9 +64,12 @@
 
 class CppFilePreambleCallbacks : public PreambleCallbacks {
 public:
-  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback,
-   PreambleBuildStats *Stats)
-  : File(File), ParsedCallback(ParsedCallback), Stats(Stats) {}
+  CppFilePreambleCallbacks(
+  PathRef File, PreambleParsedCallback ParsedCallback,
+  PreambleBuildStats *Stats,
+  std::function BeforeExecuteCallback)
+  : File(File), ParsedCallback(ParsedCallback), Stats(Stats),
+BeforeExecuteCallback(BeforeExecuteCallback) {}
 
   IncludeStructure takeIncludes() { return std::move(Includes); }
 
@@ -111,6 +114,8 @@
   }
 
   void BeforeExecute(CompilerInstance &CI) override {
+if (BeforeExecuteCallback)
+  BeforeExecuteCallback(CI);
 CanonIncludes.addSystemHeadersMapping(CI.getLangOpts());
 LangOpts = &CI.getLangOpts();
 SourceMgr = &CI.getSourceManager();
@@ -156,6 +161,7 @@
   const clang::LangOptions *LangOpts = nullptr;
   const SourceManager *SourceMgr = nullptr;
   PreambleBuildStats *Stats;
+  std::function BeforeExecuteCallback;
 };
 
 // Represents directives other than includes, where basic textual information is
@@ -477,7 +483,12 @@
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats);
+  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats,
+[&ASTListeners](CompilerInstance &CI) {
+  for (const auto &L : ASTListeners) {
+L->beforeExecute(CI);
+  }
+});
   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
   llvm::SmallString<32> AbsFileName(FileName);
   VFS->makeAbsolute(AbsFileName);
@@ -716,5 +727,6 @@
   }
   return Loc;
 }
+
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -550,6 +550,9 @@
   // Collect tokens of the main file.
   syntax::TokenCollector CollectTokens(Clang->getPreprocessor());
 
+  for (const auto &L : ASTListeners)
+L->beforeExecute(*Clang);
+
   if (llvm::Error Err = Action->Execute())
 log("Execute() failed when building AST for {0}: {1}", MainInput.getFile(),
 toString(std::move(Err)));

[PATCH] D124177: [Frontend] Simplify PrecompiledPreamble::PCHStorage. NFC

2022-04-21 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: adamcz.
Herald added a project: All.
sammccall requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

- Remove fiddly union, preambles are heavyweight
- Remove fiddly move constructors in TempPCHFile and PCHStorage, use unique_ptr
- Remove unneccesary accessors on PCHStorage
- Remove trivial InMemoryStorage
- Move implementation details into cpp file

This is a prefactoring, followup change will change the in-memory PCHStorage to
avoid extra string copies while creating it.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124177

Files:
  clang/include/clang/Frontend/PrecompiledPreamble.h
  clang/lib/Frontend/PrecompiledPreamble.cpp

Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -11,10 +11,8 @@
 //===--===//
 
 #include "clang/Frontend/PrecompiledPreamble.h"
-#include "clang/AST/DeclObjC.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangStandard.h"
-#include "clang/Basic/TargetInfo.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/FrontendActions.h"
@@ -25,7 +23,6 @@
 #include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/iterator_range.h"
 #include "llvm/Config/llvm-config.h"
@@ -192,6 +189,49 @@
   llvm::sys::fs::remove(File);
 }
 
+// A temp file that would be deleted on destructor call. If destructor is not
+// called for any reason, the file will be deleted at static objects'
+// destruction.
+// An assertion will fire if two TempPCHFiles are created with the same name,
+// so it's not intended to be used outside preamble-handling.
+class TempPCHFile {
+public:
+  // A main method used to construct TempPCHFile.
+  static std::unique_ptr create() {
+// FIXME: This is a hack so that we can override the preamble file during
+// crash-recovery testing, which is the only case where the preamble files
+// are not necessarily cleaned up.
+if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
+  return std::unique_ptr(new TempPCHFile(TmpFile));
+
+llvm::SmallString<64> File;
+// Using a version of createTemporaryFile with a file descriptor guarantees
+// that we would never get a race condition in a multi-threaded setting
+// (i.e., multiple threads getting the same temporary path).
+int FD;
+if (auto EC =
+llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File))
+  return nullptr;
+// We only needed to make sure the file exists, close the file right away.
+llvm::sys::Process::SafelyCloseFileDescriptor(FD);
+return std::unique_ptr(new TempPCHFile(File.str().str()));
+  }
+
+  TempPCHFile &operator=(const TempPCHFile &) = delete;
+  TempPCHFile(const TempPCHFile &) = delete;
+  ~TempPCHFile() { TemporaryFiles::getInstance().removeFile(FilePath); };
+
+  /// A path where temporary file is stored.
+  llvm::StringRef getFilePath() const { return FilePath; };
+
+private:
+  TempPCHFile(std::string FilePath) : FilePath(std::move(FilePath)) {
+TemporaryFiles::getInstance().addFile(this->FilePath);
+  }
+
+  std::string FilePath;
+};
+
 class PrecompilePreambleAction : public ASTFrontendAction {
 public:
   PrecompilePreambleAction(std::string *InMemStorage,
@@ -308,6 +348,46 @@
   return Lexer::ComputePreamble(Buffer.getBuffer(), LangOpts, MaxLines);
 }
 
+class PrecompiledPreamble::PCHStorage {
+public:
+  static std::unique_ptr file(std::unique_ptr File) {
+assert(File);
+std::unique_ptr S(new PCHStorage());
+S->File = std::move(File);
+return S;
+  }
+  static std::unique_ptr inMemory() {
+std::unique_ptr S(new PCHStorage());
+S->Memory.emplace();
+return S;
+  }
+
+  enum class Kind { InMemory, TempFile };
+  Kind getKind() const {
+if (Memory)
+  return Kind::InMemory;
+if (File)
+  return Kind::TempFile;
+llvm_unreachable("Neither Memory nor File?");
+  }
+  llvm::StringRef filePath() const { return File->getFilePath(); }
+  llvm::StringRef memoryContents() const { return *Memory; }
+  std::string &memoryBufferForWrite() { return *Memory; }
+
+private:
+  PCHStorage() = default;
+  PCHStorage(const PCHStorage &) = delete;
+  PCHStorage &operator=(const PCHStorage &) = delete;
+
+  llvm::Optional Memory;
+  std::unique_ptr File;
+};
+
+PrecompiledPreamble::~PrecompiledPreamble() = default;
+PrecompiledPreamble::PrecompiledPreamble(PrecompiledPreamble &&) = default;
+PrecompiledPreamble &
+PrecompiledPreamble::operator=(PrecompiledPreamble &&) = default;
+
 llvm::ErrorO

[PATCH] D124177: [Frontend] Simplify PrecompiledPreamble::PCHStorage. NFC

2022-04-21 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz accepted this revision.
adamcz added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Frontend/PrecompiledPreamble.cpp:373
+  }
+  llvm::StringRef filePath() const { return File->getFilePath(); }
+  llvm::StringRef memoryContents() const { return *Memory; }

Maybe add asserts here and below to check that Kind is indeed File or Memory?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124177

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


[PATCH] D124170: [clangd] Include Cleaner: suppress unused warnings for IWYU pragma: export

2022-04-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 424205.
kbobyrev marked an inline comment as done.
kbobyrev added a comment.

Resolve comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124170

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -511,11 +511,13 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "exported.h" // IWYU pragma: export
 #include "public.h"
 
 void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["exported.h"] = guard("");
   TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
   TU.AdditionalFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "public.h"
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -17,11 +17,13 @@
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -129,15 +131,16 @@
   // 2. HandleComment("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // HandleComment will store the last location of "IWYU pragma: keep" comment
-  // in the main file, so that when InclusionDirective is called, it will know
-  // that the next inclusion is behind the IWYU pragma.
+  // HandleComment will store the last location of "IWYU pragma: keep" (or
+  // export) comment in the main file, so that when InclusionDirective is
+  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 if (!inMainFile() || Range.getBegin().isMacroID())
   return false;
 bool Err = false;
 llvm::StringRef Text = SM.getCharacterData(Range.getBegin(), &Err);
-if (Err || !Text.consume_front(IWYUPragmaKeep))
+if (Err && !Text.consume_front(IWYUPragmaKeep) &&
+!Text.consume_front(IWYUPragmaExport))
   return false;
 unsigned Offset = SM.getFileOffset(Range.getBegin());
 LastPragmaKeepInMainFileLine =


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -511,11 +511,13 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "exported.h" // IWYU pragma: export
 #include "public.h"
 
 void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["exported.h"] = guard("");
   TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
   TU.AdditionalFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "public.h"
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -17,11 +17,13 @@
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -129,15 +131,16 @@
   // 2. HandleComment("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // HandleComment will store the last location of "IWYU pragma: keep" comment
-  // in the main file, so that when InclusionDirective is called, it will know
-  // that the next inclusion is behind the IWYU pragma.
+  // HandleComment will store the last location of "IWYU pragma: keep" (or
+  // export) comment in the main file, so that when InclusionDirective is
+  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 if (!inMainFile() || Range.getBegin().isMacroID())
   return false;
 bool Err = false;
 llvm::StringRef Text = SM.getCharacterData(Range.getBegin(), &Err);
-if (E

[clang-tools-extra] 9f05b11 - [clangd] Include Cleaner: suppress unused warnings for IWYU pragma: export

2022-04-21 Thread Kirill Bobyrev via cfe-commits

Author: Kirill Bobyrev
Date: 2022-04-21T17:00:06+02:00
New Revision: 9f05b111ee1fc48974ed515c865bdaddb5998d01

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

LOG: [clangd] Include Cleaner: suppress unused warnings for IWYU pragma: export

Add limited support for "IWYU pragma: export" - for now it just supresses the
warning similar to "IWYU pragma: keep".

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/Headers.cpp
clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Headers.cpp 
b/clang-tools-extra/clangd/Headers.cpp
index 4ee58f3b3ab52..9484bb7afa15b 100644
--- a/clang-tools-extra/clangd/Headers.cpp
+++ b/clang-tools-extra/clangd/Headers.cpp
@@ -17,11 +17,13 @@
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -136,15 +138,16 @@ class IncludeStructure::RecordHeaders : public 
PPCallbacks,
   // 2. HandleComment("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // HandleComment will store the last location of "IWYU pragma: keep" comment
-  // in the main file, so that when InclusionDirective is called, it will know
-  // that the next inclusion is behind the IWYU pragma.
+  // HandleComment will store the last location of "IWYU pragma: keep" (or
+  // export) comment in the main file, so that when InclusionDirective is
+  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 if (!inMainFile() || Range.getBegin().isMacroID())
   return false;
 bool Err = false;
 llvm::StringRef Text = SM.getCharacterData(Range.getBegin(), &Err);
-if (Err || !Text.consume_front(IWYUPragmaKeep))
+if (Err && !Text.consume_front(IWYUPragmaKeep) &&
+!Text.consume_front(IWYUPragmaExport))
   return false;
 unsigned Offset = SM.getFileOffset(Range.getBegin());
 LastPragmaKeepInMainFileLine =

diff  --git a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp 
b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
index f28ffc5139f80..8df292cd28a94 100644
--- a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -511,11 +511,13 @@ TEST(IncludeCleaner, IWYUPragmas) {
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "exported.h" // IWYU pragma: export
 #include "public.h"
 
 void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["exported.h"] = guard("");
   TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
   TU.AdditionalFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "public.h"



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


[clang-tools-extra] e1c0d2f - [clangd] Correctly identify self-contained headers included rercursively

2022-04-21 Thread Kirill Bobyrev via cfe-commits

Author: Kirill Bobyrev
Date: 2022-04-21T16:54:59+02:00
New Revision: e1c0d2fb8272dd7f8e406334ac14077154217031

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

LOG: [clangd] Correctly identify self-contained headers included rercursively

Right now when exiting the file Headers.cpp will identify the recursive
inclusion (with a new FileID) as non self-contained and will add it to the set
from which it will never be removed. As a result, we get incorrect results in
the IncludeStructure and Include Cleaner. This patch is a fix.

Reviewed By: sammccall

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

Added: 


Modified: 
clang-tools-extra/clangd/Headers.cpp
clang-tools-extra/clangd/unittests/HeadersTests.cpp
clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Headers.cpp 
b/clang-tools-extra/clangd/Headers.cpp
index acc6421798755..4ee58f3b3ab52 100644
--- a/clang-tools-extra/clangd/Headers.cpp
+++ b/clang-tools-extra/clangd/Headers.cpp
@@ -106,10 +106,17 @@ class IncludeStructure::RecordHeaders : public 
PPCallbacks,
 InBuiltinFile = false;
   // At file exit time HeaderSearchInfo is valid and can be used to
   // determine whether the file was a self-contained header or not.
-  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID))
-if (!isSelfContainedHeader(FE, PrevFID, SM, HeaderInfo))
+  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID)) {
+// isSelfContainedHeader only returns true once the full header-guard
+// structure has been seen, i.e. when exiting the *outer* copy of the
+// file. So last result wins.
+if (isSelfContainedHeader(FE, PrevFID, SM, HeaderInfo))
+  Out->NonSelfContained.erase(
+  *Out->getID(SM.getFileEntryForID(PrevFID)));
+else
   Out->NonSelfContained.insert(
   *Out->getID(SM.getFileEntryForID(PrevFID)));
+  }
   break;
 }
 case PPCallbacks::RenameFile:

diff  --git a/clang-tools-extra/clangd/unittests/HeadersTests.cpp 
b/clang-tools-extra/clangd/unittests/HeadersTests.cpp
index c0cc3b69f3519..30bac23bc602c 100644
--- a/clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -383,6 +383,7 @@ TEST_F(HeadersTest, SelfContainedHeaders) {
 #include "nonguarded.h"
 #include "pp_depend.h"
 #include "pragmaguarded.h"
+#include "recursive.h"
 )cpp";
   FS.Files["pragmaguarded.h"] = R"cpp(
 #pragma once
@@ -400,10 +401,19 @@ void foo();
   # error You have to have PP directive set to include this one!
   #endif
 )cpp";
+  FS.Files["recursive.h"] = R"cpp(
+  #ifndef RECURSIVE_H
+  #define RECURSIVE_H
+
+  #include "recursive.h"
+  
+  #endif // RECURSIVE_H
+)cpp";
 
   auto Includes = collectIncludes();
   EXPECT_TRUE(Includes.isSelfContained(getID("pragmaguarded.h", Includes)));
   EXPECT_TRUE(Includes.isSelfContained(getID("includeguarded.h", Includes)));
+  EXPECT_TRUE(Includes.isSelfContained(getID("recursive.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("nonguarded.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("pp_depend.h", Includes)));
 }

diff  --git a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp 
b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
index 4a376a87297f9..f28ffc5139f80 100644
--- a/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ b/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -538,6 +538,38 @@ TEST(IncludeCleaner, IWYUPragmas) {
   EXPECT_THAT(Unused, IsEmpty());
 }
 
+TEST(IncludeCleaner, RecursiveInclusion) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+
+void baz() {
+  foo();
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+void foo() {}
+
+#include "bar.h"
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+#include "foo.h"
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  auto Unused = computeUnusedIncludes(AST);
+  EXPECT_THAT(Unused, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang



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


[PATCH] D124166: [clangd] Correctly identify self-contained headers included rercursively

2022-04-21 Thread Kirill Bobyrev via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe1c0d2fb8272: [clangd] Correctly identify self-contained 
headers included rercursively (authored by kbobyrev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124166

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/unittests/HeadersTests.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -538,6 +538,38 @@
   EXPECT_THAT(Unused, IsEmpty());
 }
 
+TEST(IncludeCleaner, RecursiveInclusion) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+
+void baz() {
+  foo();
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+void foo() {}
+
+#include "bar.h"
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+#include "foo.h"
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  auto Unused = computeUnusedIncludes(AST);
+  EXPECT_THAT(Unused, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/HeadersTests.cpp
===
--- clang-tools-extra/clangd/unittests/HeadersTests.cpp
+++ clang-tools-extra/clangd/unittests/HeadersTests.cpp
@@ -383,6 +383,7 @@
 #include "nonguarded.h"
 #include "pp_depend.h"
 #include "pragmaguarded.h"
+#include "recursive.h"
 )cpp";
   FS.Files["pragmaguarded.h"] = R"cpp(
 #pragma once
@@ -400,10 +401,19 @@
   # error You have to have PP directive set to include this one!
   #endif
 )cpp";
+  FS.Files["recursive.h"] = R"cpp(
+  #ifndef RECURSIVE_H
+  #define RECURSIVE_H
+
+  #include "recursive.h"
+  
+  #endif // RECURSIVE_H
+)cpp";
 
   auto Includes = collectIncludes();
   EXPECT_TRUE(Includes.isSelfContained(getID("pragmaguarded.h", Includes)));
   EXPECT_TRUE(Includes.isSelfContained(getID("includeguarded.h", Includes)));
+  EXPECT_TRUE(Includes.isSelfContained(getID("recursive.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("nonguarded.h", Includes)));
   EXPECT_FALSE(Includes.isSelfContained(getID("pp_depend.h", Includes)));
 }
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -106,10 +106,17 @@
 InBuiltinFile = false;
   // At file exit time HeaderSearchInfo is valid and can be used to
   // determine whether the file was a self-contained header or not.
-  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID))
-if (!isSelfContainedHeader(FE, PrevFID, SM, HeaderInfo))
+  if (const FileEntry *FE = SM.getFileEntryForID(PrevFID)) {
+// isSelfContainedHeader only returns true once the full header-guard
+// structure has been seen, i.e. when exiting the *outer* copy of the
+// file. So last result wins.
+if (isSelfContainedHeader(FE, PrevFID, SM, HeaderInfo))
+  Out->NonSelfContained.erase(
+  *Out->getID(SM.getFileEntryForID(PrevFID)));
+else
   Out->NonSelfContained.insert(
   *Out->getID(SM.getFileEntryForID(PrevFID)));
+  }
   break;
 }
 case PPCallbacks::RenameFile:


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -538,6 +538,38 @@
   EXPECT_THAT(Unused, IsEmpty());
 }
 
+TEST(IncludeCleaner, RecursiveInclusion) {
+  TestTU TU;
+  TU.Code = R"cpp(
+#include "foo.h"
+
+void baz() {
+  foo();
+}
+)cpp";
+  TU.AdditionalFiles["foo.h"] = R"cpp(
+#ifndef FOO_H
+#define FOO_H
+
+void foo() {}
+
+#include "bar.h"
+
+#endif
+  )cpp";
+  TU.AdditionalFiles["bar.h"] = guard(R"cpp(
+#include "foo.h"
+  )cpp");
+  ParsedAST AST = TU.build();
+
+  auto ReferencedFiles = findReferencedFiles(
+  findReferencedLocations(AST), AST.getIncludeStructure(),
+  AST.getCanonicalIncludes(), AST.getSourceManager());
+  EXPECT_THAT(AST.getDiagnostics(), llvm::ValueIs(IsEmpty()));
+  auto Unused = computeUnusedIncludes(AST);
+  EXPECT_THAT(Unused, IsEmpty());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/cla

[PATCH] D124170: [clangd] Include Cleaner: suppress unused warnings for IWYU pragma: export

2022-04-21 Thread Kirill Bobyrev 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 rG9f05b111ee1f: [clangd] Include Cleaner: suppress unused 
warnings for IWYU pragma: export (authored by kbobyrev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124170

Files:
  clang-tools-extra/clangd/Headers.cpp
  clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -511,11 +511,13 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "exported.h" // IWYU pragma: export
 #include "public.h"
 
 void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["exported.h"] = guard("");
   TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
   TU.AdditionalFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "public.h"
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -17,11 +17,13 @@
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -136,15 +138,16 @@
   // 2. HandleComment("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // HandleComment will store the last location of "IWYU pragma: keep" comment
-  // in the main file, so that when InclusionDirective is called, it will know
-  // that the next inclusion is behind the IWYU pragma.
+  // HandleComment will store the last location of "IWYU pragma: keep" (or
+  // export) comment in the main file, so that when InclusionDirective is
+  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 if (!inMainFile() || Range.getBegin().isMacroID())
   return false;
 bool Err = false;
 llvm::StringRef Text = SM.getCharacterData(Range.getBegin(), &Err);
-if (Err || !Text.consume_front(IWYUPragmaKeep))
+if (Err && !Text.consume_front(IWYUPragmaKeep) &&
+!Text.consume_front(IWYUPragmaExport))
   return false;
 unsigned Offset = SM.getFileOffset(Range.getBegin());
 LastPragmaKeepInMainFileLine =


Index: clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
===
--- clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
+++ clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp
@@ -511,11 +511,13 @@
   TestTU TU;
   TU.Code = R"cpp(
 #include "behind_keep.h" // IWYU pragma: keep
+#include "exported.h" // IWYU pragma: export
 #include "public.h"
 
 void bar() { foo(); }
 )cpp";
   TU.AdditionalFiles["behind_keep.h"] = guard("");
+  TU.AdditionalFiles["exported.h"] = guard("");
   TU.AdditionalFiles["public.h"] = guard("#include \"private.h\"");
   TU.AdditionalFiles["private.h"] = guard(R"cpp(
 // IWYU pragma: private, include "public.h"
Index: clang-tools-extra/clangd/Headers.cpp
===
--- clang-tools-extra/clangd/Headers.cpp
+++ clang-tools-extra/clangd/Headers.cpp
@@ -17,11 +17,13 @@
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Path.h"
+#include 
 
 namespace clang {
 namespace clangd {
 
 const char IWYUPragmaKeep[] = "// IWYU pragma: keep";
+const char IWYUPragmaExport[] = "// IWYU pragma: export";
 
 class IncludeStructure::RecordHeaders : public PPCallbacks,
 public CommentHandler {
@@ -136,15 +138,16 @@
   // 2. HandleComment("// IWYU pragma: keep")
   // 3. InclusionDirective("bar.h")
   //
-  // HandleComment will store the last location of "IWYU pragma: keep" comment
-  // in the main file, so that when InclusionDirective is called, it will know
-  // that the next inclusion is behind the IWYU pragma.
+  // HandleComment will store the last location of "IWYU pragma: keep" (or
+  // export) comment in the main file, so that when InclusionDirective is
+  // called, it will know that the next inclusion is behind the IWYU pragma.
   bool HandleComment(Preprocessor &PP, SourceRange Range) override {
 if (!inMainFile() || Range.getBegin().isMacroID())

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

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

In D122008#3462665 , @klausler wrote:

> New comments or not, this step remains premature from my perspective.

Let me make `-flang-experimental-exec` a "hidden" option then. This way this 
flag (and the functionality that it enables) will be less discoverable (we 
still will be to use it). We will be removing it at some point anyway.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122008

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


[PATCH] D124176: [clangd] Add beforeExecute() callback to FeatureModules.

2022-04-21 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, lgtm!




Comment at: clang-tools-extra/clangd/FeatureModule.h:109
 
+// Called before the preamble build. Allows modules to modify the
+// CompilerInvocation, prefetch required files, etc.

nit: triple slashes



Comment at: clang-tools-extra/clangd/FeatureModule.h:109
 
+// Called before the preamble build. Allows modules to modify the
+// CompilerInvocation, prefetch required files, etc.

kadircet wrote:
> nit: triple slashes
comment still says `preamble build`. I'd either talk more about `Allows 
customizing the compiler instance before starting the execution on input` or 
get rid of `CompilerInvocation` in that list. as in theory modifications to 
only parts of it will be respected (since we've already issued beginsourcefile 
on compiler instance and created some structs with whatever we had in compiler 
invocation prior to this call).



Comment at: clang-tools-extra/clangd/ParsedAST.cpp:553
 
+  for (const auto &L : ASTListeners)
+L->beforeExecute(*Clang);

could you have a comment that says we must perform this after 
`Action::BeginSourceFile` to ensure PP and rest of the helper structs are 
initialized and closer to the end so that other modifications we do in clangd 
(like adjusting diag severities/marking main file as include-guarded) is 
visible to modules?

to make sure it doesn't get moved around without these in mind.



Comment at: clang-tools-extra/clangd/Preamble.cpp:72
+  : File(File), ParsedCallback(ParsedCallback), Stats(Stats),
+BeforeExecuteCallback(BeforeExecuteCallback) {}
 

nit: std::move



Comment at: clang-tools-extra/clangd/Preamble.cpp:117
   void BeforeExecute(CompilerInstance &CI) override {
+if (BeforeExecuteCallback)
+  BeforeExecuteCallback(CI);

could we move this to the bottom, to make it closer to the way parsedast calls 
it?



Comment at: clang-tools-extra/clangd/Preamble.cpp:488
+[&ASTListeners](CompilerInstance &CI) {
+  for (const auto &L : ASTListeners) {
+L->beforeExecute(CI);

nit: drop braces


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124176

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


[clang] f80e369 - [PS4] Driver: use correct --shared option

2022-04-21 Thread Paul Robinson via cfe-commits

Author: Paul Robinson
Date: 2022-04-21T08:19:42-07:00
New Revision: f80e369f61ebd33dd9377bb42fcab64d17072b18

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

LOG: [PS4] Driver: use correct --shared option

Added: 


Modified: 
clang/lib/Driver/ToolChains/PS4CPU.cpp
clang/test/Driver/ps4-ps5-linker-non-win.c
clang/test/Driver/ps4-ps5-linker-win.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/PS4CPU.cpp 
b/clang/lib/Driver/ToolChains/PS4CPU.cpp
index 55a8d4dbc24b4..35a83d79abfd1 100644
--- a/clang/lib/Driver/ToolChains/PS4CPU.cpp
+++ b/clang/lib/Driver/ToolChains/PS4CPU.cpp
@@ -143,7 +143,7 @@ void tools::PScpu::Linker::ConstructJob(Compilation &C, 
const JobAction &JA,
   if (Args.hasArg(options::OPT_rdynamic))
 CmdArgs.push_back("-export-dynamic");
   if (Args.hasArg(options::OPT_shared))
-CmdArgs.push_back("--oformat=so");
+CmdArgs.push_back("--shared");
 
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");

diff  --git a/clang/test/Driver/ps4-ps5-linker-non-win.c 
b/clang/test/Driver/ps4-ps5-linker-non-win.c
index cd7cd8e11ea07..b9686b88a7573 100644
--- a/clang/test/Driver/ps4-ps5-linker-non-win.c
+++ b/clang/test/Driver/ps4-ps5-linker-non-win.c
@@ -13,14 +13,15 @@
 // RUN: env "PATH=%t:%PATH%" %clang -### -target x86_64-scei-ps4  %s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PS4-LINKER %s
 // RUN: env "PATH=%t:%PATH%" %clang -### -target x86_64-scei-ps4  %s -shared 
2>&1 \
-// RUN:   | FileCheck --check-prefix=CHECK-PS4-LINKER %s
+// RUN:   | FileCheck --check-prefixes=CHECK-PS4-LINKER,SHARED %s
 // RUN: env "PATH=%t:%PATH%" %clang -### -target x86_64-sie-ps5  %s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PS5-LINKER %s
 // RUN: env "PATH=%t:%PATH%" %clang -### -target x86_64-sie-ps5  %s -shared 
2>&1 \
-// RUN:   | FileCheck --check-prefix=CHECK-PS5-LINKER %s
+// RUN:   | FileCheck --check-prefixes=CHECK-PS5-LINKER,SHARED %s
 
 // CHECK-PS4-LINKER: /orbis-ld
 // CHECK-PS5-LINKER: /prospero-lld
+// SHARED: "--shared"
 
 // RUN: env "PATH=%t:%PATH%" %clang -### -target x86_64-scei-ps4 %s 
-fuse-ld=gold 2>&1 \
 // RUN:   | FileCheck --check-prefix=ERROR %s

diff  --git a/clang/test/Driver/ps4-ps5-linker-win.c 
b/clang/test/Driver/ps4-ps5-linker-win.c
index ca4084d4fccff..acff2c0f1f24c 100644
--- a/clang/test/Driver/ps4-ps5-linker-win.c
+++ b/clang/test/Driver/ps4-ps5-linker-win.c
@@ -10,14 +10,15 @@
 // RUN: env "PATH=%t;%PATH%;" %clang -target x86_64-scei-ps4  %s -### 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PS4-LINKER %s
 // RUN: env "PATH=%t;%PATH%;" %clang -target x86_64-scei-ps4  %s -shared -### 
2>&1 \
-// RUN:   | FileCheck --check-prefix=CHECK-PS4-LINKER %s
+// RUN:   | FileCheck --check-prefixes=CHECK-PS4-LINKER,SHARED %s
 // RUN: env "PATH=%t;%PATH%;" %clang -target x86_64-sie-ps5  %s -### 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PS5-LINKER %s
 // RUN: env "PATH=%t;%PATH%;" %clang -target x86_64-sie-ps5  %s -shared -### 
2>&1 \
-// RUN:   | FileCheck --check-prefix=CHECK-PS5-LINKER %s
+// RUN:   | FileCheck --check-prefixes=CHECK-PS5-LINKER,SHARED %s
 
 // CHECK-PS4-LINKER: \\orbis-ld
 // CHECK-PS5-LINKER: \\prospero-lld
+// SHARED: "--shared"
 
 // RUN: env "PATH=%t;%PATH%;" %clang -target x86_64-scei-ps4 %s -fuse-ld=gold 
-### 2>&1 \
 // RUN:   | FileCheck --check-prefix=ERROR %s



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


[PATCH] D121868: [cc1as] Add support for emitting the build version load command for -darwin-target-variant

2022-04-21 Thread Byoungchan Lee via Phabricator via cfe-commits
bc-lee updated this revision to Diff 424209.
bc-lee added a comment.

Add `REQUIRES: x86-registered-target` on the test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121868

Files:
  clang/include/clang/Driver/Options.td
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/Darwin.h
  clang/test/Misc/cc1as-darwin-target-variant-triple.s
  clang/tools/driver/cc1as_main.cpp

Index: clang/tools/driver/cc1as_main.cpp
===
--- clang/tools/driver/cc1as_main.cpp
+++ clang/tools/driver/cc1as_main.cpp
@@ -144,6 +144,9 @@
   /// otherwise.
   std::string TargetABI;
 
+  /// Darwin target variant triple, the variant of the deployment target
+  /// for which the code is being compiled.
+  llvm::Optional DarwinTargetVariantTriple;
   /// @}
 
 public:
@@ -209,6 +212,9 @@
 
   // Target Options
   Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
+  if (Arg *A = Args.getLastArg(options::OPT_darwin_target_variant_triple))
+Opts.DarwinTargetVariantTriple = llvm::Triple(A->getValue());
+
   Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));
   Opts.Features = Args.getAllArgValues(OPT_target_feature);
 
@@ -407,6 +413,8 @@
   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
   std::unique_ptr MOFI(
   TheTarget->createMCObjectFileInfo(Ctx, PIC));
+  if (Opts.DarwinTargetVariantTriple)
+MOFI->setDarwinTargetVariantTriple(*Opts.DarwinTargetVariantTriple);
   Ctx.setObjectFileInfo(MOFI.get());
 
   if (Opts.SaveTemporaryLabels)
Index: clang/test/Misc/cc1as-darwin-target-variant-triple.s
===
--- /dev/null
+++ clang/test/Misc/cc1as-darwin-target-variant-triple.s
@@ -0,0 +1,34 @@
+// Run cc1as using darwin-target-variant-triple
+// REQUIRES: x86-registered-target
+// RUN: %clang -cc1as -triple x86_64-apple-macos10.9 -darwin-target-variant-triple x86_64-apple-ios13.1-macabi -filetype obj %s -o - \
+// RUN: | llvm-readobj --file-headers --macho-version-min - \
+// RUN: | FileCheck --check-prefix=CHECK %s
+
+// CHECK: File: 
+// CHECK-NEXT: Format: Mach-O 64-bit x86-64
+// CHECK-NEXT: Arch: x86_64
+// CHECK-NEXT: AddressSize: 64bit
+// CHECK-NEXT: MachHeader {
+// CHECK-NEXT:   Magic: Magic64 (0xFEEDFACF)
+// CHECK-NEXT:   CpuType: X86-64 (0x107)
+// CHECK-NEXT:   CpuSubType: CPU_SUBTYPE_X86_64_ALL (0x3)
+// CHECK-NEXT:   FileType: Relocatable (0x1)
+// CHECK-NEXT:   NumOfLoadCommands: 3
+// CHECK-NEXT:   SizeOfLoadCommands: 192
+// CHECK-NEXT:   Flags [ (0x0)
+// CHECK-NEXT:   ]
+// CHECK-NEXT:   Reserved: 0x0
+// CHECK-NEXT: }
+// CHECK-NEXT: MinVersion {
+// CHECK-NEXT:   Cmd: LC_VERSION_MIN_MACOSX
+// CHECK-NEXT:   Size: 16
+// CHECK-NEXT:   Version: 10.9
+// CHECK-NEXT:   SDK: n/a
+// CHECK-NEXT: }
+// CHECK-NEXT: MinVersion {
+// CHECK-NEXT:   Cmd: LC_BUILD_VERSION
+// CHECK-NEXT:   Size: 24
+// CHECK-NEXT:   Platform: macCatalyst
+// CHECK-NEXT:   Version: 13.1
+// CHECK-NEXT:   SDK: n/a
+// CHECK-NEXT: }
Index: clang/lib/Driver/ToolChains/Darwin.h
===
--- clang/lib/Driver/ToolChains/Darwin.h
+++ clang/lib/Driver/ToolChains/Darwin.h
@@ -489,6 +489,12 @@
 : TargetVersion) < VersionTuple(V0, V1, V2);
   }
 
+  /// Returns the darwin target variant triple, the variant of the deployment
+  /// target for which the code is being compiled.
+  Optional getTargetVariantTriple() const override {
+return TargetVariantTriple;
+  }
+
 protected:
   /// Return true if c++17 aligned allocation/deallocation functions are not
   /// implemented in the c++ standard library of the deployment target we are
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -7719,6 +7719,8 @@
 
   const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
   const std::string &TripleStr = Triple.getTriple();
+  const Optional TargetVariantTriple =
+  getToolChain().getTargetVariantTriple();
   const auto &D = getToolChain().getDriver();
 
   // Don't warn about "clang -w -c foo.s"
@@ -7736,6 +7738,10 @@
   // Add the "effective" target triple.
   CmdArgs.push_back("-triple");
   CmdArgs.push_back(Args.MakeArgString(TripleStr));
+  if (TargetVariantTriple) {
+CmdArgs.push_back("-darwin-target-variant-triple");
+CmdArgs.push_back(Args.MakeArgString(TargetVariantTriple->getTriple()));
+  }
 
   // Set the output mode, we currently only expect to be used as a real
   // assembler.
Index: clang/include/clang/Driver/ToolChain.h
===
--- clang/include/clang/Driver/ToolChain.h
+++ clang/include/clang/Driver/ToolCha

[PATCH] D121868: [cc1as] Add support for emitting the build version load command for -darwin-target-variant

2022-04-21 Thread Byoungchan Lee via Phabricator via cfe-commits
bc-lee added inline comments.



Comment at: clang/test/Misc/cc1as-darwin-target-variant-triple.s:2
+// Run cc1as using darwin-target-variant-triple
+// RUN: %clang -cc1as -triple x86_64-apple-macos10.9 
-darwin-target-variant-triple x86_64-apple-ios13.1-macabi -filetype obj %s -o - 
\
+// RUN: | llvm-readobj --file-headers --macho-version-min - \

thakis wrote:
> bc-lee wrote:
> > MaskRay wrote:
> > > `-filetype obj` on the `%clang -cc1as` line seems weird.
> > Without this, I cannot create object file and validate it using 
> > `llvm-readobj`.
> If you use `emit-obj` I think this test needs a `REQUIRES: 
> x86-registered-target`.
> 
> I'm not sure if piping binary data works on Windows – it might have stdout in 
> text mode, which will do some byte replacements.
A search for `-o -.*\n.*RUN.*llvm-readobj` in the LLVM codebase suggests that 
there are already several tests using that pattern. Does that really matter?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D121868

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


[PATCH] D124176: [clangd] Add beforeExecute() callback to FeatureModules.

2022-04-21 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz updated this revision to Diff 424215.
adamcz marked 5 inline comments as done.
adamcz added a comment.

addressed review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124176

Files:
  clang-tools-extra/clangd/FeatureModule.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp

Index: clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
===
--- clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
+++ clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
@@ -12,6 +12,7 @@
 #include "TestTU.h"
 #include "refactor/Tweak.h"
 #include "support/Logger.h"
+#include "clang/Lex/PreprocessorOptions.h"
 #include "llvm/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -85,6 +86,41 @@
   }
 }
 
+TEST(FeatureModulesTest, BeforeExecute) {
+  struct BeforeExecuteModule final : public FeatureModule {
+struct Listener : public FeatureModule::ASTListener {
+  void beforeExecute(CompilerInstance &CI) override {
+CI.getPreprocessor().SetSuppressIncludeNotFoundError(true);
+  }
+};
+std::unique_ptr astListeners() override {
+  return std::make_unique();
+};
+  };
+  FeatureModuleSet FMS;
+  FMS.add(std::make_unique());
+
+  TestTU TU = TestTU::withCode(R"cpp(
+/*error-ok*/
+#include "not_found.h"
+
+void foo() {
+  #include "not_found_not_preamble.h"
+}
+  )cpp");
+
+  {
+auto AST = TU.build();
+EXPECT_THAT(*AST.getDiagnostics(), testing::Not(testing::IsEmpty()));
+  }
+
+  TU.FeatureModules = &FMS;
+  {
+auto AST = TU.build();
+EXPECT_THAT(*AST.getDiagnostics(), testing::IsEmpty());
+  }
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -64,9 +64,12 @@
 
 class CppFilePreambleCallbacks : public PreambleCallbacks {
 public:
-  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback,
-   PreambleBuildStats *Stats)
-  : File(File), ParsedCallback(ParsedCallback), Stats(Stats) {}
+  CppFilePreambleCallbacks(
+  PathRef File, PreambleParsedCallback ParsedCallback,
+  PreambleBuildStats *Stats,
+  std::function BeforeExecuteCallback)
+  : File(File), ParsedCallback(ParsedCallback), Stats(Stats),
+BeforeExecuteCallback(std::move(BeforeExecuteCallback)) {}
 
   IncludeStructure takeIncludes() { return std::move(Includes); }
 
@@ -115,6 +118,8 @@
 LangOpts = &CI.getLangOpts();
 SourceMgr = &CI.getSourceManager();
 Includes.collect(CI);
+if (BeforeExecuteCallback)
+  BeforeExecuteCallback(CI);
   }
 
   std::unique_ptr createPPCallbacks() override {
@@ -156,6 +161,7 @@
   const clang::LangOptions *LangOpts = nullptr;
   const SourceManager *SourceMgr = nullptr;
   PreambleBuildStats *Stats;
+  std::function BeforeExecuteCallback;
 };
 
 // Represents directives other than includes, where basic textual information is
@@ -477,7 +483,11 @@
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats);
+  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats,
+[&ASTListeners](CompilerInstance &CI) {
+  for (const auto &L : ASTListeners)
+L->beforeExecute(CI);
+});
   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
   llvm::SmallString<32> AbsFileName(FileName);
   VFS->makeAbsolute(AbsFileName);
@@ -716,5 +726,6 @@
   }
   return Loc;
 }
+
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -550,6 +550,12 @@
   // Collect tokens of the main file.
   syntax::TokenCollector CollectTokens(Clang->getPreprocessor());
 
+  // To remain consistent with preamble builds, these callbacks must be called
+  // exactly here, after preprocessor is initialized and BeginSourceFile() was
+  // called already.
+  for (const auto &L : ASTListeners)
+L->beforeExecute(*Clang);
+
   if (llvm::Error Err = Action->Execute())
 log("Execute() failed when building AST for {0}: {1}", MainInput.getFile(),
 toString(std::move(Err)));
Index: clang-tools-extra/clangd/FeatureModule.h
===
--- clang-tools

[PATCH] D124180: [Frontend] avoid copy of PCH data when PrecompiledPreamble stores it in memory

2022-04-21 Thread Sam McCall via Phabricator via cfe-commits
sammccall created this revision.
sammccall added a reviewer: adamcz.
Herald added a project: All.
sammccall requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Instead of unconditionally copying the PCHBuffer into an ostream which can be
backed either by a string or a file, just make the PCHBuffer itself the
in-memory storage.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D124180

Files:
  clang/lib/Frontend/PrecompiledPreamble.cpp

Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -234,9 +234,10 @@
 
 class PrecompilePreambleAction : public ASTFrontendAction {
 public:
-  PrecompilePreambleAction(std::string *InMemStorage,
+  PrecompilePreambleAction(std::shared_ptr Buffer, bool WritePCHFile,
PreambleCallbacks &Callbacks)
-  : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
+  : Buffer(std::move(Buffer)), WritePCHFile(WritePCHFile),
+Callbacks(Callbacks) {}
 
   std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
  StringRef InFile) override;
@@ -244,6 +245,12 @@
   bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
 
   void setEmittedPreamblePCH(ASTWriter &Writer) {
+if (FileOS) {
+  *FileOS << Buffer->Data;
+  // Make sure it hits disk now.
+  FileOS->flush();
+}
+
 this->HasEmittedPreamblePCH = true;
 Callbacks.AfterPCHEmitted(Writer);
   }
@@ -262,7 +269,9 @@
   friend class PrecompilePreambleConsumer;
 
   bool HasEmittedPreamblePCH = false;
-  std::string *InMemStorage;
+  std::shared_ptr Buffer;
+  bool WritePCHFile; // otherwise the PCH is written into the PCHBuffer only.
+  std::unique_ptr FileOS; // null if in-memory
   PreambleCallbacks &Callbacks;
 };
 
@@ -272,12 +281,11 @@
  const Preprocessor &PP,
  InMemoryModuleCache &ModuleCache,
  StringRef isysroot,
- std::unique_ptr Out)
-  : PCHGenerator(PP, ModuleCache, "", isysroot,
- std::make_shared(),
+ std::shared_ptr Buffer)
+  : PCHGenerator(PP, ModuleCache, "", isysroot, std::move(Buffer),
  ArrayRef>(),
  /*AllowASTWithErrors=*/true),
-Action(Action), Out(std::move(Out)) {}
+Action(Action) {}
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 Action.Callbacks.HandleTopLevelDecl(DG);
@@ -288,15 +296,6 @@
 PCHGenerator::HandleTranslationUnit(Ctx);
 if (!hasEmittedPCH())
   return;
-
-// Write the generated bitstream to "Out".
-*Out << getPCH();
-// Make sure it hits disk now.
-Out->flush();
-// Free the buffer.
-llvm::SmallVector Empty;
-getPCH() = std::move(Empty);
-
 Action.setEmittedPreamblePCH(getWriter());
   }
 
@@ -306,7 +305,6 @@
 
 private:
   PrecompilePreambleAction &Action;
-  std::unique_ptr Out;
 };
 
 std::unique_ptr
@@ -316,21 +314,18 @@
   if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
 return nullptr;
 
-  std::unique_ptr OS;
-  if (InMemStorage) {
-OS = std::make_unique(*InMemStorage);
-  } else {
-std::string OutputFile;
-OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
+  if (WritePCHFile) {
+std::string OutputFile; // unused
+FileOS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
+if (!FileOS)
+  return nullptr;
   }
-  if (!OS)
-return nullptr;
 
   if (!CI.getFrontendOpts().RelocatablePCH)
 Sysroot.clear();
 
   return std::make_unique(
-  *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
+  *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, Buffer);
 }
 
 template  bool moveOnNoError(llvm::ErrorOr Val, T &Output) {
@@ -356,9 +351,9 @@
 S->File = std::move(File);
 return S;
   }
-  static std::unique_ptr inMemory() {
+  static std::unique_ptr inMemory(std::shared_ptr Buf) {
 std::unique_ptr S(new PCHStorage());
-S->Memory.emplace();
+S->Memory = std::move(Buf);
 return S;
   }
 
@@ -371,15 +366,16 @@
 llvm_unreachable("Neither Memory nor File?");
   }
   llvm::StringRef filePath() const { return File->getFilePath(); }
-  llvm::StringRef memoryContents() const { return *Memory; }
-  std::string &memoryBufferForWrite() { return *Memory; }
+  llvm::StringRef memoryContents() const {
+return StringRef(Memory->Data.data(), Memory->Data.size());
+  }
 
 private:
   PCHStorage() = default;
   PCHStorage(const PCHStorage &) = delete;
   PCHStorage &operator=(const PCHStorage &) = delete;
 
-  llvm::Optional Memory;
+  std::shared_ptr Memory;
   std::unique_ptr File;
 };
 
@@ -402,9 +398,10 @@
   PreprocessorOptio

[PATCH] D124176: [clangd] Add beforeExecute() callback to FeatureModules.

2022-04-21 Thread Adam Czachorowski 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 rGad46aaede6e4: [clangd] Add beforeExecute() callback to 
FeatureModules. (authored by adamcz).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124176

Files:
  clang-tools-extra/clangd/FeatureModule.h
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/Preamble.cpp
  clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp

Index: clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
===
--- clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
+++ clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp
@@ -12,6 +12,7 @@
 #include "TestTU.h"
 #include "refactor/Tweak.h"
 #include "support/Logger.h"
+#include "clang/Lex/PreprocessorOptions.h"
 #include "llvm/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
@@ -85,6 +86,41 @@
   }
 }
 
+TEST(FeatureModulesTest, BeforeExecute) {
+  struct BeforeExecuteModule final : public FeatureModule {
+struct Listener : public FeatureModule::ASTListener {
+  void beforeExecute(CompilerInstance &CI) override {
+CI.getPreprocessor().SetSuppressIncludeNotFoundError(true);
+  }
+};
+std::unique_ptr astListeners() override {
+  return std::make_unique();
+};
+  };
+  FeatureModuleSet FMS;
+  FMS.add(std::make_unique());
+
+  TestTU TU = TestTU::withCode(R"cpp(
+/*error-ok*/
+#include "not_found.h"
+
+void foo() {
+  #include "not_found_not_preamble.h"
+}
+  )cpp");
+
+  {
+auto AST = TU.build();
+EXPECT_THAT(*AST.getDiagnostics(), testing::Not(testing::IsEmpty()));
+  }
+
+  TU.FeatureModules = &FMS;
+  {
+auto AST = TU.build();
+EXPECT_THAT(*AST.getDiagnostics(), testing::IsEmpty());
+  }
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/Preamble.cpp
===
--- clang-tools-extra/clangd/Preamble.cpp
+++ clang-tools-extra/clangd/Preamble.cpp
@@ -64,9 +64,12 @@
 
 class CppFilePreambleCallbacks : public PreambleCallbacks {
 public:
-  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback,
-   PreambleBuildStats *Stats)
-  : File(File), ParsedCallback(ParsedCallback), Stats(Stats) {}
+  CppFilePreambleCallbacks(
+  PathRef File, PreambleParsedCallback ParsedCallback,
+  PreambleBuildStats *Stats,
+  std::function BeforeExecuteCallback)
+  : File(File), ParsedCallback(ParsedCallback), Stats(Stats),
+BeforeExecuteCallback(std::move(BeforeExecuteCallback)) {}
 
   IncludeStructure takeIncludes() { return std::move(Includes); }
 
@@ -115,6 +118,8 @@
 LangOpts = &CI.getLangOpts();
 SourceMgr = &CI.getSourceManager();
 Includes.collect(CI);
+if (BeforeExecuteCallback)
+  BeforeExecuteCallback(CI);
   }
 
   std::unique_ptr createPPCallbacks() override {
@@ -156,6 +161,7 @@
   const clang::LangOptions *LangOpts = nullptr;
   const SourceManager *SourceMgr = nullptr;
   PreambleBuildStats *Stats;
+  std::function BeforeExecuteCallback;
 };
 
 // Represents directives other than includes, where basic textual information is
@@ -477,7 +483,11 @@
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats);
+  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats,
+[&ASTListeners](CompilerInstance &CI) {
+  for (const auto &L : ASTListeners)
+L->beforeExecute(CI);
+});
   auto VFS = Inputs.TFS->view(Inputs.CompileCommand.Directory);
   llvm::SmallString<32> AbsFileName(FileName);
   VFS->makeAbsolute(AbsFileName);
@@ -716,5 +726,6 @@
   }
   return Loc;
 }
+
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/ParsedAST.cpp
===
--- clang-tools-extra/clangd/ParsedAST.cpp
+++ clang-tools-extra/clangd/ParsedAST.cpp
@@ -550,6 +550,12 @@
   // Collect tokens of the main file.
   syntax::TokenCollector CollectTokens(Clang->getPreprocessor());
 
+  // To remain consistent with preamble builds, these callbacks must be called
+  // exactly here, after preprocessor is initialized and BeginSourceFile() was
+  // called already.
+  for (const auto &L : ASTListeners)
+L->beforeExecute(*Clang);
+
   if (llvm::Error Err = Action->Execute())
 log("Execute() failed when building AST for {0}: {1}", MainInput.getFile(),
 toString(std::move(Err)));
Index: clang-tools-extra/c

[clang-tools-extra] ad46aae - [clangd] Add beforeExecute() callback to FeatureModules.

2022-04-21 Thread Adam Czachorowski via cfe-commits

Author: Adam Czachorowski
Date: 2022-04-21T18:03:39+02:00
New Revision: ad46aaede6e4d5a6951fc9827da994d3fbe1af44

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

LOG: [clangd] Add beforeExecute() callback to FeatureModules.

It runs immediatelly before FrontendAction::Execute() with a mutable
CompilerInstance, allowing FeatureModules to register callbacks, remap
files, etc.

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

Added: 


Modified: 
clang-tools-extra/clangd/FeatureModule.h
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/Preamble.cpp
clang-tools-extra/clangd/unittests/FeatureModulesTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/FeatureModule.h 
b/clang-tools-extra/clangd/FeatureModule.h
index 8f07b18412671..43007a297469b 100644
--- a/clang-tools-extra/clangd/FeatureModule.h
+++ b/clang-tools-extra/clangd/FeatureModule.h
@@ -20,6 +20,7 @@
 #include 
 
 namespace clang {
+class CompilerInstance;
 namespace clangd {
 struct Diag;
 class LSPBinder;
@@ -105,6 +106,11 @@ class FeatureModule {
 /// Listeners are destroyed once the AST is built.
 virtual ~ASTListener() = default;
 
+/// Called before every AST build, both for main file and preamble. The 
call
+/// happens immediately before FrontendAction::Execute(), with Preprocessor
+/// set up already and after BeginSourceFile() on main file was called.
+virtual void beforeExecute(CompilerInstance &CI) {}
+
 /// Called everytime a diagnostic is encountered. Modules can use this
 /// modify the final diagnostic, or store some information to surface code
 /// actions later on.

diff  --git a/clang-tools-extra/clangd/ParsedAST.cpp 
b/clang-tools-extra/clangd/ParsedAST.cpp
index ef744d1f893b0..235362b5d599c 100644
--- a/clang-tools-extra/clangd/ParsedAST.cpp
+++ b/clang-tools-extra/clangd/ParsedAST.cpp
@@ -550,6 +550,12 @@ ParsedAST::build(llvm::StringRef Filename, const 
ParseInputs &Inputs,
   // Collect tokens of the main file.
   syntax::TokenCollector CollectTokens(Clang->getPreprocessor());
 
+  // To remain consistent with preamble builds, these callbacks must be called
+  // exactly here, after preprocessor is initialized and BeginSourceFile() was
+  // called already.
+  for (const auto &L : ASTListeners)
+L->beforeExecute(*Clang);
+
   if (llvm::Error Err = Action->Execute())
 log("Execute() failed when building AST for {0}: {1}", MainInput.getFile(),
 toString(std::move(Err)));

diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index 0cc5b65a94d64..5ecd6f3a0bdf1 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -64,9 +64,12 @@ bool compileCommandsAreEqual(const tooling::CompileCommand 
&LHS,
 
 class CppFilePreambleCallbacks : public PreambleCallbacks {
 public:
-  CppFilePreambleCallbacks(PathRef File, PreambleParsedCallback ParsedCallback,
-   PreambleBuildStats *Stats)
-  : File(File), ParsedCallback(ParsedCallback), Stats(Stats) {}
+  CppFilePreambleCallbacks(
+  PathRef File, PreambleParsedCallback ParsedCallback,
+  PreambleBuildStats *Stats,
+  std::function BeforeExecuteCallback)
+  : File(File), ParsedCallback(ParsedCallback), Stats(Stats),
+BeforeExecuteCallback(std::move(BeforeExecuteCallback)) {}
 
   IncludeStructure takeIncludes() { return std::move(Includes); }
 
@@ -115,6 +118,8 @@ class CppFilePreambleCallbacks : public PreambleCallbacks {
 LangOpts = &CI.getLangOpts();
 SourceMgr = &CI.getSourceManager();
 Includes.collect(CI);
+if (BeforeExecuteCallback)
+  BeforeExecuteCallback(CI);
   }
 
   std::unique_ptr createPPCallbacks() override {
@@ -156,6 +161,7 @@ class CppFilePreambleCallbacks : public PreambleCallbacks {
   const clang::LangOptions *LangOpts = nullptr;
   const SourceManager *SourceMgr = nullptr;
   PreambleBuildStats *Stats;
+  std::function BeforeExecuteCallback;
 };
 
 // Represents directives other than includes, where basic textual information 
is
@@ -477,7 +483,11 @@ buildPreamble(PathRef FileName, CompilerInvocation CI,
   // to read back. We rely on dynamic index for the comments instead.
   CI.getPreprocessorOpts().WriteCommentListToPCH = false;
 
-  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats);
+  CppFilePreambleCallbacks CapturedInfo(FileName, PreambleCallback, Stats,
+[&ASTListeners](CompilerInstance &CI) {
+  for (const auto &L : ASTListeners)
+L->beforeExecute(CI);
+});
   auto VFS = Inputs.TFS->view(Inputs.CompileCom

[clang] af3fb07 - [Frontend] Simplify PrecompiledPreamble::PCHStorage. NFC

2022-04-21 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-04-21T18:10:13+02:00
New Revision: af3fb071545918f2de61142fa12d8782e5a37fa5

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

LOG: [Frontend] Simplify PrecompiledPreamble::PCHStorage. NFC

- Remove fiddly union, preambles are heavyweight
- Remove fiddly move constructors in TempPCHFile and PCHStorage, use unique_ptr
- Remove unneccesary accessors on PCHStorage
- Remove trivial InMemoryStorage
- Move implementation details into cpp file

This is a prefactoring, followup change will change the in-memory PCHStorage to
avoid extra string copies while creating it.

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

Added: 


Modified: 
clang/include/clang/Frontend/PrecompiledPreamble.h
clang/lib/Frontend/PrecompiledPreamble.cpp

Removed: 




diff  --git a/clang/include/clang/Frontend/PrecompiledPreamble.h 
b/clang/include/clang/Frontend/PrecompiledPreamble.h
index 628736f34091b..db9f33ae5961f 100644
--- a/clang/include/clang/Frontend/PrecompiledPreamble.h
+++ b/clang/include/clang/Frontend/PrecompiledPreamble.h
@@ -17,7 +17,6 @@
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Support/AlignOf.h"
 #include "llvm/Support/MD5.h"
 #include 
 #include 
@@ -86,8 +85,9 @@ class PrecompiledPreamble {
 std::shared_ptr PCHContainerOps,
 bool StoreInMemory, PreambleCallbacks &Callbacks);
 
-  PrecompiledPreamble(PrecompiledPreamble &&) = default;
-  PrecompiledPreamble &operator=(PrecompiledPreamble &&) = default;
+  PrecompiledPreamble(PrecompiledPreamble &&);
+  PrecompiledPreamble &operator=(PrecompiledPreamble &&);
+  ~PrecompiledPreamble();
 
   /// PreambleBounds used to build the preamble.
   PreambleBounds getBounds() const;
@@ -128,79 +128,12 @@ class PrecompiledPreamble {
 llvm::MemoryBuffer *MainFileBuffer) const;
 
 private:
-  PrecompiledPreamble(PCHStorage Storage, std::vector PreambleBytes,
+  PrecompiledPreamble(std::unique_ptr Storage,
+  std::vector PreambleBytes,
   bool PreambleEndsAtStartOfLine,
   llvm::StringMap FilesInPreamble,
   llvm::StringSet<> MissingFiles);
 
-  /// A temp file that would be deleted on destructor call. If destructor is 
not
-  /// called for any reason, the file will be deleted at static objects'
-  /// destruction.
-  /// An assertion will fire if two TempPCHFiles are created with the same 
name,
-  /// so it's not intended to be used outside preamble-handling.
-  class TempPCHFile {
-  public:
-// A main method used to construct TempPCHFile.
-static llvm::ErrorOr CreateNewPreamblePCHFile();
-
-  private:
-TempPCHFile(std::string FilePath);
-
-  public:
-TempPCHFile(TempPCHFile &&Other);
-TempPCHFile &operator=(TempPCHFile &&Other);
-
-TempPCHFile(const TempPCHFile &) = delete;
-~TempPCHFile();
-
-/// A path where temporary file is stored.
-llvm::StringRef getFilePath() const;
-
-  private:
-void RemoveFileIfPresent();
-
-  private:
-llvm::Optional FilePath;
-  };
-
-  class InMemoryPreamble {
-  public:
-std::string Data;
-  };
-
-  class PCHStorage {
-  public:
-enum class Kind { Empty, InMemory, TempFile };
-
-PCHStorage() = default;
-PCHStorage(TempPCHFile File);
-PCHStorage(InMemoryPreamble Memory);
-
-PCHStorage(const PCHStorage &) = delete;
-PCHStorage &operator=(const PCHStorage &) = delete;
-
-PCHStorage(PCHStorage &&Other);
-PCHStorage &operator=(PCHStorage &&Other);
-
-~PCHStorage();
-
-Kind getKind() const;
-
-TempPCHFile &asFile();
-const TempPCHFile &asFile() const;
-
-InMemoryPreamble &asMemory();
-const InMemoryPreamble &asMemory() const;
-
-  private:
-void destroy();
-void setEmpty();
-
-  private:
-Kind StorageKind = Kind::Empty;
-llvm::AlignedCharArrayUnion Storage = {};
-  };
-
   /// Data used to determine if a file used in the preamble has been changed.
   struct PreambleFileHash {
 /// All files have size set.
@@ -245,7 +178,7 @@ class PrecompiledPreamble {
IntrusiveRefCntPtr &VFS);
 
   /// Manages the memory buffer or temporary file that stores the PCH.
-  PCHStorage Storage;
+  std::unique_ptr Storage;
   /// Keeps track of the files that were used when computing the
   /// preamble, with both their buffer size and their modification time.
   ///

diff  --git a/clang/lib/Frontend/PrecompiledPreamble.cpp 
b/clang/lib/Frontend/PrecompiledPreamble.cpp
index f29cb038c2080..9f5be05a14308 100644
--- a/clang/lib/Frontend/PrecompiledPreamble.cpp
+++ b/clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -11,10 +11,8 @@
 
//===

[PATCH] D124177: [Frontend] Simplify PrecompiledPreamble::PCHStorage. NFC

2022-04-21 Thread Sam McCall via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rGaf3fb0715459: [Frontend] Simplify 
PrecompiledPreamble::PCHStorage. NFC (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D124177?vs=424202&id=424225#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124177

Files:
  clang/include/clang/Frontend/PrecompiledPreamble.h
  clang/lib/Frontend/PrecompiledPreamble.cpp

Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -11,10 +11,8 @@
 //===--===//
 
 #include "clang/Frontend/PrecompiledPreamble.h"
-#include "clang/AST/DeclObjC.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangStandard.h"
-#include "clang/Basic/TargetInfo.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/FrontendActions.h"
@@ -25,7 +23,6 @@
 #include "clang/Lex/PreprocessorOptions.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/iterator_range.h"
 #include "llvm/Config/llvm-config.h"
@@ -192,6 +189,49 @@
   llvm::sys::fs::remove(File);
 }
 
+// A temp file that would be deleted on destructor call. If destructor is not
+// called for any reason, the file will be deleted at static objects'
+// destruction.
+// An assertion will fire if two TempPCHFiles are created with the same name,
+// so it's not intended to be used outside preamble-handling.
+class TempPCHFile {
+public:
+  // A main method used to construct TempPCHFile.
+  static std::unique_ptr create() {
+// FIXME: This is a hack so that we can override the preamble file during
+// crash-recovery testing, which is the only case where the preamble files
+// are not necessarily cleaned up.
+if (const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"))
+  return std::unique_ptr(new TempPCHFile(TmpFile));
+
+llvm::SmallString<64> File;
+// Using a version of createTemporaryFile with a file descriptor guarantees
+// that we would never get a race condition in a multi-threaded setting
+// (i.e., multiple threads getting the same temporary path).
+int FD;
+if (auto EC =
+llvm::sys::fs::createTemporaryFile("preamble", "pch", FD, File))
+  return nullptr;
+// We only needed to make sure the file exists, close the file right away.
+llvm::sys::Process::SafelyCloseFileDescriptor(FD);
+return std::unique_ptr(new TempPCHFile(File.str().str()));
+  }
+
+  TempPCHFile &operator=(const TempPCHFile &) = delete;
+  TempPCHFile(const TempPCHFile &) = delete;
+  ~TempPCHFile() { TemporaryFiles::getInstance().removeFile(FilePath); };
+
+  /// A path where temporary file is stored.
+  llvm::StringRef getFilePath() const { return FilePath; };
+
+private:
+  TempPCHFile(std::string FilePath) : FilePath(std::move(FilePath)) {
+TemporaryFiles::getInstance().addFile(this->FilePath);
+  }
+
+  std::string FilePath;
+};
+
 class PrecompilePreambleAction : public ASTFrontendAction {
 public:
   PrecompilePreambleAction(std::string *InMemStorage,
@@ -308,6 +348,55 @@
   return Lexer::ComputePreamble(Buffer.getBuffer(), LangOpts, MaxLines);
 }
 
+class PrecompiledPreamble::PCHStorage {
+public:
+  static std::unique_ptr file(std::unique_ptr File) {
+assert(File);
+std::unique_ptr S(new PCHStorage());
+S->File = std::move(File);
+return S;
+  }
+  static std::unique_ptr inMemory() {
+std::unique_ptr S(new PCHStorage());
+S->Memory.emplace();
+return S;
+  }
+
+  enum class Kind { InMemory, TempFile };
+  Kind getKind() const {
+if (Memory)
+  return Kind::InMemory;
+if (File)
+  return Kind::TempFile;
+llvm_unreachable("Neither Memory nor File?");
+  }
+  llvm::StringRef filePath() const {
+assert(getKind() == Kind::TempFile);
+return File->getFilePath();
+  }
+  llvm::StringRef memoryContents() const {
+assert(getKind() == Kind::InMemory);
+return *Memory;
+  }
+  std::string &memoryBufferForWrite() {
+assert(getKind() == Kind::InMemory);
+return *Memory;
+  }
+
+private:
+  PCHStorage() = default;
+  PCHStorage(const PCHStorage &) = delete;
+  PCHStorage &operator=(const PCHStorage &) = delete;
+
+  llvm::Optional Memory;
+  std::unique_ptr File;
+};
+
+PrecompiledPreamble::~PrecompiledPreamble() = default;
+PrecompiledPreamble::PrecompiledPreamble(PrecompiledPreamble &&) = default;
+PrecompiledPreamble &
+PrecompiledPreamble::operator=(PrecompiledPreamble &&) = default;
+
 llvm::ErrorOr PrecompiledPreamble::Build(
 const CompilerInvocati

[clang] afcc6ba - [clang][HIP] Updating driver to enable archive/bitcode to bitcode linking when targeting HIPAMD toolchain

2022-04-21 Thread Jacob Lambert via cfe-commits

Author: Jacob Lambert
Date: 2022-04-21T09:24:33-07:00
New Revision: afcc6baac52fcc91d1636f6803f5c230e7018016

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

LOG: [clang][HIP] Updating driver to enable archive/bitcode to bitcode linking 
when targeting HIPAMD toolchain

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

Added: 
clang/test/Driver/hip-link-bc-to-bc.hip

Modified: 
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/HIPAMD.cpp
clang/lib/Driver/ToolChains/HIPAMD.h
clang/test/Driver/hip-phases.hip

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index c2f33f2970e1f..0e0d2b47bd663 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -3065,7 +3065,7 @@ class OffloadingActionBuilder final {
 
   // amdgcn does not support linking of object files, therefore we skip
   // backend and assemble phases to output LLVM IR. Except for generating
-  // non-relocatable device coee, where we generate fat binary for device
+  // non-relocatable device code, where we generate fat binary for device
   // code and pass to host in Backend phase.
   if (CudaDeviceActions.empty())
 return ABRT_Success;
@@ -3074,7 +3074,7 @@ class OffloadingActionBuilder final {
   CudaDeviceActions.size() == GpuArchList.size()) &&
  "Expecting one action per GPU architecture.");
   assert(!CompileHostOnly &&
- "Not expecting CUDA actions in host-only compilation.");
+ "Not expecting HIP actions in host-only compilation.");
 
   if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
   !EmitAsm) {
@@ -3203,12 +3203,16 @@ class OffloadingActionBuilder final {
  "Linker inputs and GPU arch list sizes do not match.");
 
   ActionList Actions;
-  // Append a new link action for each device.
   unsigned I = 0;
+  // Append a new link action for each device.
+  // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
   for (auto &LI : DeviceLinkerInputs) {
-// Each entry in DeviceLinkerInputs corresponds to a GPU arch.
-auto *DeviceLinkAction =
-C.MakeAction(LI, types::TY_Image);
+
+types::ID Output = Args.hasArg(options::OPT_emit_llvm)
+   ? types::TY_LLVM_BC
+   : types::TY_Image;
+
+auto *DeviceLinkAction = C.MakeAction(LI, Output);
 // Linking all inputs for the current GPU arch.
 // LI contains all the inputs for the linker.
 OffloadAction::DeviceDependences DeviceLinkDeps;
@@ -3220,6 +3224,12 @@ class OffloadingActionBuilder final {
   }
   DeviceLinkerInputs.clear();
 
+  // If emitting LLVM, do not generate final host/device compilation action
+  if (Args.hasArg(options::OPT_emit_llvm)) {
+  AL.append(Actions);
+  return;
+  }
+
   // Create a host object from all the device images by embedding them
   // in a fat binary for mixed host-device compilation. For device-only
   // compilation, creates a fat binary.
@@ -3747,7 +3757,8 @@ void Driver::handleArguments(Compilation &C, 
DerivedArgList &Args,
   phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
 
   if (FinalPhase == phases::Link) {
-if (Args.hasArg(options::OPT_emit_llvm))
+// Emitting LLVM while linking disabled except in HIPAMD Toolchain
+if (Args.hasArg(options::OPT_emit_llvm) && 
!Args.hasArg(options::OPT_hip_link))
   Diag(clang::diag::err_drv_emit_llvm_link);
 if (IsCLMode() && LTOMode != LTOK_None &&
 !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
@@ -3932,7 +3943,10 @@ void Driver::BuildActions(Compilation &C, DerivedArgList 
&Args,
   // Queue linker inputs.
   if (Phase == phases::Link) {
 assert(Phase == PL.back() && "linking must be final compilation 
step.");
-LinkerInputs.push_back(Current);
+// We don't need to generate additional link commands if emitting AMD 
bitcode
+if (!(C.getInputArgs().hasArg(options::OPT_hip_link) &&
+ (C.getInputArgs().hasArg(options::OPT_emit_llvm
+  LinkerInputs.push_back(Current);
 Current = nullptr;
 break;
   }

diff  --git a/clang/lib/Driver/ToolChains/HIPAMD.cpp 
b/clang/lib/Driver/ToolChains/HIPAMD.cpp
index 9f0ac6294e607..f672d2a108cc9 100644
--- a/clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ b/clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -72,6 +72,36 @@ static bool shouldSkipSanitizeOption(const ToolChain &TC,
   return false;
 }
 
+void AMDGCN::Linker::constructLlvmLinkCommand(Compilation &C,
+ const JobAction &JA,
+

[PATCH] D124151: [clang][HIP] Updating driver to enable archive/bitcode to bitcode linking when targeting HIPAMD toolchain

2022-04-21 Thread Jacob Lambert 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 rGafcc6baac52f: [clang][HIP] Updating driver to enable 
archive/bitcode to bitcode linking when… (authored by lamb-j).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124151

Files:
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/lib/Driver/ToolChains/HIPAMD.h
  clang/test/Driver/hip-link-bc-to-bc.hip
  clang/test/Driver/hip-phases.hip

Index: clang/test/Driver/hip-phases.hip
===
--- clang/test/Driver/hip-phases.hip
+++ clang/test/Driver/hip-phases.hip
@@ -520,3 +520,25 @@
 // MIXED2-DAG: input, "{{.*}}empty.cpp", hip, (device-hip, gfx803)
 // MIXED2-DAG: input, "{{.*}}empty.cpp", hip, (device-hip, gfx900)
 // MIXED2-NEG-NOT: input, "{{.*}}empty.cpp", c++
+
+// Test HIP bitcode to bitcode linking. Input should be bundled or unbundled bitcode, and
+// output should be unbundled linked bitcode
+
+// RUN: touch %T/bitcodeA.bc
+// RUN: touch %T/bitcodeB.bc
+// RUN: %clang -ccc-print-phases --hip-link -emit-llvm --cuda-device-only \
+// RUN: --offload-arch=gfx906 %T/bitcodeA.bc %T/bitcodeB.bc 2>&1 \
+// RUN: | FileCheck -check-prefixes=CHECK %s
+
+// CHECK: [[A0:[0-9]+]]: input, "{{.*}}bitcodeA.bc", ir
+// CHECK: [[A1:[0-9]+]]: clang-offload-unbundler, {[[A0]]}, ir
+// CHECK: [[A2:[0-9]+]]: compiler, {[[A1]]}, ir, (device-hip, [[ARCH:gfx906]])
+// CHECK: [[A3:[0-9]+]]: backend, {[[A2]]}, ir, (device-hip, [[ARCH]])
+
+// CHECK: [[B0:[0-9]+]]: input, "{{.*}}bitcodeB.bc", ir
+// CHECK: [[B1:[0-9]+]]: clang-offload-unbundler, {[[B0]]}, ir
+// CHECK: [[B2:[0-9]+]]: compiler, {[[B1]]}, ir, (device-hip, [[ARCH]])
+// CHECK: [[B3:[0-9]+]]: backend, {[[B2]]}, ir, (device-hip, [[ARCH]])
+
+// CHECK: [[L0:[0-9]+]]: linker, {[[A3]], [[B3]]}, ir, (device-hip, [[ARCH]])
+// CHECK: offload, "device-hip (amdgcn-amd-amdhsa:[[ARCH]])" {[[L0]]}, ir
Index: clang/test/Driver/hip-link-bc-to-bc.hip
===
--- /dev/null
+++ clang/test/Driver/hip-link-bc-to-bc.hip
@@ -0,0 +1,34 @@
+// REQUIRES: clang-driver, x86-registered-target, amdgpu-registered-target
+
+// Check that clang unbundles the two bitcodes and links via llvm-link
+// RUN: touch %T/bundle1.bc
+// RUN: touch %T/bundle2.bc
+
+// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
+// RUN:   %T/bundle1.bc %T/bundle2.bc \
+// RUN:   2>&1 | FileCheck -check-prefix=BITCODE %s
+
+// BITCODE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle1.bc" "-output=[[B1HOST:.*\.bc]]" "-output=[[B1DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// BITCODE: "{{.*}}clang-{{.*}}" "-o" "[[B1DEV2:.*bundle1-gfx906.bc]]" "-x" "ir" "[[B1DEV1]]"
+
+// BITCODE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle2.bc" "-output=[[B2HOST:.*\.bc]]" "-output=[[B2DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// BITCODE: "{{.*}}clang-{{.*}}" "-o" "[[B2DEV2:.*bundle2-gfx906.bc]]" "-x" "ir" "[[B2DEV1]]"
+
+// BITCODE: "{{.*}}llvm-link" "-o" "bundle1-hip-amdgcn-amd-amdhsa-gfx906.bc" "[[B1DEV2]]" "[[B2DEV2]]"
+
+// Check that clang unbundles the bitcode and archive and links via llvm-link
+// RUN: touch %T/libhipbundle.a
+// RUN: touch %T/bundle.bc
+
+// RUN: %clang -### --offload-arch=gfx906 --hip-link \
+// RUN:   -emit-llvm -fgpu-rdc --cuda-device-only \
+// RUN:   %T/bundle.bc -L%T -lhipbundle \
+// RUN:   2>&1 | FileCheck -check-prefix=ARCHIVE %s
+
+// ARCHIVE: "{{.*}}clang-offload-bundler" "-type=bc" "-targets=host-x86_64-unknown-linux-gnu,hip-amdgcn-amd-amdhsa-gfx906" "-input={{.*}}bundle.bc" "-output=[[HOST:.*\.bc]]" "-output=[[DEV1:.*\.bc]]" "-unbundle" "-allow-missing-bundles"
+// ARCHIVE: "{{.*}}clang-{{.*}}" "-o" "[[DEV2:.*\.bc]]" "-x" "ir" "[[DEV1]]"
+
+// ARCHIVE: "{{.*}}clang-offload-bundler" "-unbundle" "-type=a" "-input={{.*}}libhipbundle.a" "-targets=hip-amdgcn-amd-amdhsa-gfx906" "-output=[[AR:.*\.a]]" "-allow-missing-bundles" "-hip-openmp-compatible"
+
+// ARCHIVE: "{{.*}}llvm-link" "-o" "bundle-hip-amdgcn-amd-amdhsa-gfx906.bc" "[[DEV2]]" "[[AR]]"
Index: clang/lib/Driver/ToolChains/HIPAMD.h
===
--- clang/lib/Driver/ToolChains/HIPAMD.h
+++ clang/lib/Driver/ToolChains/HIPAMD.h
@@ -36,6 +36,10 @@
   void constructLldCommand(Compilation &C, const JobAction &JA,
const InputInfoList &Inputs, const InputInfo &Output,
const llvm::opt::ArgList &Args) const;
+  void constructLlvmLinkCommand(Compilation &C, const JobAction &JA,
+const InputInfoList &I

[PATCH] D123450: [clang-format] Parse Verilog if statements

2022-04-21 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

As first passes for adding a new language I think this looks pretty good.

``if (Keywords.isBlockBegin(*FormatTok, Style)) {``

I'm not a massive fan of handling l_brace and begin and end as the same thing, 
I might be tempted to handle them separately, as then its clear what is 
happening, but I don't think I'd block it for that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123450

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-21 Thread David Tenty via Phabricator via cfe-commits
daltenty added a comment.

In D122983#3464759 , @aaron.ballman 
wrote:

> In D122983#3464724 , @Jake-Egan 
> wrote:
>
>> Hi, we also have a failure on AIX with test-suite `call to undeclared 
>> library function '%0' with type %1; ISO C99 and later`  
>> https://lab.llvm.org/buildbot/#/builders/214/builds/825/steps/9/logs/stdio
>
> Thanks for letting me know, this should now be fixed.

Looks like there are more test-suite case breaking beyond the one you fixed:

https://lab.llvm.org/buildbot/#/builders/214/builds/842

I suspect there will be more with the scope of this change unfortunately.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2022-04-21 Thread Mark de Wever via Phabricator via cfe-commits
Mordante added a comment.

In D112921#3463887 , @pcwang-thead 
wrote:

> In D112921#3462592 , @Mordante 
> wrote:
>
>> I didn't look at the code, but I have some hints how we can test libc++.
>
> Thanks! I ran tests with no error occurred on my local machine and I really 
> want to know how to test it!

I added similar information yesterday, but I somehow didn't properly submit it.




Comment at: 
libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp:17
+// XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11}}
 
 #include 

This `// XFAIL: clang-12, clang-13` is still needed but should be `// XFAIL: 
clang-13, clang-14`. (Since the LLVM 14 release we only support these two 
versions.)

For testing it's the easiest to remove line 147 of 
`libcxx/utils/ci/buildkite-pipeline.yml`
https://github.com/llvm/llvm-project/blob/afcc6baac52fcc91d1636f6803f5c230e7018016/libcxx/utils/ci/buildkite-pipeline.yml#L147

That way all builds run. The `Bootstrapping build` builds clang and uses that 
clang to test libc++. That way we can validate which builds fail and which 
succeed. Maybe some more builds need to be (temporary) disabled.

Once we verify that works we need to:
- undo the buildkite changes
- disable this test temporary (`UNSUPPORTED: clang-15`)
- create a followup patch to reenable the test
After the change has landed it will take some time before the change is 
propagated to the CI. Once it's propagated the followup patch can be landed. 
I'm willing to create the followup patch and land it at the proper time.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112921

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

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

In D122983#3465052 , @daltenty wrote:

> In D122983#3464759 , @aaron.ballman 
> wrote:
>
>> In D122983#3464724 , @Jake-Egan 
>> wrote:
>>
>>> Hi, we also have a failure on AIX with test-suite `call to undeclared 
>>> library function '%0' with type %1; ISO C99 and later`  
>>> https://lab.llvm.org/buildbot/#/builders/214/builds/825/steps/9/logs/stdio
>>
>> Thanks for letting me know, this should now be fixed.
>
> Looks like there are more test-suite case breaking beyond the one you fixed:
>
> https://lab.llvm.org/buildbot/#/builders/214/builds/842
>
> I suspect there will be more with the scope of this change unfortunately.

I agree there will be more -- it's incredibly frustrating that the AIX bot runs 
the test-suite but stops testing after the first failure. It makes it really 
hard to maintain. :-(

I've been keeping my eye on that bot and have been fixing up the tests as they 
get noticed, but if someone who has access to AIX wanted to tell me all of the 
test failures so I could hit them all at once (or disable the warnings in 
CMakeLists.txt and Makefile), that'd be greatly appreciated!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-21 Thread Nemanja Ivanovic via Phabricator via cfe-commits
nemanjai added a comment.

@daltenty Can you please run this with the same config as the bot on one of our 
AIX machines but be sure to pass `-i` if it's `make` or `-k 0` if it's `ninja`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[clang] f296b4c - [AIX] Always pass namedsects option when linking with PGO.

2022-04-21 Thread Wael Yehia via cfe-commits

Author: Wael Yehia
Date: 2022-04-21T17:01:37Z
New Revision: f296b4c444625f84be1db27cfd52a3d16387f456

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

LOG: [AIX] Always pass namedsects option when linking with PGO.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/AIX.cpp
clang/test/Driver/aix-ld.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index e4bbf498b9cd6..37316a792f6d1 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -98,9 +98,10 @@ void aix::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 CmdArgs.push_back("-bnoentry");
   }
 
-  // Specify PGO linker option without LTO
-  if (!D.isUsingLTO() &&
-  (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
+  // PGO instrumentation generates symbols belonging to special sections, and
+  // the linker needs to place all symbols in a particular section together in
+  // memory; the AIX linker does that under an option.
+  if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
 false) ||
Args.hasFlag(options::OPT_fprofile_generate,
 options::OPT_fno_profile_generate, false) ||
@@ -115,7 +116,7 @@ void aix::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
Args.hasFlag(options::OPT_fcs_profile_generate_EQ,
 options::OPT_fno_profile_generate, false) ||
Args.hasArg(options::OPT_fcreate_profile) ||
-   Args.hasArg(options::OPT_coverage)))
+   Args.hasArg(options::OPT_coverage))
 CmdArgs.push_back("-bdbg:namedsects");
 
   // Specify linker output file.

diff  --git a/clang/test/Driver/aix-ld.c b/clang/test/Driver/aix-ld.c
index 6a1b006bf1e3b..eccae132763d5 100644
--- a/clang/test/Driver/aix-ld.c
+++ b/clang/test/Driver/aix-ld.c
@@ -692,7 +692,7 @@
 // CHECK-PGO-LTO: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-PGO-LTO: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-PGO-LTO: "{{.*}}ld{{(.exe)?}}"
-// CHECK-PGO-LTO-NOT: "-bdbg:namedsects"
+// CHECK-PGO-LTO: "-bdbg:namedsects"
 // CHECK-PGO-LTO: "-b32"
 // CHECK-PGO-LTO: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-PGO-LTO: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"



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


[PATCH] D124046: [AIX] Always pass namedsects option when linking with PGO.

2022-04-21 Thread wael yehia 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 rGf296b4c44462: [AIX] Always pass namedsects option when 
linking with PGO. (authored by w2yehia).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124046

Files:
  clang/lib/Driver/ToolChains/AIX.cpp
  clang/test/Driver/aix-ld.c


Index: clang/test/Driver/aix-ld.c
===
--- clang/test/Driver/aix-ld.c
+++ clang/test/Driver/aix-ld.c
@@ -692,7 +692,7 @@
 // CHECK-PGO-LTO: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-PGO-LTO: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-PGO-LTO: "{{.*}}ld{{(.exe)?}}"
-// CHECK-PGO-LTO-NOT: "-bdbg:namedsects"
+// CHECK-PGO-LTO: "-bdbg:namedsects"
 // CHECK-PGO-LTO: "-b32"
 // CHECK-PGO-LTO: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-PGO-LTO: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
Index: clang/lib/Driver/ToolChains/AIX.cpp
===
--- clang/lib/Driver/ToolChains/AIX.cpp
+++ clang/lib/Driver/ToolChains/AIX.cpp
@@ -98,9 +98,10 @@
 CmdArgs.push_back("-bnoentry");
   }
 
-  // Specify PGO linker option without LTO
-  if (!D.isUsingLTO() &&
-  (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
+  // PGO instrumentation generates symbols belonging to special sections, and
+  // the linker needs to place all symbols in a particular section together in
+  // memory; the AIX linker does that under an option.
+  if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
 false) ||
Args.hasFlag(options::OPT_fprofile_generate,
 options::OPT_fno_profile_generate, false) ||
@@ -115,7 +116,7 @@
Args.hasFlag(options::OPT_fcs_profile_generate_EQ,
 options::OPT_fno_profile_generate, false) ||
Args.hasArg(options::OPT_fcreate_profile) ||
-   Args.hasArg(options::OPT_coverage)))
+   Args.hasArg(options::OPT_coverage))
 CmdArgs.push_back("-bdbg:namedsects");
 
   // Specify linker output file.


Index: clang/test/Driver/aix-ld.c
===
--- clang/test/Driver/aix-ld.c
+++ clang/test/Driver/aix-ld.c
@@ -692,7 +692,7 @@
 // CHECK-PGO-LTO: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
 // CHECK-PGO-LTO: "-isysroot" "[[SYSROOT:[^"]+]]"
 // CHECK-PGO-LTO: "{{.*}}ld{{(.exe)?}}"
-// CHECK-PGO-LTO-NOT: "-bdbg:namedsects"
+// CHECK-PGO-LTO: "-bdbg:namedsects"
 // CHECK-PGO-LTO: "-b32"
 // CHECK-PGO-LTO: "-bpT:0x1000" "-bpD:0x2000"
 // CHECK-PGO-LTO: "[[SYSROOT]]/usr/lib{{/|}}crt0.o"
Index: clang/lib/Driver/ToolChains/AIX.cpp
===
--- clang/lib/Driver/ToolChains/AIX.cpp
+++ clang/lib/Driver/ToolChains/AIX.cpp
@@ -98,9 +98,10 @@
 CmdArgs.push_back("-bnoentry");
   }
 
-  // Specify PGO linker option without LTO
-  if (!D.isUsingLTO() &&
-  (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
+  // PGO instrumentation generates symbols belonging to special sections, and
+  // the linker needs to place all symbols in a particular section together in
+  // memory; the AIX linker does that under an option.
+  if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
 false) ||
Args.hasFlag(options::OPT_fprofile_generate,
 options::OPT_fno_profile_generate, false) ||
@@ -115,7 +116,7 @@
Args.hasFlag(options::OPT_fcs_profile_generate_EQ,
 options::OPT_fno_profile_generate, false) ||
Args.hasArg(options::OPT_fcreate_profile) ||
-   Args.hasArg(options::OPT_coverage)))
+   Args.hasArg(options::OPT_coverage))
 CmdArgs.push_back("-bdbg:namedsects");
 
   // Specify linker output file.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

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

In D122983#3465099 , @nemanjai wrote:

> @daltenty Can you please run this with the same config as the bot on one of 
> our AIX machines but be sure to pass `-i` if it's `make` or `-k 0` if it's 
> `ninja`?

That would be *awesome*! I have to take off for a few hours, but I'm happy to 
fix all of the issues you spot in one go when I get back in a bit. Thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D124186: [RISCV] Fix incorrect policy implement for unmasked vslidedown and vslideup.

2022-04-21 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

The intrinsic interface doesn't care about 0https://reviews.llvm.org/D124186/new/

https://reviews.llvm.org/D124186

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


[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-21 Thread Shubham Sandeep Rastogi via Phabricator via cfe-commits
rastogishubham added a comment.

Hi, this patch causes an issue with the CMake Xcode build configuration, if I 
try to use xcode as the generator with CMake, using the build command:

xcrun cmake -G Xcode -DCMAKE_BUILD_TYPE:STRING=RelWithDebInfo 
-DLLVM_ENABLE_ASSERTIONS:BOOL=TRUE -DCMAKE_C_COMPILER=/usr/bin/clang 
-DCMAKE_CXX_COMPILER=/usr/bin/clang++ -DLLVM_ENABLE_PROJECTS='clang;' 
-DCMAKE_IGNORE_PATH="/usr/lib;/usr/local/lib;/lib" 
-DLLVM_TARGETS_TO_BUILD="X86;ARM;AArch64" ../llvm

I get:

CMake Error in 
/Users/shubhamrastogi/Development/llvm-project-cas/llvm-project/clang/lib/Headers/CMakeLists.txt:

  The custom command generating
  

/Users/shubhamrastogi/Development/llvm-project-cas/llvm-project/build/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/lib/clang/15.0.0/include/float.h
  
  is attached to multiple targets:
  
x86-resource-headers
windows-resource-headers
webassembly-resource-headers
systemz-resource-headers
mips-resource-headers
arm-resource-headers
cuda-resource-headers
riscv-resource-headers
ppc-resource-headers
opencl-resource-headers
aarch64-resource-headers
hip-resource-headers
ve-resource-headers
hexagon-resource-headers
clang-resource-headers
  
  but none of these is a common dependency of the other(s).  This is not
  allowed by the Xcode "new build system".

CMake Error in 
/Users/shubhamrastogi/Development/llvm-project-cas/llvm-project/third-party/benchmark/CMakeLists.txt:

  The custom command generating
  

/Users/shubhamrastogi/Development/llvm-project-cas/llvm-project/build/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/lib/clang/15.0.0/include/float.h
  
  is attached to multiple targets:
  
x86-resource-headers
windows-resource-headers
webassembly-resource-headers
systemz-resource-headers
mips-resource-headers
arm-resource-headers
cuda-resource-headers
riscv-resource-headers
ppc-resource-headers
opencl-resource-headers
aarch64-resource-headers
hip-resource-headers
ve-resource-headers
hexagon-resource-headers
clang-resource-headers
  
  but none of these is a common dependency of the other(s).  This is not
  allowed by the Xcode "new build system".

I used git bisect to figure this out, is there some solution to this?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-04-21 Thread Erich Keane via Phabricator via cfe-commits
erichkeane updated this revision to Diff 424241.
erichkeane added a comment.
This revision is now accepted and ready to land.

Found that the recursive var-decl collection was incorrect, since all the 
values were already in the parent scopes!  So I ended up being able to fix MOST 
of the problems by simply making the 'scope' inherit when instantiating 
constraints.  This should make us use the 'lookup rules' of the parent, which 
is correct I believe.

I have 1 more pair of failures (see commented out tests in concepts.cpp) where 
the lookup for a member-variable doesn't work right.


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

https://reviews.llvm.org/D119544

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclBase.h
  clang/include/clang/Sema/Sema.h
  clang/include/clang/Sema/Template.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclBase.cpp
  clang/lib/ExtractAPI/ExtractAPIConsumer.cpp
  clang/lib/Sema/SemaConcept.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/lib/Sema/SemaTemplateDeduction.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/CXX/temp/temp.constr/temp.constr.constr/non-function-templates.cpp
  clang/test/SemaTemplate/concepts.cpp
  clang/test/SemaTemplate/cxx2a-constraint-exprs.cpp
  clang/test/SemaTemplate/deferred-concept-inst.cpp
  clang/test/SemaTemplate/instantiate-requires-clause.cpp
  clang/test/SemaTemplate/trailing-return-short-circuit.cpp

Index: clang/test/SemaTemplate/trailing-return-short-circuit.cpp
===
--- /dev/null
+++ clang/test/SemaTemplate/trailing-return-short-circuit.cpp
@@ -0,0 +1,62 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+template 
+  requires(sizeof(T) > 2) || T::value // #FOO_REQ
+void Foo(T){};// #FOO
+
+template 
+void TrailingReturn(T)   // #TRAILING
+  requires(sizeof(T) > 2) || // #TRAILING_REQ
+  T::value   // #TRAILING_REQ_VAL
+{};
+template 
+struct HasValue {
+  static constexpr bool value = B;
+};
+static_assert(sizeof(HasValue) <= 2);
+
+template 
+struct HasValueLarge {
+  static constexpr bool value = B;
+  int I;
+};
+static_assert(sizeof(HasValueLarge) > 2);
+
+void usage() {
+  // Passes the 1st check, short-circuit so the 2nd ::value is not evaluated.
+  Foo(1.0);
+  TrailingReturn(1.0);
+
+  // Fails the 1st check, but has a ::value, so the check happens correctly.
+  Foo(HasValue{});
+  TrailingReturn(HasValue{});
+
+  // Passes the 1st check, but would have passed the 2nd one.
+  Foo(HasValueLarge{});
+  TrailingReturn(HasValueLarge{});
+
+  // Fails the 1st check, fails 2nd because there is no ::value.
+  Foo(true);
+  // expected-error@-1{{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  TrailingReturn(true);
+  // expected-error@-1{{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = bool]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(_Bool) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{because substituted constraint expression is ill-formed: type 'bool' cannot be used prior to '::' because it has no members}}
+
+  // Fails the 1st check, fails 2nd because ::value is false.
+  Foo(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'Foo'}}
+  // expected-note@#FOO{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#FOO_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#FOO_REQ{{and 'HasValue::value' evaluated to false}}
+  TrailingReturn(HasValue{});
+  // expected-error@-1 {{no matching function for call to 'TrailingReturn'}}
+  // expected-note@#TRAILING{{candidate template ignored: constraints not satisfied [with T = HasValue]}}
+  // expected-note@#TRAILING_REQ{{because 'sizeof(HasValue) > 2' (1 > 2) evaluated to false}}
+  // expected-note@#TRAILING_REQ_VAL{{and 'HasValue::value' evaluated to false}}
+}
Index: clang/test/SemaTemplate/instantiate-requires-clause.cpp
===
--- clang/test/SemaTemplate/instantiate-requires-clause.cpp
+++ clang/test/SemaTemplate/instantiate-requires-clause.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++2a -x c++ %s -verify
+// RUN: %clang_cc1 -std=c++2a -x c++ %s -Wno-unused-value -verify
 
 templa

[PATCH] D119544: Deferred Concept Instantiation Implementation

2022-04-21 Thread Erich Keane via Phabricator via cfe-commits
erichkeane planned changes to this revision.
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaTemplateInstantiate.cpp:2329
+  // constraint, so we should just create a copy of the previous one.
+  // TODO: ERICH: Should this be RebuildExprInCurrentInstantiation here?
+  if (!IsEvaluatingAConstraint()) {

I'm still not sure if anything should be rebuilt here, I suspect the answer is 
MAYBE on the named-concept, but it isn't clear to me.



Comment at: clang/test/SemaTemplate/concepts.cpp:391
+
+  CausesFriendConstraint CFC;
+  FriendFunc(CFC, 1);

erichkeane wrote:
> A bunch of the tests below this all fail.
See these two tests, which fail by saying that "::local is not a member of 
class 'X'".


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

https://reviews.llvm.org/D119544

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


[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-21 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 added a comment.

In D123498#3465139 , @rastogishubham 
wrote:

> Hi, this patch causes an issue with the CMake Xcode build configuration, if I 
> try to use xcode as the generator with CMake, using the build command:
>
> I used git bisect to figure this out, is there some solution to this?

Hi Schubham!

I will go take a look to see how we can provide a long term solution. In the 
meantime, could you try the workaround here 
https://stackoverflow.com/questions/65473503/when-trying-to-generate-an-xcode-project-from-a-cmake-folder-i-get-an-error-rel?

Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


[PATCH] D124189: [CUDA][HIP] Externalize kernels with internal linkage

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

This patch is a continuation of https://reviews.llvm.org/D123353.

Not only kernels in anonymous namespace, but also template
kernels with template arguments in anonymous namespace
need to be externalized.

To be more generic, this patch checks the linkage of a kernel
assuming the kernel does not have `__global__` attribute. If
the linkage is internal then clang will externalize it.


https://reviews.llvm.org/D124189

Files:
  clang/include/clang/AST/ASTContext.h
  clang/lib/AST/ASTContext.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenCUDA/device-var-linkage.cu
  clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
  clang/test/CodeGenCUDA/managed-var.cu
  clang/test/CodeGenCUDA/static-device-var-rdc.cu

Index: clang/test/CodeGenCUDA/static-device-var-rdc.cu
===
--- clang/test/CodeGenCUDA/static-device-var-rdc.cu
+++ clang/test/CodeGenCUDA/static-device-var-rdc.cu
@@ -40,6 +40,11 @@
 // RUN:   -std=c++11 -fgpu-rdc -emit-llvm -o - -x hip %s > %t.host
 // RUN: cat %t.host | FileCheck -check-prefix=HOST-NEG %s
 
+// Check postfix for CUDA.
+
+// RUN: %clang_cc1 -no-opaque-pointers -triple nvptx -fcuda-is-device -cuid=abc \
+// RUN:   -std=c++11 -fgpu-rdc -emit-llvm -o - %s | FileCheck \
+// RUN:   -check-prefixes=CUDA %s
 
 #include "Inputs/cuda.h"
 
@@ -55,11 +60,12 @@
 // INT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x\00"
 
 // Test externalized static device variables
-// EXT-DEV-DAG: @_ZL1x__static__[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
-// EXT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x__static__[[HASH:.*]]\00"
+// EXT-DEV-DAG: @_ZL1x.static.[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
+// EXT-HOST-DAG: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x.static.[[HASH:.*]]\00"
+// CUDA-DAG: @_ZL1x__static__[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
 
-// POSTFIX: @_ZL1x__static__[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
-// POSTFIX: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x__static__[[HASH]]\00"
+// POSTFIX: @_ZL1x.static.[[HASH:.*]] = addrspace(1) externally_initialized global i32 0
+// POSTFIX: @[[DEVNAMEX:[0-9]+]] = {{.*}}c"_ZL1x.static.[[HASH]]\00"
 
 static __device__ int x;
 
@@ -73,8 +79,8 @@
 // INT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y\00"
 
 // Test externalized static device variables
-// EXT-DEV-DAG: @_ZL1y__static__[[HASH]] = addrspace(4) externally_initialized global i32 0
-// EXT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y__static__[[HASH]]\00"
+// EXT-DEV-DAG: @_ZL1y.static.[[HASH]] = addrspace(4) externally_initialized global i32 0
+// EXT-HOST-DAG: @[[DEVNAMEY:[0-9]+]] = {{.*}}c"_ZL1y.static.[[HASH]]\00"
 
 static __constant__ int y;
 
Index: clang/test/CodeGenCUDA/managed-var.cu
===
--- clang/test/CodeGenCUDA/managed-var.cu
+++ clang/test/CodeGenCUDA/managed-var.cu
@@ -52,15 +52,15 @@
 
 // NORDC-D-DAG: @_ZL2sx.managed = addrspace(1) externally_initialized global i32 1, align 4
 // NORDC-D-DAG: @_ZL2sx = addrspace(1) externally_initialized global i32 addrspace(1)* null
-// RDC-D-DAG: @_ZL2sx__static__[[HASH:.*]].managed = addrspace(1) externally_initialized global i32 1, align 4
-// RDC-D-DAG: @_ZL2sx__static__[[HASH]] = addrspace(1) externally_initialized global i32 addrspace(1)* null
+// RDC-D-DAG: @_ZL2sx.static.[[HASH:.*]].managed = addrspace(1) externally_initialized global i32 1, align 4
+// RDC-D-DAG: @_ZL2sx.static.[[HASH]] = addrspace(1) externally_initialized global i32 addrspace(1)* null
 // HOST-DAG: @_ZL2sx.managed = internal global i32 1
 // HOST-DAG: @_ZL2sx = internal externally_initialized global i32* null
 // NORDC-DAG: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx\00"
-// RDC-DAG: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx__static__[[HASH:.*]]\00"
+// RDC-DAG: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx.static.[[HASH:.*]]\00"
 
-// POSTFIX:  @_ZL2sx__static__[[HASH:.*]] = addrspace(1) externally_initialized global i32 addrspace(1)* null
-// POSTFIX: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx__static__[[HASH]]\00"
+// POSTFIX:  @_ZL2sx.static.[[HASH:.*]] = addrspace(1) externally_initialized global i32 addrspace(1)* null
+// POSTFIX: @[[DEVNAMESX:[0-9]+]] = {{.*}}c"_ZL2sx.static.[[HASH]]\00"
 static __managed__ int sx = 1;
 
 // DEV-DAG: @llvm.compiler.used
Index: clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
===
--- clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
+++ clang/test/CodeGenCUDA/kernel-in-anon-ns.cu
@@ -8,17 +8,38 @@
 
 // RUN: cat %t.dev %t.host | FileCheck %s
 
+// RUN: %clang_cc1 -triple nvptx -fcuda-is-device -cuid=abc \
+// RUN:   -aux-triple x86_64-unknown-linux-gnu -std=c++11 -fgpu-rdc \
+// RUN:   -emit-llvm -o - %s | FileCheck -check

[PATCH] D124154: [clangd] Fix a declare-constructor tweak crash on incomplete fields.

2022-04-21 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: 
clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp:182
+if (!C.hasDefinition())
+  return Skip;
 // We can't always tell if C is copyable/movable without doing Sema work.

sammccall wrote:
> Fail instead?
`Fail` seems too strict, the tweak is entirely unavailable if there is any 
incomplete-type field decls in a class, I think it is still useful to make the 
tweak available.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124154

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


[clang-tools-extra] 84051d8 - [clangd] Fix a declare-constructor tweak crash on incomplete fields.

2022-04-21 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-04-21T19:44:43+02:00
New Revision: 84051d8226d517f7728750ec4bde3ba75ca03468

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

LOG: [clangd] Fix a declare-constructor tweak crash on incomplete fields.

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
index a00b778e7dd79..bc0f4e1ce2569 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
@@ -178,6 +178,8 @@ class MemberwiseConstructor : public Tweak {
 
   // Decide what to do with a field of type C.
   static FieldAction considerClassValue(const CXXRecordDecl &C) {
+if (!C.hasDefinition())
+  return Skip;
 // We can't always tell if C is copyable/movable without doing Sema work.
 // We assume operations are possible unless we can prove not.
 bool CanCopy = C.hasUserDeclaredCopyConstructor() ||

diff  --git 
a/clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
index cc2750d557c8d..58671af9915e5 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
@@ -23,6 +23,8 @@ TWEAK_TEST(MemberwiseConstructor);
 
 TEST_F(MemberwiseConstructorTest, Availability) {
   EXPECT_AVAILABLE("^struct ^S ^{ int x, y; };");
+  // Verify no crashes on incomplete member fields.
+  EXPECT_UNAVAILABLE("/*error-ok*/class Forward; class ^A { Forward f;}");
   EXPECT_UNAVAILABLE("struct S { ^int ^x, y; }; struct ^S;");
   EXPECT_UNAVAILABLE("struct ^S {};");
   EXPECT_UNAVAILABLE("union ^S { int x; };");



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


[PATCH] D124154: [clangd] Fix a declare-constructor tweak crash on incomplete fields.

2022-04-21 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG84051d8226d5: [clangd] Fix a declare-constructor tweak crash 
on incomplete fields. (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124154

Files:
  clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
  clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp


Index: clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
@@ -23,6 +23,8 @@
 
 TEST_F(MemberwiseConstructorTest, Availability) {
   EXPECT_AVAILABLE("^struct ^S ^{ int x, y; };");
+  // Verify no crashes on incomplete member fields.
+  EXPECT_UNAVAILABLE("/*error-ok*/class Forward; class ^A { Forward f;}");
   EXPECT_UNAVAILABLE("struct S { ^int ^x, y; }; struct ^S;");
   EXPECT_UNAVAILABLE("struct ^S {};");
   EXPECT_UNAVAILABLE("union ^S { int x; };");
Index: clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
@@ -178,6 +178,8 @@
 
   // Decide what to do with a field of type C.
   static FieldAction considerClassValue(const CXXRecordDecl &C) {
+if (!C.hasDefinition())
+  return Skip;
 // We can't always tell if C is copyable/movable without doing Sema work.
 // We assume operations are possible unless we can prove not.
 bool CanCopy = C.hasUserDeclaredCopyConstructor() ||


Index: clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
===
--- clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
+++ clang-tools-extra/clangd/unittests/tweaks/MemberwiseConstructorTests.cpp
@@ -23,6 +23,8 @@
 
 TEST_F(MemberwiseConstructorTest, Availability) {
   EXPECT_AVAILABLE("^struct ^S ^{ int x, y; };");
+  // Verify no crashes on incomplete member fields.
+  EXPECT_UNAVAILABLE("/*error-ok*/class Forward; class ^A { Forward f;}");
   EXPECT_UNAVAILABLE("struct S { ^int ^x, y; }; struct ^S;");
   EXPECT_UNAVAILABLE("struct ^S {};");
   EXPECT_UNAVAILABLE("union ^S { int x; };");
Index: clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/MemberwiseConstructor.cpp
@@ -178,6 +178,8 @@
 
   // Decide what to do with a field of type C.
   static FieldAction considerClassValue(const CXXRecordDecl &C) {
+if (!C.hasDefinition())
+  return Skip;
 // We can't always tell if C is copyable/movable without doing Sema work.
 // We assume operations are possible unless we can prove not.
 bool CanCopy = C.hasUserDeclaredCopyConstructor() ||
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 6e22dac - [Frontend] avoid copy of PCH data when PrecompiledPreamble stores it in memory

2022-04-21 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-04-21T19:52:59+02:00
New Revision: 6e22dac2e2955db1310c63aec215fc22d8da258e

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

LOG: [Frontend] avoid copy of PCH data when PrecompiledPreamble stores it in 
memory

Instead of unconditionally copying the PCHBuffer into an ostream which can be
backed either by a string or a file, just make the PCHBuffer itself the
in-memory storage.

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

Added: 


Modified: 
clang/lib/Frontend/PrecompiledPreamble.cpp

Removed: 




diff  --git a/clang/lib/Frontend/PrecompiledPreamble.cpp 
b/clang/lib/Frontend/PrecompiledPreamble.cpp
index 9f5be05a14308..849723c4db28f 100644
--- a/clang/lib/Frontend/PrecompiledPreamble.cpp
+++ b/clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -234,9 +234,10 @@ class TempPCHFile {
 
 class PrecompilePreambleAction : public ASTFrontendAction {
 public:
-  PrecompilePreambleAction(std::string *InMemStorage,
+  PrecompilePreambleAction(std::shared_ptr Buffer, bool 
WritePCHFile,
PreambleCallbacks &Callbacks)
-  : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
+  : Buffer(std::move(Buffer)), WritePCHFile(WritePCHFile),
+Callbacks(Callbacks) {}
 
   std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
  StringRef InFile) override;
@@ -244,6 +245,12 @@ class PrecompilePreambleAction : public ASTFrontendAction {
   bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
 
   void setEmittedPreamblePCH(ASTWriter &Writer) {
+if (FileOS) {
+  *FileOS << Buffer->Data;
+  // Make sure it hits disk now.
+  FileOS->flush();
+}
+
 this->HasEmittedPreamblePCH = true;
 Callbacks.AfterPCHEmitted(Writer);
   }
@@ -262,7 +269,9 @@ class PrecompilePreambleAction : public ASTFrontendAction {
   friend class PrecompilePreambleConsumer;
 
   bool HasEmittedPreamblePCH = false;
-  std::string *InMemStorage;
+  std::shared_ptr Buffer;
+  bool WritePCHFile; // otherwise the PCH is written into the PCHBuffer only.
+  std::unique_ptr FileOS; // null if in-memory
   PreambleCallbacks &Callbacks;
 };
 
@@ -272,12 +281,11 @@ class PrecompilePreambleConsumer : public PCHGenerator {
  const Preprocessor &PP,
  InMemoryModuleCache &ModuleCache,
  StringRef isysroot,
- std::unique_ptr Out)
-  : PCHGenerator(PP, ModuleCache, "", isysroot,
- std::make_shared(),
+ std::shared_ptr Buffer)
+  : PCHGenerator(PP, ModuleCache, "", isysroot, std::move(Buffer),
  ArrayRef>(),
  /*AllowASTWithErrors=*/true),
-Action(Action), Out(std::move(Out)) {}
+Action(Action) {}
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 Action.Callbacks.HandleTopLevelDecl(DG);
@@ -288,15 +296,6 @@ class PrecompilePreambleConsumer : public PCHGenerator {
 PCHGenerator::HandleTranslationUnit(Ctx);
 if (!hasEmittedPCH())
   return;
-
-// Write the generated bitstream to "Out".
-*Out << getPCH();
-// Make sure it hits disk now.
-Out->flush();
-// Free the buffer.
-llvm::SmallVector Empty;
-getPCH() = std::move(Empty);
-
 Action.setEmittedPreamblePCH(getWriter());
   }
 
@@ -306,7 +305,6 @@ class PrecompilePreambleConsumer : public PCHGenerator {
 
 private:
   PrecompilePreambleAction &Action;
-  std::unique_ptr Out;
 };
 
 std::unique_ptr
@@ -316,21 +314,18 @@ 
PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
   if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
 return nullptr;
 
-  std::unique_ptr OS;
-  if (InMemStorage) {
-OS = std::make_unique(*InMemStorage);
-  } else {
-std::string OutputFile;
-OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
+  if (WritePCHFile) {
+std::string OutputFile; // unused
+FileOS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
+if (!FileOS)
+  return nullptr;
   }
-  if (!OS)
-return nullptr;
 
   if (!CI.getFrontendOpts().RelocatablePCH)
 Sysroot.clear();
 
   return std::make_unique(
-  *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, 
std::move(OS));
+  *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, Buffer);
 }
 
 template  bool moveOnNoError(llvm::ErrorOr Val, T &Output) {
@@ -356,9 +351,9 @@ class PrecompiledPreamble::PCHStorage {
 S->File = std::move(File);
 return S;
   }
-  static std::unique_ptr inMemory() {
+  static std::unique_ptr inMemory(std::shared_ptr Buf) {
 std::unique_ptr S(new PCHStorage());
-S-

[PATCH] D124180: [Frontend] avoid copy of PCH data when PrecompiledPreamble stores it in memory

2022-04-21 Thread Sam McCall 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 rG6e22dac2e295: [Frontend] avoid copy of PCH data when 
PrecompiledPreamble stores it in memory (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D124180?vs=424219&id=424249#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124180

Files:
  clang/lib/Frontend/PrecompiledPreamble.cpp

Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -234,9 +234,10 @@
 
 class PrecompilePreambleAction : public ASTFrontendAction {
 public:
-  PrecompilePreambleAction(std::string *InMemStorage,
+  PrecompilePreambleAction(std::shared_ptr Buffer, bool WritePCHFile,
PreambleCallbacks &Callbacks)
-  : InMemStorage(InMemStorage), Callbacks(Callbacks) {}
+  : Buffer(std::move(Buffer)), WritePCHFile(WritePCHFile),
+Callbacks(Callbacks) {}
 
   std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
  StringRef InFile) override;
@@ -244,6 +245,12 @@
   bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
 
   void setEmittedPreamblePCH(ASTWriter &Writer) {
+if (FileOS) {
+  *FileOS << Buffer->Data;
+  // Make sure it hits disk now.
+  FileOS->flush();
+}
+
 this->HasEmittedPreamblePCH = true;
 Callbacks.AfterPCHEmitted(Writer);
   }
@@ -262,7 +269,9 @@
   friend class PrecompilePreambleConsumer;
 
   bool HasEmittedPreamblePCH = false;
-  std::string *InMemStorage;
+  std::shared_ptr Buffer;
+  bool WritePCHFile; // otherwise the PCH is written into the PCHBuffer only.
+  std::unique_ptr FileOS; // null if in-memory
   PreambleCallbacks &Callbacks;
 };
 
@@ -272,12 +281,11 @@
  const Preprocessor &PP,
  InMemoryModuleCache &ModuleCache,
  StringRef isysroot,
- std::unique_ptr Out)
-  : PCHGenerator(PP, ModuleCache, "", isysroot,
- std::make_shared(),
+ std::shared_ptr Buffer)
+  : PCHGenerator(PP, ModuleCache, "", isysroot, std::move(Buffer),
  ArrayRef>(),
  /*AllowASTWithErrors=*/true),
-Action(Action), Out(std::move(Out)) {}
+Action(Action) {}
 
   bool HandleTopLevelDecl(DeclGroupRef DG) override {
 Action.Callbacks.HandleTopLevelDecl(DG);
@@ -288,15 +296,6 @@
 PCHGenerator::HandleTranslationUnit(Ctx);
 if (!hasEmittedPCH())
   return;
-
-// Write the generated bitstream to "Out".
-*Out << getPCH();
-// Make sure it hits disk now.
-Out->flush();
-// Free the buffer.
-llvm::SmallVector Empty;
-getPCH() = std::move(Empty);
-
 Action.setEmittedPreamblePCH(getWriter());
   }
 
@@ -306,7 +305,6 @@
 
 private:
   PrecompilePreambleAction &Action;
-  std::unique_ptr Out;
 };
 
 std::unique_ptr
@@ -316,21 +314,18 @@
   if (!GeneratePCHAction::ComputeASTConsumerArguments(CI, Sysroot))
 return nullptr;
 
-  std::unique_ptr OS;
-  if (InMemStorage) {
-OS = std::make_unique(*InMemStorage);
-  } else {
-std::string OutputFile;
-OS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
+  if (WritePCHFile) {
+std::string OutputFile; // unused
+FileOS = GeneratePCHAction::CreateOutputFile(CI, InFile, OutputFile);
+if (!FileOS)
+  return nullptr;
   }
-  if (!OS)
-return nullptr;
 
   if (!CI.getFrontendOpts().RelocatablePCH)
 Sysroot.clear();
 
   return std::make_unique(
-  *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, std::move(OS));
+  *this, CI.getPreprocessor(), CI.getModuleCache(), Sysroot, Buffer);
 }
 
 template  bool moveOnNoError(llvm::ErrorOr Val, T &Output) {
@@ -356,9 +351,9 @@
 S->File = std::move(File);
 return S;
   }
-  static std::unique_ptr inMemory() {
+  static std::unique_ptr inMemory(std::shared_ptr Buf) {
 std::unique_ptr S(new PCHStorage());
-S->Memory.emplace();
+S->Memory = std::move(Buf);
 return S;
   }
 
@@ -376,11 +371,7 @@
   }
   llvm::StringRef memoryContents() const {
 assert(getKind() == Kind::InMemory);
-return *Memory;
-  }
-  std::string &memoryBufferForWrite() {
-assert(getKind() == Kind::InMemory);
-return *Memory;
+return StringRef(Memory->Data.data(), Memory->Data.size());
   }
 
 private:
@@ -388,7 +379,7 @@
   PCHStorage(const PCHStorage &) = delete;
   PCHStorage &operator=(const PCHStorage &) = delete;
 
-  llvm::Optional Memory;
+  std::shared_ptr Memory;
   std::unique_ptr File;
 };
 
@@ -411,9 +402,10 @@
   PreprocessorOptions &PreprocessorOpts =
   PreambleInv

[clang] 1283ccb - Support z16 processor name

2022-04-21 Thread Ulrich Weigand via cfe-commits

Author: Ulrich Weigand
Date: 2022-04-21T19:58:22+02:00
New Revision: 1283ccb610feef4f2e0edf22f66a705155a0e0c7

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

LOG: Support z16 processor name

The recently announced IBM z16 processor implements the architecture
already supported as "arch14" in LLVM.  This patch adds support for
"z16" as an alternate architecture name for arch14.

Added: 
llvm/test/MC/Disassembler/SystemZ/insns-z16.txt
llvm/test/MC/SystemZ/insn-bad-z16.s
llvm/test/MC/SystemZ/insn-good-z16.s

Modified: 
clang/lib/Basic/Targets/SystemZ.cpp
clang/test/CodeGen/SystemZ/builtins-systemz-vector4.c
clang/test/CodeGen/SystemZ/builtins-systemz-zvector4-error.c
clang/test/CodeGen/SystemZ/builtins-systemz-zvector4.c
clang/test/CodeGen/SystemZ/systemz-abi-vector.c
clang/test/CodeGen/SystemZ/systemz-abi.c
clang/test/Driver/systemz-march.c
clang/test/Misc/target-invalid-cpu-note.c
clang/test/Preprocessor/predefined-arch-macros.c
llvm/lib/Support/Host.cpp
llvm/lib/Target/SystemZ/SystemZProcessors.td
llvm/test/CodeGen/SystemZ/vec-intrinsics-04.ll
llvm/unittests/Support/Host.cpp

Removed: 
llvm/test/MC/Disassembler/SystemZ/insns-arch14.txt
llvm/test/MC/SystemZ/insn-bad-arch14.s
llvm/test/MC/SystemZ/insn-good-arch14.s



diff  --git a/clang/lib/Basic/Targets/SystemZ.cpp 
b/clang/lib/Basic/Targets/SystemZ.cpp
index 3af9216315132..84874b58ba68c 100644
--- a/clang/lib/Basic/Targets/SystemZ.cpp
+++ b/clang/lib/Basic/Targets/SystemZ.cpp
@@ -104,7 +104,7 @@ static constexpr ISANameRevision ISARevisions[] = {
   {{"arch11"}, 11}, {{"z13"}, 11},
   {{"arch12"}, 12}, {{"z14"}, 12},
   {{"arch13"}, 13}, {{"z15"}, 13},
-  {{"arch14"}, 14}
+  {{"arch14"}, 14}, {{"z16"}, 14},
 };
 
 int SystemZTargetInfo::getISARevision(StringRef Name) const {

diff  --git a/clang/test/CodeGen/SystemZ/builtins-systemz-vector4.c 
b/clang/test/CodeGen/SystemZ/builtins-systemz-vector4.c
index b0cd994904134..c5ce47cea2ea8 100644
--- a/clang/test/CodeGen/SystemZ/builtins-systemz-vector4.c
+++ b/clang/test/CodeGen/SystemZ/builtins-systemz-vector4.c
@@ -1,5 +1,5 @@
 // REQUIRES: systemz-registered-target
-// RUN: %clang_cc1 -target-cpu arch14 -triple s390x-ibm-linux 
-flax-vector-conversions=none \
+// RUN: %clang_cc1 -target-cpu z16 -triple s390x-ibm-linux 
-flax-vector-conversions=none \
 // RUN: -Wall -Wno-unused -Werror -emit-llvm %s -o - | FileCheck %s
 
 typedef __attribute__((vector_size(16))) signed char vec_schar;

diff  --git a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector4-error.c 
b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector4-error.c
index a893e77acbf60..df547cb99f24b 100644
--- a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector4-error.c
+++ b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector4-error.c
@@ -1,5 +1,5 @@
 // REQUIRES: systemz-registered-target
-// RUN: %clang_cc1 -target-cpu arch14 -triple s390x-linux-gnu \
+// RUN: %clang_cc1 -target-cpu z16 -triple s390x-linux-gnu \
 // RUN: -fzvector -flax-vector-conversions=none \
 // RUN: -Wall -Wno-unused -Werror -fsyntax-only -verify %s
 

diff  --git a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector4.c 
b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector4.c
index 602886c17d198..adc55927ce366 100644
--- a/clang/test/CodeGen/SystemZ/builtins-systemz-zvector4.c
+++ b/clang/test/CodeGen/SystemZ/builtins-systemz-zvector4.c
@@ -1,8 +1,8 @@
 // REQUIRES: systemz-registered-target
-// RUN: %clang_cc1 -target-cpu arch14 -triple s390x-linux-gnu \
+// RUN: %clang_cc1 -target-cpu z16 -triple s390x-linux-gnu \
 // RUN: -O2 -fzvector -flax-vector-conversions=none \
 // RUN: -Wall -Wno-unused -Werror -emit-llvm %s -o - | FileCheck %s
-// RUN: %clang_cc1 -target-cpu arch14 -triple s390x-linux-gnu \
+// RUN: %clang_cc1 -target-cpu z16 -triple s390x-linux-gnu \
 // RUN: -O2 -fzvector -flax-vector-conversions=none \
 // RUN: -Wall -Wno-unused -Werror -S %s -o - | FileCheck %s 
--check-prefix=CHECK-ASM
 

diff  --git a/clang/test/CodeGen/SystemZ/systemz-abi-vector.c 
b/clang/test/CodeGen/SystemZ/systemz-abi-vector.c
index 4a4f03c813463..7817249da757b 100644
--- a/clang/test/CodeGen/SystemZ/systemz-abi-vector.c
+++ b/clang/test/CodeGen/SystemZ/systemz-abi-vector.c
@@ -14,6 +14,8 @@
 // RUN:   -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
 // RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple 
s390x-linux-gnu -target-cpu arch13 \
 // RUN:   -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
+// RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis -triple 
s390x-linux-gnu -target-cpu z16 \
+// RUN:   -emit-llvm -o - %s | FileCheck --check-prefix=CHECK-VECTOR %s
 // RUN: %clang_cc1 -no-opaque-pointers -no-enable-noundef-analysis

[PATCH] D122983: [C11/C2x] Change the behavior of the implicit function declaration warning

2022-04-21 Thread Nemanja Ivanovic via Phabricator via cfe-commits
nemanjai added a comment.

In D122983#3465122 , @aaron.ballman 
wrote:

> In D122983#3465099 , @nemanjai 
> wrote:
>
>> @daltenty Can you please run this with the same config as the bot on one of 
>> our AIX machines but be sure to pass `-i` if it's `make` or `-k 0` if it's 
>> `ninja`?
>
> That would be *awesome*! I have to take off for a few hours, but I'm happy to 
> fix all of the issues you spot in one go when I get back in a bit. Thank you!

Actually, I had a build ready on AIX and ran it. Looks like just 2 more:

  test-suite :: 
MultiSource/Benchmarks/MiBench/network-patricia/network-patricia.test
  test-suite :: MultiSource/Benchmarks/nbench/nbench.test


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D122983

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


[PATCH] D123498: [clang] Adding Platform/Architecture Specific Resource Header Installation Targets

2022-04-21 Thread Shubham Sandeep Rastogi via Phabricator via cfe-commits
rastogishubham added a comment.

Hi Qiongsi

Thanks for the response!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123498

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


[PATCH] D124180: [Frontend] avoid copy of PCH data when PrecompiledPreamble stores it in memory

2022-04-21 Thread Nico Weber via Phabricator via cfe-commits
thakis added subscribers: yln, thakis.
thakis added a comment.

I think this might've broken check-clangd: 
http://45.33.8.238/linux/74320/step_9.txt

The output isn't very useful though, I'm guessing @yln's recent gtest runner 
change it's not getting printed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124180

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


[PATCH] D124180: [Frontend] avoid copy of PCH data when PrecompiledPreamble stores it in memory

2022-04-21 Thread Nico Weber via Phabricator via cfe-commits
thakis added a subscriber: ychen.
thakis added a comment.

Sorry, @ychen, not @yln (D122251 )


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D124180

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


  1   2   3   >