[llvm] [clang] [clang-tools-extra] [InstCombine] Convert or concat to fshl if opposite or concat exists (PR #68502)

2023-11-12 Thread Nikita Popov via cfe-commits

nikic wrote:

Yes, I understand that this transform is only a step towards handling the full 
pattern. I'm asking for a complete, working example of the original motivating 
case. The snippets posted in 
https://github.com/llvm/llvm-project/pull/68502#discussion_r1351618002 do not 
appear to be correct, or I failed to assemble them correctly. Please provide 
complete src and tgt functions that verify with alive2.

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


[clang] 40671bb - [clang-format] Handle control statements in BreakAfterAttributes (#71995)

2023-11-12 Thread via cfe-commits

Author: Owen Pan
Date: 2023-11-12T01:08:27-08:00
New Revision: 40671bbdefb6ff83e2685576a3cb041b62f25bbe

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

LOG: [clang-format] Handle control statements in BreakAfterAttributes (#71995)

This patch doesn't work for do-while loops.

Fixed #64474.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index d496fc85f7ae71a..ff424828ff63cdb 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2049,8 +2049,10 @@ the configuration (without a prefix: ``Auto``).
 .. _BreakAfterAttributes:
 
 **BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16` :ref:`¶ `
-  Break after a group of C++11 attributes before a variable/function
-  (including constructor/destructor) declaration/definition name.
+  Break after a group of C++11 attributes before variable or function
+  (including constructor/destructor) declaration/definition names or before
+  control statements, i.e. ``if``, ``switch`` (including ``case`` and
+  ``default`` labels), ``for``, and ``while`` statements.
 
   Possible values:
 
@@ -2063,11 +2065,28 @@ the configuration (without a prefix: ``Auto``).
   const int i;
   [[gnu::const]] [[maybe_unused]]
   int j;
+
   [[nodiscard]]
   inline int f();
   [[gnu::const]] [[nodiscard]]
   int g();
 
+  [[likely]]
+  if (a)
+f();
+  else
+g();
+
+  switch (b) {
+  [[unlikely]]
+  case 1:
+++b;
+break;
+  [[likely]]
+  default:
+return;
+  }
+
   * ``ABS_Leave`` (in configuration: ``Leave``)
 Leave the line breaking after attributes as is.
 
@@ -2076,10 +2095,25 @@ the configuration (without a prefix: ``Auto``).
   [[maybe_unused]] const int i;
   [[gnu::const]] [[maybe_unused]]
   int j;
+
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]]
   int g();
 
+  [[likely]] if (a)
+f();
+  else
+g();
+
+  switch (b) {
+  [[unlikely]] case 1:
+++b;
+break;
+  [[likely]]
+  default:
+return;
+  }
+
   * ``ABS_Never`` (in configuration: ``Never``)
 Never break after attributes.
 
@@ -2087,9 +2121,23 @@ the configuration (without a prefix: ``Auto``).
 
   [[maybe_unused]] const int i;
   [[gnu::const]] [[maybe_unused]] int j;
+
   [[nodiscard]] inline int f();
   [[gnu::const]] [[nodiscard]] int g();
 
+  [[likely]] if (a)
+f();
+  else
+g();
+
+  switch (b) {
+  [[unlikely]] case 1:
+++b;
+break;
+  [[likely]] default:
+return;
+  }
+
 
 
 .. _BreakAfterJavaFieldAnnotations:

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 9442344000e142b..bc412611ef62493 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1432,10 +1432,27 @@ struct FormatStyle {
 ///   const int i;
 ///   [[gnu::const]] [[maybe_unused]]
 ///   int j;
+///
 ///   [[nodiscard]]
 ///   inline int f();
 ///   [[gnu::const]] [[nodiscard]]
 ///   int g();
+///
+///   [[likely]]
+///   if (a)
+/// f();
+///   else
+/// g();
+///
+///   switch (b) {
+///   [[unlikely]]
+///   case 1:
+/// ++b;
+/// break;
+///   [[likely]]
+///   default:
+/// return;
+///   }
 /// \endcode
 ABS_Always,
 /// Leave the line breaking after attributes as is.
@@ -1443,23 +1460,54 @@ struct FormatStyle {
 ///   [[maybe_unused]] const int i;
 ///   [[gnu::const]] [[maybe_unused]]
 ///   int j;
+///
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]]
 ///   int g();
+///
+///   [[likely]] if (a)
+/// f();
+///   else
+/// g();
+///
+///   switch (b) {
+///   [[unlikely]] case 1:
+/// ++b;
+/// break;
+///   [[likely]]
+///   default:
+/// return;
+///   }
 /// \endcode
 ABS_Leave,
 /// Never break after attributes.
 /// \code
 ///   [[maybe_unused]] const int i;
 ///   [[gnu::const]] [[maybe_unused]] int j;
+///
 ///   [[nodiscard]] inline int f();
 ///   [[gnu::const]] [[nodiscard]] int g();
+///
+///   [[likely]] if (a)
+/// f();
+///   else
+/// g();
+///
+///   switch (b) {
+///   [[unlikely]] c

[clang] [clang-format] Handle control statements in BreakAfterAttributes (PR #71995)

2023-11-12 Thread Owen Pan via cfe-commits

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


[clang] [Driver] Add LTO support for Haiku and OpenBSD (PR #72047)

2023-11-12 Thread Brad Smith via cfe-commits

https://github.com/brad0 created https://github.com/llvm/llvm-project/pull/72047

None

>From 9f374ff55cb851534a8c882770d9237f1d40a8b8 Mon Sep 17 00:00:00 2001
From: Brad Smith 
Date: Sat, 21 Oct 2023 02:18:34 -0400
Subject: [PATCH] [Driver] Add LTO support for Haiku and OpenBSD

---
 clang/lib/Driver/ToolChains/CommonArgs.cpp |  3 ++-
 clang/lib/Driver/ToolChains/Haiku.cpp  | 14 ++
 clang/lib/Driver/ToolChains/OpenBSD.cpp| 14 ++
 clang/test/Driver/emulated-tls.cpp |  2 ++
 clang/test/Driver/haiku.c  |  5 +
 clang/test/Driver/openbsd.c|  5 +
 clang/test/Driver/save-stats.c |  5 -
 7 files changed, 46 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index a81c9b6201f8158..5d2cd1959b06925 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -598,7 +598,8 @@ void tools::addLTOOptions(const ToolChain &ToolChain, const 
ArgList &Args,
   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
   const Driver &D = ToolChain.getDriver();
   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
-  llvm::sys::path::stem(Linker) != "ld.lld") {
+  llvm::sys::path::stem(Linker) != "ld.lld" &&
+  !ToolChain.getTriple().isOSOpenBSD()) {
 // Tell the linker to load the plugin. This has to come before
 // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to
 // come before any -plugin-opt/-bplugin_opt that -Wl might forward.
diff --git a/clang/lib/Driver/ToolChains/Haiku.cpp 
b/clang/lib/Driver/ToolChains/Haiku.cpp
index 1c2d6bcaf9b457d..e0d94035823fd37 100644
--- a/clang/lib/Driver/ToolChains/Haiku.cpp
+++ b/clang/lib/Driver/ToolChains/Haiku.cpp
@@ -83,6 +83,20 @@ void haiku::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 options::OPT_s, options::OPT_t, options::OPT_r});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
+  if (D.isUsingLTO()) {
+assert(!Inputs.empty() && "Must have at least one input.");
+// Find the first filename InputInfo object.
+auto Input = llvm::find_if(
+Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); });
+if (Input == Inputs.end())
+  // For a very rare case, all of the inputs to the linker are
+  // InputArg. If that happens, just use the first InputInfo.
+  Input = Inputs.begin();
+
+addLTOOptions(ToolChain, Args, CmdArgs, Output, *Input,
+  D.getLTOMode() == LTOK_Thin);
+  }
+
   addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs);
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
diff --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index d9f6b20f43ad854..798b39ce86badce 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -195,6 +195,20 @@ void openbsd::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
 options::OPT_t, options::OPT_r});
 
+  if (D.isUsingLTO()) {
+assert(!Inputs.empty() && "Must have at least one input.");
+// Find the first filename InputInfo object.
+auto Input = llvm::find_if(
+Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); });
+if (Input == Inputs.end())
+  // For a very rare case, all of the inputs to the linker are
+  // InputArg. If that happens, just use the first InputInfo.
+  Input = Inputs.begin();
+
+addLTOOptions(ToolChain, Args, CmdArgs, Output, *Input,
+  D.getLTOMode() == LTOK_Thin);
+  }
+
   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
diff --git a/clang/test/Driver/emulated-tls.cpp 
b/clang/test/Driver/emulated-tls.cpp
index 2044bc89a36634a..3ee901a8358589e 100644
--- a/clang/test/Driver/emulated-tls.cpp
+++ b/clang/test/Driver/emulated-tls.cpp
@@ -39,6 +39,8 @@
 // RUN: | FileCheck %s --check-prefix=LTO_EMUTLS
 // RUN: %clang -### -flto --target=riscv64-linux-android1 
-fno-emulated-tls %s 2>&1 \
 // RUN: | FileCheck %s --check-prefix=LTO_NOEMUTLS
+// RUN: %clang -### -flto --target=amd64-unknown-openbsd %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=LTO_EMUTLS
 
 // Default without -f[no-]emulated-tls, will be decided by the target triple.
 // DEFAULT-NOT: "-cc1" {{.*}}"-femulated-tls"
diff --git a/clang/test/Driver/haiku.c b/clang/test/Driver/haiku.c
index 965d3cf97bc36bf..e907c34b29b9955 100644
--- a/clang/test/Driver/haiku.c
+++ b/clang/test/Driver/haiku.c
@@ -75,3 +75,8 @@
 // RUN: %clang -### %s 2>&1 --target=arm-unknown-haiku \
 // RUN:   | FileCheck --check-prefix=CHECK-ARM-CPU %s
 // CHECK-ARM-CPU: "-targe

[clang] [Driver] Add LTO support for Haiku and OpenBSD (PR #72047)

2023-11-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Brad Smith (brad0)


Changes



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


7 Files Affected:

- (modified) clang/lib/Driver/ToolChains/CommonArgs.cpp (+2-1) 
- (modified) clang/lib/Driver/ToolChains/Haiku.cpp (+14) 
- (modified) clang/lib/Driver/ToolChains/OpenBSD.cpp (+14) 
- (modified) clang/test/Driver/emulated-tls.cpp (+2) 
- (modified) clang/test/Driver/haiku.c (+5) 
- (modified) clang/test/Driver/openbsd.c (+5) 
- (modified) clang/test/Driver/save-stats.c (+4-1) 


``diff
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index a81c9b6201f8158..5d2cd1959b06925 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -598,7 +598,8 @@ void tools::addLTOOptions(const ToolChain &ToolChain, const 
ArgList &Args,
   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
   const Driver &D = ToolChain.getDriver();
   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
-  llvm::sys::path::stem(Linker) != "ld.lld") {
+  llvm::sys::path::stem(Linker) != "ld.lld" &&
+  !ToolChain.getTriple().isOSOpenBSD()) {
 // Tell the linker to load the plugin. This has to come before
 // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to
 // come before any -plugin-opt/-bplugin_opt that -Wl might forward.
diff --git a/clang/lib/Driver/ToolChains/Haiku.cpp 
b/clang/lib/Driver/ToolChains/Haiku.cpp
index 1c2d6bcaf9b457d..e0d94035823fd37 100644
--- a/clang/lib/Driver/ToolChains/Haiku.cpp
+++ b/clang/lib/Driver/ToolChains/Haiku.cpp
@@ -83,6 +83,20 @@ void haiku::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 options::OPT_s, options::OPT_t, options::OPT_r});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
+  if (D.isUsingLTO()) {
+assert(!Inputs.empty() && "Must have at least one input.");
+// Find the first filename InputInfo object.
+auto Input = llvm::find_if(
+Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); });
+if (Input == Inputs.end())
+  // For a very rare case, all of the inputs to the linker are
+  // InputArg. If that happens, just use the first InputInfo.
+  Input = Inputs.begin();
+
+addLTOOptions(ToolChain, Args, CmdArgs, Output, *Input,
+  D.getLTOMode() == LTOK_Thin);
+  }
+
   addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs);
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
diff --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index d9f6b20f43ad854..798b39ce86badce 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -195,6 +195,20 @@ void openbsd::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
 options::OPT_t, options::OPT_r});
 
+  if (D.isUsingLTO()) {
+assert(!Inputs.empty() && "Must have at least one input.");
+// Find the first filename InputInfo object.
+auto Input = llvm::find_if(
+Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); });
+if (Input == Inputs.end())
+  // For a very rare case, all of the inputs to the linker are
+  // InputArg. If that happens, just use the first InputInfo.
+  Input = Inputs.begin();
+
+addLTOOptions(ToolChain, Args, CmdArgs, Output, *Input,
+  D.getLTOMode() == LTOK_Thin);
+  }
+
   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
diff --git a/clang/test/Driver/emulated-tls.cpp 
b/clang/test/Driver/emulated-tls.cpp
index 2044bc89a36634a..3ee901a8358589e 100644
--- a/clang/test/Driver/emulated-tls.cpp
+++ b/clang/test/Driver/emulated-tls.cpp
@@ -39,6 +39,8 @@
 // RUN: | FileCheck %s --check-prefix=LTO_EMUTLS
 // RUN: %clang -### -flto --target=riscv64-linux-android1 
-fno-emulated-tls %s 2>&1 \
 // RUN: | FileCheck %s --check-prefix=LTO_NOEMUTLS
+// RUN: %clang -### -flto --target=amd64-unknown-openbsd %s 2>&1 \
+// RUN: | FileCheck %s --check-prefix=LTO_EMUTLS
 
 // Default without -f[no-]emulated-tls, will be decided by the target triple.
 // DEFAULT-NOT: "-cc1" {{.*}}"-femulated-tls"
diff --git a/clang/test/Driver/haiku.c b/clang/test/Driver/haiku.c
index 965d3cf97bc36bf..e907c34b29b9955 100644
--- a/clang/test/Driver/haiku.c
+++ b/clang/test/Driver/haiku.c
@@ -75,3 +75,8 @@
 // RUN: %clang -### %s 2>&1 --target=arm-unknown-haiku \
 // RUN:   | FileCheck --check-prefix=CHECK-ARM-CPU %s
 // CHECK-ARM-CPU: "-target-cpu" "arm1176jzf-s"
+
+// Check passing LTO flags to the linker
+// RUN: %clang --target=x86_64-unknown-haiku -flto -### %s 2>&1 \
+// RUN:   | FileCheck -check

[clang-tools-extra] [clang-tidy] Fixes to readability-implicit-bool-conversion (PR #72050)

2023-11-12 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL created 
https://github.com/llvm/llvm-project/pull/72050

- Fixed issue with invalid code being generated when static_cast is put into 
fix, and no space were added before it.
- Fixed issue with duplicate parentheses being added when double implicit cast 
is used.

Closes #71848 

>From cf2f1aebe660bf8c94486e976f35d474dcc484f0 Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Sun, 12 Nov 2023 11:31:21 +
Subject: [PATCH] [clang-tidy] Fixes to readability-implicit-bool-conversion

- Fixed issue with invalid code being generated when static_cast
  is put into fix, and no space were added before it.
- Fixed issue with duplicate parentheses being added when double
  implicit cast is used.
---
 .../ImplicitBoolConversionCheck.cpp   | 22 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |  3 ++-
 .../readability/implicit-bool-conversion.cpp  |  9 
 3 files changed, 29 insertions(+), 5 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 69e6d73c4fcd7bb..5e71b2fc81de7f0 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -173,16 +173,30 @@ StringRef getEquivalentBoolLiteralForExpr(const Expr 
*Expression,
   return {};
 }
 
+bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) {
+  SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc);
+  StringRef SpaceBeforeStmtStr = Lexer::getSourceText(
+  CharSourceRange::getCharRange(PrefixRange), Context.getSourceManager(),
+  Context.getLangOpts(), nullptr);
+  if (SpaceBeforeStmtStr.empty())
+return true;
+
+  const StringRef AllowedCharacters(" \t\n\v\f\r(){}[]<>;,+=-|&~!^*/");
+  return SpaceBeforeStmtStr.rtrim(AllowedCharacters).size() ==
+ SpaceBeforeStmtStr.size();
+}
+
 void fixGenericExprCastFromBool(DiagnosticBuilder &Diag,
 const ImplicitCastExpr *Cast,
 ASTContext &Context, StringRef OtherType) {
   const Expr *SubExpr = Cast->getSubExpr();
-  bool NeedParens = !isa(SubExpr);
+  const bool NeedParens = !isa(SubExpr->IgnoreImplicit());
+  const bool NeedSpace = needsSpacePrefix(Cast->getBeginLoc(), Context);
 
   Diag << FixItHint::CreateInsertion(
-  Cast->getBeginLoc(),
-  (Twine("static_cast<") + OtherType + ">" + (NeedParens ? "(" : ""))
-  .str());
+  Cast->getBeginLoc(), (Twine() + (NeedSpace ? " " : "") + "static_cast<" +
+OtherType + ">" + (NeedParens ? "(" : ""))
+   .str());
 
   if (NeedParens) {
 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index f49c412118e7d98..e0353e4344e9b6a 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -410,7 +410,8 @@ Changes in existing checks
 - Improved :doc:`readability-implicit-bool-conversion
   ` check to take
   do-while loops into account for the `AllowIntegerConditions` and
-  `AllowPointerConditions` options.
+  `AllowPointerConditions` options. Additionally, an issue with auto-fix
+  suggestions generating invalid code in certain scenarios has been resolved.
 
 - Improved :doc:`readability-non-const-parameter
   ` check to ignore
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
index 323cf813c047000..3929984204905d3 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
@@ -478,3 +478,12 @@ namespace PR47000 {
   using IntType = int;
   int to_int2(bool x) { return IntType{x}; }
 }
+
+namespace PR71848 {
+  int fun() {
+bool foo = false;
+return( foo );
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: implicit conversion bool -> 'int' 
[readability-implicit-bool-conversion]
+// CHECK-FIXES: return static_cast( foo );
+  }
+}

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


[clang-tools-extra] [clang-tidy] Fixes to readability-implicit-bool-conversion (PR #72050)

2023-11-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Piotr Zegar (PiotrZSL)


Changes

- Fixed issue with invalid code being generated when static_cast is put into 
fix, and no space were added before it.
- Fixed issue with duplicate parentheses being added when double implicit cast 
is used.

Closes #71848 

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


3 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
(+18-4) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+2-1) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
 (+9) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 69e6d73c4fcd7bb..5e71b2fc81de7f0 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -173,16 +173,30 @@ StringRef getEquivalentBoolLiteralForExpr(const Expr 
*Expression,
   return {};
 }
 
+bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context) {
+  SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc);
+  StringRef SpaceBeforeStmtStr = Lexer::getSourceText(
+  CharSourceRange::getCharRange(PrefixRange), Context.getSourceManager(),
+  Context.getLangOpts(), nullptr);
+  if (SpaceBeforeStmtStr.empty())
+return true;
+
+  const StringRef AllowedCharacters(" \t\n\v\f\r(){}[]<>;,+=-|&~!^*/");
+  return SpaceBeforeStmtStr.rtrim(AllowedCharacters).size() ==
+ SpaceBeforeStmtStr.size();
+}
+
 void fixGenericExprCastFromBool(DiagnosticBuilder &Diag,
 const ImplicitCastExpr *Cast,
 ASTContext &Context, StringRef OtherType) {
   const Expr *SubExpr = Cast->getSubExpr();
-  bool NeedParens = !isa(SubExpr);
+  const bool NeedParens = !isa(SubExpr->IgnoreImplicit());
+  const bool NeedSpace = needsSpacePrefix(Cast->getBeginLoc(), Context);
 
   Diag << FixItHint::CreateInsertion(
-  Cast->getBeginLoc(),
-  (Twine("static_cast<") + OtherType + ">" + (NeedParens ? "(" : ""))
-  .str());
+  Cast->getBeginLoc(), (Twine() + (NeedSpace ? " " : "") + "static_cast<" +
+OtherType + ">" + (NeedParens ? "(" : ""))
+   .str());
 
   if (NeedParens) {
 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index f49c412118e7d98..e0353e4344e9b6a 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -410,7 +410,8 @@ Changes in existing checks
 - Improved :doc:`readability-implicit-bool-conversion
   ` check to take
   do-while loops into account for the `AllowIntegerConditions` and
-  `AllowPointerConditions` options.
+  `AllowPointerConditions` options. Additionally, an issue with auto-fix
+  suggestions generating invalid code in certain scenarios has been resolved.
 
 - Improved :doc:`readability-non-const-parameter
   ` check to ignore
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
index 323cf813c047000..3929984204905d3 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
@@ -478,3 +478,12 @@ namespace PR47000 {
   using IntType = int;
   int to_int2(bool x) { return IntType{x}; }
 }
+
+namespace PR71848 {
+  int fun() {
+bool foo = false;
+return( foo );
+// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: implicit conversion bool -> 'int' 
[readability-implicit-bool-conversion]
+// CHECK-FIXES: return static_cast( foo );
+  }
+}

``




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


[clang-tools-extra] [llvm] [clang] [InstCombine] Convert or concat to fshl if opposite or concat exists (PR #68502)

2023-11-12 Thread via cfe-commits

HaohaiWen wrote:

> Yes, I understand that this transform is only a step towards handling the 
> full pattern. I'm asking for a complete, working example of the original 
> motivating case. The snippets posted in [#68502 
> (comment)](https://github.com/llvm/llvm-project/pull/68502#discussion_r1351618002)
>  do not appear to be correct, or I failed to assemble them correctly. Please 
> provide complete src and tgt functions that verify with alive2.

Oh... sorry, I made a wrong IR example.
The real case looks like this: https://alive2.llvm.org/ce/z/-DXnJc
Both %x and %y are i16. The first or/fshl swaps half of of i32. The rest swaps 
byte, 4bit, 2bit.
I extended the fshl transformation to apply for both symmetric and asymmetric 
combination.



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


[clang-tools-extra] [llvm] [clang] [InstCombine] Convert or concat to fshl if opposite or concat exists (PR #68502)

2023-11-12 Thread via cfe-commits


@@ -2727,105 +2727,161 @@ Instruction 
*InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
 }
 
 /// Match UB-safe variants of the funnel shift intrinsic.
-static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
+static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC,
+ const DominatorTree &DT) {
   // TODO: Can we reduce the code duplication between this and the related
   // rotate matching code under visitSelect and visitTrunc?
   unsigned Width = Or.getType()->getScalarSizeInBits();
 
-  // First, find an or'd pair of opposite shifts:
-  // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
-  BinaryOperator *Or0, *Or1;
-  if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
-  !match(Or.getOperand(1), m_BinOp(Or1)))
+  Instruction *Or0, *Or1;
+  if (!match(Or.getOperand(0), m_Instruction(Or0)) ||
+  !match(Or.getOperand(1), m_Instruction(Or1)))
 return nullptr;
 
-  Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
-  if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0 
||
-  !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1 
||
-  Or0->getOpcode() == Or1->getOpcode())
-return nullptr;
+  bool IsFshl = true; // Sub on LSHR.
+  SmallVector FShiftArgs;
 
-  // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
-  if (Or0->getOpcode() == BinaryOperator::LShr) {
-std::swap(Or0, Or1);
-std::swap(ShVal0, ShVal1);
-std::swap(ShAmt0, ShAmt1);
-  }
-  assert(Or0->getOpcode() == BinaryOperator::Shl &&
- Or1->getOpcode() == BinaryOperator::LShr &&
- "Illegal or(shift,shift) pair");
-
-  // Match the shift amount operands for a funnel shift pattern. This always
-  // matches a subtraction on the R operand.
-  auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
-// Check for constant shift amounts that sum to the bitwidth.
-const APInt *LI, *RI;
-if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
-  if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
-return ConstantInt::get(L->getType(), *LI);
-
-Constant *LC, *RC;
-if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
-match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) 
&&
-match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) 
&&
-match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
-  return ConstantExpr::mergeUndefsWith(LC, RC);
-
-// (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
-// We limit this to X < Width in case the backend re-expands the intrinsic,
-// and has to reintroduce a shift modulo operation (InstCombine might 
remove
-// it after this fold). This still doesn't guarantee that the final codegen
-// will match this original pattern.
-if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L) {
-  KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
-  return KnownL.getMaxValue().ult(Width) ? L : nullptr;
+  // First, find an or'd pair of opposite shifts:
+  // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
+  if (isa(Or0) && isa(Or1)) {
+Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
+if (!match(Or0,
+   m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0 ||
+!match(Or1,
+   m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1 ||
+Or0->getOpcode() == Or1->getOpcode())
+  return nullptr;
+
+// Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
+if (Or0->getOpcode() == BinaryOperator::LShr) {
+  std::swap(Or0, Or1);
+  std::swap(ShVal0, ShVal1);
+  std::swap(ShAmt0, ShAmt1);
 }
+assert(Or0->getOpcode() == BinaryOperator::Shl &&
+   Or1->getOpcode() == BinaryOperator::LShr &&
+   "Illegal or(shift,shift) pair");
+
+// Match the shift amount operands for a funnel shift pattern. This always
+// matches a subtraction on the R operand.
+auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * 
{
+  // Check for constant shift amounts that sum to the bitwidth.
+  const APInt *LI, *RI;
+  if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
+if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
+  return ConstantInt::get(L->getType(), *LI);
+
+  Constant *LC, *RC;
+  if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
+  match(L,
+m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
+  match(R,
+m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
+  match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
+return ConstantExpr::mergeUndefsWith(LC, RC);
+
+  // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
+   

[clang] [X86][AVX10] Permit AVX512 options/features used together with AVX10 (PR #71318)

2023-11-12 Thread via cfe-commits

ronlieb wrote:

> @ronlieb Do you have a reproducer for this problem? I just checked the 
> definition of both intrinsics have `no-evex512` already, so shouldn't have 
> such problem. You can use -mno-evex512 as workaround for the problem anyway.

here is a small reproducer   , compile with 
clang++ -c fd_log_scalar.cpp  -mtune=skylake-avx512 -march=skylake-avx512 
-D_CPU=avx512

produces error : 
lib/clang/18/include/avx512fintrin.h:5493:41: error: always_inline function 
'_mm_setzero_pd' requires target feature 'evex512', but would be inlined into 
function '_mm_getexp_sd' that is compiled without support for 'evex512'
 5493 |  (__v2df) __B, (__v2df) _mm_setzero_pd(), (__mmask8) 
-1, _MM_FROUND_CUR_DIRECTION);
  | ^
1 error generated.


#include 

#if !(defined _CPU)
#error: please define _CPU - specific suffix to a function name
#endif

extern "C" double log_d_scalar(double);

double __attribute__ ((noinline)) log_d_scalar(double a_input)
{
__m128d va, vm, ve, vb;
double a, m, e, b, t;
long long  mu, eu;


#ifdef __AVX512F__
va = _mm_set_sd(a_input);
vm = _mm_getmant_sd(va, va, _MM_MANT_NORM_p75_1p5, _MM_MANT_SIGN_nan);
ve = _mm_getexp_sd(va, va);
vb = _mm_getexp_sd(vm, vm);
ve = _mm_sub_sd(ve, vb);
m = _mm_cvtsd_f64(vm);
e = _mm_cvtsd_f64(ve);
#endif
return m + e;
}



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


[clang] 8569465 - Add a Clang NATVIS visualizer for StringLiteral

2023-11-12 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-11-12T09:22:15-05:00
New Revision: 8569465adf5e6c792e88be56b0e6b24f1c74e633

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

LOG: Add a Clang NATVIS visualizer for StringLiteral

Added: 


Modified: 
clang/utils/ClangVisualizers/clang.natvis

Removed: 




diff  --git a/clang/utils/ClangVisualizers/clang.natvis 
b/clang/utils/ClangVisualizers/clang.natvis
index 9faaa8a8bba8cf0..0c09d3480b07a9a 100644
--- a/clang/utils/ClangVisualizers/clang.natvis
+++ b/clang/utils/ClangVisualizers/clang.natvis
@@ -1000,8 +1000,15 @@ For later versions of Visual Studio, no setup is 
required-->
 
   
   
+{*(clang::StringLiteral *)this}
 Expression of class 
{(clang::Stmt::StmtClass)StmtBits.sClass,en} and type 
{TR,view(cpp)}
   
+  
+
+  *(unsigned *)(((clang::StringLiteral 
*)this)+1)
+  (const char 
*)(((clang::StringLiteral *)this)+1)+4+4,[*(unsigned *)(((clang::StringLiteral 
*)this)+1)]s8
+
+  
   
 public
 protected



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


[llvm] [clang] [InstCombine] Use zext's nneg flag for icmp folding (PR #70845)

2023-11-12 Thread Léonard Oest O'Leary via cfe-commits

leo-ard wrote:

> Do you have the access to merge PR?

No I don't. 

Thanks for the time and insightful comments ! 

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


[llvm] [clang-tools-extra] [clang] [InstCombine] Convert or concat to fshl if opposite or concat exists (PR #68502)

2023-11-12 Thread Nikita Popov via cfe-commits

nikic wrote:

Thanks for the updated example!

To explain what I meant in first comment using this example: We would perform 
the transform https://alive2.llvm.org/ce/z/nllcB_, which does not depend at all 
on how `%yx` is constructed, and whether there is any way to form the `fshl` 
separately. If the `%yx` is appropriately constructed, the `fshl` can be 
removed (https://alive2.llvm.org/ce/z/B_KOwv, another missing transform).

Is this not a viable approach? Is there a concern here that generating both 
fshl and bitreverse may be non-profitable for targets without bitreverse? Or 
maybe supporting this makes the matching too expensive?

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


[llvm] [clang] [InstCombine] Use zext's nneg flag for icmp folding (PR #70845)

2023-11-12 Thread Yingwei Zheng via cfe-commits

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


[clang-tools-extra] f575d79 - [clangd] Use InitLLVM (#69119)

2023-11-12 Thread via cfe-commits

Author: Aleksandr Platonov
Date: 2023-11-12T20:46:47+03:00
New Revision: f575d792c6467234076f860fe7eecced620d3aae

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

LOG: [clangd] Use InitLLVM (#69119)

This patch is similar to a7acba29c19ac67c77ed282ec9432602ae21268d but
for clangd.

It allows to pass non-UTF8 encoded command line arguments (e.g. path
where compile-commands.json file is located) on Windows.

Added: 


Modified: 
clang-tools-extra/clangd/tool/ClangdMain.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp 
b/clang-tools-extra/clangd/tool/ClangdMain.cpp
index f656a8c587c6533..9fd002d0eebba5f 100644
--- a/clang-tools-extra/clangd/tool/ClangdMain.cpp
+++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp
@@ -35,6 +35,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/Program.h"
@@ -714,8 +715,8 @@ int clangdMain(int argc, char *argv[]) {
   // Clang could run on the main thread. e.g., when the flag '-check' or 
'-sync'
   // is enabled.
   clang::noteBottomOfStack();
+  llvm::InitLLVM X(argc, argv);
   llvm::InitializeAllTargetInfos();
-  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
   llvm::sys::AddSignalHandler(
   [](void *) {
 ThreadCrashReporter::runCrashHandlers();



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


[clang-tools-extra] [clangd] Use InitLLVM (PR #69119)

2023-11-12 Thread Aleksandr Platonov via cfe-commits

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


[clang-tools-extra] [clang] [llvm] [InstCombine] Convert or concat to fshl if opposite or concat exists (PR #68502)

2023-11-12 Thread Yingwei Zheng via cfe-commits


@@ -2840,6 +2841,46 @@ static Instruction *matchFunnelShift(Instruction &Or, 
InstCombinerImpl &IC) {
   return nullptr;
 
 FShiftArgs = {ShVal0, ShVal1, ShAmt};
+  } else if (isa(Or0) || isa(Or1)) {
+// If there are two 'or' instructions concat variables in opposite order,
+// the latter one can be safely convert to fshl.
+//
+// LowHigh = or (shl (zext Low), Width - ZextHighShlAmt), (zext High)
+// HighLow = or (shl (zext High), ZextHighShlAmt), (zext Low)
+// ->
+// HighLow = fshl LowHigh, LowHigh, ZextHighShlAmt
+if (!isa(Or1))
+  std::swap(Or0, Or1);
+
+Value *High, *ZextHigh, *Low;
+const APInt *ZextHighShlAmt;
+if (!match(Or0,
+   m_OneUse(m_Shl(m_Value(ZextHigh), m_APInt(ZextHighShlAmt)
+  return nullptr;
+
+if (!match(Or1, m_ZExt(m_Value(Low))) ||
+!match(ZextHigh, m_ZExt(m_Value(High

dtcxzyw wrote:

I think we don't need to check `zext`. An example without `zext`: 
https://alive2.llvm.org/ce/z/MytePb

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -24153,6 +24153,23 @@ TEST_F(FormatTest, WhitespaceSensitiveMacros) {
   verifyNoChange("FOO(String-ized&Messy+But: :Still=Intentional);", Style);
 }
 
+TEST_F(FormatTest, IgnorePPDefinitions) {

HazardyKnusperkeks wrote:

Can you also add some nested `#if` and `#define` to show the (lacking?) 
indentation?

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -24153,6 +24153,53 @@ TEST_F(FormatTest, WhitespaceSensitiveMacros) {
   verifyNoChange("FOO(String-ized&Messy+But: :Still=Intentional);", Style);
 }
 
+TEST_F(FormatTest, IgnorePPDefinitions) {
+  FormatStyle Style = getLLVMStyle();
+  Style.IgnorePPDefinitions = true;
+
+  verifyNoChange("#define  A", Style);
+  verifyNoChange("#define A   b", Style);
+  verifyNoChange("#define A  (  args   )", Style);
+  verifyNoChange("#define A  (  args   )  =  func  (  args  )", Style);
+
+  verifyNoChange("#define A x:", Style);
+  verifyNoChange("#define A a. b", Style);
+
+  // Surrounded with formatted code
+  verifyFormat("int a;\n"
+   "#define  A  a\n"
+   "int a;",
+   "int  a ;\n"
+   "#define  A  a\n"
+   "int  a ;",
+   Style);
+
+  // Columns are not broken when a limit is set
+  Style.ColumnLimit = 10;
+  verifyNoChange("#define A a a a a", Style);
+  Style.ColumnLimit = 0;
+
+  // Multiline definition
+  verifyNoChange("#define A \\\n"
+ "Line one with spaces  .  \\\n"
+ " Line two.",
+   Style);
+  verifyNoChange("#define A \\\n"
+ "a a \\\n"
+ "a\\\na",

HazardyKnusperkeks wrote:

```suggestion
 "a\\\n"
 "a",
```

For easier reading.

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -1134,6 +1134,14 @@ void UnwrappedLineParser::parsePPDefine() {
 return;
   }
 
+  if (Style.IgnorePPDefinitions) {
+do {
+  nextToken();
+} while (!eof());

HazardyKnusperkeks wrote:

I assume you have tested this on real code. Can you explain why it is okay to 
check for `eof()`? I really don't know this code, and am a bit surprised.

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -24153,6 +24153,53 @@ TEST_F(FormatTest, WhitespaceSensitiveMacros) {
   verifyNoChange("FOO(String-ized&Messy+But: :Still=Intentional);", Style);
 }
 
+TEST_F(FormatTest, IgnorePPDefinitions) {
+  FormatStyle Style = getLLVMStyle();
+  Style.IgnorePPDefinitions = true;
+
+  verifyNoChange("#define  A", Style);
+  verifyNoChange("#define A   b", Style);
+  verifyNoChange("#define A  (  args   )", Style);
+  verifyNoChange("#define A  (  args   )  =  func  (  args  )", Style);
+
+  verifyNoChange("#define A x:", Style);
+  verifyNoChange("#define A a. b", Style);
+
+  // Surrounded with formatted code

HazardyKnusperkeks wrote:

```suggestion
  // Surrounded with formatted code.
```
Always end comments on full stop.

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -4719,6 +4723,7 @@ struct FormatStyle {
R.IncludeStyle.IncludeIsMainRegex &&
IncludeStyle.IncludeIsMainSourceRegex ==
R.IncludeStyle.IncludeIsMainSourceRegex &&
+   IgnorePPDefinitions == R.IgnorePPDefinitions &&

HazardyKnusperkeks wrote:

A few lines up.

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -1355,6 +1355,8 @@ unsigned UnwrappedLineFormatter::format(
 bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
   Indent != TheLine.First->OriginalColumn;
 bool ShouldFormat = TheLine.Affected || FixIndentation;
+if (Style.IgnorePPDefinitions && TheLine.Type == LT_PreprocessorDirective)

HazardyKnusperkeks wrote:

Wouldn't this take all preprocessor directives from the formatting? This is at 
least not what the documentation states.

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -4648,6 +4648,10 @@ struct FormatStyle {
   /// \version 11
   std::vector WhitespaceSensitiveMacros;
 
+  /// Ignore formatting in preprocessor definitions.

HazardyKnusperkeks wrote:

Run `clang/docs/tools/dump_format_style.py`.

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -24153,6 +24153,53 @@ TEST_F(FormatTest, WhitespaceSensitiveMacros) {
   verifyNoChange("FOO(String-ized&Messy+But: :Still=Intentional);", Style);
 }
 
+TEST_F(FormatTest, IgnorePPDefinitions) {
+  FormatStyle Style = getLLVMStyle();
+  Style.IgnorePPDefinitions = true;
+
+  verifyNoChange("#define  A", Style);
+  verifyNoChange("#define A   b", Style);
+  verifyNoChange("#define A  (  args   )", Style);
+  verifyNoChange("#define A  (  args   )  =  func  (  args  )", Style);
+
+  verifyNoChange("#define A x:", Style);
+  verifyNoChange("#define A a. b", Style);
+
+  // Surrounded with formatted code
+  verifyFormat("int a;\n"
+   "#define  A  a\n"
+   "int a;",
+   "int  a ;\n"
+   "#define  A  a\n"
+   "int  a ;",
+   Style);
+
+  // Columns are not broken when a limit is set
+  Style.ColumnLimit = 10;
+  verifyNoChange("#define A a a a a", Style);
+  Style.ColumnLimit = 0;
+
+  // Multiline definition
+  verifyNoChange("#define A \\\n"
+ "Line one with spaces  .  \\\n"
+ " Line two.",
+   Style);
+  verifyNoChange("#define A \\\n"
+ "a a \\\n"
+ "a\\\na",
+ Style);

HazardyKnusperkeks wrote:

This doesn't look formatted.

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -24153,6 +24153,53 @@ TEST_F(FormatTest, WhitespaceSensitiveMacros) {
   verifyNoChange("FOO(String-ized&Messy+But: :Still=Intentional);", Style);
 }
 
+TEST_F(FormatTest, IgnorePPDefinitions) {
+  FormatStyle Style = getLLVMStyle();
+  Style.IgnorePPDefinitions = true;
+
+  verifyNoChange("#define  A", Style);
+  verifyNoChange("#define A   b", Style);
+  verifyNoChange("#define A  (  args   )", Style);
+  verifyNoChange("#define A  (  args   )  =  func  (  args  )", Style);
+
+  verifyNoChange("#define A x:", Style);
+  verifyNoChange("#define A a. b", Style);
+
+  // Surrounded with formatted code
+  verifyFormat("int a;\n"
+   "#define  A  a\n"
+   "int a;",
+   "int  a ;\n"
+   "#define  A  a\n"
+   "int  a ;",
+   Style);
+
+  // Columns are not broken when a limit is set
+  Style.ColumnLimit = 10;
+  verifyNoChange("#define A a a a a", Style);
+  Style.ColumnLimit = 0;
+
+  // Multiline definition
+  verifyNoChange("#define A \\\n"
+ "Line one with spaces  .  \\\n"
+ " Line two.",
+   Style);
+  verifyNoChange("#define A \\\n"
+ "a a \\\n"
+ "a\\\na",
+ Style);

HazardyKnusperkeks wrote:

```suggestion
Style);
```

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -24153,6 +24153,23 @@ TEST_F(FormatTest, WhitespaceSensitiveMacros) {
   verifyNoChange("FOO(String-ized&Messy+But: :Still=Intentional);", Style);
 }
 
+TEST_F(FormatTest, IgnorePPDefinitions) {
+  FormatStyle Style = getLLVMStyle();
+  Style.IgnorePPDefinitions = true;
+
+  verifyNoChange("#define  A", Style);
+  verifyNoChange("#define A   b", Style);
+  verifyNoChange("#define A  (  args   )", Style);
+  verifyNoChange("#define A  (  args   )  =  func  (  args  )", Style);
+  verifyNoChange("#define TEXT \\\nLine  number  one .  \\\nNumber  two .",
+ Style);
+  verifyNoChange("#define A x:", Style);
+  verifyNoChange("#define A a. b", Style);
+
+  // TODO

HazardyKnusperkeks wrote:

Actually tests with a (line and block) comment after the `#define` would be 
interesting too, should they be wrapped? Or the space after `//` added?

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


[clang] [clang-format] Option to ignore PP directives (PR #70338)

2023-11-12 Thread Björn Schäpers via cfe-commits


@@ -24153,6 +24153,23 @@ TEST_F(FormatTest, WhitespaceSensitiveMacros) {
   verifyNoChange("FOO(String-ized&Messy+But: :Still=Intentional);", Style);
 }
 
+TEST_F(FormatTest, IgnorePPDefinitions) {
+  FormatStyle Style = getLLVMStyle();
+  Style.IgnorePPDefinitions = true;
+
+  verifyNoChange("#define  A", Style);
+  verifyNoChange("#define A   b", Style);
+  verifyNoChange("#define A  (  args   )", Style);
+  verifyNoChange("#define A  (  args   )  =  func  (  args  )", Style);
+  verifyNoChange("#define TEXT \\\nLine  number  one .  \\\nNumber  two .",
+ Style);
+  verifyNoChange("#define A x:", Style);
+  verifyNoChange("#define A a. b", Style);
+
+  // TODO

HazardyKnusperkeks wrote:

I always comment every other check out, and run only this test case in a 
debugger to look where the change is needed.

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


[clang] [clang-format][NFC] Simplify parseBracedList() (PR #72010)

2023-11-12 Thread Björn Schäpers via cfe-commits

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


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


[clang-tools-extra] [clang-tidy] Improved readability-bool-conversion to be more consistent when using parentheses (PR #72068)

2023-11-12 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 created 
https://github.com/llvm/llvm-project/pull/72068

Fixes #71852

From 54743ceec9845cdc450d5c163a293e73884a8df9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sun, 12 Nov 2023 16:07:13 -0500
Subject: [PATCH] [clang-tidy] Improved readability-bool-conversion to be more
 consistent when using parentheses

Fixes #71852
---
 .../ImplicitBoolConversionCheck.cpp   |  4 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 +++
 .../readability/implicit-bool-conversion.cpp  | 30 +++
 3 files changed, 36 insertions(+), 2 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 69e6d73c4fcd7bb..9e627d281e4b0f9 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -152,7 +152,7 @@ StringRef getEquivalentBoolLiteralForExpr(const Expr 
*Expression,
 return "false";
   }
 
-  if (const auto *IntLit = dyn_cast(Expression)) {
+  if (const auto *IntLit = 
dyn_cast(Expression->IgnoreParens())) {
 return (IntLit->getValue() == 0) ? "false" : "true";
   }
 
@@ -385,7 +385,7 @@ void ImplicitBoolConversionCheck::handleCastFromBool(
   << DestType;
 
   if (const auto *BoolLiteral =
-  dyn_cast(Cast->getSubExpr())) {
+  dyn_cast(Cast->getSubExpr()->IgnoreParens())) {
 Diag << tooling::fixit::createReplacement(
 *Cast, getEquivalentForBoolLiteral(BoolLiteral, DestType, Context));
   } else {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index f49c412118e7d98..ab9ef8cdfb37a00 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -412,6 +412,10 @@ Changes in existing checks
   do-while loops into account for the `AllowIntegerConditions` and
   `AllowPointerConditions` options.
 
+- Improved :doc:`readability-implicit-bool-conversion
+  ` check to provide
+  consistent suggestions when parentheses are added to the return value. 
+
 - Improved :doc:`readability-non-const-parameter
   ` check to ignore
   false-positives in initializer list of record.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
index 323cf813c047000..f7f5d506a9ce0e0 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
@@ -472,6 +472,36 @@ bool f(S& s) {
 
 } // namespace ignore_1bit_bitfields
 
+int implicitConversionReturnInt()
+{
+return true;
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion bool -> 
'int'
+// CHECK-FIXES: return 1
+}
+
+int implicitConversionReturnIntWithParens()
+{
+return (true);
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion bool -> 
'int'
+// CHECK-FIXES: return 1
+}
+
+
+bool implicitConversionReturnBool()
+{
+return 1;
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion 'int' -> 
bool
+// CHECK-FIXES: return true
+}
+
+bool implicitConversionReturnBoolWithParens()
+{
+return (1);
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion 'int' -> 
bool
+// CHECK-FIXES: return true
+}
+
+
 namespace PR47000 {
   int to_int(bool x) { return int{x}; }
 

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


[clang-tools-extra] [clang-tidy] Improved readability-bool-conversion to be more consistent when using parentheses (PR #72068)

2023-11-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Félix-Antoine Constantin (felix642)


Changes

Fixes #71852

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


3 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp (+2-2) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
 (+30) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 69e6d73c4fcd7bb..9e627d281e4b0f9 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -152,7 +152,7 @@ StringRef getEquivalentBoolLiteralForExpr(const Expr 
*Expression,
 return "false";
   }
 
-  if (const auto *IntLit = dyn_cast(Expression)) {
+  if (const auto *IntLit = 
dyn_cast(Expression->IgnoreParens())) {
 return (IntLit->getValue() == 0) ? "false" : "true";
   }
 
@@ -385,7 +385,7 @@ void ImplicitBoolConversionCheck::handleCastFromBool(
   << DestType;
 
   if (const auto *BoolLiteral =
-  dyn_cast(Cast->getSubExpr())) {
+  dyn_cast(Cast->getSubExpr()->IgnoreParens())) {
 Diag << tooling::fixit::createReplacement(
 *Cast, getEquivalentForBoolLiteral(BoolLiteral, DestType, Context));
   } else {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index f49c412118e7d98..ab9ef8cdfb37a00 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -412,6 +412,10 @@ Changes in existing checks
   do-while loops into account for the `AllowIntegerConditions` and
   `AllowPointerConditions` options.
 
+- Improved :doc:`readability-implicit-bool-conversion
+  ` check to provide
+  consistent suggestions when parentheses are added to the return value. 
+
 - Improved :doc:`readability-non-const-parameter
   ` check to ignore
   false-positives in initializer list of record.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
index 323cf813c047000..f7f5d506a9ce0e0 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
@@ -472,6 +472,36 @@ bool f(S& s) {
 
 } // namespace ignore_1bit_bitfields
 
+int implicitConversionReturnInt()
+{
+return true;
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion bool -> 
'int'
+// CHECK-FIXES: return 1
+}
+
+int implicitConversionReturnIntWithParens()
+{
+return (true);
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion bool -> 
'int'
+// CHECK-FIXES: return 1
+}
+
+
+bool implicitConversionReturnBool()
+{
+return 1;
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion 'int' -> 
bool
+// CHECK-FIXES: return true
+}
+
+bool implicitConversionReturnBoolWithParens()
+{
+return (1);
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion 'int' -> 
bool
+// CHECK-FIXES: return true
+}
+
+
 namespace PR47000 {
   int to_int(bool x) { return int{x}; }
 

``




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


[clang-tools-extra] [clang-tidy] Improved readability-bool-conversion to be more consistent when using parentheses (PR #72068)

2023-11-12 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 4c3206c5d5dee9dc3c7ad32c09d57a7fc592bcea 
54743ceec9845cdc450d5c163a293e73884a8df9 -- 
clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
``





View the diff from clang-format here.


``diff
diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 9e627d281e..f0fca30de3 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -152,7 +152,8 @@ StringRef getEquivalentBoolLiteralForExpr(const Expr 
*Expression,
 return "false";
   }
 
-  if (const auto *IntLit = 
dyn_cast(Expression->IgnoreParens())) {
+  if (const auto *IntLit =
+  dyn_cast(Expression->IgnoreParens())) {
 return (IntLit->getValue() == 0) ? "false" : "true";
   }
 

``




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


[clang-tools-extra] [clang-tidy] Improved readability-bool-conversion to be more consistent when using parentheses (PR #72068)

2023-11-12 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 updated 
https://github.com/llvm/llvm-project/pull/72068

From 649c7b8b936d848100b58e733dd358fa1d5914fb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sun, 12 Nov 2023 16:07:13 -0500
Subject: [PATCH] [clang-tidy] Improved readability-bool-conversion to be more
 consistent when using parentheses

Fixes #71852
---
 .../ImplicitBoolConversionCheck.cpp   |  5 ++--
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 +++
 .../readability/implicit-bool-conversion.cpp  | 30 +++
 3 files changed, 37 insertions(+), 2 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 69e6d73c4fcd7bb..f0fca30de3b3c4d 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -152,7 +152,8 @@ StringRef getEquivalentBoolLiteralForExpr(const Expr 
*Expression,
 return "false";
   }
 
-  if (const auto *IntLit = dyn_cast(Expression)) {
+  if (const auto *IntLit =
+  dyn_cast(Expression->IgnoreParens())) {
 return (IntLit->getValue() == 0) ? "false" : "true";
   }
 
@@ -385,7 +386,7 @@ void ImplicitBoolConversionCheck::handleCastFromBool(
   << DestType;
 
   if (const auto *BoolLiteral =
-  dyn_cast(Cast->getSubExpr())) {
+  dyn_cast(Cast->getSubExpr()->IgnoreParens())) {
 Diag << tooling::fixit::createReplacement(
 *Cast, getEquivalentForBoolLiteral(BoolLiteral, DestType, Context));
   } else {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index f49c412118e7d98..ab9ef8cdfb37a00 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -412,6 +412,10 @@ Changes in existing checks
   do-while loops into account for the `AllowIntegerConditions` and
   `AllowPointerConditions` options.
 
+- Improved :doc:`readability-implicit-bool-conversion
+  ` check to provide
+  consistent suggestions when parentheses are added to the return value. 
+
 - Improved :doc:`readability-non-const-parameter
   ` check to ignore
   false-positives in initializer list of record.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
index 323cf813c047000..f7f5d506a9ce0e0 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp
@@ -472,6 +472,36 @@ bool f(S& s) {
 
 } // namespace ignore_1bit_bitfields
 
+int implicitConversionReturnInt()
+{
+return true;
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion bool -> 
'int'
+// CHECK-FIXES: return 1
+}
+
+int implicitConversionReturnIntWithParens()
+{
+return (true);
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion bool -> 
'int'
+// CHECK-FIXES: return 1
+}
+
+
+bool implicitConversionReturnBool()
+{
+return 1;
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion 'int' -> 
bool
+// CHECK-FIXES: return true
+}
+
+bool implicitConversionReturnBoolWithParens()
+{
+return (1);
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: implicit conversion 'int' -> 
bool
+// CHECK-FIXES: return true
+}
+
+
 namespace PR47000 {
   int to_int(bool x) { return int{x}; }
 

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


[clang-tools-extra] [clang-tidy] Improved readability-bool-conversion to be more consistent when using parentheses (PR #72068)

2023-11-12 Thread Oliver Stöneberg via cfe-commits

firewave wrote:

Another PR for this was opened a few hours ago: #71848.

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


[clang-tools-extra] [clang-tidy] Improved readability-bool-conversion to be more consistent when using parentheses (PR #72068)

2023-11-12 Thread Félix-Antoine Constantin via cfe-commits

felix642 wrote:

Hi @firewave, I think you are referencing a different issue. If I test #71852 
with PR #72050 I do not get the expected behavior.

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


[clang] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-11-12 Thread Liviu Ionescu via cfe-commits

https://github.com/ilg-ul updated 
https://github.com/llvm/llvm-project/pull/70817

>From 7fbc229ee7316d826517480ee7896c91dad941f3 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Tue, 31 Oct 2023 17:09:04 +0200
Subject: [PATCH 1/5] Add \/../include/c++/v1 to include path

On macOS, when clang is invoked via a symlink, since the InstalledDir is
where the link is located, the C++ headers are not identified and the
default system headers are used.

This fix adds a second check using the folder where the executable is
located.
---
 clang/lib/Driver/ToolChains/Darwin.cpp | 13 +
 1 file changed, 13 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index f28e08d81bf29b4..de55307385966cf 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2494,6 +2494,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
+// Check for the folder where the executable is located, if different.
+if (getDriver().getInstalledDir() != getDriver().Dir) {
+  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
+  if (getVFS().exists(InstallBin)) {
+addSystemInclude(DriverArgs, CC1Args, InstallBin);
+return;
+  } else if (DriverArgs.hasArg(options::OPT_v)) {
+llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
+ << "\"\n";
+  }
+}
+
 // Otherwise, check for (2)
 llvm::SmallString<128> SysrootUsr = Sysroot;
 llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");

>From b2f287c6a53697ac9bdce3eaa1ce55d345d734b1 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:05:50 +0200
Subject: [PATCH 2/5] Darwin.cpp: update comments

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 17 +++--
 1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index de55307385966cf..e6bcf0227d7dc65 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2470,14 +2470,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
   switch (GetCXXStdlibType(DriverArgs)) {
   case ToolChain::CST_Libcxx: {
-// On Darwin, libc++ can be installed in one of the following two places:
+// On Darwin, libc++ can be installed in one of the following places:
 // 1. Alongside the compiler in /include/c++/v1
-// 2. In a SDK (or a custom sysroot) in /usr/include/c++/v1
+// 2. Alongside the compiler in 
/../include/c++/v1
+// 3. In a SDK (or a custom sysroot) in /usr/include/c++/v1
 //
-// The precendence of paths is as listed above, i.e. we take the first path
-// that exists. Also note that we never include libc++ twice -- we take the
-// first path that exists and don't send the other paths to CC1 (otherwise
+// The precedence of paths is as listed above, i.e. we take the first path
+// that exists. Note that we never include libc++ twice -- we take the 
first
+// path that exists and don't send the other paths to CC1 (otherwise
 // include_next could break).
+//
+// Also note that in most cases, (1) and (2) are exactly the same path.
+// Those two paths will differ only when the `clang` program being run
+// is actually a symlink to the real executable.
 
 // Check for (1)
 // Get from '/bin' to '/include/c++/v1'.
@@ -2494,7 +2499,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
-// Check for the folder where the executable is located, if different.
+// (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
   InstallBin = llvm::StringRef(getDriver().Dir.c_str());
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");

>From 31b7482ffabda61c005a4cd90a07bcfec65c232e Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:08:51 +0200
Subject: [PATCH 3/5] Darwin.cpp: construct StringRef from string

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index e6bcf0227d7dc65..d89b6d60f1852e4 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2501,7 +2501,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
 // (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
-  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  InstallBin = llvm::StringRef(getDriver().Dir);
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
   

[clang-tools-extra] [clang-tidy] Improved readability-bool-conversion to be more consistent when using parentheses (PR #72068)

2023-11-12 Thread Oliver Stöneberg via cfe-commits

firewave wrote:

> Hi @firewave, I think you are referencing a different issue. If I test #71852 
> with PR #72050 I do not get the expected behavior.

Of course you are right. I missed there being two different issues. Sorry about 
the noise.

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


[clang] [clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-11-12 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti updated 
https://github.com/llvm/llvm-project/pull/70559

>From b29eb35fe8597ceefc4c615817174181a16f3c4c Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 28 Oct 2023 18:08:51 +0200
Subject: [PATCH 1/4] [clang-tidy] fix match for binaryOperator in
 ExprMutationAnalyzer for misc-const-correctness

The `ExprMutationAnalyzer`s matcher of `binaryOperator`s
that contained the variable expr, were previously narrowing the
variable to be type dependent, when the `binaryOperator` should
have been narrowed as dependent.
The variable we are trying to find mutations for does
not need to be the dependent type, the other operand of
the `binaryOperator` could be dependent.

Fixes #57297
---
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../checkers/misc/const-correctness-templates.cpp | 11 +++
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Analysis/ExprMutationAnalyzer.cpp   |  6 +++---
 clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp | 11 +++
 5 files changed, 33 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 5ce38ab48bf295f..bb75c9a3ce08125 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -308,6 +308,11 @@ Changes in existing checks
   ` check to avoid false positive 
when
   using pointer to member function.
 
+- Improved :doc:`misc-const-correctness
+  ` check to not warn on uses in
+  type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
+
 - Improved :doc:`misc-include-cleaner
   ` check by adding option
   `DeduplicateFindings` to output one finding per symbol occurrence, avoid
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
index 7b5ccabdd6ef611..415bb06020b9dc3 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
@@ -20,3 +20,14 @@ void instantiate_template_cases() {
   type_dependent_variables();
   type_dependent_variables();
 }
+
+namespace gh57297{
+struct Stream {};
+// Explicitly not declaring a (templated) stream operator
+// so the `<<` is a `binaryOperator` with a dependent type.
+template  void f() {
+  T t;
+  Stream stream;
+  stream << t;
+}
+} // namespace gh57297
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..fb9afc0646ac8cb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -683,6 +683,9 @@ Bug Fixes to AST Handling
 - Fixed a bug where RecursiveASTVisitor fails to visit the
   initializer of a bitfield.
   `Issue 64916 `_
+- Fixed a bug where ``ExprMutationAnalyzer`` did not find a potential mutation
+  for uses in type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
 
 Miscellaneous Bug Fixes
 ^^^
diff --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index f2e1beb025423cf..624a643cc60e4ba 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -296,9 +296,9 @@ const Stmt *ExprMutationAnalyzer::findDirectMutation(const 
Expr *Exp) {
   // resolved and modelled as `binaryOperator` on a dependent type.
   // Such instances are considered a modification, because they can modify
   // in different instantiations of the template.
-  binaryOperator(hasEitherOperand(
-  allOf(ignoringImpCasts(canResolveToExpr(equalsNode(Exp))),
-isTypeDependent(,
+  binaryOperator(
+  
hasEitherOperand(ignoringImpCasts(canResolveToExpr(equalsNode(Exp,
+  isTypeDependent()),
   // Within class templates and member functions the member expression 
might
   // not be resolved. In that case, the `callExpr` is considered to be a
   // modification.
diff --git a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp 
b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
index c0a398394093c48..cfa3c535ce35292 100644
--- a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -343,6 +343,17 @@ TEST(ExprMutationAnalyzerTest, UnresolvedOperator) {
   EXPECT_TRUE(isMutated(Results, AST.get()));
 }
 
+TEST(ExprMutationAnalyzerTest, DependentOperatorWithNonDependentOperand) {
+  // gh57297
+  // Explicitly not declaring a (templated) stream operator
+  // so the `<<` is a `binaryOperator` with a dependent type.
+  const auto AST = buildASTFromCode("struct Stream {}; template  "
+

[clang] [clang][ASTMatcher] Add matchers for CXXFoldExpr (PR #71245)

2023-11-12 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

Could someone please reapply the `clang` label to trigger the pr subscriber 
action?

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


[clang] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-11-12 Thread Liviu Ionescu via cfe-commits

https://github.com/ilg-ul updated 
https://github.com/llvm/llvm-project/pull/70817

>From 7fbc229ee7316d826517480ee7896c91dad941f3 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Tue, 31 Oct 2023 17:09:04 +0200
Subject: [PATCH 1/6] Add \/../include/c++/v1 to include path

On macOS, when clang is invoked via a symlink, since the InstalledDir is
where the link is located, the C++ headers are not identified and the
default system headers are used.

This fix adds a second check using the folder where the executable is
located.
---
 clang/lib/Driver/ToolChains/Darwin.cpp | 13 +
 1 file changed, 13 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index f28e08d81bf29b4..de55307385966cf 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2494,6 +2494,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
+// Check for the folder where the executable is located, if different.
+if (getDriver().getInstalledDir() != getDriver().Dir) {
+  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
+  if (getVFS().exists(InstallBin)) {
+addSystemInclude(DriverArgs, CC1Args, InstallBin);
+return;
+  } else if (DriverArgs.hasArg(options::OPT_v)) {
+llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
+ << "\"\n";
+  }
+}
+
 // Otherwise, check for (2)
 llvm::SmallString<128> SysrootUsr = Sysroot;
 llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");

>From b2f287c6a53697ac9bdce3eaa1ce55d345d734b1 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:05:50 +0200
Subject: [PATCH 2/6] Darwin.cpp: update comments

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 17 +++--
 1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index de55307385966cf..e6bcf0227d7dc65 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2470,14 +2470,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
   switch (GetCXXStdlibType(DriverArgs)) {
   case ToolChain::CST_Libcxx: {
-// On Darwin, libc++ can be installed in one of the following two places:
+// On Darwin, libc++ can be installed in one of the following places:
 // 1. Alongside the compiler in /include/c++/v1
-// 2. In a SDK (or a custom sysroot) in /usr/include/c++/v1
+// 2. Alongside the compiler in 
/../include/c++/v1
+// 3. In a SDK (or a custom sysroot) in /usr/include/c++/v1
 //
-// The precendence of paths is as listed above, i.e. we take the first path
-// that exists. Also note that we never include libc++ twice -- we take the
-// first path that exists and don't send the other paths to CC1 (otherwise
+// The precedence of paths is as listed above, i.e. we take the first path
+// that exists. Note that we never include libc++ twice -- we take the 
first
+// path that exists and don't send the other paths to CC1 (otherwise
 // include_next could break).
+//
+// Also note that in most cases, (1) and (2) are exactly the same path.
+// Those two paths will differ only when the `clang` program being run
+// is actually a symlink to the real executable.
 
 // Check for (1)
 // Get from '/bin' to '/include/c++/v1'.
@@ -2494,7 +2499,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
-// Check for the folder where the executable is located, if different.
+// (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
   InstallBin = llvm::StringRef(getDriver().Dir.c_str());
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");

>From 31b7482ffabda61c005a4cd90a07bcfec65c232e Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:08:51 +0200
Subject: [PATCH 3/6] Darwin.cpp: construct StringRef from string

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index e6bcf0227d7dc65..d89b6d60f1852e4 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2501,7 +2501,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
 // (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
-  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  InstallBin = llvm::StringRef(getDriver().Dir);
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
   

[clang-tools-extra] [clang] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-11-12 Thread Julian Schmidt via cfe-commits

5chmidti wrote:

> In tests we usually use `-fno-delayed-template-parsing` to overcome this 
> issue with templates and windows.

Done. I changed the test in `ExprMutationAnalyzerTest.cpp` to use the flag, 
`const-correctness-templates.cpp` already had it, and I changed the tested code 
back to what it was before (-formatting).

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

michael-kenzel wrote:

> I would assume this is already transformed to memcpy but I guess it won't be 
> for -O0

[I did some testing on this](https://godbolt.org/z/YMEjbxYd9): it seems that 
gcc replaces the `strcpy` with a simple `mov` even under `-O0`, but not the 
`memcpy`. clang does the reverse: it replaces the `memcpy` with a `mov` even 
under `-O0` but not the `strcpy`. So it's a bit of a wash (I didn't expect 
either compiler to transform any of these with `-O0` tbqh). Though since 
libunwind is primarily meant to be used with LLVM, this change arguably 
presents the tiniest codegen improvement. On either compiler, turning on 
optimizations (even just to `-O1`) results in the exact same codegen from 
either version (as one would expect).

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


[clang] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-11-12 Thread Liviu Ionescu via cfe-commits

https://github.com/ilg-ul updated 
https://github.com/llvm/llvm-project/pull/70817

>From 7fbc229ee7316d826517480ee7896c91dad941f3 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Tue, 31 Oct 2023 17:09:04 +0200
Subject: [PATCH 1/7] Add \/../include/c++/v1 to include path

On macOS, when clang is invoked via a symlink, since the InstalledDir is
where the link is located, the C++ headers are not identified and the
default system headers are used.

This fix adds a second check using the folder where the executable is
located.
---
 clang/lib/Driver/ToolChains/Darwin.cpp | 13 +
 1 file changed, 13 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index f28e08d81bf29b4..de55307385966cf 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2494,6 +2494,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
+// Check for the folder where the executable is located, if different.
+if (getDriver().getInstalledDir() != getDriver().Dir) {
+  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
+  if (getVFS().exists(InstallBin)) {
+addSystemInclude(DriverArgs, CC1Args, InstallBin);
+return;
+  } else if (DriverArgs.hasArg(options::OPT_v)) {
+llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
+ << "\"\n";
+  }
+}
+
 // Otherwise, check for (2)
 llvm::SmallString<128> SysrootUsr = Sysroot;
 llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");

>From b2f287c6a53697ac9bdce3eaa1ce55d345d734b1 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:05:50 +0200
Subject: [PATCH 2/7] Darwin.cpp: update comments

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 17 +++--
 1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index de55307385966cf..e6bcf0227d7dc65 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2470,14 +2470,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
   switch (GetCXXStdlibType(DriverArgs)) {
   case ToolChain::CST_Libcxx: {
-// On Darwin, libc++ can be installed in one of the following two places:
+// On Darwin, libc++ can be installed in one of the following places:
 // 1. Alongside the compiler in /include/c++/v1
-// 2. In a SDK (or a custom sysroot) in /usr/include/c++/v1
+// 2. Alongside the compiler in 
/../include/c++/v1
+// 3. In a SDK (or a custom sysroot) in /usr/include/c++/v1
 //
-// The precendence of paths is as listed above, i.e. we take the first path
-// that exists. Also note that we never include libc++ twice -- we take the
-// first path that exists and don't send the other paths to CC1 (otherwise
+// The precedence of paths is as listed above, i.e. we take the first path
+// that exists. Note that we never include libc++ twice -- we take the 
first
+// path that exists and don't send the other paths to CC1 (otherwise
 // include_next could break).
+//
+// Also note that in most cases, (1) and (2) are exactly the same path.
+// Those two paths will differ only when the `clang` program being run
+// is actually a symlink to the real executable.
 
 // Check for (1)
 // Get from '/bin' to '/include/c++/v1'.
@@ -2494,7 +2499,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
-// Check for the folder where the executable is located, if different.
+// (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
   InstallBin = llvm::StringRef(getDriver().Dir.c_str());
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");

>From 31b7482ffabda61c005a4cd90a07bcfec65c232e Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:08:51 +0200
Subject: [PATCH 3/7] Darwin.cpp: construct StringRef from string

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index e6bcf0227d7dc65..d89b6d60f1852e4 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2501,7 +2501,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
 // (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
-  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  InstallBin = llvm::StringRef(getDriver().Dir);
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
   

[clang-tools-extra] [clang-tidy] Improved readability-bool-conversion to be more consistent when using parentheses (PR #72068)

2023-11-12 Thread Piotr Zegar via cfe-commits


@@ -412,6 +412,10 @@ Changes in existing checks
   do-while loops into account for the `AllowIntegerConditions` and
   `AllowPointerConditions` options.
 
+- Improved :doc:`readability-implicit-bool-conversion

PiotrZSL wrote:

merge release notes, one entry for a check, one sentence for a change

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


[clang-tools-extra] [clang-tidy] Improved readability-bool-conversion to be more consistent when using parentheses (PR #72068)

2023-11-12 Thread Piotr Zegar via cfe-commits

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

Description for a change (commit / PR) needed.
Except that looks fine.

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


[clang] [clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-11-12 Thread Piotr Zegar via cfe-commits


@@ -308,6 +308,11 @@ Changes in existing checks
   ` check to avoid false positive 
when
   using pointer to member function.
 
+- Improved :doc:`misc-const-correctness

PiotrZSL wrote:

there is already entry for this check, just merge changes.

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


[clang] [clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-11-12 Thread Piotr Zegar via cfe-commits

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


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


[clang] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-11-12 Thread Liviu Ionescu via cfe-commits

https://github.com/ilg-ul updated 
https://github.com/llvm/llvm-project/pull/70817

>From 7fbc229ee7316d826517480ee7896c91dad941f3 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Tue, 31 Oct 2023 17:09:04 +0200
Subject: [PATCH 1/8] Add \/../include/c++/v1 to include path

On macOS, when clang is invoked via a symlink, since the InstalledDir is
where the link is located, the C++ headers are not identified and the
default system headers are used.

This fix adds a second check using the folder where the executable is
located.
---
 clang/lib/Driver/ToolChains/Darwin.cpp | 13 +
 1 file changed, 13 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index f28e08d81bf29b4..de55307385966cf 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2494,6 +2494,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
+// Check for the folder where the executable is located, if different.
+if (getDriver().getInstalledDir() != getDriver().Dir) {
+  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
+  if (getVFS().exists(InstallBin)) {
+addSystemInclude(DriverArgs, CC1Args, InstallBin);
+return;
+  } else if (DriverArgs.hasArg(options::OPT_v)) {
+llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
+ << "\"\n";
+  }
+}
+
 // Otherwise, check for (2)
 llvm::SmallString<128> SysrootUsr = Sysroot;
 llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");

>From b2f287c6a53697ac9bdce3eaa1ce55d345d734b1 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:05:50 +0200
Subject: [PATCH 2/8] Darwin.cpp: update comments

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 17 +++--
 1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index de55307385966cf..e6bcf0227d7dc65 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2470,14 +2470,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
   switch (GetCXXStdlibType(DriverArgs)) {
   case ToolChain::CST_Libcxx: {
-// On Darwin, libc++ can be installed in one of the following two places:
+// On Darwin, libc++ can be installed in one of the following places:
 // 1. Alongside the compiler in /include/c++/v1
-// 2. In a SDK (or a custom sysroot) in /usr/include/c++/v1
+// 2. Alongside the compiler in 
/../include/c++/v1
+// 3. In a SDK (or a custom sysroot) in /usr/include/c++/v1
 //
-// The precendence of paths is as listed above, i.e. we take the first path
-// that exists. Also note that we never include libc++ twice -- we take the
-// first path that exists and don't send the other paths to CC1 (otherwise
+// The precedence of paths is as listed above, i.e. we take the first path
+// that exists. Note that we never include libc++ twice -- we take the 
first
+// path that exists and don't send the other paths to CC1 (otherwise
 // include_next could break).
+//
+// Also note that in most cases, (1) and (2) are exactly the same path.
+// Those two paths will differ only when the `clang` program being run
+// is actually a symlink to the real executable.
 
 // Check for (1)
 // Get from '/bin' to '/include/c++/v1'.
@@ -2494,7 +2499,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
-// Check for the folder where the executable is located, if different.
+// (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
   InstallBin = llvm::StringRef(getDriver().Dir.c_str());
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");

>From 31b7482ffabda61c005a4cd90a07bcfec65c232e Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:08:51 +0200
Subject: [PATCH 3/8] Darwin.cpp: construct StringRef from string

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index e6bcf0227d7dc65..d89b6d60f1852e4 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2501,7 +2501,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
 // (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
-  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  InstallBin = llvm::StringRef(getDriver().Dir);
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
   

[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits


@@ -143,7 +143,7 @@ _Unwind_Backtrace(_Unwind_Trace_Fn callback, void *ref) {
   // Create a mock exception object for force unwinding.
   _Unwind_Exception ex;
   memset(&ex, '\0', sizeof(ex));
-  strcpy((char *)&ex.exception_class, "CLNGUNW");
+  memcpy(&ex.exception_class, "CLNGUNW", sizeof(ex.exception_class));

michael-kenzel wrote:

My reasoning was that if the string happened to be too long for some reason, 
we'd want to ensure that we don't write past the member. Either option, using 
the string length or member length, has the downside of not considering the 
other length. Ideally, the string would be some constant and we'd have a 
`_Static_assert` to ensure the sizes match. But I couldn't find a simple way to 
put this into plain C without making this code significantly more complex. I 
was also not quite sure what's the range of versions of C this is supposed to 
build under, which would have implications regarding whether `_Static_assert` 
can be used at all or is deprecated in favor of `static_assert`… One very 
simple solution (at least code-wise) would be to just do
```c
  _Unwind_Exception ex = {
.exception_class = 0x574E55474E4C43  // "CLNGUNW"
  };
```
But this then assumes little endian and so would be a potential ABI break?

Overall, I think it's reasonable to assume that this string isn't just gonna 
change in a way that would make it not match the size of the member anymore. 
The current implementation was already broken in that case as well. 
Unfortunately, no compiler seems to issue a warning if you make the string not 
match the size of the member.

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[clang] [clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-11-12 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti updated 
https://github.com/llvm/llvm-project/pull/70559

>From b29eb35fe8597ceefc4c615817174181a16f3c4c Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 28 Oct 2023 18:08:51 +0200
Subject: [PATCH 1/5] [clang-tidy] fix match for binaryOperator in
 ExprMutationAnalyzer for misc-const-correctness

The `ExprMutationAnalyzer`s matcher of `binaryOperator`s
that contained the variable expr, were previously narrowing the
variable to be type dependent, when the `binaryOperator` should
have been narrowed as dependent.
The variable we are trying to find mutations for does
not need to be the dependent type, the other operand of
the `binaryOperator` could be dependent.

Fixes #57297
---
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../checkers/misc/const-correctness-templates.cpp | 11 +++
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Analysis/ExprMutationAnalyzer.cpp   |  6 +++---
 clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp | 11 +++
 5 files changed, 33 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 5ce38ab48bf295f..bb75c9a3ce08125 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -308,6 +308,11 @@ Changes in existing checks
   ` check to avoid false positive 
when
   using pointer to member function.
 
+- Improved :doc:`misc-const-correctness
+  ` check to not warn on uses in
+  type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
+
 - Improved :doc:`misc-include-cleaner
   ` check by adding option
   `DeduplicateFindings` to output one finding per symbol occurrence, avoid
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
index 7b5ccabdd6ef611..415bb06020b9dc3 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
@@ -20,3 +20,14 @@ void instantiate_template_cases() {
   type_dependent_variables();
   type_dependent_variables();
 }
+
+namespace gh57297{
+struct Stream {};
+// Explicitly not declaring a (templated) stream operator
+// so the `<<` is a `binaryOperator` with a dependent type.
+template  void f() {
+  T t;
+  Stream stream;
+  stream << t;
+}
+} // namespace gh57297
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2595737e8b3b143..fb9afc0646ac8cb 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -683,6 +683,9 @@ Bug Fixes to AST Handling
 - Fixed a bug where RecursiveASTVisitor fails to visit the
   initializer of a bitfield.
   `Issue 64916 `_
+- Fixed a bug where ``ExprMutationAnalyzer`` did not find a potential mutation
+  for uses in type-dependent binary operators, when the variable that is being
+  looked at, is not the dependent operand.
 
 Miscellaneous Bug Fixes
 ^^^
diff --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index f2e1beb025423cf..624a643cc60e4ba 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -296,9 +296,9 @@ const Stmt *ExprMutationAnalyzer::findDirectMutation(const 
Expr *Exp) {
   // resolved and modelled as `binaryOperator` on a dependent type.
   // Such instances are considered a modification, because they can modify
   // in different instantiations of the template.
-  binaryOperator(hasEitherOperand(
-  allOf(ignoringImpCasts(canResolveToExpr(equalsNode(Exp))),
-isTypeDependent(,
+  binaryOperator(
+  
hasEitherOperand(ignoringImpCasts(canResolveToExpr(equalsNode(Exp,
+  isTypeDependent()),
   // Within class templates and member functions the member expression 
might
   // not be resolved. In that case, the `callExpr` is considered to be a
   // modification.
diff --git a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp 
b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
index c0a398394093c48..cfa3c535ce35292 100644
--- a/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ b/clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -343,6 +343,17 @@ TEST(ExprMutationAnalyzerTest, UnresolvedOperator) {
   EXPECT_TRUE(isMutated(Results, AST.get()));
 }
 
+TEST(ExprMutationAnalyzerTest, DependentOperatorWithNonDependentOperand) {
+  // gh57297
+  // Explicitly not declaring a (templated) stream operator
+  // so the `<<` is a `binaryOperator` with a dependent type.
+  const auto AST = buildASTFromCode("struct Stream {}; template  "
+

[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[clang] [clang-tools-extra] [clang-tidy] fix match for binaryOperator in ExprMutationAnalyzer for misc-const-correctness (PR #70559)

2023-11-12 Thread Julian Schmidt via cfe-commits


@@ -308,6 +308,11 @@ Changes in existing checks
   ` check to avoid false positive 
when
   using pointer to member function.
 
+- Improved :doc:`misc-const-correctness

5chmidti wrote:

Done. I have also reworded the release note, I think it reads better now.

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[clang] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-11-12 Thread Liviu Ionescu via cfe-commits

https://github.com/ilg-ul updated 
https://github.com/llvm/llvm-project/pull/70817

>From 7fbc229ee7316d826517480ee7896c91dad941f3 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Tue, 31 Oct 2023 17:09:04 +0200
Subject: [PATCH 1/9] Add \/../include/c++/v1 to include path

On macOS, when clang is invoked via a symlink, since the InstalledDir is
where the link is located, the C++ headers are not identified and the
default system headers are used.

This fix adds a second check using the folder where the executable is
located.
---
 clang/lib/Driver/ToolChains/Darwin.cpp | 13 +
 1 file changed, 13 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index f28e08d81bf29b4..de55307385966cf 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2494,6 +2494,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
+// Check for the folder where the executable is located, if different.
+if (getDriver().getInstalledDir() != getDriver().Dir) {
+  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
+  if (getVFS().exists(InstallBin)) {
+addSystemInclude(DriverArgs, CC1Args, InstallBin);
+return;
+  } else if (DriverArgs.hasArg(options::OPT_v)) {
+llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
+ << "\"\n";
+  }
+}
+
 // Otherwise, check for (2)
 llvm::SmallString<128> SysrootUsr = Sysroot;
 llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");

>From b2f287c6a53697ac9bdce3eaa1ce55d345d734b1 Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:05:50 +0200
Subject: [PATCH 2/9] Darwin.cpp: update comments

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 17 +++--
 1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index de55307385966cf..e6bcf0227d7dc65 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2470,14 +2470,19 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
   switch (GetCXXStdlibType(DriverArgs)) {
   case ToolChain::CST_Libcxx: {
-// On Darwin, libc++ can be installed in one of the following two places:
+// On Darwin, libc++ can be installed in one of the following places:
 // 1. Alongside the compiler in /include/c++/v1
-// 2. In a SDK (or a custom sysroot) in /usr/include/c++/v1
+// 2. Alongside the compiler in 
/../include/c++/v1
+// 3. In a SDK (or a custom sysroot) in /usr/include/c++/v1
 //
-// The precendence of paths is as listed above, i.e. we take the first path
-// that exists. Also note that we never include libc++ twice -- we take the
-// first path that exists and don't send the other paths to CC1 (otherwise
+// The precedence of paths is as listed above, i.e. we take the first path
+// that exists. Note that we never include libc++ twice -- we take the 
first
+// path that exists and don't send the other paths to CC1 (otherwise
 // include_next could break).
+//
+// Also note that in most cases, (1) and (2) are exactly the same path.
+// Those two paths will differ only when the `clang` program being run
+// is actually a symlink to the real executable.
 
 // Check for (1)
 // Get from '/bin' to '/include/c++/v1'.
@@ -2494,7 +2499,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
<< "\"\n";
 }
 
-// Check for the folder where the executable is located, if different.
+// (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
   InstallBin = llvm::StringRef(getDriver().Dir.c_str());
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");

>From 31b7482ffabda61c005a4cd90a07bcfec65c232e Mon Sep 17 00:00:00 2001
From: Liviu Ionescu 
Date: Fri, 10 Nov 2023 12:08:51 +0200
Subject: [PATCH 3/9] Darwin.cpp: construct StringRef from string

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index e6bcf0227d7dc65..d89b6d60f1852e4 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2501,7 +2501,7 @@ void DarwinClang::AddClangCXXStdlibIncludeArgs(
 
 // (2) Check for the folder where the executable is located, if different.
 if (getDriver().getInstalledDir() != getDriver().Dir) {
-  InstallBin = llvm::StringRef(getDriver().Dir.c_str());
+  InstallBin = llvm::StringRef(getDriver().Dir);
   llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
   

[clang] [clang][driver] Add \/../include/c++/v1 to include path on Darwin (PR #70817)

2023-11-12 Thread Liviu Ionescu via cfe-commits

ilg-ul wrote:

I tried to write the test, but after several atempts I was not able to properly 
check the paths... :-(

@ldionne, do you have any suggestions on how to fix the test?


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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[clang] a533b76 - [clang-format][NFC] Simplify parseBracedList() (#72010)

2023-11-12 Thread via cfe-commits

Author: Owen Pan
Date: 2023-11-12T15:55:06-08:00
New Revision: a533b76468ac1df54e2e541b05ba4c060a77c603

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

LOG: [clang-format][NFC] Simplify parseBracedList() (#72010)

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 018bc6c165485e2..c870ff01605e725 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2017,8 +2017,7 @@ void UnwrappedLineParser::parseStructuralElement(
   } else if (Style.Language == FormatStyle::LK_Proto &&
  FormatTok->is(tok::less)) {
 nextToken();
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
+parseBracedList(/*IsAngleBracket=*/true);
   }
   break;
 case tok::l_square:
@@ -2379,9 +2378,7 @@ bool UnwrappedLineParser::tryToParseChildBlock() {
   return true;
 }
 
-bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
-  bool IsEnum,
-  tok::TokenKind ClosingBraceKind) {
+bool UnwrappedLineParser::parseBracedList(bool IsAngleBracket, bool IsEnum) {
   bool HasError = false;
 
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
@@ -2403,7 +2400,7 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
 parseChildBlock();
   }
 }
-if (FormatTok->Tok.getKind() == ClosingBraceKind) {
+if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
   if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
 addUnwrappedLine();
   nextToken();
@@ -2434,14 +2431,9 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
   parseBracedList();
   break;
 case tok::less:
-  if (Style.Language == FormatStyle::LK_Proto ||
-  ClosingBraceKind == tok::greater) {
-nextToken();
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
-  } else {
-nextToken();
-  }
+  nextToken();
+  if (IsAngleBracket)
+parseBracedList(/*IsAngleBracket=*/true);
   break;
 case tok::semi:
   // JavaScript (or more precisely TypeScript) can have semicolons in 
braced
@@ -2453,8 +2445,8 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
 break;
   }
   HasError = true;
-  if (!ContinueOnSemicolons)
-return !HasError;
+  if (!IsEnum)
+return false;
   nextToken();
   break;
 case tok::comma:
@@ -3618,8 +3610,7 @@ void UnwrappedLineParser::parseConstraintExpression() {
 return;
 
   nextToken();
-  parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-  /*ClosingBraceKind=*/tok::greater);
+  parseBracedList(/*IsAngleBracket=*/true);
   break;
 
 default:
@@ -3650,8 +3641,7 @@ void UnwrappedLineParser::parseConstraintExpression() {
   nextToken();
   if (FormatTok->is(tok::less)) {
 nextToken();
-parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
-/*ClosingBraceKind=*/tok::greater);
+parseBracedList(/*IsAngleBracket=*/true);
   }
   TopLevelParensAllowed = false;
   break;
@@ -3732,8 +3722,7 @@ bool UnwrappedLineParser::parseEnum() {
 addUnwrappedLine();
 Line->Level += 1;
   }
-  bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true,
-   /*IsEnum=*/true);
+  bool HasError = !parseBracedList(/*IsAngleBracket=*/false, /*IsEnum=*/true);
   if (!Style.AllowShortEnumsOnASingleLine)
 Line->Level -= 1;
   if (HasError) {

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 39294d14e57e574..739298690bbd765 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -150,8 +150,7 @@ class UnwrappedLineParser {
   bool *HasDoWhile = nullptr,
   bool *HasLabel = nullptr);
   bool tryToParseBracedList();
-  bool parseBracedList(bool ContinueOnSemicolons = false, bool IsEnum = false,
-   tok::TokenKind ClosingBraceKind = tok::r_brace);
+  bool parseBracedList(bool IsAngleBracket = false, bool IsEnum = false);
   bool parseParens(TokenType AmpAmpTokenType = TT_Unknown);
   void parseSquare(bool LambdaIntroducer = false);
   void keepAncesto

[clang] [clang-format][NFC] Simplify parseBracedList() (PR #72010)

2023-11-12 Thread Owen Pan via cfe-commits

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


[clang] [OpenMP][Clang] Force use of `num_teams` and `thread_limit` for bare kernel (PR #68373)

2023-11-12 Thread Shilei Tian via cfe-commits

shiltian wrote:

Gentle ping

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


[clang] [openmp] [OpenMP] Directly use user's grid and block size in kernel language mode (PR #70612)

2023-11-12 Thread Shilei Tian via cfe-commits

shiltian wrote:

Gentle ping

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

https://github.com/michael-kenzel updated 
https://github.com/llvm/llvm-project/pull/72043

>From d5adc242a9c52c7de2a860489a4292b7461b6164 Mon Sep 17 00:00:00 2001
From: Michael Kenzel 
Date: Sun, 12 Nov 2023 02:46:15 +0100
Subject: [PATCH] [libunwind] Remove unnecessary strcpy dependency

---
 libunwind/src/UnwindLevel1-gcc-ext.c | 2 +-
 libunwind/test/forceunwind.pass.cpp  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/libunwind/src/UnwindLevel1-gcc-ext.c 
b/libunwind/src/UnwindLevel1-gcc-ext.c
index d343f4e6e9cc837..32c872ffade1fd0 100644
--- a/libunwind/src/UnwindLevel1-gcc-ext.c
+++ b/libunwind/src/UnwindLevel1-gcc-ext.c
@@ -143,7 +143,7 @@ _Unwind_Backtrace(_Unwind_Trace_Fn callback, void *ref) {
   // Create a mock exception object for force unwinding.
   _Unwind_Exception ex;
   memset(&ex, '\0', sizeof(ex));
-  strcpy((char *)&ex.exception_class, "CLNGUNW");
+  memcpy(&ex.exception_class, "CLNGUNW", sizeof(ex.exception_class));
 #endif
 
   // walk each frame
diff --git a/libunwind/test/forceunwind.pass.cpp 
b/libunwind/test/forceunwind.pass.cpp
index 8c26551b6d0b678..db499d8bc30894e 100644
--- a/libunwind/test/forceunwind.pass.cpp
+++ b/libunwind/test/forceunwind.pass.cpp
@@ -61,7 +61,7 @@ __attribute__((noinline)) void foo() {
 #if defined(_LIBUNWIND_ARM_EHABI)
   // Create a mock exception object.
   memset(e, '\0', sizeof(*e));
-  strcpy(reinterpret_cast(&e->exception_class), "CLNGUNW");
+  memcpy(&e->exception_class, "CLNGUNW", sizeof(e->exception_class));
 #endif
   _Unwind_ForcedUnwind(e, stop, (void *)&foo);
 }

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

michael-kenzel wrote:

I found another use of the same string copying in `tests/forceunwind.pass.cpp` 
and updated that to match.

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Michael Kenzel via cfe-commits

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


[libunwind] [libunwind] Remove unnecessary strcpy dependency (PR #72043)

2023-11-12 Thread Alexander Richardson via cfe-commits


@@ -143,7 +143,7 @@ _Unwind_Backtrace(_Unwind_Trace_Fn callback, void *ref) {
   // Create a mock exception object for force unwinding.
   _Unwind_Exception ex;
   memset(&ex, '\0', sizeof(ex));
-  strcpy((char *)&ex.exception_class, "CLNGUNW");
+  memcpy(&ex.exception_class, "CLNGUNW", sizeof(ex.exception_class));

arichardson wrote:

I agree this is fine as is. Assigning the integer directly will cause endian 
issues, so using memcpy is better.

If we want to be extra safe, we could #define the string value and  add a 
static_assert().

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


[clang] [clang][CGExprScalar] Remove no-op ptr-to-ptr bitcast (NFC) (PR #72072)

2023-11-12 Thread Youngsuk Kim via cfe-commits

https://github.com/JOE1994 created 
https://github.com/llvm/llvm-project/pull/72072

Remove bitcast added back in dcd74716f9d18 .

>From b9db2565d3d2d251bde7cd84b704861d5b41bd14 Mon Sep 17 00:00:00 2001
From: JOE1994 
Date: Sun, 12 Nov 2023 20:04:44 -0500
Subject: [PATCH] [clang][CGExprScalar] Remove no-op ptr-to-ptr bitcast (NFC)

Remove bitcast added back in dcd74716f9d18 .
---
 clang/lib/CodeGen/CGExprScalar.cpp | 8 
 1 file changed, 8 deletions(-)

diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 1a7a3f97bb779a0..2faab20fc069ee7 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -2227,14 +2227,6 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
 llvm::Value *V = CE->changesVolatileQualification()
  ? EmitLoadOfLValue(CE)
  : Visit(const_cast(E));
-if (V) {
-  // CK_NoOp can model a pointer qualification conversion, which can remove
-  // an array bound and change the IR type.
-  // FIXME: Once pointee types are removed from IR, remove this.
-  llvm::Type *T = ConvertType(DestTy);
-  if (T != V->getType())
-V = Builder.CreateBitCast(V, T);
-}
 return V;
   }
 

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


[clang] [clang][CGExprScalar] Remove no-op ptr-to-ptr bitcast (NFC) (PR #72072)

2023-11-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Youngsuk Kim (JOE1994)


Changes

Remove bitcast added back in dcd74716f9d18 .

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGExprScalar.cpp (-8) 


``diff
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 1a7a3f97bb779a0..2faab20fc069ee7 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -2227,14 +2227,6 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
 llvm::Value *V = CE->changesVolatileQualification()
  ? EmitLoadOfLValue(CE)
  : Visit(const_cast(E));
-if (V) {
-  // CK_NoOp can model a pointer qualification conversion, which can remove
-  // an array bound and change the IR type.
-  // FIXME: Once pointee types are removed from IR, remove this.
-  llvm::Type *T = ConvertType(DestTy);
-  if (T != V->getType())
-V = Builder.CreateBitCast(V, T);
-}
 return V;
   }
 

``




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


[clang] [clang][CGExprScalar] Remove no-op ptr-to-ptr bitcast (NFC) (PR #72072)

2023-11-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Youngsuk Kim (JOE1994)


Changes

Remove bitcast added back in dcd74716f9d18 .

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGExprScalar.cpp (-8) 


``diff
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 1a7a3f97bb779a0..2faab20fc069ee7 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -2227,14 +2227,6 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
 llvm::Value *V = CE->changesVolatileQualification()
  ? EmitLoadOfLValue(CE)
  : Visit(const_cast(E));
-if (V) {
-  // CK_NoOp can model a pointer qualification conversion, which can remove
-  // an array bound and change the IR type.
-  // FIXME: Once pointee types are removed from IR, remove this.
-  llvm::Type *T = ConvertType(DestTy);
-  if (T != V->getType())
-V = Builder.CreateBitCast(V, T);
-}
 return V;
   }
 

``




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


[clang] [X86][AVX10] Permit AVX512 options/features used together with AVX10 (PR #71318)

2023-11-12 Thread Phoebe Wang via cfe-commits

phoebewang wrote:

@ronlieb The reproducer can compile successfully in trunk: 
https://godbolt.org/z/hvKhGq9bq
Are you using a downstream compiler? You can check if the "emmintrin.h" has the 
same change as main trunk.
You can also check it through pre-compile the code:
```
$ clang++ -E fd_log_scalar.cpp -D_CPU | grep '_mm_setzero_pd.*{'
static __inline__ __m128d __attribute__((__always_inline__, __nodebug__, 
__target__("sse2,no-evex512"), __min_vector_width__(128))) _mm_setzero_pd(void) 
{
```
Make sure `no-evex512` is in the attribute too.

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


[clang] [clang-tools-extra] [llvm] [CodeGen][DebugInfo] Add missing debug info for jump table BB (PR #71021)

2023-11-12 Thread via cfe-commits

https://github.com/HaohaiWen updated 
https://github.com/llvm/llvm-project/pull/71021

>From 1be56cf6541d34e4e2ead3f4b3d3ce482d69f68f Mon Sep 17 00:00:00 2001
From: Haohai Wen 
Date: Thu, 2 Nov 2023 12:14:15 +0800
Subject: [PATCH 1/4] [DebugInfo] Add debug info test for jump table

Test whether jump table BB has debug info after ISel.
---
 .../Generic/debug-info-jump-table.ll  | 176 ++
 1 file changed, 176 insertions(+)
 create mode 100644 llvm/test/DebugInfo/Generic/debug-info-jump-table.ll

diff --git a/llvm/test/DebugInfo/Generic/debug-info-jump-table.ll 
b/llvm/test/DebugInfo/Generic/debug-info-jump-table.ll
new file mode 100644
index 000..b73d05441f654bb
--- /dev/null
+++ b/llvm/test/DebugInfo/Generic/debug-info-jump-table.ll
@@ -0,0 +1,176 @@
+; RUN: llc -debug-only=isel %s -o /dev/null 2>&1 | FileCheck 
--match-full-lines %s
+
+source_filename = "jump_table.c"
+target datalayout = 
"e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+@str = private unnamed_addr constant [2 x i8] c"1\00", align 1
+@str.12 = private unnamed_addr constant [2 x i8] c"2\00", align 1
+@str.13 = private unnamed_addr constant [2 x i8] c"3\00", align 1
+@str.14 = private unnamed_addr constant [2 x i8] c"4\00", align 1
+@str.15 = private unnamed_addr constant [2 x i8] c"5\00", align 1
+@str.16 = private unnamed_addr constant [2 x i8] c"6\00", align 1
+@str.17 = private unnamed_addr constant [2 x i8] c"7\00", align 1
+@str.18 = private unnamed_addr constant [2 x i8] c"8\00", align 1
+@str.19 = private unnamed_addr constant [2 x i8] c"9\00", align 1
+@str.20 = private unnamed_addr constant [3 x i8] c"10\00", align 1
+@str.21 = private unnamed_addr constant [3 x i8] c"11\00", align 1
+@str.22 = private unnamed_addr constant [3 x i8] c"12\00", align 1
+
+
+
+; Function Attrs: nofree nounwind uwtable
+define dso_local void @foo(i32 noundef %cond) local_unnamed_addr #0 !dbg !42 {
+;CHECK: Initial selection DAG: %bb.{{[0-9]+}} 'foo:entry'
+;CHECK: SelectionDAG has 5 nodes:
+;CHECK: [[TMP1:t.*]]: ch,glue = EntryToken
+;CHECK:   [[TMP2:t.*]]: i64,ch = CopyFromReg [[TMP1]], Register:i64 %{{[0-9]+}}
+;CHECK:   t{{[0-9]+}}: ch = br_jt [[TMP2]]:1, JumpTable:i64<0>, [[TMP2]]
+
+entry:
+  call void @llvm.dbg.value(metadata i32 %cond, metadata !47, metadata 
!DIExpression()), !dbg !48
+  switch i32 %cond, label %sw.epilog [
+i32 1, label %sw.bb
+i32 2, label %sw.bb1
+i32 3, label %sw.bb3
+i32 4, label %sw.bb5
+i32 5, label %sw.bb7
+i32 6, label %sw.bb9
+i32 7, label %sw.bb11
+i32 8, label %sw.bb13
+i32 9, label %sw.bb15
+i32 10, label %sw.bb17
+i32 11, label %sw.bb19
+i32 12, label %sw.bb21
+  ], !dbg !49
+
+sw.bb:; preds = %entry
+  %puts = tail call i32 @puts(ptr nonnull dereferenceable(1) @str), !dbg !50
+  br label %sw.bb1, !dbg !50
+
+sw.bb1:   ; preds = %entry, %sw.bb
+  %puts23 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.12), !dbg 
!52
+  br label %sw.bb3, !dbg !52
+
+sw.bb3:   ; preds = %entry, %sw.bb1
+  %puts24 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.13), !dbg 
!53
+  br label %sw.bb5, !dbg !53
+
+sw.bb5:   ; preds = %entry, %sw.bb3
+  %puts25 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.14), !dbg 
!54
+  br label %sw.bb7, !dbg !54
+
+sw.bb7:   ; preds = %entry, %sw.bb5
+  %puts26 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.15), !dbg 
!55
+  br label %sw.bb9, !dbg !55
+
+sw.bb9:   ; preds = %entry, %sw.bb7
+  %puts27 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.16), !dbg 
!56
+  br label %sw.bb11, !dbg !56
+
+sw.bb11:  ; preds = %entry, %sw.bb9
+  %puts28 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.17), !dbg 
!57
+  br label %sw.bb13, !dbg !57
+
+sw.bb13:  ; preds = %entry, %sw.bb11
+  %puts29 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.18), !dbg 
!58
+  br label %sw.bb15, !dbg !58
+
+sw.bb15:  ; preds = %entry, %sw.bb13
+  %puts30 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.19), !dbg 
!59
+  br label %sw.bb17, !dbg !59
+
+sw.bb17:  ; preds = %entry, %sw.bb15
+  %puts31 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.20), !dbg 
!60
+  br label %sw.bb19, !dbg !60
+
+sw.bb19:  ; preds = %entry, %sw.bb17
+  %puts32 = tail call i32 @puts(ptr nonnull dereferenceable(1) @str.21), !dbg 
!61
+  br label %sw.bb21, !dbg !61
+
+sw.bb21:  ; preds = %entry, %sw.bb19
+  %puts33 = tail ca

[llvm] [clang-tools-extra] [clang] [compiler-rt] [InferAddressSpaces] Fix constant replace to avoid modifying other functions (PR #70611)

2023-11-12 Thread Wenju He via cfe-commits

wenju-he wrote:

> I think it would be better if we could eliminate ConstantExpr addrspacecasts 
> from the IR altogether, which would avoid most of the complexity here. I 
> would also somewhat prefer to push this DFS into a helper function, but can 
> live with it inline as-is

thank you for the review. I'll draft another PR to modify 
convertUsersOfConstantsToInstructions to allow change in a function only, so 
that DFS is not need here.

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


[clang] [clang][CGExprScalar] Remove no-op ptr-to-ptr bitcast (NFC) (PR #72072)

2023-11-12 Thread Matt Arsenault via cfe-commits

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


[clang] [clang][CGExprScalar] Remove no-op ptr-to-ptr bitcast (NFC) (PR #72072)

2023-11-12 Thread Matt Arsenault via cfe-commits

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


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


[clang] [clang][CGExprScalar] Remove no-op ptr-to-ptr bitcast (NFC) (PR #72072)

2023-11-12 Thread Matt Arsenault via cfe-commits


@@ -2227,14 +2227,6 @@ Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
 llvm::Value *V = CE->changesVolatileQualification()
  ? EmitLoadOfLValue(CE)
  : Visit(const_cast(E));
-if (V) {
-  // CK_NoOp can model a pointer qualification conversion, which can remove
-  // an array bound and change the IR type.
-  // FIXME: Once pointee types are removed from IR, remove this.
-  llvm::Type *T = ConvertType(DestTy);
-  if (T != V->getType())
-V = Builder.CreateBitCast(V, T);
-}
 return V;

arsenm wrote:

Could fold this into a direct return CE->...

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


[llvm] [clang] [compiler-rt] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits

https://github.com/arsenm commented:

128-bit division should already work, we have an IR integer division expansion 
for > 64-bit divides. I think moving towards getting the infrastructure to a 
place where we can link in compiler-rt binaries is a good thing, but I don't 
think we're in a position to actually enable that at this time. We still don't 
have everything necessary to provide object linking, which this seems to rely 
on 

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


[compiler-rt] [clang] [llvm] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits

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


[compiler-rt] [llvm] [clang] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits


@@ -937,27 +938,105 @@ bool CodeGenAction::loadLinkModules(CompilerInstance 
&CI) {
 
   for (const CodeGenOptions::BitcodeFileToLink &F :
CI.getCodeGenOpts().LinkBitcodeFiles) {
-auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
-if (!BCBuf) {
+
+auto BCBufOrErr = CI.getFileManager().getBufferForFile(F.Filename);
+if (!BCBufOrErr) {
   CI.getDiagnostics().Report(diag::err_cannot_open_file)
-  << F.Filename << BCBuf.getError().message();
+  << F.Filename << BCBufOrErr.getError().message();
   LinkModules.clear();
   return true;
 }
 
+auto &BCBuf = *BCBufOrErr;
+
 Expected> ModuleOrErr =
-getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
-if (!ModuleOrErr) {
-  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
+getOwningLazyBitcodeModule(std::move(BCBuf), *VMContext);
+
+if (ModuleOrErr) {
+  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
+ F.Internalize, F.LinkFlags});
+  continue;
+} else {
+  // If parsing as bitcode failed, clear the error and try to parse as an
+  // archive.
+  handleAllErrors(ModuleOrErr.takeError(),
+  [&](const llvm::ErrorInfoBase &EIB) {});
+
+  Expected> BinOrErr =
+  llvm::object::createBinary(BCBuf->getMemBufferRef(), VMContext);
+
+  if (!BinOrErr) {
+handleAllErrors(BinOrErr.takeError(),
+[&](const llvm::ErrorInfoBase &EIB) {
+  
CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+LinkModules.clear();
+return true;
+  }
+
+  std::unique_ptr &Bin = *BinOrErr;
+
+  if (Bin->isArchive()) {
+llvm::object::Archive *Archive =
+llvm::cast(Bin.get());
+Error Err = Error::success();
+
+for (auto &Child : Archive->children(Err)) {
+  Expected ChildBufOrErr =
+  Child.getMemoryBufferRef();
+  if (!ChildBufOrErr) {

arsenm wrote:

Can you add some tests for the various error cases?

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


[clang] [llvm] [compiler-rt] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits


@@ -937,27 +938,105 @@ bool CodeGenAction::loadLinkModules(CompilerInstance 
&CI) {
 
   for (const CodeGenOptions::BitcodeFileToLink &F :
CI.getCodeGenOpts().LinkBitcodeFiles) {
-auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
-if (!BCBuf) {
+
+auto BCBufOrErr = CI.getFileManager().getBufferForFile(F.Filename);
+if (!BCBufOrErr) {
   CI.getDiagnostics().Report(diag::err_cannot_open_file)
-  << F.Filename << BCBuf.getError().message();
+  << F.Filename << BCBufOrErr.getError().message();
   LinkModules.clear();
   return true;
 }
 
+auto &BCBuf = *BCBufOrErr;
+
 Expected> ModuleOrErr =
-getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
-if (!ModuleOrErr) {
-  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
+getOwningLazyBitcodeModule(std::move(BCBuf), *VMContext);
+
+if (ModuleOrErr) {
+  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
+ F.Internalize, F.LinkFlags});
+  continue;
+} else {
+  // If parsing as bitcode failed, clear the error and try to parse as an
+  // archive.
+  handleAllErrors(ModuleOrErr.takeError(),
+  [&](const llvm::ErrorInfoBase &EIB) {});
+
+  Expected> BinOrErr =
+  llvm::object::createBinary(BCBuf->getMemBufferRef(), VMContext);
+
+  if (!BinOrErr) {
+handleAllErrors(BinOrErr.takeError(),
+[&](const llvm::ErrorInfoBase &EIB) {
+  
CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+LinkModules.clear();
+return true;
+  }
+
+  std::unique_ptr &Bin = *BinOrErr;
+
+  if (Bin->isArchive()) {
+llvm::object::Archive *Archive =
+llvm::cast(Bin.get());
+Error Err = Error::success();
+
+for (auto &Child : Archive->children(Err)) {
+  Expected ChildBufOrErr =
+  Child.getMemoryBufferRef();
+  if (!ChildBufOrErr) {
+handleAllErrors(
+ChildBufOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) 
{
+  CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+continue;
+  }
+  auto ChildBuffer = llvm::MemoryBuffer::getMemBufferCopy(
+  ChildBufOrErr->getBuffer(), 
ChildBufOrErr->getBufferIdentifier());
+
+  if (!ChildBuffer) {
+handleAllErrors(
+ChildBufOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) 
{
+  CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+continue;
+  }
+
+  Expected> ChildModuleOrErr =
+  getOwningLazyBitcodeModule(std::move(ChildBuffer), *VMContext);
+  if (!ChildModuleOrErr) {
+handleAllErrors(
+ChildModuleOrErr.takeError(),
+[&](const llvm::ErrorInfoBase &EIB) {
+  CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+continue;
+  }
+
+  LinkModules.push_back({std::move(ChildModuleOrErr.get()),

arsenm wrote:

Not sure you need the .get()

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


[clang] [llvm] [compiler-rt] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits


@@ -937,27 +938,105 @@ bool CodeGenAction::loadLinkModules(CompilerInstance 
&CI) {
 
   for (const CodeGenOptions::BitcodeFileToLink &F :
CI.getCodeGenOpts().LinkBitcodeFiles) {
-auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
-if (!BCBuf) {
+
+auto BCBufOrErr = CI.getFileManager().getBufferForFile(F.Filename);
+if (!BCBufOrErr) {
   CI.getDiagnostics().Report(diag::err_cannot_open_file)
-  << F.Filename << BCBuf.getError().message();
+  << F.Filename << BCBufOrErr.getError().message();
   LinkModules.clear();
   return true;
 }
 
+auto &BCBuf = *BCBufOrErr;
+
 Expected> ModuleOrErr =
-getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
-if (!ModuleOrErr) {
-  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
+getOwningLazyBitcodeModule(std::move(BCBuf), *VMContext);
+
+if (ModuleOrErr) {
+  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
+ F.Internalize, F.LinkFlags});
+  continue;
+} else {

arsenm wrote:

no else after continue 

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


[clang] [compiler-rt] [llvm] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits


@@ -937,27 +938,105 @@ bool CodeGenAction::loadLinkModules(CompilerInstance 
&CI) {
 
   for (const CodeGenOptions::BitcodeFileToLink &F :
CI.getCodeGenOpts().LinkBitcodeFiles) {
-auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
-if (!BCBuf) {
+
+auto BCBufOrErr = CI.getFileManager().getBufferForFile(F.Filename);
+if (!BCBufOrErr) {
   CI.getDiagnostics().Report(diag::err_cannot_open_file)
-  << F.Filename << BCBuf.getError().message();
+  << F.Filename << BCBufOrErr.getError().message();
   LinkModules.clear();
   return true;
 }
 
+auto &BCBuf = *BCBufOrErr;
+
 Expected> ModuleOrErr =
-getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
-if (!ModuleOrErr) {
-  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
+getOwningLazyBitcodeModule(std::move(BCBuf), *VMContext);
+
+if (ModuleOrErr) {
+  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
+ F.Internalize, F.LinkFlags});
+  continue;
+} else {
+  // If parsing as bitcode failed, clear the error and try to parse as an
+  // archive.
+  handleAllErrors(ModuleOrErr.takeError(),
+  [&](const llvm::ErrorInfoBase &EIB) {});
+
+  Expected> BinOrErr =
+  llvm::object::createBinary(BCBuf->getMemBufferRef(), VMContext);
+
+  if (!BinOrErr) {
+handleAllErrors(BinOrErr.takeError(),
+[&](const llvm::ErrorInfoBase &EIB) {
+  
CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+LinkModules.clear();
+return true;
+  }
+
+  std::unique_ptr &Bin = *BinOrErr;
+
+  if (Bin->isArchive()) {

arsenm wrote:

Can you split all of this out into an archive handling helper function?

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


[clang] [llvm] [compiler-rt] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits


@@ -937,27 +938,105 @@ bool CodeGenAction::loadLinkModules(CompilerInstance 
&CI) {
 
   for (const CodeGenOptions::BitcodeFileToLink &F :
CI.getCodeGenOpts().LinkBitcodeFiles) {
-auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
-if (!BCBuf) {
+
+auto BCBufOrErr = CI.getFileManager().getBufferForFile(F.Filename);
+if (!BCBufOrErr) {
   CI.getDiagnostics().Report(diag::err_cannot_open_file)
-  << F.Filename << BCBuf.getError().message();
+  << F.Filename << BCBufOrErr.getError().message();
   LinkModules.clear();
   return true;
 }
 
+auto &BCBuf = *BCBufOrErr;
+
 Expected> ModuleOrErr =
-getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
-if (!ModuleOrErr) {
-  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
+getOwningLazyBitcodeModule(std::move(BCBuf), *VMContext);
+
+if (ModuleOrErr) {
+  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
+ F.Internalize, F.LinkFlags});
+  continue;
+} else {
+  // If parsing as bitcode failed, clear the error and try to parse as an
+  // archive.
+  handleAllErrors(ModuleOrErr.takeError(),
+  [&](const llvm::ErrorInfoBase &EIB) {});
+
+  Expected> BinOrErr =
+  llvm::object::createBinary(BCBuf->getMemBufferRef(), VMContext);
+
+  if (!BinOrErr) {
+handleAllErrors(BinOrErr.takeError(),
+[&](const llvm::ErrorInfoBase &EIB) {
+  
CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+LinkModules.clear();
+return true;
+  }
+
+  std::unique_ptr &Bin = *BinOrErr;
+
+  if (Bin->isArchive()) {
+llvm::object::Archive *Archive =
+llvm::cast(Bin.get());
+Error Err = Error::success();

arsenm wrote:

I assume this doesn't require initialization 

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


[clang] [llvm] [compiler-rt] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits


@@ -596,6 +596,7 @@ static bool mustPreserveGV(const GlobalValue &GV) {
   if (const Function *F = dyn_cast(&GV))
 return F->isDeclaration() || F->getName().startswith("__asan_") ||
F->getName().startswith("__sanitizer_") ||
+   F->getName() == "__divti3" ||

arsenm wrote:

we're stuck preserving this in the IR at all times which isn't really ideal 

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


[clang] [llvm] [compiler-rt] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits


@@ -937,27 +938,105 @@ bool CodeGenAction::loadLinkModules(CompilerInstance 
&CI) {
 
   for (const CodeGenOptions::BitcodeFileToLink &F :
CI.getCodeGenOpts().LinkBitcodeFiles) {
-auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
-if (!BCBuf) {
+
+auto BCBufOrErr = CI.getFileManager().getBufferForFile(F.Filename);
+if (!BCBufOrErr) {
   CI.getDiagnostics().Report(diag::err_cannot_open_file)
-  << F.Filename << BCBuf.getError().message();
+  << F.Filename << BCBufOrErr.getError().message();
   LinkModules.clear();
   return true;
 }
 
+auto &BCBuf = *BCBufOrErr;
+
 Expected> ModuleOrErr =
-getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
-if (!ModuleOrErr) {
-  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
+getOwningLazyBitcodeModule(std::move(BCBuf), *VMContext);
+
+if (ModuleOrErr) {
+  LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
+ F.Internalize, F.LinkFlags});
+  continue;
+} else {
+  // If parsing as bitcode failed, clear the error and try to parse as an
+  // archive.
+  handleAllErrors(ModuleOrErr.takeError(),
+  [&](const llvm::ErrorInfoBase &EIB) {});
+
+  Expected> BinOrErr =
+  llvm::object::createBinary(BCBuf->getMemBufferRef(), VMContext);
+
+  if (!BinOrErr) {
+handleAllErrors(BinOrErr.takeError(),
+[&](const llvm::ErrorInfoBase &EIB) {
+  
CI.getDiagnostics().Report(diag::err_cannot_open_file)
+  << F.Filename << EIB.message();
+});
+LinkModules.clear();
+return true;
+  }
+
+  std::unique_ptr &Bin = *BinOrErr;
+
+  if (Bin->isArchive()) {
+llvm::object::Archive *Archive =
+llvm::cast(Bin.get());
+Error Err = Error::success();
+
+for (auto &Child : Archive->children(Err)) {
+  Expected ChildBufOrErr =
+  Child.getMemoryBufferRef();
+  if (!ChildBufOrErr) {

arsenm wrote:

Also the base case, a driver test would help me see what this is actually doing

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


[clang] [llvm] [compiler-rt] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Matt Arsenault via cfe-commits


@@ -3630,10 +3631,17 @@ SDValue SITargetLowering::LowerCall(CallLoweringInfo 
&CLI,
 
   std::vector Ops;
   Ops.push_back(Chain);
+  bool AddTargetGlobalAddr = true;
+  // Try to find the callee in the current module.
+  if (isa(Callee)) {
+Callee = DAG.getSymbolFunctionGlobalAddress(Callee);
+AddTargetGlobalAddr = false;
+  }

arsenm wrote:

This should be split into a separate backend only change 

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


[clang] [clang] Add per-global code model attribute (PR #72078)

2023-11-12 Thread via cfe-commits

https://github.com/heiher created 
https://github.com/llvm/llvm-project/pull/72078

This adds a per-global code model attribute, which can override the target's 
code model to access global variables.

Link: 
https://discourse.llvm.org/t/how-to-best-implement-code-model-overriding-for-certain-values/71816

Suggested-by: Arthur Eubanks 

>From 29c89161a55c2d7355a0d0b544044ea72348c086 Mon Sep 17 00:00:00 2001
From: WANG Rui 
Date: Fri, 10 Nov 2023 21:07:48 -0600
Subject: [PATCH] [clang] Add per-global code model attribute

This adds a per-global code model attribute, which can override
the target's code model to access global variables.

Link: 
https://discourse.llvm.org/t/how-to-best-implement-code-model-overriding-for-certain-values/71816

Suggested-by: Arthur Eubanks 
Signed-off-by: WANG Rui 
---
 clang/include/clang/Basic/Attr.td |  8 
 clang/include/clang/Basic/AttrDocs.td |  9 +
 .../clang/Basic/DiagnosticSemaKinds.td|  3 +++
 clang/lib/CodeGen/CodeGenModule.cpp   | 13 
 clang/lib/Sema/SemaDeclAttr.cpp   | 20 +++
 clang/test/CodeGen/attributes.c   | 15 ++
 ...a-attribute-supported-attributes-list.test |  1 +
 clang/test/Sema/attr-model.c  | 12 +++
 8 files changed, 81 insertions(+)
 create mode 100644 clang/test/Sema/attr-model.c

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 31434565becaec67..0d3742080435142f 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2694,6 +2694,14 @@ def PragmaClangTextSection : InheritableAttr {
   let Documentation = [InternalOnly];
 }
 
+def CodeModel : InheritableAttr {
+  let Spellings = [GCC<"model">];
+  let Args = [StringArgument<"Model">];
+  let Subjects =
+  SubjectList<[ GlobalVar ], ErrorDiag>;
+  let Documentation = [CodeModelDocs];
+}
+
 def Sentinel : InheritableAttr {
   let Spellings = [GCC<"sentinel">];
   let Args = [DefaultIntArgument<"Sentinel", 0>,
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index fa6f6acd0c30e883..ca09e4acb113003b 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -57,6 +57,15 @@ global variable or function should be in after translation.
   let Heading = "section, __declspec(allocate)";
 }
 
+def CodeModelDocs : Documentation {
+  let Category = DocCatVariable;
+  let Content = [{
+The ``model`` attribute allows you to specify a specific code model a
+global variable should be in after translation.
+  }];
+  let Heading = "model";
+}
+
 def UsedDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4614324babb1c917..f9305e21bd6a39b3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3401,6 +3401,9 @@ def warn_objc_redundant_literal_use : Warning<
 def err_attr_tlsmodel_arg : Error<"tls_model must be \"global-dynamic\", "
   "\"local-dynamic\", \"initial-exec\" or \"local-exec\"">;
 
+def err_attr_codemodel_arg : Error<"code_model must be \"tiny\", "
+  "\"small\", \"kernel\", \"medium\" or \"large\"">;
+
 def err_aix_attr_unsupported_tls_model : Error<"TLS model '%0' is not yet 
supported on AIX">;
 
 def err_tls_var_aligned_over_maximum : Error<
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 4c7f516e308ca003..f783130e3cbfd12e 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -4774,6 +4774,19 @@ CodeGenModule::GetOrCreateLLVMGlobal(StringRef 
MangledName, llvm::Type *Ty,
 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
   GV->setSection(".cp.rodata");
 
+// Handle code model attribute
+if (D->hasAttr()) {
+  if (const CodeModelAttr *CMA = D->getAttr()) {
+auto CM = llvm::StringSwitch(CMA->getModel())
+  .Case("tiny", llvm::CodeModel::Tiny)
+  .Case("kernel", llvm::CodeModel::Kernel)
+  .Case("medium", llvm::CodeModel::Medium)
+  .Case("large", llvm::CodeModel::Large)
+  .Default(llvm::CodeModel::Small);
+GV->setCodeModel(CM);
+  }
+}
+
 // Check if we a have a const declaration with an initializer, we may be
 // able to emit it as available_externally to expose it's value to the
 // optimizer.
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index cdb769a883550d0f..8646c494602a3ea4 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3369,6 +3369,23 @@ static void handleSectionAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   }
 }
 
+static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  StringRef Model;
+  SourceLocat

[clang] [compiler-rt] [llvm] [HIP] support 128 bit int division (PR #71978)

2023-11-12 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> Would it be feasible to consider switching to the new offloading driver mode 
> and really link with the library instead? It may be a conveniently isolated 
> use case with little/no existing users that would disrupt.

I've thought a reasonable amount about a `compiler-rt` for GPUs. Right now it's 
a little difficult because of the issue of compatibility. We could do the 
traditional "Build the library N times for N architectures", but I'd like to 
think of something more intelligent in the future. The use of 
`-mlink-builtin-bitcode` handles this by more-or-less forcing correct 
attributes.

What this patch does is a little interesting though, having the clang driver 
pick apart archives has always seemed a little weird. We did it in the past for 
AMD's old handling of static libraries. There's still a lot of that code 
leftover I want to delete. I really need to sit down and allow HIP to work with 
the new driver.

I've been messing around with generic IR a bit, and I think what might work is 
LLVM-IR that intentionally leaves off target specific attributes and then 
introduce a pass that adds them in if missing before other optimizations are 
run. Then we may be able to investigate the use of i-funcs to resolve target 
specific branches once the architecture is known (once being linked in). I 
think @JonChesterfield was thinking about something to that effect as well.

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


[clang] [clang] Add per-global code model attribute (PR #72078)

2023-11-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: hev (heiher)


Changes

This adds a per-global code model attribute, which can override the target's 
code model to access global variables.

Link: 
https://discourse.llvm.org/t/how-to-best-implement-code-model-overriding-for-certain-values/71816

Suggested-by: Arthur Eubanks 

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


8 Files Affected:

- (modified) clang/include/clang/Basic/Attr.td (+8) 
- (modified) clang/include/clang/Basic/AttrDocs.td (+9) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) 
- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+13) 
- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+20) 
- (modified) clang/test/CodeGen/attributes.c (+15) 
- (modified) clang/test/Misc/pragma-attribute-supported-attributes-list.test 
(+1) 
- (added) clang/test/Sema/attr-model.c (+12) 


``diff
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 31434565becaec67..0d3742080435142f 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2694,6 +2694,14 @@ def PragmaClangTextSection : InheritableAttr {
   let Documentation = [InternalOnly];
 }
 
+def CodeModel : InheritableAttr {
+  let Spellings = [GCC<"model">];
+  let Args = [StringArgument<"Model">];
+  let Subjects =
+  SubjectList<[ GlobalVar ], ErrorDiag>;
+  let Documentation = [CodeModelDocs];
+}
+
 def Sentinel : InheritableAttr {
   let Spellings = [GCC<"sentinel">];
   let Args = [DefaultIntArgument<"Sentinel", 0>,
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index fa6f6acd0c30e883..ca09e4acb113003b 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -57,6 +57,15 @@ global variable or function should be in after translation.
   let Heading = "section, __declspec(allocate)";
 }
 
+def CodeModelDocs : Documentation {
+  let Category = DocCatVariable;
+  let Content = [{
+The ``model`` attribute allows you to specify a specific code model a
+global variable should be in after translation.
+  }];
+  let Heading = "model";
+}
+
 def UsedDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4614324babb1c917..f9305e21bd6a39b3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3401,6 +3401,9 @@ def warn_objc_redundant_literal_use : Warning<
 def err_attr_tlsmodel_arg : Error<"tls_model must be \"global-dynamic\", "
   "\"local-dynamic\", \"initial-exec\" or \"local-exec\"">;
 
+def err_attr_codemodel_arg : Error<"code_model must be \"tiny\", "
+  "\"small\", \"kernel\", \"medium\" or \"large\"">;
+
 def err_aix_attr_unsupported_tls_model : Error<"TLS model '%0' is not yet 
supported on AIX">;
 
 def err_tls_var_aligned_over_maximum : Error<
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 4c7f516e308ca003..f783130e3cbfd12e 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -4774,6 +4774,19 @@ CodeGenModule::GetOrCreateLLVMGlobal(StringRef 
MangledName, llvm::Type *Ty,
 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
   GV->setSection(".cp.rodata");
 
+// Handle code model attribute
+if (D->hasAttr()) {
+  if (const CodeModelAttr *CMA = D->getAttr()) {
+auto CM = llvm::StringSwitch(CMA->getModel())
+  .Case("tiny", llvm::CodeModel::Tiny)
+  .Case("kernel", llvm::CodeModel::Kernel)
+  .Case("medium", llvm::CodeModel::Medium)
+  .Case("large", llvm::CodeModel::Large)
+  .Default(llvm::CodeModel::Small);
+GV->setCodeModel(CM);
+  }
+}
+
 // Check if we a have a const declaration with an initializer, we may be
 // able to emit it as available_externally to expose it's value to the
 // optimizer.
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index cdb769a883550d0f..8646c494602a3ea4 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3369,6 +3369,23 @@ static void handleSectionAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   }
 }
 
+static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  StringRef Model;
+  SourceLocation LiteralLoc;
+  // Check that it is a string.
+  if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
+return;
+
+  // Check that the value.
+  if (Model != "tiny" && Model != "small"
+  && Model != "kernel" && Model != "medium" && Model != "large") {
+S.Diag(LiteralLoc, diag::err_attr_codemodel_arg);
+return;
+  }
+
+  D->addAttr(::new (S.Context) CodeModelAttr(S.Context, AL, Model));
+}
+
 // This is used for `__declspec(code_se

[clang] [clang] Add per-global code model attribute (PR #72078)

2023-11-12 Thread via cfe-commits

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


[clang] [clang] Add per-global code model attribute (PR #72078)

2023-11-12 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 18415c8365047841c4671798e0129ca9bbd03c40 
29c89161a55c2d7355a0d0b544044ea72348c086 -- clang/test/Sema/attr-model.c 
clang/lib/CodeGen/CodeGenModule.cpp clang/lib/Sema/SemaDeclAttr.cpp 
clang/test/CodeGen/attributes.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index f783130e3c..f7347ab912 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -4778,11 +4778,11 @@ CodeGenModule::GetOrCreateLLVMGlobal(StringRef 
MangledName, llvm::Type *Ty,
 if (D->hasAttr()) {
   if (const CodeModelAttr *CMA = D->getAttr()) {
 auto CM = llvm::StringSwitch(CMA->getModel())
-  .Case("tiny", llvm::CodeModel::Tiny)
-  .Case("kernel", llvm::CodeModel::Kernel)
-  .Case("medium", llvm::CodeModel::Medium)
-  .Case("large", llvm::CodeModel::Large)
-  .Default(llvm::CodeModel::Small);
+  .Case("tiny", llvm::CodeModel::Tiny)
+  .Case("kernel", llvm::CodeModel::Kernel)
+  .Case("medium", llvm::CodeModel::Medium)
+  .Case("large", llvm::CodeModel::Large)
+  .Default(llvm::CodeModel::Small);
 GV->setCodeModel(CM);
   }
 }
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 8646c49460..3cf50284bb 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3377,8 +3377,8 @@ static void handleCodeModelAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 return;
 
   // Check that the value.
-  if (Model != "tiny" && Model != "small"
-  && Model != "kernel" && Model != "medium" && Model != "large") {
+  if (Model != "tiny" && Model != "small" && Model != "kernel" &&
+  Model != "medium" && Model != "large") {
 S.Diag(LiteralLoc, diag::err_attr_codemodel_arg);
 return;
   }

``




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


[clang] [clang] Add per-global code model attribute (PR #72078)

2023-11-12 Thread via cfe-commits

heiher wrote:

Part 1: #72077 
Part 3: #72079 

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


[clang] [clang] Add per-global code model attribute (PR #72078)

2023-11-12 Thread via cfe-commits

https://github.com/heiher updated 
https://github.com/llvm/llvm-project/pull/72078

>From 323a8f851acb085a9464b3edca1206481f2aee23 Mon Sep 17 00:00:00 2001
From: WANG Rui 
Date: Fri, 10 Nov 2023 21:07:48 -0600
Subject: [PATCH] [clang] Add per-global code model attribute

This adds a per-global code model attribute, which can override
the target's code model to access global variables.

Link: 
https://discourse.llvm.org/t/how-to-best-implement-code-model-overriding-for-certain-values/71816

Suggested-by: Arthur Eubanks 
Signed-off-by: WANG Rui 
---
 clang/include/clang/Basic/Attr.td |  8 
 clang/include/clang/Basic/AttrDocs.td |  9 +
 .../clang/Basic/DiagnosticSemaKinds.td|  3 +++
 clang/lib/CodeGen/CodeGenModule.cpp   | 13 
 clang/lib/Sema/SemaDeclAttr.cpp   | 20 +++
 clang/test/CodeGen/attributes.c   | 15 ++
 ...a-attribute-supported-attributes-list.test |  1 +
 clang/test/Sema/attr-model.c  | 12 +++
 8 files changed, 81 insertions(+)
 create mode 100644 clang/test/Sema/attr-model.c

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 31434565becaec67..0d3742080435142f 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -2694,6 +2694,14 @@ def PragmaClangTextSection : InheritableAttr {
   let Documentation = [InternalOnly];
 }
 
+def CodeModel : InheritableAttr {
+  let Spellings = [GCC<"model">];
+  let Args = [StringArgument<"Model">];
+  let Subjects =
+  SubjectList<[ GlobalVar ], ErrorDiag>;
+  let Documentation = [CodeModelDocs];
+}
+
 def Sentinel : InheritableAttr {
   let Spellings = [GCC<"sentinel">];
   let Args = [DefaultIntArgument<"Sentinel", 0>,
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index fa6f6acd0c30e883..ca09e4acb113003b 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -57,6 +57,15 @@ global variable or function should be in after translation.
   let Heading = "section, __declspec(allocate)";
 }
 
+def CodeModelDocs : Documentation {
+  let Category = DocCatVariable;
+  let Content = [{
+The ``model`` attribute allows you to specify a specific code model a
+global variable should be in after translation.
+  }];
+  let Heading = "model";
+}
+
 def UsedDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4614324babb1c917..f9305e21bd6a39b3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3401,6 +3401,9 @@ def warn_objc_redundant_literal_use : Warning<
 def err_attr_tlsmodel_arg : Error<"tls_model must be \"global-dynamic\", "
   "\"local-dynamic\", \"initial-exec\" or \"local-exec\"">;
 
+def err_attr_codemodel_arg : Error<"code_model must be \"tiny\", "
+  "\"small\", \"kernel\", \"medium\" or \"large\"">;
+
 def err_aix_attr_unsupported_tls_model : Error<"TLS model '%0' is not yet 
supported on AIX">;
 
 def err_tls_var_aligned_over_maximum : Error<
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 4c7f516e308ca003..f7347ab912aa7d74 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -4774,6 +4774,19 @@ CodeGenModule::GetOrCreateLLVMGlobal(StringRef 
MangledName, llvm::Type *Ty,
 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
   GV->setSection(".cp.rodata");
 
+// Handle code model attribute
+if (D->hasAttr()) {
+  if (const CodeModelAttr *CMA = D->getAttr()) {
+auto CM = llvm::StringSwitch(CMA->getModel())
+  .Case("tiny", llvm::CodeModel::Tiny)
+  .Case("kernel", llvm::CodeModel::Kernel)
+  .Case("medium", llvm::CodeModel::Medium)
+  .Case("large", llvm::CodeModel::Large)
+  .Default(llvm::CodeModel::Small);
+GV->setCodeModel(CM);
+  }
+}
+
 // Check if we a have a const declaration with an initializer, we may be
 // able to emit it as available_externally to expose it's value to the
 // optimizer.
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index cdb769a883550d0f..3cf50284bb3bedfc 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3369,6 +3369,23 @@ static void handleSectionAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   }
 }
 
+static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  StringRef Model;
+  SourceLocation LiteralLoc;
+  // Check that it is a string.
+  if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
+return;
+
+  // Check that the value.
+  if (Model != "tiny" && Model !=

  1   2   >