[clang] 35886dc - [clang] Remove an unintended statement, NFC

2024-04-04 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2024-04-04T09:58:43+02:00
New Revision: 35886dc63a2d024e20c10d2e1cb3f5fa5d9f72cc

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

LOG: [clang] Remove an unintended statement, NFC

Added: 


Modified: 
clang/lib/Sema/SemaTemplate.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index a2b8cc14ca764f..d3def13f495d2b 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2711,7 +2711,6 @@ SmallVector 
TemplateParamsReferencedInTemplateArgumentList(
 : TemplateParams(TemplateParams.begin(), TemplateParams.end()) {}
 
 bool VisitTemplateTypeParmType(TemplateTypeParmType *TTP) {
-  TTP->getIndex();
   MarkAppeared(TTP->getDecl());
   return true;
 }



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


[clang-tools-extra] 550e09d - [clangd][NFC] Delete dead code

2024-04-04 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2024-04-04T10:01:13+02:00
New Revision: 550e09db1ad6e8f28546fa0c24b5582e57e210c4

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

LOG: [clangd][NFC] Delete dead code

Added: 


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

Removed: 




diff  --git a/clang-tools-extra/clangd/IncludeCleaner.h 
b/clang-tools-extra/clangd/IncludeCleaner.h
index 387763de340767..624e2116be7da3 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.h
+++ b/clang-tools-extra/clangd/IncludeCleaner.h
@@ -62,15 +62,6 @@ issueIncludeCleanerDiagnostics(ParsedAST &AST, 
llvm::StringRef Code,
const ThreadsafeFS &TFS,
HeaderFilter IgnoreHeader = {});
 
-/// Affects whether standard library includes should be considered for
-/// removal. This is off by default for now due to implementation limitations:
-/// - macros are not tracked
-/// - symbol names without a unique associated header are not tracked
-/// - references to std-namespaced C types are not properly tracked:
-///   instead of std::size_t ->  we see ::size_t -> 
-/// FIXME: remove this hack once the implementation is good enough.
-void setIncludeCleanerAnalyzesStdlib(bool B);
-
 /// Converts the clangd include representation to include-cleaner
 /// include representation.
 include_cleaner::Includes convertIncludes(const ParsedAST &);



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


[libclc] 61efea7 - [libclc] Fix a couple of issues preventing in-tree builds (#87505)

2024-04-04 Thread via cfe-commits

Author: Fraser Cormack
Date: 2024-04-04T10:12:33+01:00
New Revision: 61efea7142e904e6492e1ce0566ec23d9d221c1e

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

LOG: [libclc] Fix a couple of issues preventing in-tree builds (#87505)

libclc is mentioned in the list of LLVM_ENABLE_PROJECTS but it isn't
actually possible to build it in-tree for various reasons. Users
currently have to build it via LLVM_ENABLE_EXTERNAL_PROJECTS, which
isn't very well documented.

We can't properly build in-tree because the current system needs to
"see" clang and other tools at CMake configuration time. The general
idea is that we could fix this in the future by moving the compilation
and linking of bitcode libraries to custom commands, which would remove
the dependency on CMake configuration and would allow us to build libclc
after clang and other tools are built in-tree. Since that's a bigger
change, it is being left for later.

Note that with this commit it's *still* not possible to properly build
in-tree - this commit just fixes a few little things that are in the
way. We are now able to build in-tree in the sense that it can be built
as a regular LLVM sub-project, but the tools it uses to compile the
libraries are still picked up from a pre-existing installation of LLVM,
and not from tools built during the same build as libclc.

The things fixed by this commit include:

* Its use of CMAKE_SOURCE_DIR (i.e., assuming it was the top-level
project)
* These have been converted to PROJECT_SOURCE_DIR - should have no
consequences for out-of-tree builds.
* Its prepare_builtins tool insisting on linking against the dynamic
LLVM.so.
* This has been turned from an "llvm executable" into an "llvm utility"
which links against the static libraries.
  * It was also missing a link component for the IRReader library.
* Assuming an output path for its builtin libraries (dependent on the
working directory)
* This has been changed to query CMake for the library target's output
file.
* The spirv-mesa3d and spirv64-mesa3d targets were enabled by default
(or when asking to build 'all' libclc targets), when they require
llvm-spirv as an external dependency.
* They are now only built when the user explicitly asks for them, or
when llvm-spirv is available and the user asks for 'all'.

Added: 


Modified: 
libclc/CMakeLists.txt

Removed: 




diff  --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index 9236f09d366782..2d000cf5cad8c4 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -20,21 +20,6 @@ set_property(DIRECTORY APPEND PROPERTY 
CMAKE_CONFIGURE_DEPENDS
   spirv64/lib/SOURCES
 )
 
-# List of all targets
-set( LIBCLC_TARGETS_ALL
-  amdgcn--
-  amdgcn--amdhsa
-  clspv--
-  clspv64--
-  r600--
-  nvptx--
-  nvptx64--
-  nvptx--nvidiacl
-  nvptx64--nvidiacl
-  spirv-mesa3d-
-  spirv64-mesa3d-
-)
-
 set( LIBCLC_MIN_LLVM "3.9.0" )
 
 set( LIBCLC_TARGETS_TO_BUILD "all"
@@ -51,15 +36,6 @@ if( ${LLVM_PACKAGE_VERSION} VERSION_LESS ${LIBCLC_MIN_LLVM} )
   message( FATAL_ERROR "libclc needs at least LLVM ${LIBCLC_MIN_LLVM}" )
 endif()
 
-# mesa3d environment is only available since LLVM 4.0
-if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "3.9.0" )
-  set( LIBCLC_TARGETS_ALL ${LIBCLC_TARGETS_ALL} amdgcn-mesa-mesa3d )
-endif()
-
-if( LIBCLC_TARGETS_TO_BUILD STREQUAL "all" )
-  set( LIBCLC_TARGETS_TO_BUILD ${LIBCLC_TARGETS_ALL} )
-endif()
-
 find_program( LLVM_CLANG clang PATHS ${LLVM_TOOLS_BINARY_DIR} NO_DEFAULT_PATH )
 find_program( LLVM_AS llvm-as PATHS ${LLVM_TOOLS_BINARY_DIR} NO_DEFAULT_PATH )
 find_program( LLVM_LINK llvm-link PATHS ${LLVM_TOOLS_BINARY_DIR} 
NO_DEFAULT_PATH )
@@ -76,15 +52,45 @@ if( NOT LLVM_CLANG OR NOT LLVM_OPT OR NOT LLVM_AS OR NOT 
LLVM_LINK )
   message( FATAL_ERROR "libclc toolchain incomplete!" )
 endif()
 
+# List of all targets. Note that some are added dynamically below.
+set( LIBCLC_TARGETS_ALL
+  amdgcn--
+  amdgcn--amdhsa
+  clspv--
+  clspv64--
+  r600--
+  nvptx--
+  nvptx64--
+  nvptx--nvidiacl
+  nvptx64--nvidiacl
+)
+
+# mesa3d environment is only available since LLVM 4.0
+if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "3.9.0" )
+  list( APPEND LIBCLC_TARGETS_ALL amdgcn-mesa-mesa3d )
+endif()
+
+# spirv-mesa3d and spirv64-mesa3d targets can only be built with the (optional)
+# llvm-spirv external tool.
+if( LLVM_SPIRV )
+  list( APPEND LIBCLC_TARGETS_ALL  spirv-mesa3d- spirv64-mesa3d- )
+endif()
+
+if( LIBCLC_TARGETS_TO_BUILD STREQUAL "all" )
+  set( LIBCLC_TARGETS_TO_BUILD ${LIBCLC_TARGETS_ALL} )
+endif()
+
 list( SORT LIBCLC_TARGETS_TO_BUILD )
 
+# Verify that the user hasn't requested mesa3d targets without an available
+# llvm-spirv tool.
 if( "spirv-mesa3d-" IN_LIST LIBCLC_TARGETS_TO_BUILD OR "spirv64-mesa3d-" 
IN_LIST LIBCLC_TARGETS_TO_BUILD )
   if( NOT LLVM_SPIRV )

[clang] 7a8cf95 - AArch64-Darwin: allow -mcmodel=large with (default) PIC

2024-04-04 Thread Tim Northover via cfe-commits

Author: Tim Northover
Date: 2024-04-04T10:25:30+01:00
New Revision: 7a8cf951b3bdc60feac412200ab9661e009d44ae

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

LOG: AArch64-Darwin: allow -mcmodel=large with (default) PIC

Darwin targets implement -mcmodel=large by forcing all global accesses to use
the GOT, instead of the ELF movz/movk sequence. That means it's compatible with
PIC so the Clang driver shouldn't reject the option.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/mcmodel.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index b7ec7e0a60977b..766a9b91e3c0ad 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5882,7 +5882,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   CM = "large";
 if (Triple.isAArch64(64)) {
   Ok = CM == "tiny" || CM == "small" || CM == "large";
-  if (CM == "large" && RelocationModel != llvm::Reloc::Static)
+  if (CM == "large" && !Triple.isOSBinFormatMachO() &&
+  RelocationModel != llvm::Reloc::Static)
 D.Diag(diag::err_drv_argument_only_allowed_with)
 << A->getAsString(Args) << "-fno-pic";
 } else if (Triple.isLoongArch()) {

diff  --git a/clang/test/Driver/mcmodel.c b/clang/test/Driver/mcmodel.c
index 1eb6ae16ff472d..9681c32579d71e 100644
--- a/clang/test/Driver/mcmodel.c
+++ b/clang/test/Driver/mcmodel.c
@@ -11,6 +11,7 @@
 // RUN: FileCheck --check-prefix=AIX-MCMEDIUM-OVERRIDE %s < %t.log
 // RUN: not %clang -### -c -mcmodel=lager %s 2>&1 | FileCheck 
--check-prefix=INVALID %s
 // RUN: %clang --target=aarch64 -### -S -mcmodel=large -fno-pic %s 2>&1 | 
FileCheck --check-prefix=LARGE %s
+// RUN: %clang --target=aarch64-apple-macosx -### -S -mcmodel=large %s 2>&1 | 
FileCheck --check-prefix=LARGE %s
 // RUN: not %clang --target=aarch64 -### -S -mcmodel=large -fpic %s 2>&1 | 
FileCheck --check-prefix=AARCH64-PIC-LARGE %s
 // RUN: not %clang -### -c --target=aarch64 -mcmodel=medium %s 2>&1 | 
FileCheck --check-prefix=ERR-MEDIUM %s
 // RUN: not %clang -### -c --target=aarch64 -mcmodel=kernel %s 2>&1 | 
FileCheck --check-prefix=ERR-KERNEL %s



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


[clang] cbdc86e - [clang-repl] Add call to 'InitializeAllAsmParsers' (#86727)

2024-04-04 Thread via cfe-commits

Author: Andrew V. Teylu
Date: 2024-04-04T18:10:23+08:00
New Revision: cbdc86e46c3824dda152db2bd0b9fdb3872ddf87

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

LOG: [clang-repl] Add call to 'InitializeAllAsmParsers' (#86727)

This PR fixes the following issue when working with `clang-repl`:

```
fatal error: error in backend: Inline asm not supported by this streamer 
because we don't have an asm parser for this target
```

When working with the following input (named "unit.cpp"):

```cpp
__asm(".globl _ZSt21ios_base_library_initv");
int x;
```

and then in `clang-repl`:

```
#include "unit.cpp"
x = 10;
```

Signed-off-by: Andrew V. Teylu 

Added: 
clang/test/Interpreter/inline-asm.cpp

Modified: 
clang/tools/clang-repl/ClangRepl.cpp

Removed: 




diff  --git a/clang/test/Interpreter/inline-asm.cpp 
b/clang/test/Interpreter/inline-asm.cpp
new file mode 100644
index 00..f94f14df72f80e
--- /dev/null
+++ b/clang/test/Interpreter/inline-asm.cpp
@@ -0,0 +1,17 @@
+// REQUIRES: host-supports-jit, x86_64-linux
+// UNSUPPORTED: system-aix
+//
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+//
+// RUN: cat %t/inline-asm.txt | clang-repl -Xcc="-I%t"
+
+//--- inline-asm.cpp
+__asm(".globl _ZSt21ios_base_library_initv");
+int x;
+
+//--- inline-asm.txt
+#include "inline-asm.cpp"
+x = 10;
+%quit

diff  --git a/clang/tools/clang-repl/ClangRepl.cpp 
b/clang/tools/clang-repl/ClangRepl.cpp
index 5bad8145324d06..aecf61b97fc719 100644
--- a/clang/tools/clang-repl/ClangRepl.cpp
+++ b/clang/tools/clang-repl/ClangRepl.cpp
@@ -152,6 +152,7 @@ int main(int argc, const char **argv) {
   llvm::InitializeAllTargets();
   llvm::InitializeAllTargetMCs();
   llvm::InitializeAllAsmPrinters();
+  llvm::InitializeAllAsmParsers();
 
   if (OptHostSupportsJit) {
 auto J = llvm::orc::LLJITBuilder().create();



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


[clang] bf2d785 - Fix bug in the type promotion for complex division in strict FP mode. (#87500)

2024-04-04 Thread via cfe-commits

Author: Zahira Ammarguellat
Date: 2024-04-04T06:25:41-04:00
New Revision: bf2d7858e5998bed28d437973588e0294bd54bcf

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

LOG: Fix bug in the type promotion for complex division in strict FP mode. 
(#87500)

Complex division on Windows with `-fcomplex-arithmetic=promoted` and
`-ffp-model=strict` is crashing. This patch fixes the issue.
See https://godbolt.org/z/15Gh7nvdM

Added: 


Modified: 
clang/lib/CodeGen/CGExprComplex.cpp
clang/test/CodeGen/cx-complex-range.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprComplex.cpp 
b/clang/lib/CodeGen/CGExprComplex.cpp
index a793b214645cb3..1facadd82f1701 100644
--- a/clang/lib/CodeGen/CGExprComplex.cpp
+++ b/clang/lib/CodeGen/CGExprComplex.cpp
@@ -319,12 +319,12 @@ class ComplexExprEmitter
 // doubles the exponent of SmallerType.LargestFiniteVal)
 if (llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 <=
 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) {
+  FPHasBeenPromoted = true;
   return CGF.getContext().getComplexType(HigherElementType);
 } else {
-  FPHasBeenPromoted = true;
   DiagnosticsEngine &Diags = CGF.CGM.getDiags();
   Diags.Report(diag::warn_next_larger_fp_type_same_size_than_fp);
-  return CGF.getContext().getComplexType(ElementType);
+  return QualType();
 }
   }
 
@@ -1037,7 +1037,7 @@ ComplexPairTy ComplexExprEmitter::EmitBinDiv(const 
BinOpInfo &Op) {
   LHSi = llvm::Constant::getNullValue(RHSi->getType());
 if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Improved ||
 (Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted &&
- FPHasBeenPromoted))
+ !FPHasBeenPromoted))
   return EmitRangeReductionDiv(LHSr, LHSi, RHSr, RHSi);
 else if (Op.FPFeatures.getComplexRange() == LangOptions::CX_Basic ||
  Op.FPFeatures.getComplexRange() == LangOptions::CX_Promoted)

diff  --git a/clang/test/CodeGen/cx-complex-range.c 
b/clang/test/CodeGen/cx-complex-range.c
index 9ec80252085b87..38f99230eea588 100644
--- a/clang/test/CodeGen/cx-complex-range.c
+++ b/clang/test/CodeGen/cx-complex-range.c
@@ -48,6 +48,15 @@
 // RUN: -ffast-math -complex-range=promoted -emit-llvm -o - %s \
 // RUN: | FileCheck %s --check-prefix=PRMTD_FAST
 
+// strict math mode
+// RUN: %clang_cc1 -triple x86_64-windows-pc -complex-range=promoted \
+// RUN: -ffp-contract=off -frounding-math -ffp-exception-behavior=strict \
+// RUN: -emit-llvm -o - %s | FileCheck %s --check-prefix=X86WINPRMTD_STRICT
+
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -complex-range=promoted \
+// RUN: -ffp-contract=off -frounding-math -ffp-exception-behavior=strict \
+// RUN: -emit-llvm -o - %s | FileCheck %s --check-prefix=PRMTD_STRICT
+
 // FULL-LABEL: define dso_local <2 x float> @divf(
 // FULL-SAME: <2 x float> noundef [[A_COERCE:%.*]], <2 x float> noundef 
[[B_COERCE:%.*]]) #[[ATTR0:[0-9]+]] {
 // FULL-NEXT:  entry:
@@ -504,6 +513,86 @@
 // PRMTD_FAST-NEXT:[[TMP11:%.*]] = load <2 x float>, ptr [[RETVAL]], align 
4
 // PRMTD_FAST-NEXT:ret <2 x float> [[TMP11]]
 //
+// X86WINPRMTD_STRICT-LABEL: define dso_local i64 @divf(
+// X86WINPRMTD_STRICT-SAME: i64 noundef [[A_COERCE:%.*]], i64 noundef 
[[B_COERCE:%.*]]) #[[ATTR0:[0-9]+]] {
+// X86WINPRMTD_STRICT-NEXT:  entry:
+// X86WINPRMTD_STRICT-NEXT:[[RETVAL:%.*]] = alloca { float, float }, align 
4
+// X86WINPRMTD_STRICT-NEXT:[[A:%.*]] = alloca { float, float }, align 4
+// X86WINPRMTD_STRICT-NEXT:[[B:%.*]] = alloca { float, float }, align 4
+// X86WINPRMTD_STRICT-NEXT:store i64 [[A_COERCE]], ptr [[A]], align 4
+// X86WINPRMTD_STRICT-NEXT:store i64 [[B_COERCE]], ptr [[B]], align 4
+// X86WINPRMTD_STRICT-NEXT:[[A_REALP:%.*]] = getelementptr inbounds { 
float, float }, ptr [[A]], i32 0, i32 0
+// X86WINPRMTD_STRICT-NEXT:[[A_REAL:%.*]] = load float, ptr [[A_REALP]], 
align 4
+// X86WINPRMTD_STRICT-NEXT:[[A_IMAGP:%.*]] = getelementptr inbounds { 
float, float }, ptr [[A]], i32 0, i32 1
+// X86WINPRMTD_STRICT-NEXT:[[A_IMAG:%.*]] = load float, ptr [[A_IMAGP]], 
align 4
+// X86WINPRMTD_STRICT-NEXT:[[EXT:%.*]] = call double 
@llvm.experimental.constrained.fpext.f64.f32(float [[A_REAL]], metadata 
!"fpexcept.strict") #[[ATTR3:[0-9]+]]
+// X86WINPRMTD_STRICT-NEXT:[[EXT1:%.*]] = call double 
@llvm.experimental.constrained.fpext.f64.f32(float [[A_IMAG]], metadata 
!"fpexcept.strict") #[[ATTR3]]
+// X86WINPRMTD_STRICT-NEXT:[[B_REALP:%.*]] = getelementptr inbounds { 
float, float }, ptr [[B]], i32 0, i32 0
+// X86WINPRMTD_STRICT-NEXT:[[B_REAL:%.*]] = load float, ptr [[B_REALP]], 
align 4
+// X86WINPRMTD_STRICT-NEXT:[[B_IMAGP:%.*]] = getelementptr inbounds { 
float, float }, ptr 

[clang] bbd259a - [clang][dataflow] Refactor `widen` API to be explicit about change effect. (#87233)

2024-04-04 Thread via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2024-04-04T08:39:51-04:00
New Revision: bbd259af0a4cc438dd02d5ee632cb2dc1def1f6a

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

LOG: [clang][dataflow] Refactor `widen` API to be explicit about change effect. 
(#87233)

The previous API relied on pointer equality of inputs and outputs to
signal whether a change occured. This was too subtle and led to bugs in
practice. It was also very limiting: the override could not return an 
equivalent (but
not identical) value.

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/include/clang/Analysis/FlowSensitive/DataflowLattice.h
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index c30bccd06674a4..9a65f76cdf56bc 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -43,6 +43,15 @@ enum class ComparisonResult {
   Unknown,
 };
 
+/// The result of a `widen` operation.
+struct WidenResult {
+  /// Non-null pointer to a potentially widened version of the input value.
+  Value *V;
+  /// Whether `V` represents a "change" (that is, a 
diff erent value) with
+  /// respect to the previous value in the sequence.
+  LatticeEffect Effect;
+};
+
 /// Holds the state of the program (store and heap) at a given program point.
 ///
 /// WARNING: Symbolic values that are created by the environment for static
@@ -104,14 +113,17 @@ class Environment {
 /// serve as a comparison operation, by indicating whether the widened 
value
 /// is equivalent to the previous value.
 ///
-/// Returns either:
-///
-///   `nullptr`, if this value is not of interest to the model, or
-///
-///   `&Prev`, if the widened value is equivalent to `Prev`, or
-///
-///   A non-null value that approximates `Current`. `Prev` is available to
-///   inform the chosen approximation.
+/// Returns one of the folowing:
+/// *  `std::nullopt`, if this value is not of interest to the
+/// model.
+/// *  A `WidenResult` with:
+///*  A non-null `Value *` that points either to `Current` or a widened
+///   version of `Current`. This value must be consistent with
+///   the flow condition of `CurrentEnv`. We particularly caution
+///   against using `Prev`, which is rarely consistent.
+///*  A `LatticeEffect` indicating whether the value should be
+///   considered a new value (`Changed`) or one *equivalent* (if not
+///   necessarily equal) to `Prev` (`Unchanged`).
 ///
 /// `PrevEnv` and `CurrentEnv` can be used to query child values and path
 /// condition implications of `Prev` and `Current`, respectively.
@@ -122,17 +134,19 @@ class Environment {
 ///
 ///  `Prev` and `Current` must be assigned to the same storage location in
 ///  `PrevEnv` and `CurrentEnv`, respectively.
-virtual Value *widen(QualType Type, Value &Prev, const Environment 
&PrevEnv,
- Value &Current, Environment &CurrentEnv) {
+virtual std::optional widen(QualType Type, Value &Prev,
+ const Environment &PrevEnv,
+ Value &Current,
+ Environment &CurrentEnv) {
   // The default implementation reduces to just comparison, since 
comparison
   // is required by the API, even if no widening is performed.
   switch (compare(Type, Prev, PrevEnv, Current, CurrentEnv)) {
-case ComparisonResult::Same:
-  return &Prev;
-case ComparisonResult::Different:
-  return &Current;
-case ComparisonResult::Unknown:
-  return nullptr;
+  case ComparisonResult::Unknown:
+return std::nullopt;
+  case ComparisonResult::Same:
+return WidenResult{&Current, LatticeEffect::Unchanged};
+  case ComparisonResult::Different:
+return WidenResult{&Current, LatticeEffect::Changed};
   }
   llvm_unreachable("all cases in switch covered");
 }
@@ -236,8 +250,8 @@ class Environment {
   ///
   ///  `PrevEnv` must be the immediate previous version of the environment.
   ///  `PrevEnv` and `this` must use the same `DataflowAnalysisContext`.
-  LatticeJoinEffect widen(const Environment &PrevEnv,
-  Environment::ValueModel &Model);
+  LatticeEffect widen(const Environment &PrevEnv,
+  Env

[clang] 417a068 - [clang][CGBlocks] Remove unused variable "refType" [NFC]

2024-04-04 Thread Mikael Holmen via cfe-commits

Author: Mikael Holmen
Date: 2024-04-04T15:07:36+02:00
New Revision: 417a068b63c01d79511fe3732dd52377b05d06fc

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

LOG: [clang][CGBlocks] Remove unused variable "refType" [NFC]

Without the change gcc warned like
 ../../clang/lib/CodeGen/CGBlocks.cpp:965:21: warning: unused variable 
'refType' [-Wunused-variable]
   965 | } else if (auto refType = type->getAs()) {
   | ^~~

Added: 


Modified: 
clang/lib/CodeGen/CGBlocks.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGBlocks.cpp b/clang/lib/CodeGen/CGBlocks.cpp
index a01f2c7c979840..47f063b5501cc6 100644
--- a/clang/lib/CodeGen/CGBlocks.cpp
+++ b/clang/lib/CodeGen/CGBlocks.cpp
@@ -962,7 +962,7 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const 
CGBlockInfo &blockInfo) {
   }
 
 // If it's a reference variable, copy the reference into the block field.
-} else if (auto refType = type->getAs()) {
+} else if (type->getAs()) {
   Builder.CreateStore(src.emitRawPointer(*this), blockField);
 
   // If type is const-qualified, copy the value into the block field.



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


[clang] 1bce411 - MIPS/Clang: Set HasUnalignedAccess false if +strict-align (#87257)

2024-04-04 Thread via cfe-commits

Author: YunQiang Su
Date: 2024-04-04T21:51:25+08:00
New Revision: 1bce411073a1deafef998d0fe9e3ae74c4cef1e5

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

LOG: MIPS/Clang: Set HasUnalignedAccess false if +strict-align (#87257)

TargetInfo has HasUnalignedAccess support now. For MIPSr6, we should set
it according strict-align.

For pre-R6, we always set strict-align and HasUnalignedAccess to false.

Added: 


Modified: 
clang/lib/Basic/Targets/Mips.h

Removed: 




diff  --git a/clang/lib/Basic/Targets/Mips.h b/clang/lib/Basic/Targets/Mips.h
index c9dcf434c93b0b..0d6e4b4d080890 100644
--- a/clang/lib/Basic/Targets/Mips.h
+++ b/clang/lib/Basic/Targets/Mips.h
@@ -318,6 +318,7 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 FPMode = isFP64Default() ? FP64 : FPXX;
 NoOddSpreg = false;
 bool OddSpregGiven = false;
+bool StrictAlign = false;
 
 for (const auto &Feature : Features) {
   if (Feature == "+single-float")
@@ -330,6 +331,10 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 IsMicromips = true;
   else if (Feature == "+mips32r6" || Feature == "+mips64r6")
 HasUnalignedAccess = true;
+  // We cannot be sure that the order of strict-align vs mips32r6.
+  // Thus we need an extra variable here.
+  else if (Feature == "+strict-align")
+StrictAlign = true;
   else if (Feature == "+dsp")
 DspRev = std::max(DspRev, DSP1);
   else if (Feature == "+dspr2")
@@ -368,6 +373,9 @@ class LLVM_LIBRARY_VISIBILITY MipsTargetInfo : public 
TargetInfo {
 if (FPMode == FPXX && !OddSpregGiven)
   NoOddSpreg = true;
 
+if (StrictAlign)
+  HasUnalignedAccess = false;
+
 setDataLayout();
 
 return true;



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


[clang] 110e933 - CGOpenMPRuntime.cpp - fix Wparentheses warning. NFC.

2024-04-04 Thread Simon Pilgrim via cfe-commits

Author: Simon Pilgrim
Date: 2024-04-04T14:59:00+01:00
New Revision: 110e933b7ae9150710a48b586fd3da39439079c2

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

LOG: CGOpenMPRuntime.cpp - fix Wparentheses warning. NFC.

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index bc363313dec6f8..8eb10584699fad 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -2648,9 +2648,9 @@ void CGOpenMPRuntime::emitDistributeStaticInit(
 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
   SourceLocation Loc,
   OpenMPDirectiveKind DKind) {
-  assert(DKind == OMPD_distribute || DKind == OMPD_for ||
- DKind == OMPD_sections &&
- "Expected distribute, for, or sections directive kind");
+  assert((DKind == OMPD_distribute || DKind == OMPD_for ||
+  DKind == OMPD_sections) &&
+ "Expected distribute, for, or sections directive kind");
   if (!CGF.HaveInsertPoint())
 return;
   // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);



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


[clang] 8ebf7b7 - [InstallAPI][Test] Add test for invalid verification mode (#87602)

2024-04-04 Thread via cfe-commits

Author: Cyndy Ishida
Date: 2024-04-04T07:46:55-07:00
New Revision: 8ebf7b7d7aed45889415669e0c7353f9b528161a

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

LOG: [InstallAPI][Test] Add test for invalid verification mode (#87602)

Added: 


Modified: 
clang/test/InstallAPI/driver-invalid-options.test

Removed: 




diff  --git a/clang/test/InstallAPI/driver-invalid-options.test 
b/clang/test/InstallAPI/driver-invalid-options.test
index 69f3b2d66ab8b6..0c630eacd18368 100644
--- a/clang/test/InstallAPI/driver-invalid-options.test
+++ b/clang/test/InstallAPI/driver-invalid-options.test
@@ -7,3 +7,9 @@
 // RUN: not clang-installapi -target x86_64-apple-ios-simulator  %s -o tmp.tbd 
2> %t 
 // RUN: FileCheck --check-prefix INVALID_INSTALL_NAME -input-file %t %s
 // INVALID_INSTALL_NAME: error: no install name specified: add -install_name 

+
+/// Check invalid verification mode.
+// RUN: not clang-installapi -install_name Foo -target arm64-apple-ios13 \
+// RUN: --verify-mode=Invalid -o tmp.tbd 2> %t
+// RUN: FileCheck --check-prefix INVALID_VERIFY_MODE -input-file %t %s 
+// INVALID_VERIFY_MODE: error: invalid value 'Invalid' in 
'--verify-mode=Invalid'



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


[clang] dcab42a - [TBAA] Test for tbaa.struct metadata with bitfields in big endian layout (#87617)

2024-04-04 Thread via cfe-commits

Author: Julian Nagele
Date: 2024-04-04T17:44:50+01:00
New Revision: dcab42a0f9aab1d06aadc821e64af381da744819

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

LOG: [TBAA] Test for tbaa.struct metadata with bitfields in big endian layout 
(#87617)

This test exposes what I think is invalid tbaa.struct metadata currently
generated for bitfields when using big endian layout. The regions given
by `!{i64 2, i64 4, [[META3:![0-9]+]], i64 4, i64 4 ...` are
overlapping. This issue was originally observed in
https://github.com/llvm/llvm-project/pull/86709.

Added: 
clang/test/CodeGen/tbaa-struct-bitfield-endianness.cpp

Modified: 


Removed: 




diff  --git a/clang/test/CodeGen/tbaa-struct-bitfield-endianness.cpp 
b/clang/test/CodeGen/tbaa-struct-bitfield-endianness.cpp
new file mode 100644
index 00..80884b49ddc669
--- /dev/null
+++ b/clang/test/CodeGen/tbaa-struct-bitfield-endianness.cpp
@@ -0,0 +1,39 @@
+// RUN: %clang_cc1 -triple aarch64_be-apple-darwin -emit-llvm -o - -O1 %s | \
+// RUN: FileCheck -check-prefixes=CHECK,CHECK-BE %s
+// RUN: %clang_cc1 -triple aarch64-apple-darwin -emit-llvm -o - -O1 %s | \
+// RUN: FileCheck -check-prefixes=CHECK,CHECK-LE %s
+//
+// Check that TBAA metadata for structs containing bitfields is
+// consistent between big and little endian layouts.
+//
+// FIXME: The metadata below is invalid for the big endian layout: the
+// start offset of 2 is incorrect.
+
+struct NamedBitfields {
+  int f1 : 8;
+  int f2 : 8;
+  unsigned f3 : 1;
+  unsigned f4 : 15;
+  int f5;
+  double f6;
+};
+
+// CHECK-LABEL: _Z4copyP14NamedBitfieldsS0_
+// CHECK-SAME: ptr nocapture noundef writeonly [[A1:%.*]], ptr nocapture 
noundef readonly [[A2:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:tail call void @llvm.memcpy.p0.p0.i64(ptr noundef nonnull 
align 8 dereferenceable(16) [[A1]], ptr noundef nonnull align 8 
dereferenceable(16) [[A2]], i64 16, i1 false), !tbaa.struct 
[[TBAA_STRUCT2:![0-9]+]]
+// CHECK-NEXT:ret void
+//
+void copy(NamedBitfields *a1, NamedBitfields *a2) {
+  *a1 = *a2;
+}
+
+// CHECK-BE: [[TBAA_STRUCT2]] = !{i64 2, i64 4, [[META3:![0-9]+]], i64 4, i64 
4, [[META6:![0-9]+]], i64 8, i64 8, [[META8:![0-9]+]]}
+// CHECK-LE: [[TBAA_STRUCT2]] = !{i64 0, i64 4, [[META3:![0-9]+]], i64 4, i64 
4, [[META6:![0-9]+]], i64 8, i64 8, [[META8:![0-9]+]]}
+// CHECK: [[META3]] = !{[[META4:![0-9]+]], [[META4]], i64 0}
+// CHECK: [[META4]] = !{!"omnipotent char", [[META5:![0-9]+]], i64 0}
+// CHECK: [[META5]] = !{!"Simple C++ TBAA"}
+// CHECK: [[META6]] = !{[[META7:![0-9]+]], [[META7]], i64 0}
+// CHECK: [[META7]] = !{!"int", [[META4]], i64 0}
+// CHECK: [[META8]] = !{[[META9:![0-9]+]], [[META9]], i64 0}
+// CHECK: [[META9]] = !{!"double", [[META4]], i64 0}



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


[libclc] 338ecfb - [libclc] Use VERSION_GREATER_EQUAL where appropriate. NFC

2024-04-04 Thread Fraser Cormack via cfe-commits

Author: Fraser Cormack
Date: 2024-04-04T17:56:40+01:00
New Revision: 338ecfbac351e4b211836ad73d75bbdf729e9134

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

LOG: [libclc] Use VERSION_GREATER_EQUAL where appropriate. NFC

This was added in CMake 3.7, which might explain why it wasn't used
before.

Also reformat a couple of comments.

Added: 


Modified: 
libclc/CMakeLists.txt

Removed: 




diff  --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index 2d000cf5cad8c4..21e5cac688227d 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -20,7 +20,7 @@ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
   spirv64/lib/SOURCES
 )
 
-set( LIBCLC_MIN_LLVM "3.9.0" )
+set( LIBCLC_MIN_LLVM 3.9.0 )
 
 set( LIBCLC_TARGETS_TO_BUILD "all"
 CACHE STRING "Semicolon-separated list of targets to build, or 'all'." )
@@ -32,7 +32,7 @@ include(AddLLVM)
 
 message( STATUS "libclc LLVM version: ${LLVM_PACKAGE_VERSION}" )
 
-if( ${LLVM_PACKAGE_VERSION} VERSION_LESS ${LIBCLC_MIN_LLVM} )
+if( LLVM_PACKAGE_VERSION VERSION_LESS LIBCLC_MIN_LLVM )
   message( FATAL_ERROR "libclc needs at least LLVM ${LIBCLC_MIN_LLVM}" )
 endif()
 
@@ -66,7 +66,7 @@ set( LIBCLC_TARGETS_ALL
 )
 
 # mesa3d environment is only available since LLVM 4.0
-if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "3.9.0" )
+if( LLVM_PACKAGE_VERSION VERSION_GREATER_EQUAL 4.0.0 )
   list( APPEND LIBCLC_TARGETS_ALL amdgcn-mesa-mesa3d )
 endif()
 
@@ -102,7 +102,7 @@ set( LLVM_VERSION_DEFINE 
"-DHAVE_LLVM=0x${LLVM_VERSION_MAJOR}0${LLVM_VERSION_MIN
 
 
 # LLVM 13 enables standard includes by default
-if( ${LLVM_PACKAGE_VERSION} VERSION_GREATER "12.99.99" )
+if( LLVM_PACKAGE_VERSION VERSION_GREATER_EQUAL 13.0.0 )
   set( CMAKE_LLAsm_FLAGS "${CMAKE_LLAsm_FLAGS} -cl-no-stdinc" )
   set( CMAKE_CLC_FLAGS "${CMAKE_CLC_FLAGS} -cl-no-stdinc" )
 endif()
@@ -205,7 +205,7 @@ foreach( t ${LIBCLC_TARGETS_TO_BUILD} )
 list( APPEND dirs amdgpu )
   endif()
 
-  #nvptx is special
+  # nvptx is special
   if( ${ARCH} STREQUAL nvptx OR ${ARCH} STREQUAL nvptx64 )
 set( DARCH ptx )
   else()
@@ -226,8 +226,8 @@ foreach( t ${LIBCLC_TARGETS_TO_BUILD} )
 endforeach()
   endforeach()
 
-  # Add the generated convert.cl here to prevent adding
-  # the one listed in SOURCES
+  # Add the generated convert.cl here to prevent adding the one listed in
+  # SOURCES
   if( NOT ${ARCH} STREQUAL "spirv" AND NOT ${ARCH} STREQUAL "spirv64" )
 if( NOT ENABLE_RUNTIME_SUBNORMAL AND NOT ${ARCH} STREQUAL "clspv" AND
 NOT ${ARCH} STREQUAL "clspv64" )



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


[clang] [flang] [flang][Frontend] Implement printing defined macros via -dM (PR #87627)

2024-04-04 Thread Krzysztof Parzyszek via cfe-commits

https://github.com/kparzysz updated 
https://github.com/llvm/llvm-project/pull/87627

>From f4917dcf99664442d262226cd1ce1058646d7a55 Mon Sep 17 00:00:00 2001
From: Krzysztof Parzyszek 
Date: Wed, 3 Apr 2024 17:09:24 -0500
Subject: [PATCH 1/6] [flang][Frontend] Implement printing defined macros via
 -dM

This should work the same way as in clang.
---
 clang/include/clang/Driver/Options.td |   2 +-
 clang/lib/Driver/ToolChains/Flang.cpp |   5 +-
 .../flang/Frontend/PreprocessorOptions.h  |   3 +
 flang/include/flang/Parser/parsing.h  |   5 +
 flang/lib/Frontend/CompilerInvocation.cpp |   1 +
 flang/lib/Frontend/FrontendActions.cpp|   4 +-
 flang/lib/Parser/parsing.cpp  |  18 ++-
 flang/lib/Parser/preprocessor.cpp | 128 ++
 flang/lib/Parser/preprocessor.h   |   6 +
 flang/test/Driver/driver-help-hidden.f90  |   1 +
 flang/test/Driver/driver-help.f90 |   2 +
 flang/test/Preprocessing/show-macros1.F90 |  14 ++
 flang/test/Preprocessing/show-macros2.F90 |   6 +
 flang/test/Preprocessing/show-macros3.F90 |  10 ++
 14 files changed, 196 insertions(+), 9 deletions(-)
 create mode 100644 flang/test/Preprocessing/show-macros1.F90
 create mode 100644 flang/test/Preprocessing/show-macros2.F90
 create mode 100644 flang/test/Preprocessing/show-macros3.F90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c3e90a70925b78..b1ed29cb1cbc44 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1446,7 +1446,7 @@ def dD : Flag<["-"], "dD">, Group, 
Visibility<[ClangOption, CC1Option]>
 def dI : Flag<["-"], "dI">, Group, Visibility<[ClangOption, 
CC1Option]>,
   HelpText<"Print include directives in -E mode in addition to normal output">,
   MarshallingInfoFlag>;
-def dM : Flag<["-"], "dM">, Group, Visibility<[ClangOption, 
CC1Option]>,
+def dM : Flag<["-"], "dM">, Group, Visibility<[ClangOption, 
CC1Option, FlangOption, FC1Option]>,
   HelpText<"Print macro definitions in -E mode instead of normal output">;
 def dead__strip : Flag<["-"], "dead_strip">;
 def dependency_file : Separate<["-"], "dependency-file">,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 70daa699e3a949..bfd07addfca811 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -688,7 +688,10 @@ void Flang::ConstructJob(Compilation &C, const JobAction 
&JA,
   CmdArgs.push_back(Args.MakeArgString(TripleStr));
 
   if (isa(JA)) {
-  CmdArgs.push_back("-E");
+CmdArgs.push_back("-E");
+if (Args.getLastArg(options::OPT_dM)) {
+  CmdArgs.push_back("-dM");
+}
   } else if (isa(JA) || isa(JA)) {
 if (JA.getType() == types::TY_Nothing) {
   CmdArgs.push_back("-fsyntax-only");
diff --git a/flang/include/flang/Frontend/PreprocessorOptions.h 
b/flang/include/flang/Frontend/PreprocessorOptions.h
index b2e9ac0e963b73..13a91ee9a184f8 100644
--- a/flang/include/flang/Frontend/PreprocessorOptions.h
+++ b/flang/include/flang/Frontend/PreprocessorOptions.h
@@ -56,6 +56,9 @@ struct PreprocessorOptions {
   // -fno-reformat: Emit cooked character stream as -E output
   bool noReformat{false};
 
+  // -dM: Show macro definitions with -dM -E
+  bool showMacros{false};
+
   void addMacroDef(llvm::StringRef name) {
 macros.emplace_back(std::string(name), false);
   }
diff --git a/flang/include/flang/Parser/parsing.h 
b/flang/include/flang/Parser/parsing.h
index e80d8f724ac8f4..14891c44dacafd 100644
--- a/flang/include/flang/Parser/parsing.h
+++ b/flang/include/flang/Parser/parsing.h
@@ -16,6 +16,7 @@
 #include "provenance.h"
 #include "flang/Common/Fortran-features.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 
 #include 
 #include 
@@ -23,6 +24,8 @@
 
 namespace Fortran::parser {
 
+class Preprocessor;
+
 struct Options {
   Options() {}
 
@@ -59,6 +62,7 @@ class Parsing {
   const SourceFile *Prescan(const std::string &path, Options);
   void EmitPreprocessedSource(
   llvm::raw_ostream &, bool lineDirectives = true) const;
+  void EmitPreprocessorMacros(llvm::raw_ostream &) const;
   void DumpCookedChars(llvm::raw_ostream &) const;
   void DumpProvenance(llvm::raw_ostream &) const;
   void DumpParsingLog(llvm::raw_ostream &) const;
@@ -83,6 +87,7 @@ class Parsing {
   const char *finalRestingPlace_{nullptr};
   std::optional parseTree_;
   ParsingLog log_;
+  std::unique_ptr preprocessor_;
 };
 } // namespace Fortran::parser
 #endif // FORTRAN_PARSER_PARSING_H_
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index c830c7af2462c9..8ce6ab7baf4812 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -772,6 +772,7 @@ static void 
parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
 
   opts.noReformat = args.hasA

[clang] [Headers] Don't declare unreachable() from stddef.h in C++ (PR #86748)

2024-04-04 Thread Ian Anderson via cfe-commits

ian-twilightcoder wrote:

> LGTM, though we should have a release note about the change because we've 
> been exposing the macro since Clang 17. I don't think this warrant a 
> potentially breaking change notice, though, just a regular bugfix one.

I think we weren't exposing `unreachable` in C++ at all in Clang 17, and it's 
only exposed in Clang 18 if something sets the new `__needs_unreachable`? I can 
still release note it if you think it's worth calling out.

https://github.com/llvm/llvm-project/pull/86748
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [flang] [flang][Frontend] Implement printing defined macros via -dM (PR #87627)

2024-04-04 Thread Krzysztof Parzyszek via cfe-commits


@@ -83,6 +87,7 @@ class Parsing {
   const char *finalRestingPlace_{nullptr};
   std::optional parseTree_;
   ParsingLog log_;
+  std::unique_ptr preprocessor_;

kparzysz wrote:

Done.

https://github.com/llvm/llvm-project/pull/87627
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Headers] Don't declare unreachable() from stddef.h in C++ (PR #86748)

2024-04-04 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> Is that still worth mention in the release notes do you think?

Oh duh, that's right, this requires someone to define the `__need` macro to get 
it, so no, I don't think it needs a release note. Sorry for the noise!

https://github.com/llvm/llvm-project/pull/86748
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Jon Roelofs via cfe-commits


@@ -673,6 +673,9 @@ option(LLVM_USE_OPROFILE
 option(LLVM_EXTERNALIZE_DEBUGINFO
   "Generate dSYM files and strip executables and libraries (Darwin Only)" OFF)
 
+option(LLVM_ENABLE_NO_EXPORTED_SYMBOLS

jroelofs wrote:

The double negative is confusing. Maybe invert it, and make the name 
`LLVM_ENABLE_EXPORTED_SYMBOLS`?

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [OpenACC][NFC] Add OpenACC Clause AST Nodes/infrastructure (PR #87675)

2024-04-04 Thread Erich Keane via cfe-commits


@@ -30,13 +31,23 @@ class OpenACCConstructStmt : public Stmt {
   /// the directive.
   SourceRange Range;
 
-  // TODO OPENACC: Clauses should probably be collected in this class.
+  /// The list of clauses.  This is stored here as an ArrayRef, as this is the

erichkeane wrote:

Most of this patch is just boilerplate, but THIS decision I think is the 
important one.  I could EITHER have the base clause store an 
`llvm::SmallVector` of clause pointers, OR do the trailing storage trick I'm 
doing here.  The trailing-storage seemed closest to being what OMP does, but is 
a bit extra rigamarole to make work.

https://github.com/llvm/llvm-project/pull/87675
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [OpenACC][NFC] Add OpenACC Clause AST Nodes/infrastructure (PR #87675)

2024-04-04 Thread Erich Keane via cfe-commits


@@ -30,13 +31,23 @@ class OpenACCConstructStmt : public Stmt {
   /// the directive.
   SourceRange Range;
 
-  // TODO OPENACC: Clauses should probably be collected in this class.
+  /// The list of clauses.  This is stored here as an ArrayRef, as this is the
+  /// most convienient place to access the list, however the list itself should
+  /// be stored in leaf nodes, likely in trailing-storage.
+  MutableArrayRef Clauses;
 
 protected:
   OpenACCConstructStmt(StmtClass SC, OpenACCDirectiveKind K,
SourceLocation Start, SourceLocation End)
   : Stmt(SC), Kind(K), Range(Start, End) {}
 
+  // Used only for initialization, the leaf class can initialize this to

erichkeane wrote:

This ends up being necessary because the trailing storage isn't initialized 
when we do construction, so the derived classes need to set this after this 
class is constructed (and their trailing storage base is legal to do stuff 
with).

https://github.com/llvm/llvm-project/pull/87675
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Headers] Don't declare unreachable() from stddef.h in C++ (PR #86748)

2024-04-04 Thread Ian Anderson via cfe-commits

ian-twilightcoder wrote:

> > Is that still worth mention in the release notes do you think?
> 
> Oh duh, that's right, this requires someone to define the `__need` macro to 
> get it, so no, I don't think it needs a release note. Sorry for the noise!

👍 thanks for bearing with me on this!

https://github.com/llvm/llvm-project/pull/86748
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] df69a30 - [Headers] Don't declare unreachable() from stddef.h in C++ (#86748)

2024-04-04 Thread via cfe-commits

Author: Ian Anderson
Date: 2024-04-04T13:01:49-07:00
New Revision: df69a305253f1d1b4a4066055a07101a4cc03e55

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

LOG: [Headers] Don't declare unreachable() from stddef.h in C++ (#86748)

Even if __need_unreachable is set, stddef.h should not declare
unreachable() in C++ because it conflicts with the declaration in
\.

Added: 


Modified: 
clang/lib/Headers/__stddef_unreachable.h

Removed: 




diff  --git a/clang/lib/Headers/__stddef_unreachable.h 
b/clang/lib/Headers/__stddef_unreachable.h
index 518580c92d3f5d..61df43e9732f8a 100644
--- a/clang/lib/Headers/__stddef_unreachable.h
+++ b/clang/lib/Headers/__stddef_unreachable.h
@@ -7,6 +7,8 @@
  *===---===
  */
 
+#ifndef __cplusplus
+
 /*
  * When -fbuiltin-headers-in-system-modules is set this is a non-modular header
  * and needs to behave as if it was textual.
@@ -15,3 +17,5 @@
 (__has_feature(modules) && !__building_module(_Builtin_stddef))
 #define unreachable() __builtin_unreachable()
 #endif
+
+#endif



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


[clang] [Headers] Don't declare unreachable() from stddef.h in C++ (PR #86748)

2024-04-04 Thread Ian Anderson via cfe-commits

https://github.com/ian-twilightcoder closed 
https://github.com/llvm/llvm-project/pull/86748
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Headers] Don't declare unreachable() from stddef.h in C++ (PR #86748)

2024-04-04 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> > > Is that still worth mention in the release notes do you think?
> > 
> > 
> > Oh duh, that's right, this requires someone to define the `__need` macro to 
> > get it, so no, I don't think it needs a release note. Sorry for the noise!
> 
> 👍 thanks for bearing with me on this!

Likewise! :-)

https://github.com/llvm/llvm-project/pull/86748
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Implement resource binding type prefix mismatch errors (PR #87578)

2024-04-04 Thread Chris B via cfe-commits


@@ -7367,6 +7367,75 @@ static void handleHLSLResourceBindingAttr(Sema &S, Decl 
*D,
 return;
   }
 
+  VarDecl *VD = dyn_cast(D);
+  HLSLBufferDecl *BD = dyn_cast(D);
+
+  if (VD || BD) {
+llvm::hlsl::ResourceClass RC;
+std::string varTy = "";
+if (VD) {
+
+  const Type *Ty = VD->getType()->getPointeeOrArrayElementType();
+  if (!Ty)
+return;
+  QualType t = ((ElaboratedType *)Ty)->getNamedType();
+  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
+  if (!RD)
+return;
+
+  if (auto TDecl = dyn_cast(RD))
+RD = TDecl->getSpecializedTemplate()->getTemplatedDecl();
+  RD = RD->getCanonicalDecl();
+  const auto *Attr = RD->getAttr();
+  if (!Attr)
+return;
+
+  RC = Attr->getResourceClass();
+  varTy = RD->getNameAsString();
+} else {
+  if (BD->isCBuffer()) {
+RC = llvm::hlsl::ResourceClass::CBuffer;
+varTy = "cbuffer";
+  } else {
+RC = llvm::hlsl::ResourceClass::CBuffer;
+varTy = "tbuffer";
+  }
+}
+switch (RC) {
+case llvm::hlsl::ResourceClass::SRV: {
+  if (Slot.substr(0, 1) != "t")
+S.Diag(ArgLoc, diag::err_hlsl_mismatching_register_type_and_name)
+<< Slot.substr(0, 1) << varTy << "t";
+  break;
+}
+case llvm::hlsl::ResourceClass::UAV: {
+  if (Slot.substr(0, 1) != "u")
+S.Diag(ArgLoc, diag::err_hlsl_mismatching_register_type_and_name)
+<< Slot.substr(0, 1) << varTy << "u";
+  break;
+}
+case llvm::hlsl::ResourceClass::CBuffer: {
+  if (Slot.substr(0, 1) != "b")
+S.Diag(ArgLoc, diag::err_hlsl_mismatching_register_type_and_name)
+<< Slot.substr(0, 1) << varTy << "b";
+  break;
+}
+case llvm::hlsl::ResourceClass::Sampler: {
+  if (Slot.substr(0, 1) != "s")
+S.Diag(ArgLoc, diag::err_hlsl_mismatching_register_type_and_name)
+<< Slot.substr(0, 1) << varTy << "s";
+  break;
+}
+case llvm::hlsl::ResourceClass::Invalid: {
+  llvm_unreachable("Resource class should be valid.");
+  break;
+}
+
+default:
+  break;
+}

llvm-beanz wrote:

Or if we're covering all cases in the switch we should leave off the default 
case so that it produces a warning if we add a new resource class.

https://github.com/llvm/llvm-project/pull/87578
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [flang] [flang][Frontend] Implement printing defined macros via -dM (PR #87627)

2024-04-04 Thread Krzysztof Parzyszek via cfe-commits

https://github.com/kparzysz updated 
https://github.com/llvm/llvm-project/pull/87627

>From f4917dcf99664442d262226cd1ce1058646d7a55 Mon Sep 17 00:00:00 2001
From: Krzysztof Parzyszek 
Date: Wed, 3 Apr 2024 17:09:24 -0500
Subject: [PATCH 1/7] [flang][Frontend] Implement printing defined macros via
 -dM

This should work the same way as in clang.
---
 clang/include/clang/Driver/Options.td |   2 +-
 clang/lib/Driver/ToolChains/Flang.cpp |   5 +-
 .../flang/Frontend/PreprocessorOptions.h  |   3 +
 flang/include/flang/Parser/parsing.h  |   5 +
 flang/lib/Frontend/CompilerInvocation.cpp |   1 +
 flang/lib/Frontend/FrontendActions.cpp|   4 +-
 flang/lib/Parser/parsing.cpp  |  18 ++-
 flang/lib/Parser/preprocessor.cpp | 128 ++
 flang/lib/Parser/preprocessor.h   |   6 +
 flang/test/Driver/driver-help-hidden.f90  |   1 +
 flang/test/Driver/driver-help.f90 |   2 +
 flang/test/Preprocessing/show-macros1.F90 |  14 ++
 flang/test/Preprocessing/show-macros2.F90 |   6 +
 flang/test/Preprocessing/show-macros3.F90 |  10 ++
 14 files changed, 196 insertions(+), 9 deletions(-)
 create mode 100644 flang/test/Preprocessing/show-macros1.F90
 create mode 100644 flang/test/Preprocessing/show-macros2.F90
 create mode 100644 flang/test/Preprocessing/show-macros3.F90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c3e90a70925b78..b1ed29cb1cbc44 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1446,7 +1446,7 @@ def dD : Flag<["-"], "dD">, Group, 
Visibility<[ClangOption, CC1Option]>
 def dI : Flag<["-"], "dI">, Group, Visibility<[ClangOption, 
CC1Option]>,
   HelpText<"Print include directives in -E mode in addition to normal output">,
   MarshallingInfoFlag>;
-def dM : Flag<["-"], "dM">, Group, Visibility<[ClangOption, 
CC1Option]>,
+def dM : Flag<["-"], "dM">, Group, Visibility<[ClangOption, 
CC1Option, FlangOption, FC1Option]>,
   HelpText<"Print macro definitions in -E mode instead of normal output">;
 def dead__strip : Flag<["-"], "dead_strip">;
 def dependency_file : Separate<["-"], "dependency-file">,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 70daa699e3a949..bfd07addfca811 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -688,7 +688,10 @@ void Flang::ConstructJob(Compilation &C, const JobAction 
&JA,
   CmdArgs.push_back(Args.MakeArgString(TripleStr));
 
   if (isa(JA)) {
-  CmdArgs.push_back("-E");
+CmdArgs.push_back("-E");
+if (Args.getLastArg(options::OPT_dM)) {
+  CmdArgs.push_back("-dM");
+}
   } else if (isa(JA) || isa(JA)) {
 if (JA.getType() == types::TY_Nothing) {
   CmdArgs.push_back("-fsyntax-only");
diff --git a/flang/include/flang/Frontend/PreprocessorOptions.h 
b/flang/include/flang/Frontend/PreprocessorOptions.h
index b2e9ac0e963b73..13a91ee9a184f8 100644
--- a/flang/include/flang/Frontend/PreprocessorOptions.h
+++ b/flang/include/flang/Frontend/PreprocessorOptions.h
@@ -56,6 +56,9 @@ struct PreprocessorOptions {
   // -fno-reformat: Emit cooked character stream as -E output
   bool noReformat{false};
 
+  // -dM: Show macro definitions with -dM -E
+  bool showMacros{false};
+
   void addMacroDef(llvm::StringRef name) {
 macros.emplace_back(std::string(name), false);
   }
diff --git a/flang/include/flang/Parser/parsing.h 
b/flang/include/flang/Parser/parsing.h
index e80d8f724ac8f4..14891c44dacafd 100644
--- a/flang/include/flang/Parser/parsing.h
+++ b/flang/include/flang/Parser/parsing.h
@@ -16,6 +16,7 @@
 #include "provenance.h"
 #include "flang/Common/Fortran-features.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 
 #include 
 #include 
@@ -23,6 +24,8 @@
 
 namespace Fortran::parser {
 
+class Preprocessor;
+
 struct Options {
   Options() {}
 
@@ -59,6 +62,7 @@ class Parsing {
   const SourceFile *Prescan(const std::string &path, Options);
   void EmitPreprocessedSource(
   llvm::raw_ostream &, bool lineDirectives = true) const;
+  void EmitPreprocessorMacros(llvm::raw_ostream &) const;
   void DumpCookedChars(llvm::raw_ostream &) const;
   void DumpProvenance(llvm::raw_ostream &) const;
   void DumpParsingLog(llvm::raw_ostream &) const;
@@ -83,6 +87,7 @@ class Parsing {
   const char *finalRestingPlace_{nullptr};
   std::optional parseTree_;
   ParsingLog log_;
+  std::unique_ptr preprocessor_;
 };
 } // namespace Fortran::parser
 #endif // FORTRAN_PARSER_PARSING_H_
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index c830c7af2462c9..8ce6ab7baf4812 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -772,6 +772,7 @@ static void 
parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
 
   opts.noReformat = args.hasA

[clang] [Clang][Docs] use CommonOptionsParser::create instead of protected constructor on libTooling tutorial (NFC) (PR #70427)

2024-04-04 Thread Xulei Liu via cfe-commits

Xulei-NL wrote:

Nice that the author has created this PR for fixing the inconsistent LibTooling 
document. This PR is very important to clang LibTooling beginners. Could the 
reviewers please approve it soon? :smiley:

https://github.com/llvm/llvm-project/pull/70427
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Implement resource binding type prefix mismatch errors (PR #87578)

2024-04-04 Thread Chris B via cfe-commits


@@ -7367,6 +7367,75 @@ static void handleHLSLResourceBindingAttr(Sema &S, Decl 
*D,
 return;
   }
 
+  VarDecl *VD = dyn_cast(D);
+  HLSLBufferDecl *BD = dyn_cast(D);
+
+  if (VD || BD) {
+llvm::hlsl::ResourceClass RC;
+std::string varTy = "";
+if (VD) {
+
+  const Type *Ty = VD->getType()->getPointeeOrArrayElementType();
+  if (!Ty)
+return;
+  QualType t = ((ElaboratedType *)Ty)->getNamedType();
+  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
+  if (!RD)
+return;
+
+  if (auto TDecl = dyn_cast(RD))
+RD = TDecl->getSpecializedTemplate()->getTemplatedDecl();
+  RD = RD->getCanonicalDecl();
+  const auto *Attr = RD->getAttr();
+  if (!Attr)
+return;
+
+  RC = Attr->getResourceClass();
+  varTy = RD->getNameAsString();
+} else {
+  if (BD->isCBuffer()) {
+RC = llvm::hlsl::ResourceClass::CBuffer;
+varTy = "cbuffer";
+  } else {
+RC = llvm::hlsl::ResourceClass::CBuffer;
+varTy = "tbuffer";
+  }
+}
+switch (RC) {
+case llvm::hlsl::ResourceClass::SRV: {
+  if (Slot.substr(0, 1) != "t")

llvm-beanz wrote:

Or we could replace all the `Slot.substr(0,1)` calls just with `Slot[0]` and 
compare characters instead of strings.

https://github.com/llvm/llvm-project/pull/87578
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [flang] [flang][Frontend] Implement printing defined macros via -dM (PR #87627)

2024-04-04 Thread Krzysztof Parzyszek via cfe-commits

https://github.com/kparzysz updated 
https://github.com/llvm/llvm-project/pull/87627

>From f4917dcf99664442d262226cd1ce1058646d7a55 Mon Sep 17 00:00:00 2001
From: Krzysztof Parzyszek 
Date: Wed, 3 Apr 2024 17:09:24 -0500
Subject: [PATCH 1/8] [flang][Frontend] Implement printing defined macros via
 -dM

This should work the same way as in clang.
---
 clang/include/clang/Driver/Options.td |   2 +-
 clang/lib/Driver/ToolChains/Flang.cpp |   5 +-
 .../flang/Frontend/PreprocessorOptions.h  |   3 +
 flang/include/flang/Parser/parsing.h  |   5 +
 flang/lib/Frontend/CompilerInvocation.cpp |   1 +
 flang/lib/Frontend/FrontendActions.cpp|   4 +-
 flang/lib/Parser/parsing.cpp  |  18 ++-
 flang/lib/Parser/preprocessor.cpp | 128 ++
 flang/lib/Parser/preprocessor.h   |   6 +
 flang/test/Driver/driver-help-hidden.f90  |   1 +
 flang/test/Driver/driver-help.f90 |   2 +
 flang/test/Preprocessing/show-macros1.F90 |  14 ++
 flang/test/Preprocessing/show-macros2.F90 |   6 +
 flang/test/Preprocessing/show-macros3.F90 |  10 ++
 14 files changed, 196 insertions(+), 9 deletions(-)
 create mode 100644 flang/test/Preprocessing/show-macros1.F90
 create mode 100644 flang/test/Preprocessing/show-macros2.F90
 create mode 100644 flang/test/Preprocessing/show-macros3.F90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c3e90a70925b78..b1ed29cb1cbc44 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1446,7 +1446,7 @@ def dD : Flag<["-"], "dD">, Group, 
Visibility<[ClangOption, CC1Option]>
 def dI : Flag<["-"], "dI">, Group, Visibility<[ClangOption, 
CC1Option]>,
   HelpText<"Print include directives in -E mode in addition to normal output">,
   MarshallingInfoFlag>;
-def dM : Flag<["-"], "dM">, Group, Visibility<[ClangOption, 
CC1Option]>,
+def dM : Flag<["-"], "dM">, Group, Visibility<[ClangOption, 
CC1Option, FlangOption, FC1Option]>,
   HelpText<"Print macro definitions in -E mode instead of normal output">;
 def dead__strip : Flag<["-"], "dead_strip">;
 def dependency_file : Separate<["-"], "dependency-file">,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 70daa699e3a949..bfd07addfca811 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -688,7 +688,10 @@ void Flang::ConstructJob(Compilation &C, const JobAction 
&JA,
   CmdArgs.push_back(Args.MakeArgString(TripleStr));
 
   if (isa(JA)) {
-  CmdArgs.push_back("-E");
+CmdArgs.push_back("-E");
+if (Args.getLastArg(options::OPT_dM)) {
+  CmdArgs.push_back("-dM");
+}
   } else if (isa(JA) || isa(JA)) {
 if (JA.getType() == types::TY_Nothing) {
   CmdArgs.push_back("-fsyntax-only");
diff --git a/flang/include/flang/Frontend/PreprocessorOptions.h 
b/flang/include/flang/Frontend/PreprocessorOptions.h
index b2e9ac0e963b73..13a91ee9a184f8 100644
--- a/flang/include/flang/Frontend/PreprocessorOptions.h
+++ b/flang/include/flang/Frontend/PreprocessorOptions.h
@@ -56,6 +56,9 @@ struct PreprocessorOptions {
   // -fno-reformat: Emit cooked character stream as -E output
   bool noReformat{false};
 
+  // -dM: Show macro definitions with -dM -E
+  bool showMacros{false};
+
   void addMacroDef(llvm::StringRef name) {
 macros.emplace_back(std::string(name), false);
   }
diff --git a/flang/include/flang/Parser/parsing.h 
b/flang/include/flang/Parser/parsing.h
index e80d8f724ac8f4..14891c44dacafd 100644
--- a/flang/include/flang/Parser/parsing.h
+++ b/flang/include/flang/Parser/parsing.h
@@ -16,6 +16,7 @@
 #include "provenance.h"
 #include "flang/Common/Fortran-features.h"
 #include "llvm/Support/raw_ostream.h"
+#include 
 #include 
 #include 
 #include 
@@ -23,6 +24,8 @@
 
 namespace Fortran::parser {
 
+class Preprocessor;
+
 struct Options {
   Options() {}
 
@@ -59,6 +62,7 @@ class Parsing {
   const SourceFile *Prescan(const std::string &path, Options);
   void EmitPreprocessedSource(
   llvm::raw_ostream &, bool lineDirectives = true) const;
+  void EmitPreprocessorMacros(llvm::raw_ostream &) const;
   void DumpCookedChars(llvm::raw_ostream &) const;
   void DumpProvenance(llvm::raw_ostream &) const;
   void DumpParsingLog(llvm::raw_ostream &) const;
@@ -83,6 +87,7 @@ class Parsing {
   const char *finalRestingPlace_{nullptr};
   std::optional parseTree_;
   ParsingLog log_;
+  std::unique_ptr preprocessor_;
 };
 } // namespace Fortran::parser
 #endif // FORTRAN_PARSER_PARSING_H_
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index c830c7af2462c9..8ce6ab7baf4812 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -772,6 +772,7 @@ static void 
parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
 
   opts.noReformat = args.hasA

[clang] [llvm] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP kernels (PR #87695)

2024-04-04 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 created 
https://github.com/llvm/llvm-project/pull/87695

Summary:
This new attribute was introduced recently. We already do this for NVPTX
kernels so we should apply this for AMDGPU as well. This patch simply
applies this metadata in cases where a lower bound is known


>From a314dadecad6f12db20c34a133ec7bb084a77b5d Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Thu, 4 Apr 2024 15:10:55 -0500
Subject: [PATCH] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP
 kernels

Summary:
This new attribute was introduced recently. We already do this for NVPTX
kernels so we should apply this for AMDGPU as well. This patch simply
applies this metadata in cases where a lower bound is known
---
 clang/test/OpenMP/thread_limit_amdgpu.c   | 34 +++
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |  3 ++
 2 files changed, 37 insertions(+)
 create mode 100644 clang/test/OpenMP/thread_limit_amdgpu.c

diff --git a/clang/test/OpenMP/thread_limit_amdgpu.c 
b/clang/test/OpenMP/thread_limit_amdgpu.c
new file mode 100644
index 00..f884eeb73c3ff1
--- /dev/null
+++ b/clang/test/OpenMP/thread_limit_amdgpu.c
@@ -0,0 +1,34 @@
+// Test target codegen - host bc file has to be created first.
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-unknown-linux-gnu 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-x86-host.bc
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple amdgcn-amd-amdhsa 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-target-device 
-fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+void foo(int N) {
+#pragma omp target teams distribute parallel for simd
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd thread_limit(4)
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd 
ompx_attribute(__attribute__((launch_bounds(42, 42
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd 
ompx_attribute(__attribute__((launch_bounds(42, 42 num_threads(22)
+  for (int i = 0; i < N; ++i)
+;
+}
+
+#endif
+
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l10({{.*}}) #[[ATTR1:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l13({{.*}}) #[[ATTR2:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l16({{.*}}) #[[ATTR3:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l19({{.*}}) #[[ATTR4:.+]] {
+
+// CHECK: attributes #[[ATTR1]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,256" {{.*}} }
+// CHECK: attributes #[[ATTR2]] = { {{.*}} "amdgpu-flat-work-group-size"="1,4" 
{{.*}} }
+// CHECK: attributes #[[ATTR3]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,42" "amdgpu-max-num-workgroups"="42,1,1"{{.*}} 
}
+// CHECK: attributes #[[ATTR4]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,22" "amdgpu-max-num-workgroups"="42,1,1"{{.*}} 
}
diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 16507a69ea8502..4fe44b10d1bd0e 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4791,6 +4791,9 @@ void OpenMPIRBuilder::writeTeamsForKernel(const Triple 
&T, Function &Kernel,
   updateNVPTXMetadata(Kernel, "maxclusterrank", UB, true);
 updateNVPTXMetadata(Kernel, "minctasm", LB, false);
   }
+  if (T.isAMDGPU()) {
+Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(LB) + ",1,1");
+  }
   Kernel.addFnAttr("omp_target_num_teams", std::to_string(LB));
 }
 

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


[clang] [llvm] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP kernels (PR #87695)

2024-04-04 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Joseph Huber (jhuber6)


Changes

Summary:
This new attribute was introduced recently. We already do this for NVPTX
kernels so we should apply this for AMDGPU as well. This patch simply
applies this metadata in cases where a lower bound is known


---
Full diff: https://github.com/llvm/llvm-project/pull/87695.diff


2 Files Affected:

- (added) clang/test/OpenMP/thread_limit_amdgpu.c (+34) 
- (modified) llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp (+3) 


``diff
diff --git a/clang/test/OpenMP/thread_limit_amdgpu.c 
b/clang/test/OpenMP/thread_limit_amdgpu.c
new file mode 100644
index 00..f884eeb73c3ff1
--- /dev/null
+++ b/clang/test/OpenMP/thread_limit_amdgpu.c
@@ -0,0 +1,34 @@
+// Test target codegen - host bc file has to be created first.
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-unknown-linux-gnu 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-x86-host.bc
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple amdgcn-amd-amdhsa 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-target-device 
-fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+void foo(int N) {
+#pragma omp target teams distribute parallel for simd
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd thread_limit(4)
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd 
ompx_attribute(__attribute__((launch_bounds(42, 42
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd 
ompx_attribute(__attribute__((launch_bounds(42, 42 num_threads(22)
+  for (int i = 0; i < N; ++i)
+;
+}
+
+#endif
+
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l10({{.*}}) #[[ATTR1:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l13({{.*}}) #[[ATTR2:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l16({{.*}}) #[[ATTR3:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l19({{.*}}) #[[ATTR4:.+]] {
+
+// CHECK: attributes #[[ATTR1]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,256" {{.*}} }
+// CHECK: attributes #[[ATTR2]] = { {{.*}} "amdgpu-flat-work-group-size"="1,4" 
{{.*}} }
+// CHECK: attributes #[[ATTR3]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,42" "amdgpu-max-num-workgroups"="42,1,1"{{.*}} 
}
+// CHECK: attributes #[[ATTR4]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,22" "amdgpu-max-num-workgroups"="42,1,1"{{.*}} 
}
diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 16507a69ea8502..4fe44b10d1bd0e 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4791,6 +4791,9 @@ void OpenMPIRBuilder::writeTeamsForKernel(const Triple 
&T, Function &Kernel,
   updateNVPTXMetadata(Kernel, "maxclusterrank", UB, true);
 updateNVPTXMetadata(Kernel, "minctasm", LB, false);
   }
+  if (T.isAMDGPU()) {
+Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(LB) + ",1,1");
+  }
   Kernel.addFnAttr("omp_target_num_teams", std::to_string(LB));
 }
 

``




https://github.com/llvm/llvm-project/pull/87695
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [InstallAPI] Add test to validate cc1 arg forwading (PR #87666)

2024-04-04 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/87666

>From 6b2f262d1e69724d4eb96f5ad75aa2c202f3eb2d Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Thu, 4 Apr 2024 10:36:47 -0700
Subject: [PATCH] [InstallAPI] Add test to validate cc1 arg forwading

---
 .../Foundation.framework/Headers/Foundation.h | 19 +++
 .../InstallAPI/extra-exclude-headers.test | 22 +---
 .../InstallAPI/forwarded-search-paths.test| 34 +++
 3 files changed, 54 insertions(+), 21 deletions(-)
 create mode 100644 
clang/test/InstallAPI/Inputs/Foundation/Foundation.framework/Headers/Foundation.h
 create mode 100644 clang/test/InstallAPI/forwarded-search-paths.test

diff --git 
a/clang/test/InstallAPI/Inputs/Foundation/Foundation.framework/Headers/Foundation.h
 
b/clang/test/InstallAPI/Inputs/Foundation/Foundation.framework/Headers/Foundation.h
new file mode 100644
index 00..e731b59ac5308b
--- /dev/null
+++ 
b/clang/test/InstallAPI/Inputs/Foundation/Foundation.framework/Headers/Foundation.h
@@ -0,0 +1,19 @@
+@interface NSObject 
+@end
+
+typedef unsigned char BOOL; 
+#ifndef NS_AVAILABLE
+#define NS_AVAILABLE(x,y) __attribute__((availability(macosx,introduced=x)))
+#endif 
+#ifndef NS_UNAVAILABLE
+#define NS_UNAVAILABLE  __attribute__((unavailable))
+#endif 
+#ifndef NS_DEPRECATED_MAC
+#define NS_DEPRECATED_MAC(x,y) 
__attribute__((availability(macosx,introduced=x,deprecated=y,message="" )));
+#endif 
+
+@interface NSManagedObject
+@end 
+
+@interface NSSet 
+@end 
diff --git a/clang/test/InstallAPI/extra-exclude-headers.test 
b/clang/test/InstallAPI/extra-exclude-headers.test
index 663ca1a5d5000d..addb81f5386f3e 100644
--- a/clang/test/InstallAPI/extra-exclude-headers.test
+++ b/clang/test/InstallAPI/extra-exclude-headers.test
@@ -2,6 +2,7 @@
 ; RUN: split-file %s %t
 ; RUN: mkdir -p %t/System/Library/Frameworks 
 ; RUN: cp -r %S/Inputs/Simple/Simple.framework %t/System/Library/Frameworks/
+; RUN: cp -r %S/Inputs/Foundation/Foundation.framework 
%t/System/Library/Frameworks/
 ; RUN: sed -e "s|DSTROOT|%/t|g" %t/inputs.json.in > %t/inputs.json
 ; RUN: yaml2obj %S/Inputs/Simple/Simple.yaml -o %t/Simple 
 
@@ -184,24 +185,3 @@
   ],
   "version": "3"
 }
-
-;--- System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
-@interface NSObject 
-@end
-
-typedef unsigned char BOOL; 
-#ifndef NS_AVAILABLE
-#define NS_AVAILABLE(x,y) __attribute__((availability(macosx,introduced=x)))
-#endif 
-#ifndef NS_UNAVAILABLE
-#define NS_UNAVAILABLE  __attribute__((unavailable))
-#endif 
-#ifndef NS_DEPRECATED_MAC
-#define NS_DEPRECATED_MAC(x,y) 
__attribute__((availability(macosx,introduced=x,deprecated=y,message="" )));
-#endif 
-
-@interface NSManagedObject
-@end 
-
-@interface NSSet 
-@end 
diff --git a/clang/test/InstallAPI/forwarded-search-paths.test 
b/clang/test/InstallAPI/forwarded-search-paths.test
new file mode 100644
index 00..dc1e9006060f44
--- /dev/null
+++ b/clang/test/InstallAPI/forwarded-search-paths.test
@@ -0,0 +1,34 @@
+; RUN: rm -rf %t
+; RUN: split-file %s %t
+; RUN: sed -e "s|DSTROOT|%/t|g" %t/input.json.in > %t/input.json
+
+; RUN: mkdir -p %t/System/Library/Frameworks 
+; RUN: cp -r %S/Inputs/Foundation/Foundation.framework 
%t/System/Library/Frameworks/
+; RUN: cp -r %S/Inputs/Simple/Simple.framework %t/System/Library/Frameworks/
+; RUN: yaml2obj %S/Inputs/Simple/Simple.yaml -o %t/Simple 
+; RUN: mkdir -p %t/usr/include/after
+
+; RUN: clang-installapi -target x86_64-apple-macosx10.12 \
+; RUN: -install_name 
/System/Library/Frameworks/Simple.framework/Versions/A/Simple \
+; RUN: -current_version 1.2.3 -compatibility_version 1 -o %t/Simple.tbd \
+; RUN: -idirafter %t/usr/include/after \
+; RUN: -F %t/System/Library/Frameworks \
+; RUN: --verify-against=%t/Simple --verify-mode=ErrorsOnly \
+; RUN: %t/input.json  -v 2>&1 | FileCheck %s
+
+; CHECK: "-idirafter" {{.*}}/usr/include/after"
+; CHECK: #include "..." search starts here:
+; CHECK: #include <...> search starts here:
+; CHECK: usr/include/after 
+; CHECK-NEXT: End of search list.
+
+;--- input.json.in
+{
+  "version" : "3",
+  "headers" : [
+{
+  "type" : "public",
+  "path" : 
"DSTROOT/System/Library/Frameworks/Simple.framework/Headers/Basic.h"
+}
+  ]
+}

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


[clang] [libTooling] Fix `getFileRangeForEdit` for inner nested template types (PR #87673)

2024-04-04 Thread Eric Li via cfe-commits

https://github.com/tJener updated 
https://github.com/llvm/llvm-project/pull/87673

>From 697551dd155cd8ada0d93ce8aa2951a9f9f3d4b4 Mon Sep 17 00:00:00 2001
From: Eric Li 
Date: Thu, 4 Apr 2024 14:04:25 -0400
Subject: [PATCH 1/2] [libTooling] Fix `getFileRangeForEdit` for inner nested
 template types

When there is `>>` in source from the right brackets of a nested
template, the end location of the inner template points intto a
scratch space with a single `>` token. This prevents the lexer from
seeing the `>>` token in the original source.

However, this causes the range to appear to be partially in a macro,
and is problematic if we are trying to avoid ranges with any macro
expansions.

This change detects this odd case in token ranges, converting it to
the corresponding character range without the expansion.
---
 clang/lib/Tooling/Transformer/SourceCode.cpp | 61 ++--
 clang/unittests/Tooling/SourceCodeTest.cpp   | 29 ++
 2 files changed, 85 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Tooling/Transformer/SourceCode.cpp 
b/clang/lib/Tooling/Transformer/SourceCode.cpp
index 6aae834b0db563..114f6ba4833cb0 100644
--- a/clang/lib/Tooling/Transformer/SourceCode.cpp
+++ b/clang/lib/Tooling/Transformer/SourceCode.cpp
@@ -101,6 +101,56 @@ static bool spelledInMacroDefinition(SourceLocation Loc,
   return false;
 }
 
+// Returns the expansion loc of `Loc` if `Loc` is the location of the `>` token
+// of an inner nested template, where the inner and outer templates end 
brackets
+// are spelled as `>>`.
+//
+// Clang handles the `>>` in nested templates by placing the `SourceLocation`
+// of the inner template end bracket in scratch space. This forces it to be a
+// separate token (otherwise it would be lexed as `>>`), but that means it also
+// looks like a macro.
+static std::optional getExpansionForNestedTemplateGreater(
+SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
+  if (Loc.isMacroID()) {
+auto SpellingLoc = SM.getSpellingLoc(Loc);
+auto ExpansionLoc = SM.getExpansionLoc(Loc);
+Token SpellingTok, ExpansionTok;
+if (Lexer::getRawToken(SpellingLoc, SpellingTok, SM, LangOpts,
+   /*IgnoreWhiteSpace=*/false)) {
+  return std::nullopt;
+}
+if (Lexer::getRawToken(ExpansionLoc, ExpansionTok, SM, LangOpts,
+   /*IgnoreWhiteSpace=*/false)) {
+  return std::nullopt;
+}
+if (SpellingTok.getKind() == tok::greater &&
+ExpansionTok.getKind() == tok::greatergreater) {
+  return ExpansionLoc;
+}
+  }
+  return std::nullopt;
+}
+
+// Returns `Range`, but adjusted to smooth over oddities introduced by Clang.
+static CharSourceRange
+cleanRangeForAvoidingMacros(CharSourceRange Range, const SourceManager &SM,
+const LangOptions &LangOpts) {
+  if (Range.isTokenRange()) {
+auto B =
+getExpansionForNestedTemplateGreater(Range.getBegin(), SM, LangOpts);
+auto E = getExpansionForNestedTemplateGreater(Range.getEnd(), SM, 
LangOpts);
+if (E) {
+  // We can't use the expansion location with a token range, because that
+  // will lex as `>>`. So we instead convert to a char range.
+  return CharSourceRange::getCharRange(B.value_or(Range.getBegin()),
+   E->getLocWithOffset(1));
+} else if (B) {
+  return CharSourceRange::getTokenRange(*B, Range.getEnd());
+}
+  }
+  return Range;
+}
+
 static CharSourceRange getRange(const CharSourceRange &EditRange,
 const SourceManager &SM,
 const LangOptions &LangOpts,
@@ -109,13 +159,14 @@ static CharSourceRange getRange(const CharSourceRange 
&EditRange,
   if (IncludeMacroExpansion) {
 Range = Lexer::makeFileCharRange(EditRange, SM, LangOpts);
   } else {
-if (spelledInMacroDefinition(EditRange.getBegin(), SM) ||
-spelledInMacroDefinition(EditRange.getEnd(), SM))
+auto AdjustedRange = cleanRangeForAvoidingMacros(EditRange, SM, LangOpts);
+if (spelledInMacroDefinition(AdjustedRange.getBegin(), SM) ||
+spelledInMacroDefinition(AdjustedRange.getEnd(), SM))
   return {};
 
-auto B = SM.getSpellingLoc(EditRange.getBegin());
-auto E = SM.getSpellingLoc(EditRange.getEnd());
-if (EditRange.isTokenRange())
+auto B = SM.getSpellingLoc(AdjustedRange.getBegin());
+auto E = SM.getSpellingLoc(AdjustedRange.getEnd());
+if (AdjustedRange.isTokenRange())
   E = Lexer::getLocForEndOfToken(E, 0, SM, LangOpts);
 Range = CharSourceRange::getCharRange(B, E);
   }
diff --git a/clang/unittests/Tooling/SourceCodeTest.cpp 
b/clang/unittests/Tooling/SourceCodeTest.cpp
index 3641d2ee453f4a..def9701ccdf1e0 100644
--- a/clang/unittests/Tooling/SourceCodeTest.cpp
+++ b/clang/unittests/Tooling/SourceCodeTest.cpp
@@ -50,6 +50,15 @@ struct CallsVisitor : TestVisitor {
   std::function OnCall;
 };
 
+struct TypeLocVisitor : 

[clang] [libTooling] Fix `getFileRangeForEdit` for inner nested template types (PR #87673)

2024-04-04 Thread Eric Li via cfe-commits

https://github.com/tJener edited https://github.com/llvm/llvm-project/pull/87673
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Disable missing definition warning on pure virtual functions (PR #74510)

2024-04-04 Thread Shafik Yaghmour via cfe-commits


@@ -18931,7 +18931,7 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, 
FunctionDecl *Func,
   //   constant evaluated
   bool NeededForConstantEvaluation =
   isPotentiallyConstantEvaluatedContext(*this) &&
-  isImplicitlyDefinableConstexprFunction(Func);
+  isImplicitlyDefinableConstexprFunction(Func) && !Func->isPure();

shafik wrote:

I am not sure the diagnostic makes sense in that case since it can never 
actually be called. 

https://github.com/llvm/llvm-project/pull/74510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] Add ``ignoringParenImpCasts`` in ``hasAnyArgument`` fix#75754 (PR #87268)

2024-04-04 Thread via cfe-commits

https://github.com/komalverma04 updated 
https://github.com/llvm/llvm-project/pull/87268

>From 9b5781108081565e4009c3809eab623387655f1c Mon Sep 17 00:00:00 2001
From: komalverma04 
Date: Mon, 1 Apr 2024 22:43:10 +0530
Subject: [PATCH 1/4] [clang-tidy] Add ignoringParenImpCasts in hasAnyArgument

---
 .../bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp| 2 +-
 .../clang-tidy/bugprone/MisplacedWideningCastCheck.cpp| 2 +-
 .../bugprone/MultipleNewInOneExpressionCheck.cpp  | 8 
 .../clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp  | 2 +-
 .../bugprone/StringLiteralWithEmbeddedNulCheck.cpp| 2 +-
 .../bugprone/SuspiciousStringviewDataUsageCheck.cpp   | 2 +-
 .../clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp| 4 ++--
 .../clang-tidy/modernize/UseEmplaceCheck.cpp  | 6 +++---
 .../performance/InefficientStringConcatenationCheck.cpp   | 4 ++--
 9 files changed, 16 insertions(+), 16 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
 
b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
index 40e4ab6c8b12af..415183d5c57ba7 100644
--- 
a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
@@ -24,7 +24,7 @@ void MisplacedOperatorInStrlenInAllocCheck::registerMatchers(
 
   const auto BadUse =
   callExpr(callee(StrLenFunc),
-   hasAnyArgument(ignoringImpCasts(
+   hasAnyArgument(ignoringParenImpCasts(
binaryOperator(
hasOperatorName("+"),

hasRHS(ignoringParenImpCasts(integerLiteral(equals(1)
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp
index a1f92aae55448c..b62829a3776572 100644
--- a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp
@@ -42,7 +42,7 @@ void MisplacedWideningCastCheck::registerMatchers(MatchFinder 
*Finder) {
 
   Finder->addMatcher(varDecl(hasInitializer(Cast)), this);
   Finder->addMatcher(returnStmt(hasReturnValue(Cast)), this);
-  Finder->addMatcher(callExpr(hasAnyArgument(Cast)), this);
+  Finder->addMatcher(callExpr(hasAnyArgument(ignoringParenImpCasts(Cast))), 
this);
   Finder->addMatcher(binaryOperator(hasOperatorName("="), hasRHS(Cast)), this);
   Finder->addMatcher(
   binaryOperator(isComparisonOperator(), hasEitherOperand(Cast)), this);
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp
index 41191a3cfed23a..b8dbea600fd368 100644
--- a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp
@@ -96,17 +96,17 @@ void 
MultipleNewInOneExpressionCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   callExpr(
   hasAnyArgument(
-  expr(HasNewExpr1).bind("arg1")),
+  ignoringParenImpCasts(expr(HasNewExpr1).bind("arg1"))),
   hasAnyArgument(
-  expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2")),
+  ignoringParenImpCasts(expr(HasNewExpr2, 
unless(equalsBoundNode("arg1"))).bind("arg2"))),
   hasAncestor(BadAllocCatchingTryBlock)),
   this);
   Finder->addMatcher(
   cxxConstructExpr(
   hasAnyArgument(
-  expr(HasNewExpr1).bind("arg1")),
+  ignoringParenImpCasts(expr(HasNewExpr1).bind("arg1"))),
   hasAnyArgument(
-  expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2")),
+  ignoringParenImpCasts(expr(HasNewExpr2, 
unless(equalsBoundNode("arg1"))).bind("arg2"))),
   unless(isListInitialization()),
   hasAncestor(BadAllocCatchingTryBlock)),
   this);
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
index 977241e91b9a93..d322f2488f8082 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -621,7 +621,7 @@ void 
NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) {
   auto MallocLengthExpr = allOf(
   callee(functionDecl(
   hasAnyName("::alloca", "::calloc", "malloc", "realloc"))),
-  hasAnyArgument(allOf(unless(SizeExpr), 
expr().bind(DestMallocExprName;
+  hasAnyArgument(ignoringParenImpCasts(allOf(unless(SizeExpr), 
expr().bind(DestMallocExprName);
 
   // - Example:  (char *)malloc(length);
   auto DestMalloc = anyOf(callExpr(MallocLengthExpr),
diff --git 
a/cl

[clang-tools-extra] Add ``ignoringParenImpCasts`` in ``hasAnyArgument`` fix#75754 (PR #87268)

2024-04-04 Thread via cfe-commits

https://github.com/komalverma04 updated 
https://github.com/llvm/llvm-project/pull/87268

>From 9b5781108081565e4009c3809eab623387655f1c Mon Sep 17 00:00:00 2001
From: komalverma04 
Date: Mon, 1 Apr 2024 22:43:10 +0530
Subject: [PATCH 1/4] [clang-tidy] Add ignoringParenImpCasts in hasAnyArgument

---
 .../bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp| 2 +-
 .../clang-tidy/bugprone/MisplacedWideningCastCheck.cpp| 2 +-
 .../bugprone/MultipleNewInOneExpressionCheck.cpp  | 8 
 .../clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp  | 2 +-
 .../bugprone/StringLiteralWithEmbeddedNulCheck.cpp| 2 +-
 .../bugprone/SuspiciousStringviewDataUsageCheck.cpp   | 2 +-
 .../clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp| 4 ++--
 .../clang-tidy/modernize/UseEmplaceCheck.cpp  | 6 +++---
 .../performance/InefficientStringConcatenationCheck.cpp   | 4 ++--
 9 files changed, 16 insertions(+), 16 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
 
b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
index 40e4ab6c8b12af..415183d5c57ba7 100644
--- 
a/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp
@@ -24,7 +24,7 @@ void MisplacedOperatorInStrlenInAllocCheck::registerMatchers(
 
   const auto BadUse =
   callExpr(callee(StrLenFunc),
-   hasAnyArgument(ignoringImpCasts(
+   hasAnyArgument(ignoringParenImpCasts(
binaryOperator(
hasOperatorName("+"),

hasRHS(ignoringParenImpCasts(integerLiteral(equals(1)
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp
index a1f92aae55448c..b62829a3776572 100644
--- a/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/MisplacedWideningCastCheck.cpp
@@ -42,7 +42,7 @@ void MisplacedWideningCastCheck::registerMatchers(MatchFinder 
*Finder) {
 
   Finder->addMatcher(varDecl(hasInitializer(Cast)), this);
   Finder->addMatcher(returnStmt(hasReturnValue(Cast)), this);
-  Finder->addMatcher(callExpr(hasAnyArgument(Cast)), this);
+  Finder->addMatcher(callExpr(hasAnyArgument(ignoringParenImpCasts(Cast))), 
this);
   Finder->addMatcher(binaryOperator(hasOperatorName("="), hasRHS(Cast)), this);
   Finder->addMatcher(
   binaryOperator(isComparisonOperator(), hasEitherOperand(Cast)), this);
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp
index 41191a3cfed23a..b8dbea600fd368 100644
--- a/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp
@@ -96,17 +96,17 @@ void 
MultipleNewInOneExpressionCheck::registerMatchers(MatchFinder *Finder) {
   Finder->addMatcher(
   callExpr(
   hasAnyArgument(
-  expr(HasNewExpr1).bind("arg1")),
+  ignoringParenImpCasts(expr(HasNewExpr1).bind("arg1"))),
   hasAnyArgument(
-  expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2")),
+  ignoringParenImpCasts(expr(HasNewExpr2, 
unless(equalsBoundNode("arg1"))).bind("arg2"))),
   hasAncestor(BadAllocCatchingTryBlock)),
   this);
   Finder->addMatcher(
   cxxConstructExpr(
   hasAnyArgument(
-  expr(HasNewExpr1).bind("arg1")),
+  ignoringParenImpCasts(expr(HasNewExpr1).bind("arg1"))),
   hasAnyArgument(
-  expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2")),
+  ignoringParenImpCasts(expr(HasNewExpr2, 
unless(equalsBoundNode("arg1"))).bind("arg2"))),
   unless(isListInitialization()),
   hasAncestor(BadAllocCatchingTryBlock)),
   this);
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
index 977241e91b9a93..d322f2488f8082 100644
--- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp
@@ -621,7 +621,7 @@ void 
NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) {
   auto MallocLengthExpr = allOf(
   callee(functionDecl(
   hasAnyName("::alloca", "::calloc", "malloc", "realloc"))),
-  hasAnyArgument(allOf(unless(SizeExpr), 
expr().bind(DestMallocExprName;
+  hasAnyArgument(ignoringParenImpCasts(allOf(unless(SizeExpr), 
expr().bind(DestMallocExprName);
 
   // - Example:  (char *)malloc(length);
   auto DestMalloc = anyOf(callExpr(MallocLengthExpr),
diff --git 
a/cl

[clang] [llvm] [HLSL][DXIL][SPIRV] Implementation of an abstraction for intrinsic selection of HLSL backends (PR #87171)

2024-04-04 Thread Chris B via cfe-commits


@@ -0,0 +1,47 @@
+
+//===- CGHLSLUtils.h - Utility functions for HLSL CodeGen ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file provides utility functions for HLSL code generation.
+// It is used to abstract away implementation details of backends.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_CODEGEN_CGHLSLUTILS_H
+#define LLVM_CLANG_LIB_CODEGEN_CGHLSLUTILS_H
+
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
+#include "llvm/IR/IntrinsicsSPIRV.h"
+
+// Define the function generator macro
+#define GENERATE_HLSL_INTRINSIC_FUNCTION(name) 
\
+  static llvm::Intrinsic::ID get_hlsl_##name##_intrinsic(  
\
+  const llvm::Triple::ArchType Arch) { 
\
+switch (Arch) {
\
+case llvm::Triple::dxil:   
\
+  return llvm::Intrinsic::dx_##name;   
\
+case llvm::Triple::spirv:  
\
+  return llvm::Intrinsic::spv_##name;  
\
+default:   
\
+  llvm_unreachable("Intrinsic " #name  
\
+   " not supported by target architecture");   
\
+}  
\
+  }
+
+namespace clang::CodeGen {
+class HLSLUtils {

llvm-beanz wrote:

Given that the template doesn't cover all cases, it seems like it probably adds 
complexity that isn't needed since all cases can be handled by the other macro 
approach.

https://github.com/llvm/llvm-project/pull/87171
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL][DXIL][SPIRV] Implementation of an abstraction for intrinsic selection of HLSL backends (PR #87171)

2024-04-04 Thread Farzon Lotfi via cfe-commits


@@ -0,0 +1,47 @@
+
+//===- CGHLSLUtils.h - Utility functions for HLSL CodeGen ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file provides utility functions for HLSL code generation.
+// It is used to abstract away implementation details of backends.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_LIB_CODEGEN_CGHLSLUTILS_H
+#define LLVM_CLANG_LIB_CODEGEN_CGHLSLUTILS_H
+
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
+#include "llvm/IR/IntrinsicsSPIRV.h"
+
+// Define the function generator macro
+#define GENERATE_HLSL_INTRINSIC_FUNCTION(name) 
\
+  static llvm::Intrinsic::ID get_hlsl_##name##_intrinsic(  
\
+  const llvm::Triple::ArchType Arch) { 
\
+switch (Arch) {
\
+case llvm::Triple::dxil:   
\
+  return llvm::Intrinsic::dx_##name;   
\
+case llvm::Triple::spirv:  
\
+  return llvm::Intrinsic::spv_##name;  
\
+default:   
\
+  llvm_unreachable("Intrinsic " #name  
\
+   " not supported by target architecture");   
\
+}  
\
+  }
+
+namespace clang::CodeGen {
+class HLSLUtils {

farzonl wrote:

I'll remove the template

https://github.com/llvm/llvm-project/pull/87171
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP kernels (PR #87695)

2024-04-04 Thread Shilei Tian via cfe-commits


@@ -4791,6 +4791,9 @@ void OpenMPIRBuilder::writeTeamsForKernel(const Triple 
&T, Function &Kernel,
   updateNVPTXMetadata(Kernel, "maxclusterrank", UB, true);
 updateNVPTXMetadata(Kernel, "minctasm", LB, false);
   }
+  if (T.isAMDGPU()) {

shiltian wrote:

```suggestion
  if (T.isAMDGPU())
Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(LB) + ",1,1");
```

https://github.com/llvm/llvm-project/pull/87695
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP kernels (PR #87695)

2024-04-04 Thread Shilei Tian via cfe-commits

https://github.com/shiltian approved this pull request.

LG

https://github.com/llvm/llvm-project/pull/87695
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP kernels (PR #87695)

2024-04-04 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/87695

>From a314dadecad6f12db20c34a133ec7bb084a77b5d Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Thu, 4 Apr 2024 15:10:55 -0500
Subject: [PATCH 1/2] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP
 kernels

Summary:
This new attribute was introduced recently. We already do this for NVPTX
kernels so we should apply this for AMDGPU as well. This patch simply
applies this metadata in cases where a lower bound is known
---
 clang/test/OpenMP/thread_limit_amdgpu.c   | 34 +++
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |  3 ++
 2 files changed, 37 insertions(+)
 create mode 100644 clang/test/OpenMP/thread_limit_amdgpu.c

diff --git a/clang/test/OpenMP/thread_limit_amdgpu.c 
b/clang/test/OpenMP/thread_limit_amdgpu.c
new file mode 100644
index 00..f884eeb73c3ff1
--- /dev/null
+++ b/clang/test/OpenMP/thread_limit_amdgpu.c
@@ -0,0 +1,34 @@
+// Test target codegen - host bc file has to be created first.
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-unknown-linux-gnu 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-x86-host.bc
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple amdgcn-amd-amdhsa 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-target-device 
-fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+void foo(int N) {
+#pragma omp target teams distribute parallel for simd
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd thread_limit(4)
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd 
ompx_attribute(__attribute__((launch_bounds(42, 42
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd 
ompx_attribute(__attribute__((launch_bounds(42, 42 num_threads(22)
+  for (int i = 0; i < N; ++i)
+;
+}
+
+#endif
+
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l10({{.*}}) #[[ATTR1:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l13({{.*}}) #[[ATTR2:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l16({{.*}}) #[[ATTR3:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l19({{.*}}) #[[ATTR4:.+]] {
+
+// CHECK: attributes #[[ATTR1]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,256" {{.*}} }
+// CHECK: attributes #[[ATTR2]] = { {{.*}} "amdgpu-flat-work-group-size"="1,4" 
{{.*}} }
+// CHECK: attributes #[[ATTR3]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,42" "amdgpu-max-num-workgroups"="42,1,1"{{.*}} 
}
+// CHECK: attributes #[[ATTR4]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,22" "amdgpu-max-num-workgroups"="42,1,1"{{.*}} 
}
diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 16507a69ea8502..4fe44b10d1bd0e 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4791,6 +4791,9 @@ void OpenMPIRBuilder::writeTeamsForKernel(const Triple 
&T, Function &Kernel,
   updateNVPTXMetadata(Kernel, "maxclusterrank", UB, true);
 updateNVPTXMetadata(Kernel, "minctasm", LB, false);
   }
+  if (T.isAMDGPU()) {
+Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(LB) + ",1,1");
+  }
   Kernel.addFnAttr("omp_target_num_teams", std::to_string(LB));
 }
 

>From f4710bad402366d4694da84bf24459f62e6c6b42 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Thu, 4 Apr 2024 15:54:29 -0500
Subject: [PATCH 2/2] Update llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp

Co-authored-by: Shilei Tian 
---
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 4fe44b10d1bd0e..1188075c7b2c47 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4791,7 +4791,8 @@ void OpenMPIRBuilder::writeTeamsForKernel(const Triple 
&T, Function &Kernel,
   updateNVPTXMetadata(Kernel, "maxclusterrank", UB, true);
 updateNVPTXMetadata(Kernel, "minctasm", LB, false);
   }
-  if (T.isAMDGPU()) {
+  if (T.isAMDGPU())
+Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(LB) + ",1,1");
 Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(LB) + ",1,1");
   }
   Kernel.addFnAttr("omp_target_num_teams", std::to_string(LB));

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


[clang] [llvm] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP kernels (PR #87695)

2024-04-04 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/87695

>From 1738c7f54bc838eac29402c4248db063d908d575 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Thu, 4 Apr 2024 15:10:55 -0500
Subject: [PATCH] [OpenMP] Add amdgpu-num-work-groups attribute to OpenMP
 kernels

Summary:
This new attribute was introduced recently. We already do this for NVPTX
kernels so we should apply this for AMDGPU as well. This patch simply
applies this metadata in cases where a lower bound is known
---
 clang/test/OpenMP/thread_limit_amdgpu.c   | 34 +++
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |  3 ++
 2 files changed, 37 insertions(+)
 create mode 100644 clang/test/OpenMP/thread_limit_amdgpu.c

diff --git a/clang/test/OpenMP/thread_limit_amdgpu.c 
b/clang/test/OpenMP/thread_limit_amdgpu.c
new file mode 100644
index 00..f884eeb73c3ff1
--- /dev/null
+++ b/clang/test/OpenMP/thread_limit_amdgpu.c
@@ -0,0 +1,34 @@
+// Test target codegen - host bc file has to be created first.
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-unknown-linux-gnu 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm-bc %s -o %t-x86-host.bc
+// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple amdgcn-amd-amdhsa 
-fopenmp-targets=amdgcn-amd-amdhsa -emit-llvm %s -fopenmp-is-target-device 
-fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+void foo(int N) {
+#pragma omp target teams distribute parallel for simd
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd thread_limit(4)
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd 
ompx_attribute(__attribute__((launch_bounds(42, 42
+  for (int i = 0; i < N; ++i)
+;
+#pragma omp target teams distribute parallel for simd 
ompx_attribute(__attribute__((launch_bounds(42, 42 num_threads(22)
+  for (int i = 0; i < N; ++i)
+;
+}
+
+#endif
+
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l10({{.*}}) #[[ATTR1:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l13({{.*}}) #[[ATTR2:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l16({{.*}}) #[[ATTR3:.+]] {
+// CHECK: define weak_odr protected amdgpu_kernel void 
@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+__Z3fooi_}}l19({{.*}}) #[[ATTR4:.+]] {
+
+// CHECK: attributes #[[ATTR1]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,256" {{.*}} }
+// CHECK: attributes #[[ATTR2]] = { {{.*}} "amdgpu-flat-work-group-size"="1,4" 
{{.*}} }
+// CHECK: attributes #[[ATTR3]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,42" "amdgpu-max-num-workgroups"="42,1,1"{{.*}} 
}
+// CHECK: attributes #[[ATTR4]] = { {{.*}} 
"amdgpu-flat-work-group-size"="1,22" "amdgpu-max-num-workgroups"="42,1,1"{{.*}} 
}
diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 16507a69ea8502..7fd8474c2ec890 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -4791,6 +4791,9 @@ void OpenMPIRBuilder::writeTeamsForKernel(const Triple 
&T, Function &Kernel,
   updateNVPTXMetadata(Kernel, "maxclusterrank", UB, true);
 updateNVPTXMetadata(Kernel, "minctasm", LB, false);
   }
+  if (T.isAMDGPU())
+Kernel.addFnAttr("amdgpu-max-num-workgroups", llvm::utostr(LB) + ",1,1");
+
   Kernel.addFnAttr("omp_target_num_teams", std::to_string(LB));
 }
 

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


[clang] [clang] Disable missing definition warning on pure virtual functions (PR #74510)

2024-04-04 Thread Shafik Yaghmour via cfe-commits


@@ -18931,7 +18931,7 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, 
FunctionDecl *Func,
   //   constant evaluated
   bool NeededForConstantEvaluation =
   isPotentiallyConstantEvaluatedContext(*this) &&
-  isImplicitlyDefinableConstexprFunction(Func);
+  isImplicitlyDefinableConstexprFunction(Func) && !Func->isPure();

shafik wrote:

Thank to @erichkeane I realized I am wrong, we can actually define a pure 
virtual function. So we do want to retain the diagnostic here.

https://github.com/llvm/llvm-project/pull/74510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL][DXIL][SPIRV] Implementation of an abstraction for intrinsic selection of HLSL backends (PR #87171)

2024-04-04 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/87171

>From 6e088142af4196f11bc006e0024d4ca0ac4e08f0 Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 28 Mar 2024 21:05:36 -0400
Subject: [PATCH 01/11] [HLSL][DXIL][SPIRV] Intrinsic unification PR

---
 clang/include/clang/Basic/Builtins.td |   6 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  19 ++
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  | 112 +++
 clang/lib/Sema/SemaChecking.cpp   |   1 +
 clang/test/CodeGenHLSL/builtins/all.hlsl  | 277 ++
 llvm/include/llvm/IR/Intrinsics.td|  12 +
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   4 +-
 llvm/include/llvm/IR/IntrinsicsSPIRV.td   |   3 +-
 .../Target/SPIRV/SPIRVInstructionSelector.cpp |  19 ++
 .../test/CodeGen/SPIRV/hlsl-intrinsics/all.ll |  95 ++
 10 files changed, 545 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/all.hlsl
 create mode 100644 llvm/test/CodeGen/SPIRV/hlsl-intrinsics/all.ll

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index f421223ff087de..d6ceb450bd106b 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4587,6 +4587,12 @@ def GetDeviceSideMangledName : LangBuiltin<"CUDA_LANG"> {
 }
 
 // HLSL
+def HLSLAll : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_all"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "bool(...)";
+}
+
 def HLSLAny : LangBuiltin<"HLSL_LANG"> {
   let Spellings = ["__builtin_hlsl_elementwise_any"];
   let Attributes = [NoThrow, Const];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 2537e715b63ee4..2acf799f168785 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -51,6 +51,7 @@
 #include "llvm/IR/IntrinsicsR600.h"
 #include "llvm/IR/IntrinsicsRISCV.h"
 #include "llvm/IR/IntrinsicsS390.h"
+#include "llvm/IR/IntrinsicsSPIRV.h"
 #include "llvm/IR/IntrinsicsVE.h"
 #include "llvm/IR/IntrinsicsWebAssembly.h"
 #include "llvm/IR/IntrinsicsX86.h"
@@ -18166,12 +18167,30 @@ Intrinsic::ID getDotProductIntrinsic(QualType QT, int 
elementCount) {
   return Intrinsic::dx_udot;
 }
 
+Intrinsic::ID getAllIntrinsic(const llvm::Triple::ArchType Arch) {
+  switch (Arch) {
+  case llvm::Triple::dxil:
+return Intrinsic::dx_all;
+  case llvm::Triple::spirv:
+return Intrinsic::spv_all;
+  default:
+llvm_unreachable("Input semantic not supported by target");
+  }
+}
+
 Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned BuiltinID,
 const CallExpr *E) {
   if (!getLangOpts().HLSL)
 return nullptr;
 
   switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_elementwise_all: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+return Builder.CreateIntrinsic(
+/*ReturnType=*/llvm::Type::getInt1Ty(getLLVMContext()),
+getAllIntrinsic(CGM.getTarget().getTriple().getArch()),
+ArrayRef{Op0}, nullptr, "hlsl.all");
+  }
   case Builtin::BI__builtin_hlsl_elementwise_any: {
 Value *Op0 = EmitScalarExpr(E->getArg(0));
 return Builder.CreateIntrinsic(
diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index 9fb6204f90c9a8..06409c6fc77417 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -100,6 +100,118 @@ double3 abs(double3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_abs)
 double4 abs(double4);
 
+//===--===//
+// all builtins
+//===--===//
+
+/// \fn bool all(T x)
+/// \brief Returns True if all components of the \a x parameter are non-zero;
+/// otherwise, false. \param x The input value.
+
+#ifdef __HLSL_ENABLE_16_BIT
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t2);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t3);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t4);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t2);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t3);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t4);
+#endif
+
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(half);
+_HLSL_16

[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Dave Lee via cfe-commits


@@ -673,6 +673,9 @@ option(LLVM_USE_OPROFILE
 option(LLVM_EXTERNALIZE_DEBUGINFO
   "Generate dSYM files and strip executables and libraries (Darwin Only)" OFF)
 
+option(LLVM_ENABLE_NO_EXPORTED_SYMBOLS

kastiglione wrote:

should the name reflect the opposite of the default? if so maybe 
`LLVM_DISABLE_EXPORTED_SYMBOLS`?

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL][DXIL][SPIRV] Implementation of an abstraction for intrinsic selection of HLSL backends (PR #87171)

2024-04-04 Thread Chris B via cfe-commits

https://github.com/llvm-beanz approved this pull request.


https://github.com/llvm/llvm-project/pull/87171
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Dave Lee via cfe-commits

kastiglione wrote:

Thanks for adding this! I've been using `CMAKE_EXE_LINKER_FLAGS` to 
`-Wl,-no_exported_symbols`, and have had no problems.

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [driver] Make --version show if assertions, etc. are enabled (PR #87585)

2024-04-04 Thread Cassie Jones via cfe-commits

https://github.com/porglezomp updated 
https://github.com/llvm/llvm-project/pull/87585

>From a104ff0a445dfe5c6e6cfcf3734f6c0942eca082 Mon Sep 17 00:00:00 2001
From: Cassie Jones 
Date: Thu, 28 Mar 2024 13:58:19 -0700
Subject: [PATCH 1/6] [driver] Make --version show if assertions, etc. are
 enabled

It's useful to have some significant build options visible in the
version when investigating problems with a specific compiler artifact.
This makes it easy to see if assertions, expensive checks, sanitizers,
etc. are enabled when checking a compiler version.
---
 clang/lib/Driver/Driver.cpp | 38 +
 clang/test/Driver/version-build-config.test |  6 
 2 files changed, 44 insertions(+)
 create mode 100644 clang/test/Driver/version-build-config.test

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 7a53764364ce4d..37180efb7ea67b 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -2002,6 +2002,44 @@ void Driver::PrintVersion(const Compilation &C, 
raw_ostream &OS) const {
   // Print out the install directory.
   OS << "InstalledDir: " << Dir << '\n';
 
+  // Print out build configuration options that impact the compiler's runtime
+  // behavior. Intended for identifying the source of issues when reproducing
+  // changes.
+  std::vector BuildOptions = {
+#if !__OPTIMIZE__
+  "+unoptimized",
+#endif
+#ifndef NDEBUG
+  "+assertions",
+#endif
+#ifdef EXPENSIVE_CHECKS
+  "+expensive-checks",
+#endif
+#if __has_feature(address_sanitizer)
+  "+asan",
+#endif
+#if __has_feature(undefined_behavior_sanitizer)
+  "+ubsan",
+#endif
+#if __has_feature(memory_sanitizer)
+  "+msan",
+#endif
+#if __has_feature(dataflow_sanitizer)
+  "+dfsan",
+#endif
+  };
+  if (!BuildOptions.empty()) {
+OS << "Build configuration: ";
+bool FirstOption = true;
+for (const auto &Option : BuildOptions) {
+  if (!FirstOption)
+OS << ", ";
+  OS << Option;
+  FirstOption = false;
+}
+OS << '\n';
+  }
+
   // If configuration files were used, print their paths.
   for (auto ConfigFile : ConfigFiles)
 OS << "Configuration file: " << ConfigFile << '\n';
diff --git a/clang/test/Driver/version-build-config.test 
b/clang/test/Driver/version-build-config.test
new file mode 100644
index 00..3d183f372908ea
--- /dev/null
+++ b/clang/test/Driver/version-build-config.test
@@ -0,0 +1,6 @@
+# REQUIRES: asserts
+# RUN: %clang --version 2>&1 | FileCheck %s
+
+# CHECK: clang version
+# When assertions are enabled, we should have a build configuration line that 
reflects that
+# CHECK: Build configuration: {{.*}}+assertions

>From efc90ba92c29f1cd14f508f56a82a1f03f960401 Mon Sep 17 00:00:00 2001
From: Cassie Jones 
Date: Wed, 3 Apr 2024 22:01:39 -0700
Subject: [PATCH 2/6] Address review feedback

---
 clang/lib/Driver/Driver.cpp | 31 ++-
 1 file changed, 14 insertions(+), 17 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 37180efb7ea67b..680c58e4ea43d8 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -2005,38 +2005,35 @@ void Driver::PrintVersion(const Compilation &C, 
raw_ostream &OS) const {
   // Print out build configuration options that impact the compiler's runtime
   // behavior. Intended for identifying the source of issues when reproducing
   // changes.
-  std::vector BuildOptions = {
-#if !__OPTIMIZE__
-  "+unoptimized",
+  SmallVector BuildOptions = {
+#if __GNUC__ && !__OPTIMIZE__
+// FIXME: __OPTIMIZE__ is not available on MSVC, this will never show there
+"+unoptimized",
 #endif
 #ifndef NDEBUG
-  "+assertions",
+"+assertions",
 #endif
 #ifdef EXPENSIVE_CHECKS
-  "+expensive-checks",
+"+expensive-checks",
 #endif
 #if __has_feature(address_sanitizer)
-  "+asan",
+"+asan",
 #endif
 #if __has_feature(undefined_behavior_sanitizer)
-  "+ubsan",
+"+ubsan",
 #endif
 #if __has_feature(memory_sanitizer)
-  "+msan",
+"+msan",
 #endif
 #if __has_feature(dataflow_sanitizer)
-  "+dfsan",
+"+dfsan",
 #endif
   };
   if (!BuildOptions.empty()) {
-OS << "Build configuration: ";
-bool FirstOption = true;
-for (const auto &Option : BuildOptions) {
-  if (!FirstOption)
-OS << ", ";
-  OS << Option;
-  FirstOption = false;
-}
+OS << "Build config: ";
+llvm::interleaveComma(BuildOptions, OS, [&OS](const StringRef &Option) {
+OS << Option;
+});
 OS << '\n';
   }
 

>From 1213ba2f965a0577fc6504e967ae17346da4ef4f Mon Sep 17 00:00:00 2001
From: Cassie Jones 
Date: Wed, 3 Apr 2024 22:02:19 -0700
Subject: [PATCH 3/6] Move LLVM_IS_DEBUG_BUILD into Support/CommandLine.h

Allow us to reuse this logic in the feature printing.
---
 clang/lib/Driver/Driver.cpp |  3 +--
 llvm/include/llvm/Support/CommandLine.h | 22 ++
 llvm/lib/Support/CommandLine.cpp| 

[clang] [clang] Disable missing definition warning on pure virtual functions (PR #74510)

2024-04-04 Thread Shafik Yaghmour via cfe-commits


@@ -18931,7 +18931,7 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, 
FunctionDecl *Func,
   //   constant evaluated
   bool NeededForConstantEvaluation =
   isPotentiallyConstantEvaluatedContext(*this) &&
-  isImplicitlyDefinableConstexprFunction(Func);
+  isImplicitlyDefinableConstexprFunction(Func) && !Func->isPure();

shafik wrote:

I am not sure why moving it down silences the diagnostic, I would think doing 
`(OdrUse == OdrUseContext::Used || NeededForConstantEvaluation || 
!Func->isPure())` should work. 

Can you explain in more detail?

https://github.com/llvm/llvm-project/pull/74510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Implement resource binding type prefix mismatch errors (PR #87578)

2024-04-04 Thread Joshua Batista via cfe-commits

https://github.com/bob80905 updated 
https://github.com/llvm/llvm-project/pull/87578

>From 3960050439964fe3c0536696490b284a6c470cd1 Mon Sep 17 00:00:00 2001
From: Joshua Batista 
Date: Wed, 3 Apr 2024 13:15:59 -0700
Subject: [PATCH 1/2] implement binding type error for t/cbuffers and rwbuffers

---
 .../clang/Basic/DiagnosticSemaKinds.td|  1 +
 clang/lib/Sema/HLSLExternalSemaSource.cpp | 19 +++--
 clang/lib/Sema/SemaDeclAttr.cpp   | 73 ++-
 .../resource_binding_attr_error_mismatch.hlsl | 65 +
 4 files changed, 149 insertions(+), 9 deletions(-)
 create mode 100644 
clang/test/SemaHLSL/resource_binding_attr_error_mismatch.hlsl

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 51af81bf1f6fc5..9a0946276f80fb 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12149,6 +12149,7 @@ def err_hlsl_missing_semantic_annotation : Error<
 def err_hlsl_init_priority_unsupported : Error<
   "initializer priorities are not supported in HLSL">;
 
+def err_hlsl_mismatching_register_type_and_name: Error<"invalid register name 
prefix '%0' for register type '%1' (expected '%2')">;
 def err_hlsl_unsupported_register_type : Error<"invalid resource class 
specifier '%0' used; expected 'b', 's', 't', or 'u'">;
 def err_hlsl_unsupported_register_number : Error<"register number should be an 
integer">;
 def err_hlsl_expected_space : Error<"invalid space specifier '%0' used; 
expected 'space' followed by an integer, like space1">;
diff --git a/clang/lib/Sema/HLSLExternalSemaSource.cpp 
b/clang/lib/Sema/HLSLExternalSemaSource.cpp
index 1a1febf7a35241..479689ec82dcee 100644
--- a/clang/lib/Sema/HLSLExternalSemaSource.cpp
+++ b/clang/lib/Sema/HLSLExternalSemaSource.cpp
@@ -119,8 +119,10 @@ struct BuiltinTypeDeclBuilder {
 ResourceKind RK, bool IsROV) {
 if (Record->isCompleteDefinition())
   return *this;
-Record->addAttr(HLSLResourceAttr::CreateImplicit(Record->getASTContext(),
- RC, RK, IsROV));
+HLSLResourceAttr *attr = HLSLResourceAttr::CreateImplicit(
+Record->getASTContext(), RC, RK, IsROV);
+
+Record->addAttr(attr);
 return *this;
   }
 
@@ -482,15 +484,18 @@ static BuiltinTypeDeclBuilder 
setupBufferType(CXXRecordDecl *Decl, Sema &S,
   bool IsROV) {
   return BuiltinTypeDeclBuilder(Decl)
   .addHandleMember()
-  .addDefaultHandleConstructor(S, RC)
-  .annotateResourceClass(RC, RK, IsROV);
+  .addDefaultHandleConstructor(S, RC);
 }
 
 void HLSLExternalSemaSource::defineHLSLTypesWithForwardDeclarations() {
   CXXRecordDecl *Decl;
-  Decl = BuiltinTypeDeclBuilder(*SemaPtr, HLSLNamespace, "RWBuffer")
- .addSimpleTemplateParams({"element_type"})
- .Record;
+  Decl =
+  BuiltinTypeDeclBuilder(*SemaPtr, HLSLNamespace, "RWBuffer")
+  .addSimpleTemplateParams({"element_type"})
+  .annotateResourceClass(ResourceClass::UAV, ResourceKind::TypedBuffer,
+ /*IsROV=*/false)
+  .Record;
+
   onCompletion(Decl, [this](CXXRecordDecl *Decl) {
 setupBufferType(Decl, *SemaPtr, ResourceClass::UAV,
 ResourceKind::TypedBuffer, /*IsROV=*/false)
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index f25f3afd0f4af2..e720fe56c3ea17 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -7333,12 +7333,12 @@ static void handleHLSLResourceBindingAttr(Sema &S, Decl 
*D,
   } else {
 Slot = Str;
   }
-
+  QualType Ty = ((clang::ValueDecl *)D)->getType();
   // Validate.
   if (!Slot.empty()) {
 switch (Slot[0]) {
-case 'u':
 case 'b':
+case 'u':
 case 's':
 case 't':
   break;
@@ -7367,6 +7367,75 @@ static void handleHLSLResourceBindingAttr(Sema &S, Decl 
*D,
 return;
   }
 
+  VarDecl *VD = dyn_cast(D);
+  HLSLBufferDecl *BD = dyn_cast(D);
+
+  if (VD || BD) {
+llvm::hlsl::ResourceClass RC;
+std::string varTy = "";
+if (VD) {
+
+  const Type *Ty = VD->getType()->getPointeeOrArrayElementType();
+  if (!Ty)
+return;
+  QualType t = ((ElaboratedType *)Ty)->getNamedType();
+  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
+  if (!RD)
+return;
+
+  if (auto TDecl = dyn_cast(RD))
+RD = TDecl->getSpecializedTemplate()->getTemplatedDecl();
+  RD = RD->getCanonicalDecl();
+  const auto *Attr = RD->getAttr();
+  if (!Attr)
+return;
+
+  RC = Attr->getResourceClass();
+  varTy = RD->getNameAsString();
+} else {
+  if (BD->isCBuffer()) {
+RC = llvm::hlsl::ResourceClass::CBuffer;
+varTy = "cbuffer";
+  } else {
+RC = llvm::hlsl::ResourceClass::CBuffer;
+v

[clang] [llvm] [driver] Make --version show if assertions, etc. are enabled (PR #87585)

2024-04-04 Thread Cassie Jones via cfe-commits

porglezomp wrote:

The result of those refactors I now have a new build option to support hiding 
the version, should I be touching the `utils/bazel` with this patch?

https://github.com/llvm/llvm-project/pull/87585
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Implement resource binding type prefix mismatch errors (PR #87578)

2024-04-04 Thread Chris B via cfe-commits


@@ -7403,41 +7403,36 @@ static void handleHLSLResourceBindingAttr(Sema &S, Decl 
*D,
 }
 switch (RC) {
 case llvm::hlsl::ResourceClass::SRV: {
-  if (Slot.substr(0, 1) != "t")
+  if (Slot[0] != 't')
 S.Diag(ArgLoc, diag::err_hlsl_mismatching_register_type_and_name)
 << Slot.substr(0, 1) << varTy << "t";
   break;
 }
 case llvm::hlsl::ResourceClass::UAV: {
-  if (Slot.substr(0, 1) != "u")
+  if (Slot[0] != 'u')
 S.Diag(ArgLoc, diag::err_hlsl_mismatching_register_type_and_name)
 << Slot.substr(0, 1) << varTy << "u";
   break;
 }
 case llvm::hlsl::ResourceClass::CBuffer: {
-  if (Slot.substr(0, 1) != "b")
+  if (Slot[0] != 'b')
 S.Diag(ArgLoc, diag::err_hlsl_mismatching_register_type_and_name)
 << Slot.substr(0, 1) << varTy << "b";
   break;
 }
 case llvm::hlsl::ResourceClass::Sampler: {
-  if (Slot.substr(0, 1) != "s")
+  if (Slot[0] != 's')
 S.Diag(ArgLoc, diag::err_hlsl_mismatching_register_type_and_name)
 << Slot.substr(0, 1) << varTy << "s";
   break;
 }
-case llvm::hlsl::ResourceClass::Invalid: {
+default: {

llvm-beanz wrote:

It would be better to have this be the Invalid case. Then the compiler will 
warn if new enum values get added that aren't handled.

https://github.com/llvm/llvm-project/pull/87578
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/87684

>From 3ac6872328334384fa20998541fac841add767d9 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Thu, 4 Apr 2024 12:08:28 -0700
Subject: [PATCH 1/2] [cmake] Build executables with -no_exported_symbols when
 building Apple toolchain

Building the Apple way turns off plugin support, meaning we don't need to be 
exporting unloadable symbols from all executables.
While deadstripping effects aren't expected to change, enabling this across all 
tools prevents the creation of export tries. This saves us ~3.5 MB's in just 
the universal build of `clang`.
---
 clang/cmake/caches/Apple-stage2.cmake   |  1 +
 lldb/cmake/caches/Apple-lldb-base.cmake |  1 +
 llvm/CMakeLists.txt |  3 +++
 llvm/cmake/modules/AddLLVM.cmake| 30 ++---
 llvm/docs/CMake.rst |  4 
 5 files changed, 31 insertions(+), 8 deletions(-)

diff --git a/clang/cmake/caches/Apple-stage2.cmake 
b/clang/cmake/caches/Apple-stage2.cmake
index 72cdedd611bc96..faf61fd1fe9ecb 100644
--- a/clang/cmake/caches/Apple-stage2.cmake
+++ b/clang/cmake/caches/Apple-stage2.cmake
@@ -15,6 +15,7 @@ set(LLVM_ENABLE_ZLIB ON CACHE BOOL "")
 set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
 set(LLVM_ENABLE_MODULES ON CACHE BOOL "")
 set(LLVM_EXTERNALIZE_DEBUGINFO ON CACHE BOOL "")
+set(LLVM_ENABLE_NO_EXPORTED_SYMBOLS ON CACHE BOOL "")
 set(CLANG_PLUGIN_SUPPORT OFF CACHE BOOL "")
 set(CLANG_SPAWN_CC1 ON CACHE BOOL "")
 set(BUG_REPORT_URL "http://developer.apple.com/bugreporter/"; CACHE STRING "")
diff --git a/lldb/cmake/caches/Apple-lldb-base.cmake 
b/lldb/cmake/caches/Apple-lldb-base.cmake
index 4d4f02bfae95bd..021538896b2346 100644
--- a/lldb/cmake/caches/Apple-lldb-base.cmake
+++ b/lldb/cmake/caches/Apple-lldb-base.cmake
@@ -3,6 +3,7 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE BOOL "")
 
 set(LLVM_TARGETS_TO_BUILD X86;ARM;AArch64 CACHE STRING "")
 set(LLVM_ENABLE_ASSERTIONS ON CACHE BOOL "")
+set(LLVM_ENABLE_NO_EXPORTED_SYMBOLS ON CACHE BOOL "")
 
 set(LIBCXX_ENABLE_SHARED OFF CACHE BOOL "")
 set(LIBCXX_ENABLE_STATIC OFF CACHE BOOL "")
diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index 6f5647d70d8bc1..7e393acacb80d8 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -673,6 +673,9 @@ option(LLVM_USE_OPROFILE
 option(LLVM_EXTERNALIZE_DEBUGINFO
   "Generate dSYM files and strip executables and libraries (Darwin Only)" OFF)
 
+option(LLVM_ENABLE_NO_EXPORTED_SYMBOLS
+  "When building executables, disable any symbol exports (Darwin Only)" OFF)
+
 set(LLVM_CODESIGNING_IDENTITY "" CACHE STRING
   "Sign executables and dylibs with the given identity or skip if empty 
(Darwin Only)")
 
diff --git a/llvm/cmake/modules/AddLLVM.cmake b/llvm/cmake/modules/AddLLVM.cmake
index 745935f1405170..141a97c852e24f 100644
--- a/llvm/cmake/modules/AddLLVM.cmake
+++ b/llvm/cmake/modules/AddLLVM.cmake
@@ -258,15 +258,24 @@ if (NOT DEFINED LLVM_LINKER_DETECTED AND NOT WIN32)
 endif()
   endif()
 
-  # Apple's linker complains about duplicate libraries, which CMake likes to do
-  # to support ELF platforms. To silence that warning, we can use
-  # -no_warn_duplicate_libraries, but only in versions of the linker that
-  # support that flag.
-  if(NOT LLVM_USE_LINKER AND ${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
+  if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
 include(CheckLinkerFlag)
-check_linker_flag(C "-Wl,-no_warn_duplicate_libraries" 
LLVM_LINKER_SUPPORTS_NO_WARN_DUPLICATE_LIBRARIES)
-  else()
-set(LLVM_LINKER_SUPPORTS_NO_WARN_DUPLICATE_LIBRARIES OFF CACHE INTERNAL "")
+# Linkers that support Darwin allow a setting to internalize all symbol 
exports, 
+# aiding in reducing binary size and often is applicable for executables.
+check_linker_flag(C "-Wl,-no_exported_symbols" 
LLVM_LINKER_SUPPORTS_NO_EXPORTED_SYMBOLS)
+
+if (NOT LLVM_USE_LINKER) 
+  # Apple's linker complains about duplicate libraries, which CMake likes 
to do
+  # to support ELF platforms. To silence that warning, we can use
+  # -no_warn_duplicate_libraries, but only in versions of the linker that
+  # support that flag.
+  check_linker_flag(C "-Wl,-no_warn_duplicate_libraries" 
LLVM_LINKER_SUPPORTS_NO_WARN_DUPLICATE_LIBRARIES)
+else()
+  set(LLVM_LINKER_SUPPORTS_NO_WARN_DUPLICATE_LIBRARIES OFF CACHE INTERNAL 
"")
+endif()
+  
+  else() 
+set(LLVM_LINKER_SUPPORTS_NO_EXPORTED_SYMBOLS OFF CACHE INTERNAL "")
   endif()
 endif()
 
@@ -1029,6 +1038,11 @@ macro(add_llvm_executable name)
 add_llvm_symbol_exports( ${name} ${LLVM_EXPORTED_SYMBOL_FILE} )
   endif(LLVM_EXPORTED_SYMBOL_FILE)
 
+  if (LLVM_ENABLE_NO_EXPORTED_SYMBOLS AND 
LLVM_LINKER_SUPPORTS_NO_EXPORTED_SYMBOLS)
+set_property(TARGET ${name} APPEND_STRING PROPERTY
+  LINK_FLAGS " -Wl,-no_exported_symbols")
+  endif()
+
   if (LLVM_LINK_LLVM_DYLIB AND NOT ARG_DISABLE_LLVM_LINK_LLVM_DYLIB)
 set(USE_SHARED USE_SHARED)
   end

[clang] [llvm] [driver] Make --version show if assertions, etc. are enabled (PR #87585)

2024-04-04 Thread Cassie Jones via cfe-commits


@@ -2002,6 +2002,44 @@ void Driver::PrintVersion(const Compilation &C, 
raw_ostream &OS) const {
   // Print out the install directory.
   OS << "InstalledDir: " << Dir << '\n';
 
+  // Print out build configuration options that impact the compiler's runtime
+  // behavior. Intended for identifying the source of issues when reproducing
+  // changes.
+  std::vector BuildOptions = {
+#if !__OPTIMIZE__
+  "+unoptimized",
+#endif
+#ifndef NDEBUG
+  "+assertions",
+#endif
+#ifdef EXPENSIVE_CHECKS
+  "+expensive-checks",
+#endif
+#if __has_feature(address_sanitizer)
+  "+asan",
+#endif
+#if __has_feature(undefined_behavior_sanitizer)
+  "+ubsan",
+#endif
+#if __has_feature(memory_sanitizer)
+  "+msan",
+#endif
+#if __has_feature(dataflow_sanitizer)
+  "+dfsan",
+#endif
+  };
+  if (!BuildOptions.empty()) {

porglezomp wrote:

Added this as `LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG` which defaults on, is 
there anything I should do to update the release scripts here or is that for 
someone else to do?

https://github.com/llvm/llvm-project/pull/87585
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Cyndy Ishida via cfe-commits


@@ -673,6 +673,9 @@ option(LLVM_USE_OPROFILE
 option(LLVM_EXTERNALIZE_DEBUGINFO
   "Generate dSYM files and strip executables and libraries (Darwin Only)" OFF)
 
+option(LLVM_ENABLE_NO_EXPORTED_SYMBOLS

cyndyishida wrote:

No preference here. Whatever seems easier for others to understand.

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [driver] Make --version show if assertions, etc. are enabled (PR #87585)

2024-04-04 Thread Jon Roelofs via cfe-commits

jroelofs wrote:

> The result of those refactors I now have a new build option to support hiding 
> the version, should I be touching the `utils/bazel` with this patch?

cc @nico

https://github.com/llvm/llvm-project/pull/87585
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread via cfe-commits

jimingham wrote:

lldb can and does present its external symbol interface through LLDB.framework. 
 I can't see any reason why it would also need to export symbols from the 
executable.  The lldb driver is just a fairly small convenience wrapper around 
the API's from LLDB.framework, its job is to handle command-line arguments and 
start up a debugger from LLDB.framework.

Jim 

> On Apr 4, 2024, at 2:01 PM, Dave Lee ***@***.***> wrote:
> 
> 
> Thanks for adding this! I've been using CMAKE_EXE_LINKER_FLAGS to 
> -Wl,-no_exported_symbols, and have had no problems.
> 
> —
> Reply to this email directly, view it on GitHub 
> , or 
> unsubscribe 
> .
> You are receiving this because you are on a team that was mentioned.
> 



https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Implement resource binding type prefix mismatch errors (PR #87578)

2024-04-04 Thread Joshua Batista via cfe-commits

https://github.com/bob80905 updated 
https://github.com/llvm/llvm-project/pull/87578

>From 3960050439964fe3c0536696490b284a6c470cd1 Mon Sep 17 00:00:00 2001
From: Joshua Batista 
Date: Wed, 3 Apr 2024 13:15:59 -0700
Subject: [PATCH 1/3] implement binding type error for t/cbuffers and rwbuffers

---
 .../clang/Basic/DiagnosticSemaKinds.td|  1 +
 clang/lib/Sema/HLSLExternalSemaSource.cpp | 19 +++--
 clang/lib/Sema/SemaDeclAttr.cpp   | 73 ++-
 .../resource_binding_attr_error_mismatch.hlsl | 65 +
 4 files changed, 149 insertions(+), 9 deletions(-)
 create mode 100644 
clang/test/SemaHLSL/resource_binding_attr_error_mismatch.hlsl

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 51af81bf1f6fc5..9a0946276f80fb 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12149,6 +12149,7 @@ def err_hlsl_missing_semantic_annotation : Error<
 def err_hlsl_init_priority_unsupported : Error<
   "initializer priorities are not supported in HLSL">;
 
+def err_hlsl_mismatching_register_type_and_name: Error<"invalid register name 
prefix '%0' for register type '%1' (expected '%2')">;
 def err_hlsl_unsupported_register_type : Error<"invalid resource class 
specifier '%0' used; expected 'b', 's', 't', or 'u'">;
 def err_hlsl_unsupported_register_number : Error<"register number should be an 
integer">;
 def err_hlsl_expected_space : Error<"invalid space specifier '%0' used; 
expected 'space' followed by an integer, like space1">;
diff --git a/clang/lib/Sema/HLSLExternalSemaSource.cpp 
b/clang/lib/Sema/HLSLExternalSemaSource.cpp
index 1a1febf7a35241..479689ec82dcee 100644
--- a/clang/lib/Sema/HLSLExternalSemaSource.cpp
+++ b/clang/lib/Sema/HLSLExternalSemaSource.cpp
@@ -119,8 +119,10 @@ struct BuiltinTypeDeclBuilder {
 ResourceKind RK, bool IsROV) {
 if (Record->isCompleteDefinition())
   return *this;
-Record->addAttr(HLSLResourceAttr::CreateImplicit(Record->getASTContext(),
- RC, RK, IsROV));
+HLSLResourceAttr *attr = HLSLResourceAttr::CreateImplicit(
+Record->getASTContext(), RC, RK, IsROV);
+
+Record->addAttr(attr);
 return *this;
   }
 
@@ -482,15 +484,18 @@ static BuiltinTypeDeclBuilder 
setupBufferType(CXXRecordDecl *Decl, Sema &S,
   bool IsROV) {
   return BuiltinTypeDeclBuilder(Decl)
   .addHandleMember()
-  .addDefaultHandleConstructor(S, RC)
-  .annotateResourceClass(RC, RK, IsROV);
+  .addDefaultHandleConstructor(S, RC);
 }
 
 void HLSLExternalSemaSource::defineHLSLTypesWithForwardDeclarations() {
   CXXRecordDecl *Decl;
-  Decl = BuiltinTypeDeclBuilder(*SemaPtr, HLSLNamespace, "RWBuffer")
- .addSimpleTemplateParams({"element_type"})
- .Record;
+  Decl =
+  BuiltinTypeDeclBuilder(*SemaPtr, HLSLNamespace, "RWBuffer")
+  .addSimpleTemplateParams({"element_type"})
+  .annotateResourceClass(ResourceClass::UAV, ResourceKind::TypedBuffer,
+ /*IsROV=*/false)
+  .Record;
+
   onCompletion(Decl, [this](CXXRecordDecl *Decl) {
 setupBufferType(Decl, *SemaPtr, ResourceClass::UAV,
 ResourceKind::TypedBuffer, /*IsROV=*/false)
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index f25f3afd0f4af2..e720fe56c3ea17 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -7333,12 +7333,12 @@ static void handleHLSLResourceBindingAttr(Sema &S, Decl 
*D,
   } else {
 Slot = Str;
   }
-
+  QualType Ty = ((clang::ValueDecl *)D)->getType();
   // Validate.
   if (!Slot.empty()) {
 switch (Slot[0]) {
-case 'u':
 case 'b':
+case 'u':
 case 's':
 case 't':
   break;
@@ -7367,6 +7367,75 @@ static void handleHLSLResourceBindingAttr(Sema &S, Decl 
*D,
 return;
   }
 
+  VarDecl *VD = dyn_cast(D);
+  HLSLBufferDecl *BD = dyn_cast(D);
+
+  if (VD || BD) {
+llvm::hlsl::ResourceClass RC;
+std::string varTy = "";
+if (VD) {
+
+  const Type *Ty = VD->getType()->getPointeeOrArrayElementType();
+  if (!Ty)
+return;
+  QualType t = ((ElaboratedType *)Ty)->getNamedType();
+  const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
+  if (!RD)
+return;
+
+  if (auto TDecl = dyn_cast(RD))
+RD = TDecl->getSpecializedTemplate()->getTemplatedDecl();
+  RD = RD->getCanonicalDecl();
+  const auto *Attr = RD->getAttr();
+  if (!Attr)
+return;
+
+  RC = Attr->getResourceClass();
+  varTy = RD->getNameAsString();
+} else {
+  if (BD->isCBuffer()) {
+RC = llvm::hlsl::ResourceClass::CBuffer;
+varTy = "cbuffer";
+  } else {
+RC = llvm::hlsl::ResourceClass::CBuffer;
+v

[clang] [llvm] [HLSL][DXIL][SPIRV] Implementation of an abstraction for intrinsic selection of HLSL backends (PR #87171)

2024-04-04 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/87171

>From 6e088142af4196f11bc006e0024d4ca0ac4e08f0 Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 28 Mar 2024 21:05:36 -0400
Subject: [PATCH 01/11] [HLSL][DXIL][SPIRV] Intrinsic unification PR

---
 clang/include/clang/Basic/Builtins.td |   6 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  19 ++
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  | 112 +++
 clang/lib/Sema/SemaChecking.cpp   |   1 +
 clang/test/CodeGenHLSL/builtins/all.hlsl  | 277 ++
 llvm/include/llvm/IR/Intrinsics.td|  12 +
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   4 +-
 llvm/include/llvm/IR/IntrinsicsSPIRV.td   |   3 +-
 .../Target/SPIRV/SPIRVInstructionSelector.cpp |  19 ++
 .../test/CodeGen/SPIRV/hlsl-intrinsics/all.ll |  95 ++
 10 files changed, 545 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/all.hlsl
 create mode 100644 llvm/test/CodeGen/SPIRV/hlsl-intrinsics/all.ll

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index f421223ff087de..d6ceb450bd106b 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4587,6 +4587,12 @@ def GetDeviceSideMangledName : LangBuiltin<"CUDA_LANG"> {
 }
 
 // HLSL
+def HLSLAll : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_all"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "bool(...)";
+}
+
 def HLSLAny : LangBuiltin<"HLSL_LANG"> {
   let Spellings = ["__builtin_hlsl_elementwise_any"];
   let Attributes = [NoThrow, Const];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 2537e715b63ee4..2acf799f168785 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -51,6 +51,7 @@
 #include "llvm/IR/IntrinsicsR600.h"
 #include "llvm/IR/IntrinsicsRISCV.h"
 #include "llvm/IR/IntrinsicsS390.h"
+#include "llvm/IR/IntrinsicsSPIRV.h"
 #include "llvm/IR/IntrinsicsVE.h"
 #include "llvm/IR/IntrinsicsWebAssembly.h"
 #include "llvm/IR/IntrinsicsX86.h"
@@ -18166,12 +18167,30 @@ Intrinsic::ID getDotProductIntrinsic(QualType QT, int 
elementCount) {
   return Intrinsic::dx_udot;
 }
 
+Intrinsic::ID getAllIntrinsic(const llvm::Triple::ArchType Arch) {
+  switch (Arch) {
+  case llvm::Triple::dxil:
+return Intrinsic::dx_all;
+  case llvm::Triple::spirv:
+return Intrinsic::spv_all;
+  default:
+llvm_unreachable("Input semantic not supported by target");
+  }
+}
+
 Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned BuiltinID,
 const CallExpr *E) {
   if (!getLangOpts().HLSL)
 return nullptr;
 
   switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_elementwise_all: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+return Builder.CreateIntrinsic(
+/*ReturnType=*/llvm::Type::getInt1Ty(getLLVMContext()),
+getAllIntrinsic(CGM.getTarget().getTriple().getArch()),
+ArrayRef{Op0}, nullptr, "hlsl.all");
+  }
   case Builtin::BI__builtin_hlsl_elementwise_any: {
 Value *Op0 = EmitScalarExpr(E->getArg(0));
 return Builder.CreateIntrinsic(
diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index 9fb6204f90c9a8..06409c6fc77417 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -100,6 +100,118 @@ double3 abs(double3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_abs)
 double4 abs(double4);
 
+//===--===//
+// all builtins
+//===--===//
+
+/// \fn bool all(T x)
+/// \brief Returns True if all components of the \a x parameter are non-zero;
+/// otherwise, false. \param x The input value.
+
+#ifdef __HLSL_ENABLE_16_BIT
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t2);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t3);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(int16_t4);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t2);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t3);
+_HLSL_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(uint16_t4);
+#endif
+
+_HLSL_16BIT_AVAILABILITY(shadermodel, 6.2)
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_all)
+bool all(half);
+_HLSL_16

[clang] [analyzer] Set and display CSA analysis entry points as notes on debugging (PR #84823)

2024-04-04 Thread Artem Dergachev via cfe-commits


@@ -788,7 +791,7 @@ class PathDiagnostic : public llvm::FoldingSetNode {
   PathDiagnostic(StringRef CheckerName, const Decl *DeclWithIssue,
  StringRef bugtype, StringRef verboseDesc, StringRef shortDesc,
  StringRef category, PathDiagnosticLocation LocationToUnique,
- const Decl *DeclToUnique,
+ const Decl *DeclToUnique, const Decl *AnalysisEntryPoint,

haoNoQ wrote:

I mean, this is a debug feature. Debug features are great but it's probably ok 
to have them slightly incorrect or incomplete if it means that they're no 
longer associated with increased complexity, with paying for something we don't 
use.

Out of those AST checkers, how many are emitting diagnostics outside of the 
entry function / decl-with-issue function? If you append
```
[debug] This bubble's decl name is 'foo()'
```
to _every_ message bubble, would that entirely cover all your needs?

I can easily see how there could be a checker that always warns outside of the 
entry function. If that's the case then it's probably incredibly useful for 
debugging to quickly know which entry function inspired the warning. But at the 
same time I'm not sure I can think of a good example when the same information 
wouldn't be useful for the *user* as well; maybe the users could benefit from a 
user-facing note too? (Somewhat similarly to how Clang explains template 
instantiation stack when diagnosing problems in individual template 
instantiations. (Something we cannot mimic in static analysis tools because the 
instantiation stack is already lost.))

https://github.com/llvm/llvm-project/pull/84823
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 18380c5 - [UBSAN][HWASAN] Remove redundant flags (#87709)

2024-04-04 Thread via cfe-commits

Author: Vitaly Buka
Date: 2024-04-04T14:32:30-07:00
New Revision: 18380c522a90dd849caca3da28cd26c4c4c53eaf

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

LOG: [UBSAN][HWASAN] Remove redundant flags (#87709)

Presense of `cutoff-hot` or `random-skip-rate`
should be enough to trigger optimization.

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
clang/test/CodeGen/remote-traps.c
llvm/include/llvm/Transforms/Instrumentation/RemoveTrapsPass.h
llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
llvm/lib/Transforms/Instrumentation/RemoveTrapsPass.cpp
llvm/test/Instrumentation/HWAddressSanitizer/pgo-opt-out-no-ps.ll
llvm/test/Instrumentation/HWAddressSanitizer/pgo-opt-out.ll

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index c8b2a93ae47add..e25a17658a3487 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -100,9 +100,6 @@ using namespace llvm;
 namespace llvm {
 extern cl::opt PrintPipelinePasses;
 
-static cl::opt ClRemoveTraps("clang-remove-traps", cl::Optional,
-   cl::desc("Insert remove-traps pass."));
-
 // Experiment to move sanitizers earlier.
 static cl::opt ClSanitizeOnOptimizerEarlyEP(
 "sanitizer-early-opt-ep", cl::Optional,
@@ -750,7 +747,7 @@ static void addSanitizers(const Triple &TargetTriple,
 PB.registerOptimizerLastEPCallback(SanitizersCallback);
   }
 
-  if (ClRemoveTraps) {
+  if (RemoveTrapsPass::IsRequested()) {
 // We can optimize after inliner, and PGO profile matching. The hook below
 // is called at the end `buildFunctionSimplificationPipeline`, which called
 // from `buildInlinerPipeline`, which called after profile matching.

diff  --git a/clang/test/CodeGen/remote-traps.c 
b/clang/test/CodeGen/remote-traps.c
index 6751afb96d25f2..6983ddbca89291 100644
--- a/clang/test/CodeGen/remote-traps.c
+++ b/clang/test/CodeGen/remote-traps.c
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow %s -o - | FileCheck %s 
-// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow -mllvm -clang-remove-traps -mllvm 
-remove-traps-random-rate=1 %s -o - | FileCheck %s --implicit-check-not="call 
void @llvm.ubsantrap" --check-prefixes=REMOVE
+// RUN: %clang_cc1 -O1 -emit-llvm -fsanitize=signed-integer-overflow 
-fsanitize-trap=signed-integer-overflow -mllvm -remove-traps-random-rate=1 %s 
-o - | FileCheck %s --implicit-check-not="call void @llvm.ubsantrap" 
--check-prefixes=REMOVE
 
 int test(int x) {
   return x + 123;

diff  --git a/llvm/include/llvm/Transforms/Instrumentation/RemoveTrapsPass.h 
b/llvm/include/llvm/Transforms/Instrumentation/RemoveTrapsPass.h
index 58f6bbcec5dc9d..bae15840f99282 100644
--- a/llvm/include/llvm/Transforms/Instrumentation/RemoveTrapsPass.h
+++ b/llvm/include/llvm/Transforms/Instrumentation/RemoveTrapsPass.h
@@ -25,6 +25,8 @@ namespace llvm {
 class RemoveTrapsPass : public PassInfoMixin {
 public:
   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
+
+  static bool IsRequested();
 };
 
 } // namespace llvm

diff  --git a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
index ee7301f90f5389..ad1cd9c1f6bf12 100644
--- a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -182,11 +182,6 @@ static cl::opt ClWithTls(
  "platforms that support this"),
 cl::Hidden, cl::init(true));
 
-static cl::opt
-CSelectiveInstrumentation("hwasan-selective-instrumentation",
-  cl::desc("Use selective instrumentation"),
-  cl::Hidden, cl::init(false));
-
 static cl::opt ClHotPercentileCutoff("hwasan-percentile-cutoff-hot",
   cl::desc("Hot percentile cuttoff."));
 
@@ -1503,6 +1498,8 @@ bool 
HWAddressSanitizer::selectiveInstrumentationShouldSkip(
 std::bernoulli_distribution D(ClRandomSkipRate);
 return (D(*Rng));
   }
+  if (!ClHotPercentileCutoff.getNumOccurrences())
+return false;
   auto &MAMProxy = FAM.getResult(F);
   ProfileSummaryInfo *PSI =
   MAMProxy.getCachedResult(*F.getParent());
@@ -1527,7 +1524,7 @@ void HWAddressSanitizer::sanitizeFunction(Function &F,
 
   NumTotalFuncs++;
 
-  if (CSelectiveInstrumentation && selectiveInstrumentationShouldSkip(F, FAM))
+  if (selectiveInstrumentationShouldSkip(F, FAM))
 return;
 
   NumInstrumentedFuncs++;

diff  --git a/llvm/lib/Transforms/Instrumentation/RemoveTrapsPass.cpp 
b/llvm/lib/Transforms/Instrumentat

[clang] [analyzer] `canReasonAbout` does not support `nonloc::LazyCompoundVal` (PR #87521)

2024-04-04 Thread Artem Dergachev via cfe-commits


@@ -0,0 +1,17 @@
+// REQUIRES: crash-recovery, asserts

haoNoQ wrote:

You probably don't need this. There's no need to disable a perfectly normal 
test just because it didn't crash before the patch in that configuration. It's 
still nice to know that it doesn't crash after the patch _regardless of_ 
configuration.

https://github.com/llvm/llvm-project/pull/87521
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Jon Roelofs via cfe-commits


@@ -673,6 +673,9 @@ option(LLVM_USE_OPROFILE
 option(LLVM_EXTERNALIZE_DEBUGINFO
   "Generate dSYM files and strip executables and libraries (Darwin Only)" OFF)
 
+option(LLVM_ENABLE_NO_EXPORTED_SYMBOLS

jroelofs wrote:

Flags like this shouldn't have `DISABLE` in their name either. It's 
ambiguous/confusing whether `LLVM_DISABLE_THING=On` means THING=ON or THING=Off.

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] `canReasonAbout` does not support `nonloc::LazyCompoundVal` (PR #87521)

2024-04-04 Thread Artem Dergachev via cfe-commits

haoNoQ wrote:

> Here's the traceback for the second set:

The constraint manager doesn't even exist yet at the moment of time represented 
by this backtrace. There's something else going on. I suspect that you're 
loading checkers as clang plugins and one of them is causing it.

https://github.com/llvm/llvm-project/pull/87521
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [driver] Make --version show if assertions, etc. are enabled (PR #87585)

2024-04-04 Thread Cassie Jones via cfe-commits


@@ -2002,6 +2002,44 @@ void Driver::PrintVersion(const Compilation &C, 
raw_ostream &OS) const {
   // Print out the install directory.
   OS << "InstalledDir: " << Dir << '\n';
 
+  // Print out build configuration options that impact the compiler's runtime
+  // behavior. Intended for identifying the source of issues when reproducing
+  // changes.
+  std::vector BuildOptions = {

porglezomp wrote:

I moved this to a global variable to support the API, so I think 
`ArrayRef` ends up being the appropriate type in the end.

https://github.com/llvm/llvm-project/pull/87585
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [driver] Make --version show if assertions, etc. are enabled (PR #87585)

2024-04-04 Thread Cassie Jones via cfe-commits

https://github.com/porglezomp edited 
https://github.com/llvm/llvm-project/pull/87585
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [driver] Make --version show if assertions, etc. are enabled (PR #87585)

2024-04-04 Thread Jon Roelofs via cfe-commits


@@ -0,0 +1,6 @@
+# REQUIRES: asserts
+# RUN: %clang --version 2>&1 | FileCheck %s
+
+# CHECK: clang version
+# When assertions are enabled, we should have a build configuration line that 
reflects that
+# CHECK: Build configuration: {{.*}}+assertions

jroelofs wrote:

```suggestion
# CHECK: Build config: {{.*}}+assertions
```

https://github.com/llvm/llvm-project/pull/87585
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [clang][CodeGen] Fix templated constructors in base classes introduce bugs. (PR #87310)

2024-04-04 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

If you don't like the current rules, you can ask the C++ standard committee to 
change them.  (See https://isocpp.org/std/submit-issue .)

https://github.com/llvm/llvm-project/pull/87310
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [driver] Make --version show if assertions, etc. are enabled (PR #87585)

2024-04-04 Thread Jon Roelofs via cfe-commits


@@ -2734,6 +2734,40 @@ void cl::PrintHelpMessage(bool Hidden, bool Categorized) 
{
 CommonOptions->CategorizedHiddenPrinter.printHelp();
 }
 
+ArrayRef cl::CompilerBuildConfig = {
+#if LLVM_IS_DEBUG_BUILD
+"+unoptimized",
+#endif
+#ifndef NDEBUG
+"+assertions",
+#endif
+#ifdef EXPENSIVE_CHECKS
+"+expensive-checks",
+#endif
+#if __has_feature(address_sanitizer)
+"+asan",
+#endif
+#if __has_feature(undefined_behavior_sanitizer)
+"+ubsan",
+#endif
+#if __has_feature(memory_sanitizer)
+"+msan",
+#endif
+#if __has_feature(dataflow_sanitizer)
+"+dfsan",
+#endif
+};
+
+// Utility function for printing the build config.
+void cl::printBuildConfig(raw_ostream &OS) {
+#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
+  OS << "Build config: ";
+  llvm::interleaveComma(cl::CompilerBuildConfig, OS,
+[&OS](const StringRef &Option) { OS << Option; });

jroelofs wrote:

```suggestion
  llvm::interleaveComma(cl::CompilerBuildConfig, OS);
```

https://github.com/llvm/llvm-project/pull/87585
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Dan Liew via cfe-commits

https://github.com/delcypher edited 
https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Dan Liew via cfe-commits


@@ -673,6 +673,9 @@ option(LLVM_USE_OPROFILE
 option(LLVM_EXTERNALIZE_DEBUGINFO
   "Generate dSYM files and strip executables and libraries (Darwin Only)" OFF)
 
+option(LLVM_ENABLE_EXPORTED_SYMBOLS

delcypher wrote:

We may want to rename this. The name hints that this option applies to 
everything but actually it only applies to executables and not libraries. E.g. 
`LLVM_ENABLE_TOOLS_WITH_EXPORTED_SYMBOLS`

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Dan Liew via cfe-commits


@@ -654,6 +654,11 @@ enabled sub-projects. Nearly all of these variable names 
begin with
   Generate dSYM files and strip executables and libraries (Darwin Only).
   Defaults to OFF.
 
+**LLVM_ENABLE_EXPORTED_SYMBOLS**:BOOL
+  When building executables, preserve symbol exports. Defaults to ON. 
+  You can use this option to disable exported symbols on all executable build

delcypher wrote:

```suggestion
  Setting this option to ``OFF`` removes exported symbols from all executables.
```

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Dan Liew via cfe-commits

https://github.com/delcypher requested changes to this pull request.

Generally looks good. I have some minor nits. I'd like to see 
`LLVM_ENABLE_EXPORTED_SYMBOLS` renamed to avoid ambiguity.

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Dan Liew via cfe-commits


@@ -654,6 +654,11 @@ enabled sub-projects. Nearly all of these variable names 
begin with
   Generate dSYM files and strip executables and libraries (Darwin Only).
   Defaults to OFF.
 
+**LLVM_ENABLE_EXPORTED_SYMBOLS**:BOOL
+  When building executables, preserve symbol exports. Defaults to ON. 
+  You can use this option to disable exported symbols on all executable build

delcypher wrote:

Nit: Documentation tends not to use "You" as the subject.

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [HLSL][DXIL][SPIRV] Implementation of an abstraction for intrinsic selection of HLSL backends (PR #87171)

2024-04-04 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl edited 
https://github.com/llvm/llvm-project/pull/87171
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [driver] Make --version show if assertions, etc. are enabled (PR #87585)

2024-04-04 Thread Cassie Jones via cfe-commits

https://github.com/porglezomp updated 
https://github.com/llvm/llvm-project/pull/87585

>From a104ff0a445dfe5c6e6cfcf3734f6c0942eca082 Mon Sep 17 00:00:00 2001
From: Cassie Jones 
Date: Thu, 28 Mar 2024 13:58:19 -0700
Subject: [PATCH 1/7] [driver] Make --version show if assertions, etc. are
 enabled

It's useful to have some significant build options visible in the
version when investigating problems with a specific compiler artifact.
This makes it easy to see if assertions, expensive checks, sanitizers,
etc. are enabled when checking a compiler version.
---
 clang/lib/Driver/Driver.cpp | 38 +
 clang/test/Driver/version-build-config.test |  6 
 2 files changed, 44 insertions(+)
 create mode 100644 clang/test/Driver/version-build-config.test

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 7a53764364ce4d..37180efb7ea67b 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -2002,6 +2002,44 @@ void Driver::PrintVersion(const Compilation &C, 
raw_ostream &OS) const {
   // Print out the install directory.
   OS << "InstalledDir: " << Dir << '\n';
 
+  // Print out build configuration options that impact the compiler's runtime
+  // behavior. Intended for identifying the source of issues when reproducing
+  // changes.
+  std::vector BuildOptions = {
+#if !__OPTIMIZE__
+  "+unoptimized",
+#endif
+#ifndef NDEBUG
+  "+assertions",
+#endif
+#ifdef EXPENSIVE_CHECKS
+  "+expensive-checks",
+#endif
+#if __has_feature(address_sanitizer)
+  "+asan",
+#endif
+#if __has_feature(undefined_behavior_sanitizer)
+  "+ubsan",
+#endif
+#if __has_feature(memory_sanitizer)
+  "+msan",
+#endif
+#if __has_feature(dataflow_sanitizer)
+  "+dfsan",
+#endif
+  };
+  if (!BuildOptions.empty()) {
+OS << "Build configuration: ";
+bool FirstOption = true;
+for (const auto &Option : BuildOptions) {
+  if (!FirstOption)
+OS << ", ";
+  OS << Option;
+  FirstOption = false;
+}
+OS << '\n';
+  }
+
   // If configuration files were used, print their paths.
   for (auto ConfigFile : ConfigFiles)
 OS << "Configuration file: " << ConfigFile << '\n';
diff --git a/clang/test/Driver/version-build-config.test 
b/clang/test/Driver/version-build-config.test
new file mode 100644
index 00..3d183f372908ea
--- /dev/null
+++ b/clang/test/Driver/version-build-config.test
@@ -0,0 +1,6 @@
+# REQUIRES: asserts
+# RUN: %clang --version 2>&1 | FileCheck %s
+
+# CHECK: clang version
+# When assertions are enabled, we should have a build configuration line that 
reflects that
+# CHECK: Build configuration: {{.*}}+assertions

>From efc90ba92c29f1cd14f508f56a82a1f03f960401 Mon Sep 17 00:00:00 2001
From: Cassie Jones 
Date: Wed, 3 Apr 2024 22:01:39 -0700
Subject: [PATCH 2/7] Address review feedback

---
 clang/lib/Driver/Driver.cpp | 31 ++-
 1 file changed, 14 insertions(+), 17 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 37180efb7ea67b..680c58e4ea43d8 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -2005,38 +2005,35 @@ void Driver::PrintVersion(const Compilation &C, 
raw_ostream &OS) const {
   // Print out build configuration options that impact the compiler's runtime
   // behavior. Intended for identifying the source of issues when reproducing
   // changes.
-  std::vector BuildOptions = {
-#if !__OPTIMIZE__
-  "+unoptimized",
+  SmallVector BuildOptions = {
+#if __GNUC__ && !__OPTIMIZE__
+// FIXME: __OPTIMIZE__ is not available on MSVC, this will never show there
+"+unoptimized",
 #endif
 #ifndef NDEBUG
-  "+assertions",
+"+assertions",
 #endif
 #ifdef EXPENSIVE_CHECKS
-  "+expensive-checks",
+"+expensive-checks",
 #endif
 #if __has_feature(address_sanitizer)
-  "+asan",
+"+asan",
 #endif
 #if __has_feature(undefined_behavior_sanitizer)
-  "+ubsan",
+"+ubsan",
 #endif
 #if __has_feature(memory_sanitizer)
-  "+msan",
+"+msan",
 #endif
 #if __has_feature(dataflow_sanitizer)
-  "+dfsan",
+"+dfsan",
 #endif
   };
   if (!BuildOptions.empty()) {
-OS << "Build configuration: ";
-bool FirstOption = true;
-for (const auto &Option : BuildOptions) {
-  if (!FirstOption)
-OS << ", ";
-  OS << Option;
-  FirstOption = false;
-}
+OS << "Build config: ";
+llvm::interleaveComma(BuildOptions, OS, [&OS](const StringRef &Option) {
+OS << Option;
+});
 OS << '\n';
   }
 

>From 1213ba2f965a0577fc6504e967ae17346da4ef4f Mon Sep 17 00:00:00 2001
From: Cassie Jones 
Date: Wed, 3 Apr 2024 22:02:19 -0700
Subject: [PATCH 3/7] Move LLVM_IS_DEBUG_BUILD into Support/CommandLine.h

Allow us to reuse this logic in the feature printing.
---
 clang/lib/Driver/Driver.cpp |  3 +--
 llvm/include/llvm/Support/CommandLine.h | 22 ++
 llvm/lib/Support/CommandLine.cpp| 

[clang] [ARM64EC] Fix compilation of intrin.h in ARM64EC mode. (PR #87717)

2024-04-04 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic created 
https://github.com/llvm/llvm-project/pull/87717

intrin.h checks for x86_64. But the "x86_64" define is also defined for 
ARM64EC, and we don't support all the intrinsics in ARM64EC mode. Fix the 
preprocessor checks to handle this correctly.  (If we actually need some of 
these intrinsics in ARM64EC mode, we can revisit later.)

Not exactly sure how I didn't run into this issue before now... I think I've 
built code that requires these headers, but maybe not since the define fix 
landed.

>From 4de12f20fe15262a63414c8fe3bcd23b777853b3 Mon Sep 17 00:00:00 2001
From: Eli Friedman 
Date: Thu, 4 Apr 2024 14:25:36 -0700
Subject: [PATCH] [ARM64EC] Fix compilation of intrin.h in ARM64EC mode.

intrin.h checks for x86_64, but we don't support all the intrinsics in
ARM64EC mode. Fix the preprocessor checks to handle this correctly.  (If
we actually need some of these intrinsics in ARM64EC mode, we can
revisit later.)

Not exactly sure how I didn't run into this issue before now... I think
I've built code that requires these headers, but maybe not since the
define fix landed.
---
 clang/lib/Headers/intrin.h   | 17 +
 clang/lib/Headers/intrin0.h  |  4 ++--
 clang/test/Headers/ms-intrin.cpp | 14 --
 3 files changed, 23 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Headers/intrin.h b/clang/lib/Headers/intrin.h
index fd27955fbe002d..40073b4a9f9c31 100644
--- a/clang/lib/Headers/intrin.h
+++ b/clang/lib/Headers/intrin.h
@@ -18,7 +18,7 @@
 #include 
 
 /* First include the standard intrinsics. */
-#if defined(__i386__) || defined(__x86_64__)
+#if defined(__i386__) || (defined(__x86_64__) && !defined(__arm64ec__))
 #include 
 #endif
 
@@ -166,7 +166,7 @@ unsigned __int32 xbegin(void);
 void _xend(void);
 
 /* These additional intrinsics are turned on in x64/amd64/x86_64 mode. */
-#ifdef __x86_64__
+#if defined(__x86_64__) && !defined(__arm64ec__)
 void __addgsbyte(unsigned long, unsigned char);
 void __addgsdword(unsigned long, unsigned long);
 void __addgsqword(unsigned long, unsigned __int64);
@@ -236,7 +236,8 @@ __int64 _mul128(__int64, __int64, __int64 *);
 
/**\
 |* movs, stos
 
\**/
-#if defined(__i386__) || defined(__x86_64__)
+
+#if defined(__i386__) || (defined(__x86_64__) && !defined(__arm64ec__))
 static __inline__ void __DEFAULT_FN_ATTRS __movsb(unsigned char *__dst,
   unsigned char const *__src,
   size_t __n) {
@@ -305,7 +306,7 @@ static __inline__ void __DEFAULT_FN_ATTRS __stosw(unsigned 
short *__dst,
: "memory");
 }
 #endif
-#ifdef __x86_64__
+#if defined(__x86_64__) && !defined(__arm64ec__)
 static __inline__ void __DEFAULT_FN_ATTRS __movsq(
 unsigned long long *__dst, unsigned long long const *__src, size_t __n) {
   __asm__ __volatile__("rep movsq"
@@ -324,7 +325,7 @@ static __inline__ void __DEFAULT_FN_ATTRS __stosq(unsigned 
__int64 *__dst,
 
/**\
 |* Misc
 
\**/
-#if defined(__i386__) || defined(__x86_64__)
+#if defined(__i386__) || (defined(__x86_64__) && !defined(__arm64ec__))
 static __inline__ void __DEFAULT_FN_ATTRS __halt(void) {
   __asm__ volatile("hlt");
 }
@@ -339,7 +340,7 @@ static __inline__ void __DEFAULT_FN_ATTRS __nop(void) {
 
/**\
 |* MS AArch64 specific
 
\**/
-#if defined(__aarch64__)
+#if defined(__aarch64__) || defined(__arm64ec__)
 unsigned __int64 __getReg(int);
 long _InterlockedAdd(long volatile *Addend, long Value);
 __int64 _InterlockedAdd64(__int64 volatile *Addend, __int64 Value);
@@ -383,7 +384,7 @@ void __cdecl __prefetch(void *);
 
/**\
 |* Privileged intrinsics
 
\**/
-#if defined(__i386__) || defined(__x86_64__)
+#if defined(__i386__) || (defined(__x86_64__)  && !defined(__arm64ec__))
 static __inline__ unsigned __int64 __DEFAULT_FN_ATTRS
 __readmsr(unsigned long __register) {
   // Loads the contents of a 64-bit model specific register (MSR) specified in
@@ -397,7 +398,6 @@ __readmsr(unsigned long __register) {
   __asm__ ("rdmsr" : "=d"(__edx), "=a"(__eax) : "c"(__register));
   return (((unsigned __int64)__edx) << 32) | (unsigned __int64)__eax;
 }
-#endif
 
 static __inline__ unsigned __LPTRINT_TYPE__ __DEFAULT_FN_ATTRS __readcr3(void) 
{
   unsigned __LPTRINT_TYPE__ __cr3_val;
@@ -413,6 +413,7 @@ static __inline__ void __DEFAULT_FN_ATTRS
 __writecr3(unsigne

[clang] [ARM64EC] Fix compilation of intrin.h in ARM64EC mode. (PR #87717)

2024-04-04 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-x86

@llvm/pr-subscribers-clang

Author: Eli Friedman (efriedma-quic)


Changes

intrin.h checks for x86_64. But the "x86_64" define is also defined for 
ARM64EC, and we don't support all the intrinsics in ARM64EC mode. Fix the 
preprocessor checks to handle this correctly.  (If we actually need some of 
these intrinsics in ARM64EC mode, we can revisit later.)

Not exactly sure how I didn't run into this issue before now... I think I've 
built code that requires these headers, but maybe not since the define fix 
landed.

---
Full diff: https://github.com/llvm/llvm-project/pull/87717.diff


3 Files Affected:

- (modified) clang/lib/Headers/intrin.h (+9-8) 
- (modified) clang/lib/Headers/intrin0.h (+2-2) 
- (modified) clang/test/Headers/ms-intrin.cpp (+12-2) 


``diff
diff --git a/clang/lib/Headers/intrin.h b/clang/lib/Headers/intrin.h
index fd27955fbe002d..40073b4a9f9c31 100644
--- a/clang/lib/Headers/intrin.h
+++ b/clang/lib/Headers/intrin.h
@@ -18,7 +18,7 @@
 #include 
 
 /* First include the standard intrinsics. */
-#if defined(__i386__) || defined(__x86_64__)
+#if defined(__i386__) || (defined(__x86_64__) && !defined(__arm64ec__))
 #include 
 #endif
 
@@ -166,7 +166,7 @@ unsigned __int32 xbegin(void);
 void _xend(void);
 
 /* These additional intrinsics are turned on in x64/amd64/x86_64 mode. */
-#ifdef __x86_64__
+#if defined(__x86_64__) && !defined(__arm64ec__)
 void __addgsbyte(unsigned long, unsigned char);
 void __addgsdword(unsigned long, unsigned long);
 void __addgsqword(unsigned long, unsigned __int64);
@@ -236,7 +236,8 @@ __int64 _mul128(__int64, __int64, __int64 *);
 
/**\
 |* movs, stos
 
\**/
-#if defined(__i386__) || defined(__x86_64__)
+
+#if defined(__i386__) || (defined(__x86_64__) && !defined(__arm64ec__))
 static __inline__ void __DEFAULT_FN_ATTRS __movsb(unsigned char *__dst,
   unsigned char const *__src,
   size_t __n) {
@@ -305,7 +306,7 @@ static __inline__ void __DEFAULT_FN_ATTRS __stosw(unsigned 
short *__dst,
: "memory");
 }
 #endif
-#ifdef __x86_64__
+#if defined(__x86_64__) && !defined(__arm64ec__)
 static __inline__ void __DEFAULT_FN_ATTRS __movsq(
 unsigned long long *__dst, unsigned long long const *__src, size_t __n) {
   __asm__ __volatile__("rep movsq"
@@ -324,7 +325,7 @@ static __inline__ void __DEFAULT_FN_ATTRS __stosq(unsigned 
__int64 *__dst,
 
/**\
 |* Misc
 
\**/
-#if defined(__i386__) || defined(__x86_64__)
+#if defined(__i386__) || (defined(__x86_64__) && !defined(__arm64ec__))
 static __inline__ void __DEFAULT_FN_ATTRS __halt(void) {
   __asm__ volatile("hlt");
 }
@@ -339,7 +340,7 @@ static __inline__ void __DEFAULT_FN_ATTRS __nop(void) {
 
/**\
 |* MS AArch64 specific
 
\**/
-#if defined(__aarch64__)
+#if defined(__aarch64__) || defined(__arm64ec__)
 unsigned __int64 __getReg(int);
 long _InterlockedAdd(long volatile *Addend, long Value);
 __int64 _InterlockedAdd64(__int64 volatile *Addend, __int64 Value);
@@ -383,7 +384,7 @@ void __cdecl __prefetch(void *);
 
/**\
 |* Privileged intrinsics
 
\**/
-#if defined(__i386__) || defined(__x86_64__)
+#if defined(__i386__) || (defined(__x86_64__)  && !defined(__arm64ec__))
 static __inline__ unsigned __int64 __DEFAULT_FN_ATTRS
 __readmsr(unsigned long __register) {
   // Loads the contents of a 64-bit model specific register (MSR) specified in
@@ -397,7 +398,6 @@ __readmsr(unsigned long __register) {
   __asm__ ("rdmsr" : "=d"(__edx), "=a"(__eax) : "c"(__register));
   return (((unsigned __int64)__edx) << 32) | (unsigned __int64)__eax;
 }
-#endif
 
 static __inline__ unsigned __LPTRINT_TYPE__ __DEFAULT_FN_ATTRS __readcr3(void) 
{
   unsigned __LPTRINT_TYPE__ __cr3_val;
@@ -413,6 +413,7 @@ static __inline__ void __DEFAULT_FN_ATTRS
 __writecr3(unsigned __INTPTR_TYPE__ __cr3_val) {
   __asm__ ("mov {%0, %%cr3|cr3, %0}" : : "r"(__cr3_val) : "memory");
 }
+#endif
 
 #ifdef __cplusplus
 }
diff --git a/clang/lib/Headers/intrin0.h b/clang/lib/Headers/intrin0.h
index 31f362ec84d5c5..338535d3d51736 100644
--- a/clang/lib/Headers/intrin0.h
+++ b/clang/lib/Headers/intrin0.h
@@ -15,7 +15,7 @@
 #ifndef __INTRIN0_H
 #define __INTRIN0_H
 
-#ifdef __x86_64__
+#if defined(__x86_64__) && !defined(__arm64ec__)
 #include 
 #endif
 
@@ -55,7 +55,7 @@ unsigned __int64

[clang] [ARM64EC] Fix compilation of intrin.h in ARM64EC mode. (PR #87717)

2024-04-04 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

CC @bylaws @mstorsjo @cjacek @MaxEW707 @CaseyCarter

https://github.com/llvm/llvm-project/pull/87717
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Cyndy Ishida via cfe-commits


@@ -654,6 +654,11 @@ enabled sub-projects. Nearly all of these variable names 
begin with
   Generate dSYM files and strip executables and libraries (Darwin Only).
   Defaults to OFF.
 
+**LLVM_ENABLE_EXPORTED_SYMBOLS**:BOOL
+  When building executables, preserve symbol exports. Defaults to ON. 
+  You can use this option to disable exported symbols on all executable build

cyndyishida wrote:

That's what I initially thought as well but a lot of the LLVM_INCLUDE* 
variables on the lines below follow a "You can use this option..." And they 
also have similar behavior which defaults to ON. 

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ARM64EC] Fix compilation of intrin.h in ARM64EC mode. (PR #87717)

2024-04-04 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff eeaaf33fc296d52a28252ba0d6cfe187b7b3412f 
4de12f20fe15262a63414c8fe3bcd23b777853b3 -- clang/lib/Headers/intrin.h 
clang/lib/Headers/intrin0.h clang/test/Headers/ms-intrin.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Headers/intrin.h b/clang/lib/Headers/intrin.h
index 40073b4a9f..e890dcd7fe 100644
--- a/clang/lib/Headers/intrin.h
+++ b/clang/lib/Headers/intrin.h
@@ -384,7 +384,7 @@ void __cdecl __prefetch(void *);
 
/**\
 |* Privileged intrinsics
 
\**/
-#if defined(__i386__) || (defined(__x86_64__)  && !defined(__arm64ec__))
+#if defined(__i386__) || (defined(__x86_64__) && !defined(__arm64ec__))
 static __inline__ unsigned __int64 __DEFAULT_FN_ATTRS
 __readmsr(unsigned long __register) {
   // Loads the contents of a 64-bit model specific register (MSR) specified in

``




https://github.com/llvm/llvm-project/pull/87717
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Jonas Devlieghere via cfe-commits


@@ -673,6 +673,9 @@ option(LLVM_USE_OPROFILE
 option(LLVM_EXTERNALIZE_DEBUGINFO
   "Generate dSYM files and strip executables and libraries (Darwin Only)" OFF)
 
+option(LLVM_ENABLE_EXPORTED_SYMBOLS

JDevlieghere wrote:

"tools" has a pretty specific meaning for LLVM so I think that will actually 
cause more confusion (i.e. I would expect that option to apply to 
`llvm-dwarfdump`, but not to `clang`). I'm personally fine with the current 
concise name. 

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 75e7e7d - [flang] Add --gcc-toolchain and --gcc-install-dir options to flang. (#87360)

2024-04-04 Thread via cfe-commits

Author: Michael Kruse
Date: 2024-04-05T00:02:06+02:00
New Revision: 75e7e7d327e0458b151fbe1e6b3a9ac0a5081f76

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

LOG: [flang] Add --gcc-toolchain and --gcc-install-dir options to flang. 
(#87360)

The `--gcc-toolchain` and `--gcc-install-dir` option were previously only 
visible to the Clang driver, but not Flang. These determine which assembler, 
linker, and libraries to use, e.g. for cross-compiling, and therefore are 
relevant for Flang as well.

Tests are implemented using a mock GCC installation in `basic_cross_linux_tree` 
copied over from Clang's tests. The Clang driver already contains tests with 
`--driver-mode=flang` but `flang-new` is an entirely different executable 
(containing the `-fc1` stage) that should be tested as well. While not all 
files in `basic_cross_linux_tree` are strictly needed for testing those two 
driver flags, they will be necessarily needed for future added flags such as 
`--rtlib`.
 
Also remove the entry `*.o` in flang's `.gitignore` since `crt*.o` files are 
needed in the GCC mock installation.

Fixes #86729

Added: 

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/bin/i386-unknown-linux-gnu-as

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/bin/i386-unknown-linux-gnu-ld

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/bin/i386-unknown-linux-gnu-ld.bfd

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/bin/i386-unknown-linux-gnu-ld.gold

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/bin/x86_64-unknown-linux-gnu-as

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/bin/x86_64-unknown-linux-gnu-ld

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/bin/x86_64-unknown-linux-gnu-ld.bfd

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/bin/x86_64-unknown-linux-gnu-ld.gold

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/i386-unknown-linux-gnu/bin/as

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/i386-unknown-linux-gnu/bin/ld

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/i386-unknown-linux-gnu/bin/ld.bfd

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/i386-unknown-linux-gnu/bin/ld.gold

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/i386-unknown-linux-gnu/lib/.keep

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/lib/gcc/i386-unknown-linux-gnu/10.2.0/crtbegin.o

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/10.2.0/crtbegin.o

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/10.2.0/crtbeginT.o

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/10.2.0/crtfastmath.o

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/10.2.0/x32/crtbegin.o

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/10.2.0/x32/crtbeginT.o

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/lib/gcc/x86_64-unknown-linux-gnu/10.2.0/x32/crtfastmath.o

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/x86_64-unknown-linux-gnu/bin/as

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/x86_64-unknown-linux-gnu/bin/ld

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/x86_64-unknown-linux-gnu/bin/ld.bfd

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/x86_64-unknown-linux-gnu/bin/ld.gold

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/x86_64-unknown-linux-gnu/bin/ld.lld

flang/test/Driver/Inputs/basic_cross_linux_tree/usr/x86_64-unknown-linux-gnu/lib/.keep
flang/test/Driver/gcc-toolchain-install-dir.f90

Modified: 
clang/include/clang/Driver/Options.td
flang/.gitignore
flang/test/Driver/driver-help-hidden.f90
flang/test/Driver/driver-help.f90

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c3e90a70925b78..12e8dc7912c3b8 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -802,9 +802,11 @@ def B : JoinedOrSeparate<["-"], "B">, 
MetaVarName<"">,
 HelpText<"Search $prefix$file for executables, libraries, and data files. "
 "If $prefix is a directory, search $prefix/$file">;
 def gcc_install_dir_EQ : Joined<["--"], "gcc-install-dir=">,
+  Visibility<[ClangOption, FlangOption]>,
   HelpText<"Use GCC installation in the specified directory. The directory 
ends with path components like 'lib{,32,64}/gcc{,-cross}/$triple/$version'. "
   "Note: executables (e.g. ld) used by the compiler are not overridden by the 
selected GCC installation">;
 def gcc_toolchain : Joined<["--"], "gcc-toolchain=">, Flags<[NoXarchOption]>,
+  Visibility<[ClangOption, FlangOption]>,
   HelpTe

[clang] [flang] [flang] Add --gcc-toolchain and --gcc-install-dir options to flang. (PR #87360)

2024-04-04 Thread Michael Kruse via cfe-commits

https://github.com/Meinersbur closed 
https://github.com/llvm/llvm-project/pull/87360
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][CodeGen] Guard ubsan checks with `llvm.allow.ubsan.check` (PR #87436)

2024-04-04 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka updated 
https://github.com/llvm/llvm-project/pull/87436

>From eec9a27ff0451b923d8ca7d4ff23eb6b8dffa56c Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Tue, 2 Apr 2024 17:18:58 -0700
Subject: [PATCH 1/3] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20ch?=
 =?UTF-8?q?anges=20to=20main=20this=20commit=20is=20based=20on?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4

[skip ci]
---
 clang/test/CodeGen/allow-ubsan-check.c | 207 +
 1 file changed, 207 insertions(+)
 create mode 100644 clang/test/CodeGen/allow-ubsan-check.c

diff --git a/clang/test/CodeGen/allow-ubsan-check.c 
b/clang/test/CodeGen/allow-ubsan-check.c
new file mode 100644
index 00..bc425230c8ec75
--- /dev/null
+++ b/clang/test/CodeGen/allow-ubsan-check.c
@@ -0,0 +1,207 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 4
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -o - %s 
-fsanitize=signed-integer-overflow,integer-divide-by-zero,null | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -o - %s 
-fsanitize=signed-integer-overflow,integer-divide-by-zero,null 
-fsanitize-trap=signed-integer-overflow,integer-divide-by-zero,null | FileCheck 
%s --check-prefixes=TRAP
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -emit-llvm -o - %s 
-fsanitize=signed-integer-overflow,integer-divide-by-zero,null 
-fsanitize-recover=signed-integer-overflow,integer-divide-by-zero,null | 
FileCheck %s --check-prefixes=RECOVER
+
+
+// CHECK-LABEL: define dso_local i32 @div(
+// CHECK-SAME: i32 noundef [[X:%.*]], i32 noundef [[Y:%.*]]) #[[ATTR0:[0-9]+]] 
{
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[X_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:[[Y_ADDR:%.*]] = alloca i32, align 4
+// CHECK-NEXT:store i32 [[X]], ptr [[X_ADDR]], align 4
+// CHECK-NEXT:store i32 [[Y]], ptr [[Y_ADDR]], align 4
+// CHECK-NEXT:[[TMP0:%.*]] = load i32, ptr [[X_ADDR]], align 4
+// CHECK-NEXT:[[TMP1:%.*]] = load i32, ptr [[Y_ADDR]], align 4
+// CHECK-NEXT:[[TMP2:%.*]] = icmp ne i32 [[TMP1]], 0, !nosanitize 
[[META2:![0-9]+]]
+// CHECK-NEXT:[[TMP3:%.*]] = icmp ne i32 [[TMP0]], -2147483648, 
!nosanitize [[META2]]
+// CHECK-NEXT:[[TMP4:%.*]] = icmp ne i32 [[TMP1]], -1, !nosanitize 
[[META2]]
+// CHECK-NEXT:[[OR:%.*]] = or i1 [[TMP3]], [[TMP4]], !nosanitize [[META2]]
+// CHECK-NEXT:[[TMP5:%.*]] = and i1 [[TMP2]], [[OR]], !nosanitize [[META2]]
+// CHECK-NEXT:br i1 [[TMP5]], label [[CONT:%.*]], label 
[[HANDLER_DIVREM_OVERFLOW:%.*]], !prof [[PROF3:![0-9]+]], !nosanitize [[META2]]
+// CHECK:   handler.divrem_overflow:
+// CHECK-NEXT:[[TMP6:%.*]] = zext i32 [[TMP0]] to i64, !nosanitize 
[[META2]]
+// CHECK-NEXT:[[TMP7:%.*]] = zext i32 [[TMP1]] to i64, !nosanitize 
[[META2]]
+// CHECK-NEXT:call void @__ubsan_handle_divrem_overflow_abort(ptr 
@[[GLOB1:[0-9]+]], i64 [[TMP6]], i64 [[TMP7]]) #[[ATTR3:[0-9]+]], !nosanitize 
[[META2]]
+// CHECK-NEXT:unreachable, !nosanitize [[META2]]
+// CHECK:   cont:
+// CHECK-NEXT:[[DIV:%.*]] = sdiv i32 [[TMP0]], [[TMP1]]
+// CHECK-NEXT:ret i32 [[DIV]]
+//
+// TRAP-LABEL: define dso_local i32 @div(
+// TRAP-SAME: i32 noundef [[X:%.*]], i32 noundef [[Y:%.*]]) #[[ATTR0:[0-9]+]] {
+// TRAP-NEXT:  entry:
+// TRAP-NEXT:[[X_ADDR:%.*]] = alloca i32, align 4
+// TRAP-NEXT:[[Y_ADDR:%.*]] = alloca i32, align 4
+// TRAP-NEXT:store i32 [[X]], ptr [[X_ADDR]], align 4
+// TRAP-NEXT:store i32 [[Y]], ptr [[Y_ADDR]], align 4
+// TRAP-NEXT:[[TMP0:%.*]] = load i32, ptr [[X_ADDR]], align 4
+// TRAP-NEXT:[[TMP1:%.*]] = load i32, ptr [[Y_ADDR]], align 4
+// TRAP-NEXT:[[TMP2:%.*]] = icmp ne i32 [[TMP1]], 0, !nosanitize 
[[META2:![0-9]+]]
+// TRAP-NEXT:[[TMP3:%.*]] = icmp ne i32 [[TMP0]], -2147483648, !nosanitize 
[[META2]]
+// TRAP-NEXT:[[TMP4:%.*]] = icmp ne i32 [[TMP1]], -1, !nosanitize [[META2]]
+// TRAP-NEXT:[[OR:%.*]] = or i1 [[TMP3]], [[TMP4]], !nosanitize [[META2]]
+// TRAP-NEXT:[[TMP5:%.*]] = and i1 [[TMP2]], [[OR]], !nosanitize [[META2]]
+// TRAP-NEXT:br i1 [[TMP5]], label [[CONT:%.*]], label [[TRAP:%.*]], 
!nosanitize [[META2]]
+// TRAP:   trap:
+// TRAP-NEXT:call void @llvm.ubsantrap(i8 3) #[[ATTR3:[0-9]+]], 
!nosanitize [[META2]]
+// TRAP-NEXT:unreachable, !nosanitize [[META2]]
+// TRAP:   cont:
+// TRAP-NEXT:[[DIV:%.*]] = sdiv i32 [[TMP0]], [[TMP1]]
+// TRAP-NEXT:ret i32 [[DIV]]
+//
+// RECOVER-LABEL: define dso_local i32 @div(
+// RECOVER-SAME: i32 noundef [[X:%.*]], i32 noundef [[Y:%.*]]) 
#[[ATTR0:[0-9]+]] {
+// RECOVER-NEXT:  entry:
+// RECOVER-NEXT:[[X_ADDR:%.*]] = alloca i32, align 4
+// RECOVER-NEXT:[[Y_ADDR:%.*]] = alloca i32, align 4
+// RECOVER-NEXT:store i32 [[X]], ptr [[X_ADDR]], align 4
+// RECOVER-NEXT:store i32 [[Y]], ptr [[Y_ADDR]], align 4
+// RECOVER-NEXT:[[TMP0:%.*]] = l

[clang] [lldb] [llvm] [cmake] Build executables with -no_exported_symbols when building Apple toolchain (PR #87684)

2024-04-04 Thread Cyndy Ishida via cfe-commits


@@ -673,6 +673,9 @@ option(LLVM_USE_OPROFILE
 option(LLVM_EXTERNALIZE_DEBUGINFO
   "Generate dSYM files and strip executables and libraries (Darwin Only)" OFF)
 
+option(LLVM_ENABLE_EXPORTED_SYMBOLS

cyndyishida wrote:

Would `LLVM_ENABLE_EXECUTABLES_WITH_EXPORTED_SYMBOLS` be too long?

https://github.com/llvm/llvm-project/pull/87684
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [cmake] Remove custom linker flag check function (PR #86602)

2024-04-04 Thread Keith Smiley via cfe-commits

https://github.com/keith updated https://github.com/llvm/llvm-project/pull/86602

>From 36886d298c349246b18684cd76dad9dd245f10ba Mon Sep 17 00:00:00 2001
From: Keith Smiley 
Date: Mon, 25 Mar 2024 16:42:39 -0700
Subject: [PATCH] [cmake] Remove custom linker flag check function

Since LLVM now requires a minimum cmake version of 3.20.0, we no longer
need this abstraction and can use the built in version directly as we do
for the other feature check functions.
---
 clang/tools/clang-repl/CMakeLists.txt|  2 +-
 clang/tools/driver/CMakeLists.txt|  4 +--
 clang/tools/libclang/CMakeLists.txt  |  3 +--
 llvm/cmake/modules/AddLLVM.cmake |  4 +--
 llvm/cmake/modules/HandleLLVMOptions.cmake   |  8 +++---
 llvm/cmake/modules/HandleLLVMStdlib.cmake|  6 ++---
 llvm/cmake/modules/LLVMCheckLinkerFlag.cmake | 28 
 7 files changed, 13 insertions(+), 42 deletions(-)
 delete mode 100644 llvm/cmake/modules/LLVMCheckLinkerFlag.cmake

diff --git a/clang/tools/clang-repl/CMakeLists.txt 
b/clang/tools/clang-repl/CMakeLists.txt
index d3dec1984b78d2..69634f78aeafe8 100644
--- a/clang/tools/clang-repl/CMakeLists.txt
+++ b/clang/tools/clang-repl/CMakeLists.txt
@@ -29,7 +29,7 @@ endif()
 # gold. This flag tells the linker to build a PLT for the full address range.
 # Linkers without this flag are assumed to support proper PLTs by default.
 set(flag_long_plt "-Wl,--long-plt")
-llvm_check_linker_flag(CXX ${flag_long_plt} HAVE_LINKER_FLAG_LONG_PLT)
+check_linker_flag(CXX ${flag_long_plt} HAVE_LINKER_FLAG_LONG_PLT)
 if(HAVE_LINKER_FLAG_LONG_PLT)
   target_link_options(clang-repl PRIVATE ${flag_long_plt})
 endif()
diff --git a/clang/tools/driver/CMakeLists.txt 
b/clang/tools/driver/CMakeLists.txt
index d70b92b0984e52..ca825d9b3e036e 100644
--- a/clang/tools/driver/CMakeLists.txt
+++ b/clang/tools/driver/CMakeLists.txt
@@ -104,7 +104,7 @@ endif()
 
 if(CLANG_ORDER_FILE AND
 (LLVM_LINKER_IS_APPLE OR LLVM_LINKER_IS_GOLD OR LLVM_LINKER_IS_LLD))
-  include(LLVMCheckLinkerFlag)
+  include(CheckLinkerFlag)
 
   if (LLVM_LINKER_IS_APPLE OR (LLVM_LINKER_IS_LLD AND APPLE))
 set(LINKER_ORDER_FILE_OPTION "-Wl,-order_file,${CLANG_ORDER_FILE}")
@@ -115,7 +115,7 @@ if(CLANG_ORDER_FILE AND
   endif()
 
   # This is a test to ensure the actual order file works with the linker.
-  llvm_check_linker_flag(CXX ${LINKER_ORDER_FILE_OPTION} 
LINKER_ORDER_FILE_WORKS)
+  check_linker_flag(CXX ${LINKER_ORDER_FILE_OPTION} LINKER_ORDER_FILE_WORKS)
 
   # Passing an empty order file disables some linker layout optimizations.
   # To work around this and enable workflows for re-linking when the order file
diff --git a/clang/tools/libclang/CMakeLists.txt 
b/clang/tools/libclang/CMakeLists.txt
index b5b6d2807d714c..32abedf59478b7 100644
--- a/clang/tools/libclang/CMakeLists.txt
+++ b/clang/tools/libclang/CMakeLists.txt
@@ -190,8 +190,7 @@ if(ENABLE_SHARED)
   include(CheckLinkerFlag)
   # The Solaris 11.4 linker supports a subset of GNU ld version scripts,
   # but requires a special option to enable it.
-  llvm_check_linker_flag(CXX "-Wl,-z,gnu-version-script-compat"
- LINKER_SUPPORTS_Z_GNU_VERSION_SCRIPT_COMPAT)
+  check_linker_flag(CXX "-Wl,-z,gnu-version-script-compat" 
LINKER_SUPPORTS_Z_GNU_VERSION_SCRIPT_COMPAT)
   # Older Solaris (and illumos) linker does not support GNU ld version 
scripts
   # and does not support GNU version script compat.
   if (LINKER_SUPPORTS_Z_GNU_VERSION_SCRIPT_COMPAT)
diff --git a/llvm/cmake/modules/AddLLVM.cmake b/llvm/cmake/modules/AddLLVM.cmake
index 745935f1405170..32693bdd3d3197 100644
--- a/llvm/cmake/modules/AddLLVM.cmake
+++ b/llvm/cmake/modules/AddLLVM.cmake
@@ -302,8 +302,8 @@ function(add_link_opts target_name)
   elseif(${CMAKE_SYSTEM_NAME} MATCHES "SunOS" AND LLVM_LINKER_IS_SOLARISLD)
 # Support for ld -z discard-unused=sections was only added in
 # Solaris 11.4.  GNU ld ignores it, but warns every time.
-include(LLVMCheckLinkerFlag)
-llvm_check_linker_flag(CXX "-Wl,-z,discard-unused=sections" 
LINKER_SUPPORTS_Z_DISCARD_UNUSED)
+include(CheckLinkerFlag)
+check_linker_flag(CXX "-Wl,-z,discard-unused=sections" 
LINKER_SUPPORTS_Z_DISCARD_UNUSED)
 if (LINKER_SUPPORTS_Z_DISCARD_UNUSED)
   set_property(TARGET ${target_name} APPEND_STRING PROPERTY
LINK_FLAGS " -Wl,-z,discard-unused=sections")
diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index 185266c0861e86..a4688f069f7210 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -1077,8 +1077,8 @@ if (LLVM_USE_SPLIT_DWARF AND
   if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR
   CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
 add_compile_options($<$:-gsplit-dwarf>)
-include(LLVMCheckLinkerFlag)
-llvm_check_linker_flag(CXX "-Wl,--gdb-index" LINKER_SUPPOR

[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-04 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay edited 
https://github.com/llvm/llvm-project/pull/87130
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-04 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/87130

>From 23422a0b3af3e070fed5ae86ed0f67acec066c0a Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Fri, 29 Mar 2024 17:48:14 -0700
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.5-bogner
---
 clang/lib/Sema/CMakeLists.txt |  1 +
 clang/lib/Sema/SemaDeclAttr.cpp   | 31 +--
 clang/test/AST/ast-dump-attr-json.cpp |  1 +
 clang/test/Sema/alias-unused.c| 30 +-
 4 files changed, 51 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Sema/CMakeLists.txt b/clang/lib/Sema/CMakeLists.txt
index e8bff07ced0cfa..7657536fabd1eb 100644
--- a/clang/lib/Sema/CMakeLists.txt
+++ b/clang/lib/Sema/CMakeLists.txt
@@ -1,5 +1,6 @@
 set(LLVM_LINK_COMPONENTS
   Core
+  Demangle
   FrontendHLSL
   FrontendOpenMP
   MC
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index f25f3afd0f4af2..8ed5242f325e5e 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -42,6 +42,7 @@
 #include "clang/Sema/SemaInternal.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/Demangle/Demangle.h"
 #include "llvm/IR/Assumptions.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/Support/Error.h"
@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);
+  if (Demangled)
+Str = Demangled;
+  const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
+  LookupResult LR(S, target, Sema::LookupOrdinaryName);
+  if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
+for (NamedDecl *ND : LR)
+  ND->markUsed(S.Context);
+  free(Demangled);
+}
+
 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   StringRef Str;
   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
@@ -1992,6 +2010,7 @@ static void handleIFuncAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 return;
   }
 
+  markUsedForAliasOrIfunc(S, D, AL, Str);
   D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
 }
 
@@ -2026,17 +2045,7 @@ static void handleAliasAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 }
   }
 
-  // Mark target used to prevent unneeded-internal-declaration warnings.
-  if (!S.LangOpts.CPlusPlus) {
-// FIXME: demangle Str for C++, as the attribute refers to the mangled
-// linkage name, not the pre-mangled identifier.
-const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
-LookupResult LR(S, target, Sema::LookupOrdinaryName);
-if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
-  for (NamedDecl *ND : LR)
-ND->markUsed(S.Context);
-  }
-
+  markUsedForAliasOrIfunc(S, D, AL, Str);
   D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
 }
 
diff --git a/clang/test/AST/ast-dump-attr-json.cpp 
b/clang/test/AST/ast-dump-attr-json.cpp
index 051c2956abfdf7..883e584bfedf07 100644
--- a/clang/test/AST/ast-dump-attr-json.cpp
+++ b/clang/test/AST/ast-dump-attr-json.cpp
@@ -46,6 +46,7 @@ __thread __attribute__ ((tls_model ("local-exec"))) int 
tls_model_var;
 // CHECK-NEXT:"tokLen": 11
 // CHECK-NEXT:   }
 // CHECK-NEXT:  },
+// CHECK-NEXT:  "isUsed": true,
 // CHECK-NEXT:  "name": "global_decl",
 // CHECK-NEXT:  "mangledName": "global_decl",
 // CHECK-NEXT:  "type": {
diff --git a/clang/test/Sema/alias-unused.c b/clang/test/Sema/alias-unused.c
index de9fc8cc737662..030b5737a93a21 100644
--- a/clang/test/Sema/alias-unused.c
+++ b/clang/test/Sema/alias-unused.c
@@ -1,7 +1,35 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunneeded-internal-declaration -x 
c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c++ -verify %s
+
+#ifdef __cplusplus
+extern "C" {
+#else
 // expected-no-diagnostics
+#endif
 static int f(void) { return 42; }
 int g(void) __attribute__((alias("f")));
 
 static int foo [] = { 42, 0xDEAD };
 extern typeof(foo) bar __attribute__((unused, alias("foo")));
+
+static int (*resolver(void))(void) { return f; }
+int ifunc(void) __attribute__((ifunc("resolver")));
+
+#ifdef __cplusplus
+}
+
+/// We demangle alias/ifunc target and mark all found functions as used.
+static int f1(int

[clang] [OpenACC][NFC] Add OpenACC Clause AST Nodes/infrastructure (PR #87675)

2024-04-04 Thread Alexey Bataev via cfe-commits


@@ -11751,3 +11753,67 @@ void ASTRecordReader::readOMPChildren(OMPChildren 
*Data) {
   for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
 Data->getChildren()[I] = readStmt();
 }
+
+OpenACCClause *ASTRecordReader::readOpenACCClause() {
+  OpenACCClauseKind ClauseKind = readEnum();
+  SourceLocation BeginLoc = readSourceLocation();
+  SourceLocation EndLoc = readSourceLocation();
+
+  // TODO OpenACC: We don't have these used anywhere, but eventually we should
+  // be constructing the Clauses with them, so these casts can go away.
+  (void)BeginLoc;
+  (void)EndLoc;

alexey-bataev wrote:

[[maybe_unused]]?

https://github.com/llvm/llvm-project/pull/87675
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [OpenACC][NFC] Add OpenACC Clause AST Nodes/infrastructure (PR #87675)

2024-04-04 Thread Alexey Bataev via cfe-commits


@@ -47,6 +58,7 @@ class OpenACCConstructStmt : public Stmt {
 
   SourceLocation getBeginLoc() const { return Range.getBegin(); }
   SourceLocation getEndLoc() const { return Range.getEnd(); }
+  const ArrayRef clauses() const { return Clauses; }

alexey-bataev wrote:

```suggestion
  ArrayRef clauses() const { return Clauses; }
```

https://github.com/llvm/llvm-project/pull/87675
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [OpenACC][NFC] Add OpenACC Clause AST Nodes/infrastructure (PR #87675)

2024-04-04 Thread Alexey Bataev via cfe-commits


@@ -30,13 +31,23 @@ class OpenACCConstructStmt : public Stmt {
   /// the directive.
   SourceRange Range;
 
-  // TODO OPENACC: Clauses should probably be collected in this class.
+  /// The list of clauses.  This is stored here as an ArrayRef, as this is the
+  /// most convienient place to access the list, however the list itself should
+  /// be stored in leaf nodes, likely in trailing-storage.
+  MutableArrayRef Clauses;

alexey-bataev wrote:

Why need to keep as MutbleArrayRef, not just ArrayRef?

https://github.com/llvm/llvm-project/pull/87675
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [OpenACC][NFC] Add OpenACC Clause AST Nodes/infrastructure (PR #87675)

2024-04-04 Thread Alexey Bataev via cfe-commits


@@ -94,9 +94,10 @@ StmtResult 
SemaOpenACC::ActOnEndStmtDirective(OpenACCDirectiveKind K,
   case OpenACCDirectiveKind::Parallel:
   case OpenACCDirectiveKind::Serial:
   case OpenACCDirectiveKind::Kernels:
+// TODO OpenACC: Add clauses to the construct here.
 return OpenACCComputeConstruct::Create(
 getASTContext(), K, StartLoc, EndLoc,
-AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
+/*Clauses=*/{}, AssocStmt.isUsable() ? AssocStmt.get() : nullptr);

alexey-bataev wrote:

```suggestion
/*Clauses=*/std::nullopt, AssocStmt.isUsable() ? AssocStmt.get() : 
nullptr);
```

https://github.com/llvm/llvm-project/pull/87675
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [OpenACC][NFC] Add OpenACC Clause AST Nodes/infrastructure (PR #87675)

2024-04-04 Thread Alexey Bataev via cfe-commits


@@ -101,24 +113,45 @@ class OpenACCAssociatedStmtConstruct : public 
OpenACCConstructStmt {
 /// those three, as they are semantically identical, and have only minor
 /// differences in the permitted list of clauses, which can be differentiated 
by
 /// the 'Kind'.
-class OpenACCComputeConstruct : public OpenACCAssociatedStmtConstruct {
+class OpenACCComputeConstruct final
+: public OpenACCAssociatedStmtConstruct,
+  public llvm::TrailingObjects {
   friend class ASTStmtWriter;
   friend class ASTStmtReader;
   friend class ASTContext;
-  OpenACCComputeConstruct()
-  : OpenACCAssociatedStmtConstruct(
-OpenACCComputeConstructClass, OpenACCDirectiveKind::Invalid,
-SourceLocation{}, SourceLocation{}, /*AssociatedStmt=*/nullptr) {}
+  OpenACCComputeConstruct(unsigned NumClauses)
+  : OpenACCAssociatedStmtConstruct(OpenACCComputeConstructClass,
+   OpenACCDirectiveKind::Invalid,
+   SourceLocation{}, SourceLocation{},
+   /*AssociatedStmt=*/nullptr) {
+// We cannot send the TrailingObjects storage to the base class (which 
holds
+// a reference to the data) until it is constructed, so we have to set it
+// separately here.
+memset(getTrailingObjects(), 0,
+   NumClauses * sizeof(const OpenACCClause *));

alexey-bataev wrote:

I think there is something like uninitialized_init or something like , which 
can be used instead

https://github.com/llvm/llvm-project/pull/87675
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-04 Thread Fangrui Song via cfe-commits


@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);

MaskRay wrote:

I added a `S.getASTContext().getCXXABIKind() != TargetCXXABI::Microsoft` check.

Note: while `alias` works for Windows, it is only checked in tests 
CodeGenCXX/visibility-dllstorageclass.cpp/CodeGen/debug-info-alias-pointer.c . 
I don't consider it used publicly.

I've also updated the description to say that our behavior is different from 
GCC for `extern "C" { static void f(); }`. So, the C++ handling is best-effort.

https://github.com/llvm/llvm-project/pull/87130
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-04 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay edited 
https://github.com/llvm/llvm-project/pull/87130
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-04 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay edited 
https://github.com/llvm/llvm-project/pull/87130
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-04 Thread Fangrui Song via cfe-commits


@@ -1,7 +1,35 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunneeded-internal-declaration -x 
c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c++ -verify %s
+
+#ifdef __cplusplus
+extern "C" {
+#else
 // expected-no-diagnostics
+#endif
 static int f(void) { return 42; }
 int g(void) __attribute__((alias("f")));
 
 static int foo [] = { 42, 0xDEAD };
 extern typeof(foo) bar __attribute__((unused, alias("foo")));
+
+static int (*resolver(void))(void) { return f; }
+int ifunc(void) __attribute__((ifunc("resolver")));
+
+#ifdef __cplusplus
+}
+
+/// We demangle alias/ifunc target and mark all found functions as used.
+static int f1(int) { return 42; }

MaskRay wrote:

Added AST::createMangleContex and avoided false positives.

https://github.com/llvm/llvm-project/pull/87130
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] Mark alias/ifunc targets used and consider mangled names (PR #87130)

2024-04-04 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/87130

>From 23422a0b3af3e070fed5ae86ed0f67acec066c0a Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Fri, 29 Mar 2024 17:48:14 -0700
Subject: [PATCH 1/2] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20in?=
 =?UTF-8?q?itial=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.5-bogner
---
 clang/lib/Sema/CMakeLists.txt |  1 +
 clang/lib/Sema/SemaDeclAttr.cpp   | 31 +--
 clang/test/AST/ast-dump-attr-json.cpp |  1 +
 clang/test/Sema/alias-unused.c| 30 +-
 4 files changed, 51 insertions(+), 12 deletions(-)

diff --git a/clang/lib/Sema/CMakeLists.txt b/clang/lib/Sema/CMakeLists.txt
index e8bff07ced0cfa..7657536fabd1eb 100644
--- a/clang/lib/Sema/CMakeLists.txt
+++ b/clang/lib/Sema/CMakeLists.txt
@@ -1,5 +1,6 @@
 set(LLVM_LINK_COMPONENTS
   Core
+  Demangle
   FrontendHLSL
   FrontendOpenMP
   MC
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index f25f3afd0f4af2..8ed5242f325e5e 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -42,6 +42,7 @@
 #include "clang/Sema/SemaInternal.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/Demangle/Demangle.h"
 #include "llvm/IR/Assumptions.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/Support/Error.h"
@@ -1980,6 +1981,23 @@ static void handleWeakRefAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
 }
 
+// Mark alias/ifunc target as used. For C++, we look up the demangled name
+// ignoring parameters. This should handle the majority of use cases while
+// leaveing false positives for namespace scope names and false negatives in
+// the presence of overloads.
+static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
+StringRef Str) {
+  char *Demangled = llvm::itaniumDemangle(Str, /*ParseParams=*/false);
+  if (Demangled)
+Str = Demangled;
+  const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
+  LookupResult LR(S, target, Sema::LookupOrdinaryName);
+  if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
+for (NamedDecl *ND : LR)
+  ND->markUsed(S.Context);
+  free(Demangled);
+}
+
 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   StringRef Str;
   if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
@@ -1992,6 +2010,7 @@ static void handleIFuncAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 return;
   }
 
+  markUsedForAliasOrIfunc(S, D, AL, Str);
   D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
 }
 
@@ -2026,17 +2045,7 @@ static void handleAliasAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 }
   }
 
-  // Mark target used to prevent unneeded-internal-declaration warnings.
-  if (!S.LangOpts.CPlusPlus) {
-// FIXME: demangle Str for C++, as the attribute refers to the mangled
-// linkage name, not the pre-mangled identifier.
-const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
-LookupResult LR(S, target, Sema::LookupOrdinaryName);
-if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
-  for (NamedDecl *ND : LR)
-ND->markUsed(S.Context);
-  }
-
+  markUsedForAliasOrIfunc(S, D, AL, Str);
   D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
 }
 
diff --git a/clang/test/AST/ast-dump-attr-json.cpp 
b/clang/test/AST/ast-dump-attr-json.cpp
index 051c2956abfdf7..883e584bfedf07 100644
--- a/clang/test/AST/ast-dump-attr-json.cpp
+++ b/clang/test/AST/ast-dump-attr-json.cpp
@@ -46,6 +46,7 @@ __thread __attribute__ ((tls_model ("local-exec"))) int 
tls_model_var;
 // CHECK-NEXT:"tokLen": 11
 // CHECK-NEXT:   }
 // CHECK-NEXT:  },
+// CHECK-NEXT:  "isUsed": true,
 // CHECK-NEXT:  "name": "global_decl",
 // CHECK-NEXT:  "mangledName": "global_decl",
 // CHECK-NEXT:  "type": {
diff --git a/clang/test/Sema/alias-unused.c b/clang/test/Sema/alias-unused.c
index de9fc8cc737662..030b5737a93a21 100644
--- a/clang/test/Sema/alias-unused.c
+++ b/clang/test/Sema/alias-unused.c
@@ -1,7 +1,35 @@
-// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunneeded-internal-declaration -x 
c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c -verify %s
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -Wunused -x c++ -verify %s
+
+#ifdef __cplusplus
+extern "C" {
+#else
 // expected-no-diagnostics
+#endif
 static int f(void) { return 42; }
 int g(void) __attribute__((alias("f")));
 
 static int foo [] = { 42, 0xDEAD };
 extern typeof(foo) bar __attribute__((unused, alias("foo")));
+
+static int (*resolver(void))(void) { return f; }
+int ifunc(void) __attribute__((ifunc("resolver")));
+
+#ifdef __cplusplus
+}
+
+/// We demangle alias/ifunc target and mark all found functions as used.
+static int f1

  1   2   3   >