[PATCH] D144164: [clang][Interp] Handle PtrMemOps

2023-02-15 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, tahonermann, shafik.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This is a result of the discussions in https://reviews.llvm.org/D141472 and 
https://reviews.llvm.org/D142630.

We need to consider virtual functions when calling function pointers as well.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144164

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Interp.h
  clang/test/AST/Interp/literals.cpp
  clang/test/AST/Interp/records.cpp

Index: clang/test/AST/Interp/records.cpp
===
--- clang/test/AST/Interp/records.cpp
+++ clang/test/AST/Interp/records.cpp
@@ -488,6 +488,55 @@
   constexpr SS ss;
   static_assert(ss.a == 1);
 }
+
+namespace VirtualFunctionPointers {
+  struct S {
+virtual constexpr int func() const { return 1; }
+  };
+
+  struct Middle : S {
+constexpr Middle(int i) : i(i) {}
+int i;
+  };
+
+  struct Other {
+constexpr Other(int k) : k(k) {}
+int k;
+  };
+
+  struct S2 : Middle, Other {
+int j;
+constexpr S2(int i, int j, int k) : Middle(i), Other(k), j(j) {}
+virtual constexpr int func() const { return i + j + k  + S::func(); }
+  };
+
+  constexpr S s;
+  constexpr decltype(::func) foo = ::func;
+  constexpr int value = (s.*foo)();
+  static_assert(value == 1);
+
+
+  constexpr S2 s2(1, 2, 3);
+  static_assert(s2.i == 1);
+  static_assert(s2.j == 2);
+  static_assert(s2.k == 3);
+
+  constexpr int value2 = s2.func();
+  constexpr int value3 = (s2.*foo)();
+  static_assert(value3 == 7);
+
+  constexpr int dynamicDispatch(const S ) {
+constexpr decltype(::func) SFunc = ::func;
+
+return (s.*SFunc)();
+  }
+
+  static_assert(dynamicDispatch(s) == 1);
+  static_assert(dynamicDispatch(s2) == 7);
+};
+
+
+
 };
 #endif
 
Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -135,13 +135,10 @@
 // ref-error{{to a function type}}
 
 
-
-  /// FIXME: The following code should be accepted.
   struct S {
 void func();
   };
-  constexpr void (S::*Func)() = ::func; // expected-error {{must be initialized by a constant expression}} \
-  // expected-error {{interpreter failed to evaluate an expression}}
+  constexpr void (S::*Func)() = ::func;
   static_assert(sizeof(Func) == sizeof(::func), "");
 
 
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -1586,6 +1586,9 @@
   if (!F || !F->isConstexpr())
 return false;
 
+  if (F->isVirtual())
+return CallVirt(S, OpPC, F);
+
   return Call(S, OpPC, F);
 }
 
Index: clang/lib/AST/Interp/Context.cpp
===
--- clang/lib/AST/Interp/Context.cpp
+++ clang/lib/AST/Interp/Context.cpp
@@ -78,12 +78,6 @@
 const LangOptions ::getLangOpts() const { return Ctx.getLangOpts(); }
 
 std::optional Context::classify(QualType T) const {
-  if (T->isFunctionPointerType() || T->isFunctionReferenceType())
-return PT_FnPtr;
-
-  if (T->isReferenceType() || T->isPointerType())
-return PT_Ptr;
-
   if (T->isBooleanType())
 return PT_Bool;
 
@@ -123,9 +117,23 @@
   if (T->isFloatingType())
 return PT_Float;
 
+  if (T->isFunctionPointerType() || T->isFunctionReferenceType() ||
+  T->isFunctionProtoType() ||
+  T->isSpecificBuiltinType(BuiltinType::BoundMember))
+return PT_FnPtr;
+
+  if (T->isReferenceType() || T->isPointerType())
+return PT_Ptr;
+
   if (auto *AT = dyn_cast(T))
 return classify(AT->getValueType());
 
+  if (auto *DT = dyn_cast(T))
+return classify(DT->getUnderlyingType());
+
+  if (auto *DT = dyn_cast(T))
+return classify(DT->getPointeeType());
+
   return {};
 }
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -211,6 +211,10 @@
   std::optional LT = classify(LHS->getType());
   std::optional RT = classify(RHS->getType());
   std::optional T = classify(BO->getType());
+
+  if (BO->isPtrMemOp())
+return this->visit(RHS);
+
   if (!LT || !RT || !T) {
 return this->bail(BO);
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D143418: [libclang] Add API to set preferred temp dir path

2023-02-15 Thread Igor Kushnir via Phabricator via cfe-commits
vedgy added a comment.

In D143418#4125756 , @aaron.ballman 
wrote:

>> 3. `clang_createIndex()` initializes global options based on environment 
>> variable values:
>>
>>   if (getenv("LIBCLANG_BGPRIO_INDEX"))
>>   CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
>>  
>> CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
>> if (getenv("LIBCLANG_BGPRIO_EDIT"))
>>   CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
>>  
>> CXGlobalOpt_ThreadBackgroundPriorityForEditing);
>>
>> The recommended in documentation usage of `clang_CXIndex_setGlobalOptions` 
>> is:
>>
>>   * \code
>>   * CXIndex idx = ...;
>>   * clang_CXIndex_setGlobalOptions(idx,
>>   * clang_CXIndex_getGlobalOptions(idx) |
>>   * CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
>>   * \endcode
>>
>> So making these options part of `struct CXIndexOptions` and deprecating 
>> `clang_CXIndex_setGlobalOptions` requires introducing another global 
>> function that would read the environment variables:
>>
>>   CINDEX_LINKAGE unsigned clang_getDefaultGlobalOptions();
>>
>> Is this the right approach?
>
> Hmm, to make this patch easier, I think we might want to leave the 
> environment variable behavior alone and not shift these into the options 
> structure (yet?). Naively, I think it makes sense for these to eventually 
> live in the options structure, but we could expose them in a few different 
> ways (an option to prefer the env variable over a manual value as it is today 
> or an option to prefer the manual value over the env variable for folks who 
> want more hermetic behavior). WDYT? My opinion here isn't super strong, so if 
> you have a strong desire to deprecate and add a replacement API, I think 
> that's a defensible course to take.

On second thought, the proposed `clang_getDefaultGlobalOptions()` API already 
offers users a choice to either prefer or override each option value from the 
env. variables, just like the existing `clang_CXIndex_[gs]etGlobalOptions` API. 
The environment variables are binary options: an existence, not value, of an 
env. variable determines an initial option value. So I don't understand what 
are the two different ways to expose these options.

In D143418#4130042 , @aaron.ballman 
wrote:

> In D143418#4126266 , @vedgy wrote:
>
>> 
>
> I've been trying to think of benefits for using a fixed-size integer type and 
> the closest I can come is the consistency of the structure size across 
> targets, but I don't think we need that consistency. I don't have a strong 
> preference for `unsigned` vs `size_t`, so how about we go with your slight 
> preference for `unsigned` unless someone finds a reason to use something else?

Sounds good. Here is my current WIP API version:

  typedef struct CXIndexOptions {
/**
 * The size of struct CIndexOptions used for option versioning.
 *
 * Always assign sizeof(CIndexOptions) to this member right after
 * creating a CXIndexOptions object.
 */
unsigned Size;
/**
 * \see clang_createIndex()
 */
int ExcludeDeclarationsFromPCH : 1;
int DisplayDiagnostics : 1;
/**
 * The path to a directory, in which to store temporary PCH files. If null 
or
 * empty, the default system temporary directory is used. These PCH files 
are
 * deleted on clean exit but stay on disk if the program crashes or is 
killed.
 *
 * Libclang does not create the directory at the specified path in the file
 * system. Therefore it must exist, or storing PCH files will fail.
 */
const char *PreambleStoragePath;
/**
 * Specifies a path which will contain log files for certain libclang
 * invocations. A null value implies that libclang invocations are not 
logged.
 */
const char *InvocationEmissionPath;
  } CXIndexOptions;
  
  /**
   * Provides a shared context for creating translation units.
   *
   * Call this function instead of clang_createIndex() if you need to configure
   * the additional options in CXIndexOptions.
   *
   * \returns The created index or null in case of error, such as an unsupported
   * value of options->Size.
   *
   * For example:
   * \code
   * CXIndex createIndex(const char *ApplicationTemporaryPath) {
   *   const int ExcludeDeclarationsFromPCH = 1;
   *   const int DisplayDiagnostics = 1;
   * #if CINDEX_VERSION_MINOR >= 64
   *   CIndexOptions Opts;
   *   Opts.Size = sizeof(CIndexOptions);
   *   Opts.ExcludeDeclarationsFromPCH = ExcludeDeclarationsFromPCH;
   *   Opts.DisplayDiagnostics = DisplayDiagnostics;
   *   Opts.PreambleStoragePath = ApplicationTemporaryPath;
   *   Opts.InvocationEmissionPath = NULL;
   *   CIndex Idx = clang_createIndexWithOptions();
   *   if (Idx)
   * return Idx;
   *   fprintf(stderr, "clang_createIndexWithOptions() 

[clang] 999ead9 - [Modules] Code cleanup after removing ModulesTS

2023-02-15 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2023-02-16T15:22:38+08:00
New Revision: 999ead9dc9080cf95445149e6dae1de087ef90b8

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

LOG: [Modules] Code cleanup after removing ModulesTS

Some codes become unused after we remove ModulesTS.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaModule.cpp
clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
clang/test/CXX/module/module.interface/p1.cpp
clang/test/Modules/cxx20-10-2-ex1.cpp
clang/test/Modules/cxx20-export-import.cpp
clang/test/Modules/cxx20-import-diagnostics-a.cpp
clang/test/Modules/export-in-non-modules.cpp
clang/test/SemaCXX/modules.cppm

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index af714de6b6072..5ab134592e865 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11229,8 +11229,7 @@ def err_export_using_internal : Error<
   "using declaration referring to %1 with %select{internal|module|unknown}0 "
   "linkage cannot be exported">;
 def err_export_not_in_module_interface : Error<
-  "export declaration can only be used within a module interface unit"
-  "%select{ after the module declaration|}0">;
+  "export declaration can only be used within a module purview">;
 def err_export_inline_not_defined : Error<
   "inline function not defined%select{| before the private module fragment}0">;
 def err_export_partition_impl : Error<

diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 223190602d921..80b6f9d0ab1d5 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2280,8 +2280,6 @@ class Sema final {
 SourceLocation BeginLoc;
 clang::Module *Module = nullptr;
 bool ModuleInterface = false;
-bool IsPartition = false;
-bool ImplicitGlobalModuleFragment = false;
 VisibleModuleSet OuterVisibleModules;
   };
   /// The modules we're currently parsing.

diff  --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index c8a855d79a8e8..d9d0ed6784f46 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1196,8 +1196,7 @@ void Sema::ActOnEndOfTranslationUnit() {
   // A global-module-fragment is only permitted within a module unit.
   bool DiagnosedMissingModuleDeclaration = false;
   if (!ModuleScopes.empty() &&
-  ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment &&
-  !ModuleScopes.back().ImplicitGlobalModuleFragment) {
+  ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
 Diag(ModuleScopes.back().BeginLoc,
  diag::err_module_declaration_missing_after_global_module_introducer);
 DiagnosedMissingModuleDeclaration = true;

diff  --git a/clang/lib/Sema/SemaModule.cpp b/clang/lib/Sema/SemaModule.cpp
index 1fd1941ebf429..f1c409078f413 100644
--- a/clang/lib/Sema/SemaModule.cpp
+++ b/clang/lib/Sema/SemaModule.cpp
@@ -125,7 +125,6 @@ void Sema::HandleStartOfHeaderUnit() {
   ModuleScopes.back().BeginLoc = StartOfTU;
   ModuleScopes.back().Module = Mod;
   ModuleScopes.back().ModuleInterface = true;
-  ModuleScopes.back().IsPartition = false;
   VisibleModules.setVisible(Mod, StartOfTU);
 
   // From now on, we have an owning module for all declarations we see.
@@ -373,7 +372,6 @@ Sema::ActOnModuleDecl(SourceLocation StartLoc, 
SourceLocation ModuleLoc,
   ModuleScopes.back().BeginLoc = StartLoc;
   ModuleScopes.back().Module = Mod;
   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
-  ModuleScopes.back().IsPartition = IsPartition;
   VisibleModules.setVisible(Mod, ModuleLoc);
 
   // From now on, we have an owning module for all declarations we see.
@@ -601,9 +599,7 @@ DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
 // [module.interface]p1:
 // An export-declaration shall inhabit a namespace scope and appear in the
 // purview of a module interface unit.
-Diag(ExportLoc, diag::err_export_not_in_module_interface)
-<< (!ModuleScopes.empty() &&
-!ModuleScopes.back().ImplicitGlobalModuleFragment);
+Diag(ExportLoc, diag::err_export_not_in_module_interface);
   }
 
   // In some cases we need to know if an entity was present in a directly-
@@ -980,8 +976,6 @@ Module *Sema::PushGlobalModuleFragment(SourceLocation 
BeginLoc,
   // Enter the scope of the global module.
   ModuleScopes.push_back({BeginLoc, GlobalModuleFragment,
   /*ModuleInterface=*/false,
-  /*IsPartition=*/false,
-  

[PATCH] D144135: [clang-tidy] Add performance-enum-size check

2023-02-15 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL created this revision.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
PiotrZSL updated this revision to Diff 497787.
PiotrZSL added a comment.
PiotrZSL updated this revision to Diff 497804.
PiotrZSL updated this revision to Diff 497826.
Eugene.Zelenko added reviewers: aaron.ballman, carlosgalvezp.
PiotrZSL marked 4 inline comments as done.
PiotrZSL updated this revision to Diff 497887.
PiotrZSL published this revision for review.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Removed change in list.rst that is related to 
cppcoreguidelines-avoid-capture-default-when-capturing-this.
Looks like that check have fixes but didnt mark fixes in that file.


PiotrZSL added a comment.

Fix typo in documentation.


PiotrZSL added a comment.

Fix tests on windows (they use int as base for enums, when on linux unsigned 
int is used)


PiotrZSL added a comment.

Fix review comments


PiotrZSL added a comment.

Ready for review




Comment at: clang-tools-extra/clang-tidy/performance/EnumSizeCheck.cpp:99
+  const auto *MatchedDecl = Result.Nodes.getNodeAs("e");
+  auto BaseType = MatchedDecl->getIntegerType().getCanonicalType();
+  if (not BaseType->isIntegerType())

Please do not use `auto` unless type is explicitly spelled in same function or 
iterator.



Comment at: clang-tools-extra/clang-tidy/performance/EnumSizeCheck.cpp:100
+  auto BaseType = MatchedDecl->getIntegerType().getCanonicalType();
+  if (not BaseType->isIntegerType())
+return;

I don't think that literal boolean operators are part of LLVM coding guidelines.



Comment at: clang-tools-extra/clang-tidy/performance/EnumSizeCheck.cpp:103
+
+  auto Size = Result.Context->getTypeSize(BaseType) / 8U;
+  if (1U == Size)

Ditto.



Comment at: clang-tools-extra/clang-tidy/performance/EnumSizeCheck.cpp:120
+  auto NewType = getNewType(Size, MinV, MaxV);
+  if (not NewType.first or Size <= NewType.second)
+return;

Ditto.


Finds enum type definitions that could use smaller integral type as a base.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144135

Files:
  clang-tools-extra/clang-tidy/performance/CMakeLists.txt
  clang-tools-extra/clang-tidy/performance/EnumSizeCheck.cpp
  clang-tools-extra/clang-tidy/performance/EnumSizeCheck.h
  clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/performance/enum-size.rst
  clang-tools-extra/test/clang-tidy/checkers/performance/enum-size.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance/enum-size.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/performance/enum-size.cpp
@@ -0,0 +1,94 @@
+// RUN: %check_clang_tidy -std=c++17-or-later %s performance-enum-size %t -- \
+// RUN:   -config="{CheckOptions: [{key: performance-enum-size.EnumIgnoreRegexp, value: '^::IgnoredEnum$'}]}"
+
+namespace std
+{
+using uint8_t = unsigned char;
+using int8_t = signed char;
+using uint16_t = unsigned short;
+using int16_t = signed short;
+using uint32_t = unsigned int;
+using int32_t = signed int;
+}
+
+enum class Value
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: enum 'Value' derive from 'int' of size 4 bytes, derive from 'std::uint8_t' to reduce it size to 1 [performance-enum-size]
+{
+supported
+};
+
+
+enum class EnumClass : std::int16_t
+// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: enum 'EnumClass' derive from 'std::int16_t' (aka 'short') of size 2 bytes, derive from 'std::uint8_t' to reduce it size to 1 [performance-enum-size]
+{
+supported
+};
+
+enum EnumWithType : std::uint16_t
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumWithType' derive from 'std::uint16_t' (aka 'unsigned short') of size 2 bytes, derive from 'std::uint8_t' to reduce it size to 1 [performance-enum-size]
+{
+supported,
+supported2
+};
+
+enum EnumWithNegative
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumWithNegative' derive from 'int' of size 4 bytes, derive from 'std::int8_t' to reduce it size to 1 [performance-enum-size]
+{
+s1 = -128,
+s2 = -100,
+s3 = 100,
+s4 = 127
+};
+
+enum EnumThatCanBeReducedTo2Bytes
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumThatCanBeReducedTo2Bytes' derive from 'int' of size 4 bytes, derive from 'std::int16_t' to reduce it size to 2 [performance-enum-size]
+{
+a1 = -128,
+a2 = 0x6EEE
+};
+
+enum EnumOnlyNegative
+// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: enum 'EnumOnlyNegative' derive from 'int' of size 4 bytes, derive from 'std::int8_t' to reduce it size to 1 [performance-enum-size]
+{
+b1 = -125,
+b2 = -50,
+b3 = -10
+};
+
+enum 

[PATCH] D144037: [clang-tidy] allow tests to use --config-file instead of --config

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

LGTM, thanks for the fix!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144037

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


[PATCH] D144157: Add 128-bit integer support to enum element

2023-02-15 Thread zhouyizhou via Phabricator via cfe-commits
zhouyizhou updated this revision to Diff 497893.

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

https://reviews.llvm.org/D144157

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/enum.c


Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -1,4 +1,9 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify 
-pedantic
+enum b {
+   b0 = (__uint128_t)-1, // expected-warning {{ISO C restricts enumerator 
values to range of 'int'}}
+   b1 = (__uint128_t)0x123456789abcdef0ULL << 64|0x0fedcba987654321ULL, // 
expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+};
+
 enum e {A,
 B = 42LL << 32,// expected-warning {{ISO C restricts 
enumerator values to range of 'int'}}
   C = -4, D = 12456 };
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19568,9 +19568,6 @@
 return;
   }
 
-  // TODO: If the result value doesn't fit in an int, it must be a long or long
-  // long value.  ISO C does not support this, but GCC does as an extension,
-  // emit a warning.
   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
@@ -19690,14 +19687,24 @@
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongTy : Context.LongTy;
-} else {
+} else if (NumPositiveBits <= Context.getTargetInfo().getLongLongWidth()) {
   BestWidth = Context.getTargetInfo().getLongLongWidth();
-  assert(NumPositiveBits <= BestWidth &&
- "How could an initializer get larger than ULL?");
   BestType = Context.UnsignedLongLongTy;
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongLongTy : Context.LongLongTy;
+} else {
+  BestWidth = 128;
+  assert(NumPositiveBits <= BestWidth &&
+ "How could an initializer get larger than 128-bit?");
+  assert(Context.getTargetInfo().hasInt128Type() &&
+ "How could an initializer get larger than ULL in target without "
+ "128-bit interger type support?");
+  BestType = Context.UnsignedInt128Ty;
+  BestPromotionType =
+  (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
+  ? Context.UnsignedInt128Ty
+  : Context.Int128Ty;
 }
   }
 


Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -1,4 +1,9 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify -pedantic
+enum b {
+   b0 = (__uint128_t)-1, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+   b1 = (__uint128_t)0x123456789abcdef0ULL << 64|0x0fedcba987654321ULL, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+};
+
 enum e {A,
 B = 42LL << 32,// expected-warning {{ISO C restricts enumerator values to range of 'int'}}
   C = -4, D = 12456 };
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19568,9 +19568,6 @@
 return;
   }
 
-  // TODO: If the result value doesn't fit in an int, it must be a long or long
-  // long value.  ISO C does not support this, but GCC does as an extension,
-  // emit a warning.
   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
@@ -19690,14 +19687,24 @@
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongTy : Context.LongTy;
-} else {
+} else if (NumPositiveBits <= Context.getTargetInfo().getLongLongWidth()) {
   BestWidth = Context.getTargetInfo().getLongLongWidth();
-  assert(NumPositiveBits <= BestWidth &&
- "How could an initializer get larger than ULL?");
   BestType = Context.UnsignedLongLongTy;
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongLongTy : Context.LongLongTy;
+} else {
+  BestWidth = 128;
+  assert(NumPositiveBits <= BestWidth &&
+ "How could an initializer get larger than 128-bit?");
+  assert(Context.getTargetInfo().hasInt128Type() &&
+ "How could an initializer get larger than ULL in target without "
+ "128-bit interger type support?");
+  

[PATCH] D144157: Add 128-bit integer support to enum element

2023-02-15 Thread zhouyizhou via Phabricator via cfe-commits
zhouyizhou updated this revision to Diff 497889.
zhouyizhou added a comment.

reformat the patch according to Chuanqi's Advice


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

https://reviews.llvm.org/D144157

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/enum.c


Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -1,4 +1,9 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify 
-pedantic
+enum b {
+   b0 = (__uint128_t)-1, // expected-warning {{ISO C restricts enumerator 
values to range of 'int'}}
+   b1 = (__uint128_t)0x123456789abcdef0ULL << 64|0x0fedcba987654321ULL, // 
expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+};
+
 enum e {A,
 B = 42LL << 32,// expected-warning {{ISO C restricts 
enumerator values to range of 'int'}}
   C = -4, D = 12456 };
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19690,14 +19690,24 @@
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongTy : Context.LongTy;
-} else {
+} else if (NumPositiveBits <= Context.getTargetInfo().getLongLongWidth()) {
   BestWidth = Context.getTargetInfo().getLongLongWidth();
-  assert(NumPositiveBits <= BestWidth &&
- "How could an initializer get larger than ULL?");
   BestType = Context.UnsignedLongLongTy;
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongLongTy : Context.LongLongTy;
+} else {
+  BestWidth = 128;
+  assert(NumPositiveBits <= BestWidth &&
+ "How could an initializer get larger than 128-bit?");
+  assert(Context.getTargetInfo().hasInt128Type() &&
+ "How could an initializer get larger than ULL in target without "
+ "128-bit interger type support?");
+  BestType = Context.UnsignedInt128Ty;
+  BestPromotionType =
+  (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
+  ? Context.UnsignedInt128Ty
+  : Context.Int128Ty;
 }
   }
 


Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -1,4 +1,9 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify -pedantic
+enum b {
+   b0 = (__uint128_t)-1, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+   b1 = (__uint128_t)0x123456789abcdef0ULL << 64|0x0fedcba987654321ULL, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+};
+
 enum e {A,
 B = 42LL << 32,// expected-warning {{ISO C restricts enumerator values to range of 'int'}}
   C = -4, D = 12456 };
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19690,14 +19690,24 @@
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongTy : Context.LongTy;
-} else {
+} else if (NumPositiveBits <= Context.getTargetInfo().getLongLongWidth()) {
   BestWidth = Context.getTargetInfo().getLongLongWidth();
-  assert(NumPositiveBits <= BestWidth &&
- "How could an initializer get larger than ULL?");
   BestType = Context.UnsignedLongLongTy;
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongLongTy : Context.LongLongTy;
+} else {
+  BestWidth = 128;
+  assert(NumPositiveBits <= BestWidth &&
+ "How could an initializer get larger than 128-bit?");
+  assert(Context.getTargetInfo().hasInt128Type() &&
+ "How could an initializer get larger than ULL in target without "
+ "128-bit interger type support?");
+  BestType = Context.UnsignedInt128Ty;
+  BestPromotionType =
+  (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
+  ? Context.UnsignedInt128Ty
+  : Context.Int128Ty;
 }
   }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144157: Add 128-bit integer support to enum element

2023-02-15 Thread zhouyizhou via Phabricator via cfe-commits
zhouyizhou added a comment.

In D144157#4131103 , @ChuanqiXu wrote:

>> debian build bot won't let me pass, so I clang-formatted the function 
>> ActOnEnumBody
>
> You can try `git diff -U0 --no-color --relative HEAD^ | 
> clang/tools/clang-format/clang-format-diff.py -p1 -i` to format the changed 
> part only. Currently there are many untouched part changed due to the format. 
> This is not good.

Thank you for your valuable advice, the command is fantastic indeed. I will 
resend the patch immediately.  
Thanks again
Cheers Zhouyi


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

https://reviews.llvm.org/D144157

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


[PATCH] D144157: Add 128-bit integer support to enum element

2023-02-15 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

> debian build bot won't let me pass, so I clang-formatted the function 
> ActOnEnumBody

You can try `git diff -U0 --no-color --relative HEAD^ | 
clang/tools/clang-format/clang-format-diff.py -p1 -i` to format the changed 
part only. Currently there are many untouched part changed due to the format. 
This is not good.


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

https://reviews.llvm.org/D144157

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


[clang] 612f3ac - [Modules] Remove -fmodules-ts

2023-02-15 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2023-02-16T14:40:32+08:00
New Revision: 612f3ac26f8cdb7487408b5541b224876564e57c

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

LOG: [Modules] Remove -fmodules-ts

As the diagnostic message shows, we should remove -fmodules-ts flag in
clang/llvm17. Since clang/llvm16 is already branched. We can remove the
depreacared flag now.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/Decl.h
clang/include/clang/AST/DeclBase.h
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Basic/DiagnosticFrontendKinds.td
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Basic/Linkage.h
clang/include/clang/Basic/TokenKinds.def
clang/include/clang/Driver/Options.td
clang/lib/AST/Decl.cpp
clang/lib/Basic/IdentifierTable.cpp
clang/lib/CodeGen/ItaniumCXXABI.cpp
clang/lib/CodeGen/MicrosoftCXXABI.cpp
clang/lib/Driver/ToolChains/Clang.cpp
clang/lib/Frontend/FrontendActions.cpp
clang/lib/Index/IndexSymbol.cpp
clang/lib/Lex/PPDirectives.cpp
clang/lib/Lex/Preprocessor.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Parse/Parser.cpp
clang/lib/Sema/Sema.cpp
clang/lib/Sema/SemaModule.cpp
clang/tools/libclang/CIndex.cpp
clang/tools/libclang/CXIndexDataConsumer.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index abb6f0ae8e92e..b91a973b9a666 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -96,6 +96,8 @@ Modified Compiler Flags
 
 Removed Compiler Flags
 -
+- The deprecated flag `-fmodules-ts` is removed. Please use ``-std=c++20``
+  or higher to use standard C++ modules instead.
 
 Attribute Changes in Clang
 --

diff  --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 863f6ac57f2aa..b32d021b1c695 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -4707,7 +4707,7 @@ class ImportDecl final : public Decl,
   static bool classofKind(Kind K) { return K == Import; }
 };
 
-/// Represents a C++ Modules TS module export declaration.
+/// Represents a standard C++ module export declaration.
 ///
 /// For example:
 /// \code

diff  --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index ef5d4d7e7b7b5..7c3b755a438f1 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -810,7 +810,7 @@ class alignas(8) Decl {
   }
 
   /// Get the module that owns this declaration for linkage purposes.
-  /// There only ever is such a module under the C++ Modules TS.
+  /// There only ever is such a standard C++ module.
   ///
   /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
   /// all declarations in a global module fragment are unowned.

diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 8d557846c6ff0..35325de4a34a4 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -638,10 +638,6 @@ def warn_deperecated_fcoroutines_ts_flag : Warning<
   "the '-fcoroutines-ts' flag is deprecated and it will be removed in Clang 
17; "
   "use '-std=c++20' or higher to use standard C++ coroutines instead">,
   InGroup;
-def warn_deprecated_fmodules_ts_flag : Warning<
-  "the '-fmodules-ts' flag is deprecated and it will be removed in Clang 17; "
-  "use '-std=c++20' or higher to use standard C++ modules instead">,
-  InGroup>;
 
 def err_drv_cannot_mix_options : Error<"cannot specify '%1' along with '%0'">;
 

diff  --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index d0f672ae5a1bd..c2bce23e9a53f 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -209,7 +209,7 @@ def note_incompatible_analyzer_plugin_api : Note<
 def err_module_build_requires_fmodules : Error<
   "module compilation requires '-fmodules'">;
 def err_module_interface_requires_cpp_modules : Error<
-  "module interface compilation requires '-std=c++20' or '-fmodules-ts'">;
+  "module interface compilation requires '-std=c++20'">;
 def warn_module_config_mismatch : Warning<
   "module file %0 cannot be loaded due to a configuration mismatch with the 
current "
   "compilation">, InGroup>, 
DefaultError;

diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index d1cbe43064391..20bddca48cba1 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -171,7 +171,6 @@ 

[PATCH] D144136: Add a "remark" to report on array accesses

2023-02-15 Thread Kees Cook via Phabricator via cfe-commits
kees added a comment.

This information will be useful for evaluating the coverage of the bounds 
checker for a given program, which in turn can help guide both improvements to 
the bounds checker (e.g. adding knowledge from 
`__builtin_dynamic_object_size()`) and improvements to the built code base 
(e.g. refactoring data structures to take advantage of known compile-time or 
run-time bounds that will be covered by the bounds checker). It answers the 
question, "What percentage of array accesses are being bounds checked?" (With 
the implied goal of reaching 100% going forward.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144136

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


[clang] 7e6e636 - Use llvm::has_single_bit (NFC)

2023-02-15 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2023-02-15T22:17:27-08:00
New Revision: 7e6e636fb683a854de27f56b2da7d157a0b70f4e

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

LOG: Use llvm::has_single_bit (NFC)

This patch replaces isPowerOf2_32 with llvm::has_single_bit
where the argument is wider than uint32_t.

Added: 


Modified: 
clang/lib/CodeGen/CGNonTrivialStruct.cpp
llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
llvm/lib/CodeGen/GlobalISel/LegalityPredicates.cpp
llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
llvm/lib/CodeGen/TargetLoweringBase.cpp
llvm/lib/Target/AArch64/GISel/AArch64InstructionSelector.cpp
llvm/lib/Target/AArch64/GISel/AArch64LegalizerInfo.cpp
llvm/lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp
llvm/lib/Target/ARM/ARMISelLowering.cpp
llvm/lib/Target/AVR/AVRISelLowering.cpp
llvm/lib/Target/PowerPC/AsmParser/PPCAsmParser.cpp
llvm/lib/Target/PowerPC/PPCISelLowering.cpp
llvm/lib/Target/RISCV/RISCVISelLowering.cpp
llvm/lib/Target/RISCV/RISCVInstrInfo.cpp
llvm/lib/Target/RISCV/RISCVSubtarget.cpp
llvm/lib/Target/X86/X86ISelLowering.cpp
llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
llvm/utils/TableGen/DAGISelMatcherGen.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGNonTrivialStruct.cpp 
b/clang/lib/CodeGen/CGNonTrivialStruct.cpp
index 7efb4d7efe5af..a10e51b8cb441 100644
--- a/clang/lib/CodeGen/CGNonTrivialStruct.cpp
+++ b/clang/lib/CodeGen/CGNonTrivialStruct.cpp
@@ -522,7 +522,8 @@ struct GenBinaryFunc : CopyStructVisitor,
 Address SrcAddr = this->getAddrWithOffset(Addrs[SrcIdx], this->Start);
 
 // Emit memcpy.
-if (Size.getQuantity() >= 16 || !llvm::isPowerOf2_32(Size.getQuantity())) {
+if (Size.getQuantity() >= 16 ||
+!llvm::has_single_bit(Size.getQuantity())) {
   llvm::Value *SizeVal =
   llvm::ConstantInt::get(this->CGF->SizeTy, Size.getQuantity());
   DstAddr =

diff  --git a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp 
b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
index 5fc267458a7af..81863c1edd6b2 100644
--- a/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp
@@ -535,7 +535,7 @@ bool 
CombinerHelper::matchCombineExtendingLoads(MachineInstr ,
 
   // For non power-of-2 types, they will very likely be legalized into multiple
   // loads. Don't bother trying to match them into extending loads.
-  if (!isPowerOf2_32(LoadValueTy.getSizeInBits()))
+  if (!llvm::has_single_bit(LoadValueTy.getSizeInBits()))
 return false;
 
   // Find the preferred type aside from the any-extends (unless it's the only

diff  --git a/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp 
b/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
index aefdf2079486f..fffbb862d390f 100644
--- a/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
@@ -1018,7 +1018,7 @@ void 
IRTranslator::emitBitTestHeader(SwitchCG::BitTestBlock ,
 
   LLT MaskTy = SwitchOpTy;
   if (MaskTy.getSizeInBits() > PtrTy.getSizeInBits() ||
-  !isPowerOf2_32(MaskTy.getSizeInBits()))
+  !llvm::has_single_bit(MaskTy.getSizeInBits()))
 MaskTy = LLT::scalar(PtrTy.getSizeInBits());
   else {
 // Ensure that the type will fit the mask value.

diff  --git a/llvm/lib/CodeGen/GlobalISel/LegalityPredicates.cpp 
b/llvm/lib/CodeGen/GlobalISel/LegalityPredicates.cpp
index 54a82cac95d58..2c77ed8b06008 100644
--- a/llvm/lib/CodeGen/GlobalISel/LegalityPredicates.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/LegalityPredicates.cpp
@@ -164,7 +164,8 @@ LegalityPredicate 
LegalityPredicates::sizeNotMultipleOf(unsigned TypeIdx,
 LegalityPredicate LegalityPredicates::sizeNotPow2(unsigned TypeIdx) {
   return [=](const LegalityQuery ) {
 const LLT QueryTy = Query.Types[TypeIdx];
-return QueryTy.isScalar() && !isPowerOf2_32(QueryTy.getSizeInBits());
+return QueryTy.isScalar() &&
+   !llvm::has_single_bit(QueryTy.getSizeInBits());
   };
 }
 
@@ -184,14 +185,16 @@ LegalityPredicate LegalityPredicates::sameSize(unsigned 
TypeIdx0,
 
 LegalityPredicate LegalityPredicates::memSizeInBytesNotPow2(unsigned MMOIdx) {
   return [=](const LegalityQuery ) {
-return !isPowerOf2_32(Query.MMODescrs[MMOIdx].MemoryTy.getSizeInBytes());
+return !llvm::has_single_bit(
+Query.MMODescrs[MMOIdx].MemoryTy.getSizeInBytes());
   };
 }
 
 LegalityPredicate LegalityPredicates::memSizeNotByteSizePow2(unsigned MMOIdx) {
   return [=](const LegalityQuery ) {
 const LLT MemTy = Query.MMODescrs[MMOIdx].MemoryTy;
-return !MemTy.isByteSized() || !isPowerOf2_32(MemTy.getSizeInBytes());
+return !MemTy.isByteSized() ||
+   

[PATCH] D143919: [Clang] Copy strictfp attribute from pattern to instantiation

2023-02-15 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff added a comment.

In D143919#4130178 , @efriedma wrote:

> If the "strictfp" attribute is based on the contents of the function body, 
> should we recompute it when the function is instantiated, as opposed to 
> copying it?  For example, say you have a pragma inside an "if constexpr"; 
> should that set the strictfp attribute if it's discarded?
>
> Otherwise, I guess updateAttrsForLateParsedTemplate makes sense.

Recomputing is certainly a better solution, as it would provide actual 
properties. It however should be applied to all instantiations, not only late 
parsed. With this change the code:

  template 
  T templ_01(T x, T y) {
if constexpr (F) {
  #pragma STDC FENV_ACCESS ON
  return x - y;
} else
return x + y;
  }
  
  float func_02(float x, float y) {
return templ_01(x, y);
  }
  
  float func_03(float x, float y) {
return templ_01(x, y);
  }

compiled without late parsing produces `func_03` with strictfp attribute. 
However constarined intrinsics in it are semantically equivalent to 
non-constrained operations. Adding unneeded strictfp attribute is not an error.




Comment at: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp:824
+  continue;
+}
+

efriedma wrote:
> Is this necessary?  The non-delayed-parsed case seems to work correctly on 
> trunk without any changes, so I suspect the autogenerated 
> sema::instantiateTemplateAttribute is doing the right thing.
Yes, it is necessary. Without it the code from the added test crashes, as 
constrained intrinsic is used in a function without strictfp attribute.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143919

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


[clang] d54888a - [Modules] Refactor modules-ts tests to use standard c++ modules

2023-02-15 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2023-02-16T14:05:16+08:00
New Revision: d54888a3ebb141cdbb5e88ed7a3a2a54d24fc904

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

LOG: [Modules] Refactor modules-ts tests to use standard c++ modules

We're going to remove the support for modules-ts. But there are a lot of
tests which uses -fmodules-ts. We shouldn't remove them simply. This
patch refactor these tests to use standard c++ modules.

Added: 
clang/test/CXX/module/basic/basic.def.odr/p4.cppm
clang/test/CXX/module/basic/basic.def.odr/p6.cppm
clang/test/CXX/module/basic/basic.link/module-declaration.cpp
clang/test/CXX/module/basic/basic.link/p2.cppm
clang/test/CXX/module/basic/basic.link/p3.cppm
clang/test/CXX/module/basic/basic.search/module-import.cppm
clang/test/CXX/module/codegen-basics.cppm
clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.export/p1.cppm
clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.import/p1.cppm
clang/test/CXX/module/dcl.dcl/dcl.module/dcl.module.interface/p1.cppm
clang/test/CXX/module/dcl.dcl/dcl.module/p1.cpp
clang/test/CXX/module/dcl.dcl/dcl.module/p2.cpp
clang/test/CXX/module/dcl.dcl/dcl.module/p5.cpp
clang/test/Modules/anon-linkage.cppm
clang/test/SemaCXX/modules.cppm

Modified: 
clang/test/CodeGenCXX/cxx20-module-nested-1.cppm
clang/test/CodeGenCXX/cxx20-module-nested-2.cppm
clang/test/Modules/diag-flags.cpp
clang/test/Modules/diag-pragma.cpp
clang/test/Modules/import-syntax.c
clang/test/Modules/mismatch-diagnostics.cpp
clang/test/Parser/cxx-modules-interface.cppm
clang/test/SemaCXX/anonymous-union-export.cpp
clang/unittests/AST/DeclTest.cpp

Removed: 
clang/test/CXX/modules-ts/basic/basic.def.odr/p4/module.cpp
clang/test/CXX/modules-ts/basic/basic.def.odr/p4/module.cppm
clang/test/CXX/modules-ts/basic/basic.def.odr/p4/user.cpp
clang/test/CXX/modules-ts/basic/basic.def.odr/p6/global-vs-module.cpp
clang/test/CXX/modules-ts/basic/basic.def.odr/p6/module-vs-global.cpp
clang/test/CXX/modules-ts/basic/basic.def.odr/p6/module-vs-module.cpp
clang/test/CXX/modules-ts/basic/basic.link/module-declaration.cpp
clang/test/CXX/modules-ts/basic/basic.link/p2/module.cpp
clang/test/CXX/modules-ts/basic/basic.link/p2/module.cppm
clang/test/CXX/modules-ts/basic/basic.link/p2/other.cpp
clang/test/CXX/modules-ts/basic/basic.link/p3.cppm
clang/test/CXX/modules-ts/basic/basic.search/module-import.cpp
clang/test/CXX/modules-ts/codegen-basics.cppm
clang/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.export/p1.cpp
clang/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.import/p1.cpp
clang/test/CXX/modules-ts/dcl.dcl/dcl.module/dcl.module.interface/p1.cpp
clang/test/CXX/modules-ts/dcl.dcl/dcl.module/p1.cpp
clang/test/CXX/modules-ts/dcl.dcl/dcl.module/p2.cpp
clang/test/CXX/modules-ts/dcl.dcl/dcl.module/p5.cpp
clang/test/Driver/modules-ts.cpp
clang/test/Lexer/modules-ts.cpp
clang/test/Modules/anon-linkage.cpp
clang/test/SemaCXX/modules-ts.cppm



diff  --git a/clang/test/CXX/modules-ts/basic/basic.def.odr/p4/module.cppm 
b/clang/test/CXX/module/basic/basic.def.odr/p4.cppm
similarity index 54%
rename from clang/test/CXX/modules-ts/basic/basic.def.odr/p4/module.cppm
rename to clang/test/CXX/module/basic/basic.def.odr/p4.cppm
index c25c32da9cfd0..a07913c1e08e1 100644
--- a/clang/test/CXX/modules-ts/basic/basic.def.odr/p4/module.cppm
+++ b/clang/test/CXX/module/basic/basic.def.odr/p4.cppm
@@ -1,5 +1,15 @@
-// RUN: %clang_cc1 -fmodules-ts %s -triple %itanium_abi_triple -emit-llvm -o - 
| FileCheck %s --implicit-check-not unused_inline --implicit-check-not 
unused_stastic_global_module
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+//
+// RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple 
-emit-llvm -o - | FileCheck %t/Module.cppm --implicit-check-not unused_inline 
--implicit-check-not unused_stastic_global_module
+//
+// RUN: %clang_cc1 -std=c++20 %t/Module.cppm -triple %itanium_abi_triple 
-emit-module-interface -o %t/Module.pcm
+// RUN: %clang_cc1 -std=c++20 %t/module.cpp -triple %itanium_abi_triple 
-fmodule-file=%t/Module.pcm -emit-llvm -o - | FileCheck %t/module.cpp 
--implicit-check-not=unused --implicit-check-not=global_module
+//
+// RUN: %clang_cc1 -std=c++20 %t/user.cpp -triple %itanium_abi_triple 
-fmodule-file=%t/Module.pcm -emit-llvm -o - | FileCheck %t/user.cpp 
--implicit-check-not=unused --implicit-check-not=global_module
 
+//--- Module.cppm
 // CHECK-DAG: @extern_var_global_module = external {{(dso_local )?}}global
 // CHECK-DAG: @inline_var_global_module = linkonce_odr {{(dso_local )?}}global
 // CHECK-DAG: @_ZL24static_var_global_module = internal global

[PATCH] D144157: Add 128-bit integer support to enum element

2023-02-15 Thread zhouyizhou via Phabricator via cfe-commits
zhouyizhou updated this revision to Diff 497884.
zhouyizhou added a comment.

debian build bot won't me pass,  so I clang-formatted the function ActOnEnumBody


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

https://reviews.llvm.org/D144157

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/enum.c

Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -1,4 +1,9 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify -pedantic
+enum b {
+   b0 = (__uint128_t)-1, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+   b1 = (__uint128_t)0x123456789abcdef0ULL << 64|0x0fedcba987654321ULL, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+};
+
 enum e {A,
 B = 42LL << 32,// expected-warning {{ISO C restricts enumerator values to range of 'int'}}
   C = -4, D = 12456 };
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19557,9 +19557,9 @@
 
   if (Enum->isDependentType()) {
 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
-  EnumConstantDecl *ECD =
-cast_or_null(Elements[i]);
-  if (!ECD) continue;
+  EnumConstantDecl *ECD = cast_or_null(Elements[i]);
+  if (!ECD)
+continue;
 
   ECD->setType(EnumType);
 }
@@ -19568,9 +19568,6 @@
 return;
   }
 
-  // TODO: If the result value doesn't fit in an int, it must be a long or long
-  // long value.  ISO C does not support this, but GCC does as an extension,
-  // emit a warning.
   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
@@ -19581,9 +19578,9 @@
   unsigned NumPositiveBits = 0;
 
   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
-EnumConstantDecl *ECD =
-  cast_or_null(Elements[i]);
-if (!ECD) continue;  // Already issued a diagnostic.
+EnumConstantDecl *ECD = cast_or_null(Elements[i]);
+if (!ECD)
+  continue; // Already issued a diagnostic.
 
 const llvm::APSInt  = ECD->getInitVal();
 
@@ -19594,8 +19591,8 @@
   unsigned ActiveBits = InitVal.getActiveBits();
   NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
 } else {
-  NumNegativeBits = std::max(NumNegativeBits,
- (unsigned)InitVal.getMinSignedBits());
+  NumNegativeBits =
+  std::max(NumNegativeBits, (unsigned)InitVal.getMinSignedBits());
 }
   }
 
@@ -19637,8 +19634,7 @@
   BestPromotionType = BestType;
 
 BestWidth = Context.getIntWidth(BestType);
-  }
-  else if (NumNegativeBits) {
+  } else if (NumNegativeBits) {
 // If there is a negative value, figure out the smallest integer type (of
 // int/long/longlong) that fits.
 // If it's packed, check also if it fits a char or a short.
@@ -19681,23 +19677,36 @@
 } else if (NumPositiveBits <= IntWidth) {
   BestType = Context.UnsignedIntTy;
   BestWidth = IntWidth;
-  BestPromotionType
-= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
-   ? Context.UnsignedIntTy : Context.IntTy;
+  BestPromotionType =
+  (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
+  ? Context.UnsignedIntTy
+  : Context.IntTy;
 } else if (NumPositiveBits <=
(BestWidth = Context.getTargetInfo().getLongWidth())) {
   BestType = Context.UnsignedLongTy;
-  BestPromotionType
-= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
-   ? Context.UnsignedLongTy : Context.LongTy;
-} else {
+  BestPromotionType =
+  (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
+  ? Context.UnsignedLongTy
+  : Context.LongTy;
+} else if (NumPositiveBits <= Context.getTargetInfo().getLongLongWidth()) {
   BestWidth = Context.getTargetInfo().getLongLongWidth();
-  assert(NumPositiveBits <= BestWidth &&
- "How could an initializer get larger than ULL?");
   BestType = Context.UnsignedLongLongTy;
-  BestPromotionType
-= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
-   ? Context.UnsignedLongLongTy : Context.LongLongTy;
+  BestPromotionType =
+  (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
+  ? Context.UnsignedLongLongTy
+  : Context.LongLongTy;
+} else {
+  BestWidth = 128;
+  assert(NumPositiveBits <= BestWidth &&
+ "How could an initializer get larger than 128-bit?");
+  assert(Context.getTargetInfo().hasInt128Type() &&
+ "How could an initializer get larger than ULL "
+   

[PATCH] D144147: [Clang][RISCV] Sort test cases into its mnemonics

2023-02-15 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5e815372480d: [Clang][RISCV] Sort test cases into its 
mnemonics (authored by eopXD).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144147

Files:
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt_rod.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vlmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vlmul_ext_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vlmul_trunc_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfncvt_rod.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfncvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfwcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vlmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vlmul_ext_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vlmul_trunc_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfncvt_rod.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfncvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfwcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vzext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vzext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vzext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vzext_vf8.c

[PATCH] D144136: Add a "remark" to report on array accesses

2023-02-15 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

What would the information be useful for?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144136

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


[PATCH] D144147: [Clang][RISCV] Sort test cases into its mnemonics

2023-02-15 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144147

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


[PATCH] D144157: Add 128-bit integer support to enum element

2023-02-15 Thread zhouyizhou via Phabricator via cfe-commits
zhouyizhou updated this revision to Diff 497874.
zhouyizhou added a comment.

add assertion for int128 support


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

https://reviews.llvm.org/D144157

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/enum.c


Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -1,7 +1,12 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify 
-pedantic
+enum b {
+   b0 = (__uint128_t)-1, // expected-warning {{ISO C restricts enumerator 
values to range of 'int'}}
+   b1 = (__uint128_t)0x123456789abcdef0ULL << 64|0x0fedcba987654321ULL, // 
expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+};
+
 enum e {A,
-B = 42LL << 32,// expected-warning {{ISO C restricts 
enumerator values to range of 'int'}}
-  C = -4, D = 12456 };
+   B = 42LL << 32,// expected-warning {{ISO C restricts enumerator 
values to range of 'int'}}
+   C = -4, D = 12456 };
 
 enum f { a = -2147483648, b = 2147483647 }; // ok.
 
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19568,9 +19568,6 @@
 return;
   }
 
-  // TODO: If the result value doesn't fit in an int, it must be a long or long
-  // long value.  ISO C does not support this, but GCC does as an extension,
-  // emit a warning.
   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
@@ -19690,14 +19687,23 @@
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongTy : Context.LongTy;
-} else {
+} else if (NumPositiveBits <= Context.getTargetInfo().getLongLongWidth()) {
   BestWidth = Context.getTargetInfo().getLongLongWidth();
-  assert(NumPositiveBits <= BestWidth &&
- "How could an initializer get larger than ULL?");
   BestType = Context.UnsignedLongLongTy;
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongLongTy : Context.LongLongTy;
+} else {
+  BestWidth = 128;
+  assert(NumPositiveBits <= BestWidth &&
+"How could an initializer get larger than 128-bit?");
+  assert(Context.getTargetInfo().hasInt128Type() &&
+"How could an initializer get larger than ULL "
+"in target without 128-bit interger type support?");
+  BestType = Context.UnsignedInt128Ty;
+  BestPromotionType 
+= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
+   ? Context.UnsignedInt128Ty : Context.Int128Ty;
 }
   }
 


Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -1,7 +1,12 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify -pedantic
+enum b {
+   b0 = (__uint128_t)-1, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+   b1 = (__uint128_t)0x123456789abcdef0ULL << 64|0x0fedcba987654321ULL, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+};
+
 enum e {A,
-B = 42LL << 32,// expected-warning {{ISO C restricts enumerator values to range of 'int'}}
-  C = -4, D = 12456 };
+   B = 42LL << 32,// expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+   C = -4, D = 12456 };
 
 enum f { a = -2147483648, b = 2147483647 }; // ok.
 
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19568,9 +19568,6 @@
 return;
   }
 
-  // TODO: If the result value doesn't fit in an int, it must be a long or long
-  // long value.  ISO C does not support this, but GCC does as an extension,
-  // emit a warning.
   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
@@ -19690,14 +19687,23 @@
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongTy : Context.LongTy;
-} else {
+} else if (NumPositiveBits <= Context.getTargetInfo().getLongLongWidth()) {
   BestWidth = Context.getTargetInfo().getLongLongWidth();
-  assert(NumPositiveBits <= BestWidth &&
- "How could an initializer get larger than ULL?");
   BestType = Context.UnsignedLongLongTy;
   BestPromotionType
 = (NumPositiveBits == BestWidth || 

[PATCH] D144100: [clang] Fix a bug that allowed some overflowing octal escape sequences

2023-02-15 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added inline comments.



Comment at: clang/lib/Lex/LiteralSupport.cpp:266
   }
-  if (ResultChar & 0x02000)
+  // About to shift out a digit?
+  if (ResultChar & 0xE000)

Maybe the comment should be more specific such as "one of the top three bits 
are set" or something similar.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144100

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


[PATCH] D144157: Add 128-bit integer support to enum element

2023-02-15 Thread zhouyizhou via Phabricator via cfe-commits
zhouyizhou created this revision.
zhouyizhou added reviewers: aaron.ballman, doug.gregor, eddy-geek, rjmccall, 
MaskRay, ChuanqiXu, pengfei.
Herald added a project: All.
zhouyizhou requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add 128-bit integer support to enum element like GCC extension do.

Also remove comment: "TODO" from the code.  This comment is added by 
4ef40013d75ca ("Implement capturing of enum values and chaining of enums 
together"), while 6791a0d43b681 ("Improve handling of enumerator values for C 
and C++") has accomplished that "TODO".

I don't have write access to LLVM

Signed-off-by: Zhouyi Zhou 

Thanks a lot
Zhouyi


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144157

Files:
  clang/lib/Sema/SemaDecl.cpp
  clang/test/Sema/enum.c


Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -1,7 +1,12 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify 
-pedantic
+enum b {
+   b0 = (__uint128_t)-1, // expected-warning {{ISO C restricts enumerator 
values to range of 'int'}}
+   b1 = (__uint128_t)0x123456789abcdef0ULL << 64|0x0fedcba987654321ULL, // 
expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+};
+
 enum e {A,
-B = 42LL << 32,// expected-warning {{ISO C restricts 
enumerator values to range of 'int'}}
-  C = -4, D = 12456 };
+   B = 42LL << 32,// expected-warning {{ISO C restricts enumerator 
values to range of 'int'}}
+   C = -4, D = 12456 };
 
 enum f { a = -2147483648, b = 2147483647 }; // ok.
 
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19568,9 +19568,6 @@
 return;
   }
 
-  // TODO: If the result value doesn't fit in an int, it must be a long or long
-  // long value.  ISO C does not support this, but GCC does as an extension,
-  // emit a warning.
   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
@@ -19690,14 +19687,20 @@
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongTy : Context.LongTy;
-} else {
+} else if (NumPositiveBits <= Context.getTargetInfo().getLongLongWidth()) {
   BestWidth = Context.getTargetInfo().getLongLongWidth();
-  assert(NumPositiveBits <= BestWidth &&
- "How could an initializer get larger than ULL?");
   BestType = Context.UnsignedLongLongTy;
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongLongTy : Context.LongLongTy;
+} else {
+  BestWidth = 128;
+  assert(NumPositiveBits <= BestWidth &&
+ "How could an initializer get larger than unsigned 128-bit 
integer type?");
+  BestType = Context.UnsignedInt128Ty;
+  BestPromotionType
+= (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
+   ? Context.UnsignedInt128Ty : Context.Int128Ty;
 }
   }
 


Index: clang/test/Sema/enum.c
===
--- clang/test/Sema/enum.c
+++ clang/test/Sema/enum.c
@@ -1,7 +1,12 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify -pedantic
+enum b {
+   b0 = (__uint128_t)-1, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+   b1 = (__uint128_t)0x123456789abcdef0ULL << 64|0x0fedcba987654321ULL, // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+};
+
 enum e {A,
-B = 42LL << 32,// expected-warning {{ISO C restricts enumerator values to range of 'int'}}
-  C = -4, D = 12456 };
+   B = 42LL << 32,// expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+   C = -4, D = 12456 };
 
 enum f { a = -2147483648, b = 2147483647 }; // ok.
 
Index: clang/lib/Sema/SemaDecl.cpp
===
--- clang/lib/Sema/SemaDecl.cpp
+++ clang/lib/Sema/SemaDecl.cpp
@@ -19568,9 +19568,6 @@
 return;
   }
 
-  // TODO: If the result value doesn't fit in an int, it must be a long or long
-  // long value.  ISO C does not support this, but GCC does as an extension,
-  // emit a warning.
   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
@@ -19690,14 +19687,20 @@
   BestPromotionType
 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
? Context.UnsignedLongTy : Context.LongTy;
-   

[PATCH] D144120: [HLSL] add log library functions

2023-02-15 Thread Xiang Li via Phabricator via cfe-commits
python3kgae accepted this revision.
python3kgae added a comment.
This revision is now accepted and ready to land.

LGTM.
Just fix the newline at end of file for the tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144120

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


[PATCH] D141785: [Clang][LoongArch] Implement patchable function entry

2023-02-15 Thread Lu Weining via Phabricator via cfe-commits
SixWeining accepted this revision.
SixWeining added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D141785

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


[PATCH] D142584: [CodeGen] Add a boolean flag to `Address::getPointer` and `Lvalue::getPointer` that indicates whether the pointer is known not to be null

2023-02-15 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added inline comments.



Comment at: clang/lib/CodeGen/Address.h:67
   return;
-// Currently the max supported alignment is much less than 1 << 63 and is
+// Currently the max supported alignment is much less than 1 << 32 and is
 // guaranteed to be a power of 2, so we can store the log of the alignment

efriedma wrote:
> ahatanak wrote:
> > efriedma wrote:
> > > This comment isn't right.  The max alignment is, as far as I can tell, 
> > > 1<<32 exactly.  (But there's something weird going on with very large 
> > > values... somehow `int a[1LL<<32] __attribute((aligned(1ULL<<32))) = {};` 
> > > ignores the alignment.)
> > The following function generated by tablegen (and a few others directly or 
> > indirectly calling the function) returns a 32-bit int, but it should be 
> > returning a 64-bit int.
> > 
> > https://github.com/llvm/llvm-project/blob/main/clang/utils/TableGen/ClangAttrEmitter.cpp#L532
> Filed https://github.com/llvm/llvm-project/issues/60752 so we don't lose 
> track of this.
I just realized we can't reduce the number of bits used for alignment here as 
we need 6 bits for alignment of `1 << 32`.

Should we allocate additional memory when `AlignLog` is either 31 or 32? If the 
5-bit alignment is equal to `0b1`, it would mean that there is an 
out-of-line storage large enough to hold the alignment and any other extra 
information that is needed. I think https://reviews.llvm.org/D117262#3267899 
proposes a similar idea.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142584

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


[PATCH] D139741: [clang][CodeGen] Use base subobject type layout for potentially-overlapping fields

2023-02-15 Thread Vladislav Dzhidzhoev via Phabricator via cfe-commits
dzhidzhoev added inline comments.



Comment at: clang/lib/CodeGen/CGRecordLayoutBuilder.cpp:370
+  const auto StorageAlignment = getAlignment(StorageType);
+  if (LayoutSize % StorageAlignment || Layout.getDataSize() % StorageAlignment)
 Packed = true;

efriedma wrote:
> dzhidzhoev wrote:
> > efriedma wrote:
> > > Should this be `if (Layout.getSize() % StorageAlignment || 
> > > Layout.getDataSize() % StorageAlignment)`?  The dependency on 
> > > isNoUniqueAddress is a bit confusing.
> > For base class subobjects, base class DataSize is used to compute the whole 
> > object size in RecordLayoutBuilder.cpp, and base subobject LLVM type (with 
> > ".base" suffix) is computed in addition to standard layout LLVM type in 
> > CGRecordLayoutBuilder.cpp.
> > 
> > Currently, both base subobject and standard layout LLVM types of the same 
> > class are supposed to agree on packedness, as stated in bb51300970b7. Thus, 
> > if one is packed, both are marked as packed, as done in 
> > CGRecordLowering::determinePacked. 
> > 
> > For data members of class/struct type, declared with [[no_unique_address]] 
> > attribute, DataSize is used to compute the whole object size in 
> > RecordLayoutBuilder.cpp, but standard layout LLVM type is used to represent 
> > the field in the whole class's LLVM type.
> > This patch proposes to use the base subobject LLVM type instead of the 
> > default LLVM type of a class to lay out a no_unique_address member of this 
> > class type.
> > 
> > Nextly, the patch proposes to create an unpadded LLVM type for unions, in 
> > addition to the default LLVM type. It is used to lay out the union members 
> > having no_unique_address attribute. Existing code for creating base 
> > subobject layout of classes are reused for unions, therefore, packedness of 
> > potentially-overlapping union LLVM type and of default union LLVM types 
> > must agree as well as for classes. 
> That doesn't really get at what I was asking.
> 
> `LayoutSize % StorageAlignment || Layout.getDataSize() % StorageAlignment` is 
> basically equivalent to `isNoUniqueAddress ? Layout.getDataSize() % 
> StorageAlignment != 0 : (Layout.getSize() % StorageAlignment || 
> Layout.getDataSize() % StorageAlignment)`.  From my understanding, you want 
> isNoUniqueAddress=true to agree with isNoUniqueAddress=false on whether the 
> result is packed.  So why are the checks different?
Thanks, sorry for misunderstanding.

It seems that if Layout.getSize() isn't aligned by StorageAlignment, 
Layout.getDataSize() isn't aligned by it too, thus `Layout.getDataSize() % 
StorageAlignment` is enough in that condition (at least, it doesn't break any 
check-clang tests).
I have added an assert on that assumption.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139741

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


[PATCH] D144149: [Serialization] Don't warn when a deserialized category is equivalent to an existing one.

2023-02-15 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added inline comments.



Comment at: clang/lib/Serialization/ASTReaderDecl.cpp:4188
+  llvm::DenseSet> NonEquivalentDecls;
+  StructuralEquivalenceContext Ctx(
+  Cat->getASTContext(), Existing->getASTContext(),

Decided to use StructuralEquivalenceContext here because we already use it to 
compare `ObjCCategoryDecl` in ASTReader.cpp.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144149

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


[PATCH] D144149: [Serialization] Don't warn when a deserialized category is equivalent to an existing one.

2023-02-15 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added reviewers: ChuanqiXu, jansvoboda11.
Herald added a subscriber: ributzka.
Herald added a project: All.
vsapsai requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

A single class allows multiple categories to be defined for it. But if
two of such categories have the same name, we emit a warning. It's not a
hard error but a good indication of a potential mistake.

With modules, we can end up with the same category in different modules.
Diagnosing such a situation has little value as the categories in
different modules are equivalent and don't reflect the usage of the same
name for different purposes. When we deserialize a duplicate category,
compare it to an existing one and warn only when the new one is
different.

rdar://104582081


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144149

Files:
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/test/Modules/compare-objc-interface.m
  clang/test/Modules/hidden-duplicates.m
  clang/test/Modules/objc-categories.m

Index: clang/test/Modules/objc-categories.m
===
--- clang/test/Modules/objc-categories.m
+++ clang/test/Modules/objc-categories.m
@@ -8,8 +8,6 @@
 
 @import category_bottom;
 
-// expected-note@Inputs/category_left.h:14 {{previous definition}}
-// expected-warning@Inputs/category_right.h:12 {{duplicate definition of category}}
 // expected-note@Inputs/category_top.h:1 {{receiver is instance of class declared here}}
 
 @interface Foo(Source)
Index: clang/test/Modules/hidden-duplicates.m
===
--- clang/test/Modules/hidden-duplicates.m
+++ clang/test/Modules/hidden-duplicates.m
@@ -32,6 +32,7 @@
 
 @interface NSObject @end
 @class ForwardDeclaredInterfaceWithoutDefinition;
+@interface NSObject(CategoryForTesting) @end
 
 NSObject *interfaceDefinition(NSObject *o);
 NSObject *forwardDeclaredInterface(NSObject *o);
Index: clang/test/Modules/compare-objc-interface.m
===
--- clang/test/Modules/compare-objc-interface.m
+++ clang/test/Modules/compare-objc-interface.m
@@ -444,3 +444,54 @@
 // expected-error@first.h:* {{'CompareLastImplAttribute' has different definitions in different modules; first difference is definition in module 'First.Hidden' found property 'lastImplAttribute' with 'direct' attribute}}
 // expected-note-re@second.h:* {{but in {{'Second'|definition here}} found property 'lastImplAttribute' with different 'direct' attribute}}
 #endif
+
+#if defined(FIRST)
+@interface CompareMatchingCategories: NSObject @end
+@interface CompareMatchingCategories(Matching)
+- (int)testMethod;
+@end
+
+@interface CompareMismatchingCategories1: NSObject @end
+@interface CompareMismatchingCategories1(Category1)
+- (void)presentMethod;
+@end
+@interface CompareMismatchingCategories2: NSObject @end
+@interface CompareMismatchingCategories2(Category2)
+@end
+
+@interface CompareDifferentCategoryNames: NSObject @end
+@interface CompareDifferentCategoryNames(CategoryFirst)
+- (void)firstMethod:(int)x;
+@end
+#elif defined(SECOND)
+@interface CompareMatchingCategories: NSObject @end
+@interface CompareMatchingCategories(Matching)
+- (int)testMethod;
+@end
+
+@interface CompareMismatchingCategories1: NSObject @end
+@interface CompareMismatchingCategories1(Category1)
+@end
+@interface CompareMismatchingCategories2: NSObject @end
+@interface CompareMismatchingCategories2(Category2)
+- (void)presentMethod;
+@end
+
+@interface CompareDifferentCategoryNames: NSObject @end
+@interface CompareDifferentCategoryNames(CategorySecond)
+- (void)secondMethod;
+@end
+#else
+CompareMatchingCategories *compareMatchingCategories; // no diagnostic
+CompareMismatchingCategories1 *compareMismatchingCategories1;
+#ifdef TEST_MODULAR
+// expected-warning@second.h:* {{duplicate definition of category 'Category1' on interface 'CompareMismatchingCategories1'}}
+// expected-note@first.h:* {{previous definition is here}}
+#endif
+CompareMismatchingCategories2 *compareMismatchingCategories2;
+#ifdef TEST_MODULAR
+// expected-warning@second.h:* {{duplicate definition of category 'Category2' on interface 'CompareMismatchingCategories2'}}
+// expected-note@first.h:* {{previous definition is here}}
+#endif
+CompareDifferentCategoryNames *compareDifferentCategoryNames; // no diagnostic
+#endif
Index: clang/lib/Serialization/ASTReaderDecl.cpp
===
--- clang/lib/Serialization/ASTReaderDecl.cpp
+++ clang/lib/Serialization/ASTReaderDecl.cpp
@@ -14,6 +14,7 @@
 #include "ASTCommon.h"
 #include "ASTReaderInternals.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTStructuralEquivalence.h"
 #include "clang/AST/Attr.h"
 #include "clang/AST/AttrIterator.h"
 #include "clang/AST/Decl.h"
@@ -4181,23 +4182,22 @@
   // Check for 

[PATCH] D139741: [clang][CodeGen] Use base subobject type layout for potentially-overlapping fields

2023-02-15 Thread Vladislav Dzhidzhoev via Phabricator via cfe-commits
dzhidzhoev updated this revision to Diff 497847.
dzhidzhoev added a comment.

Simplified condition in lowerUnion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D139741

Files:
  clang/include/clang/AST/Decl.h
  clang/lib/AST/Decl.cpp
  clang/lib/AST/RecordLayoutBuilder.cpp
  clang/lib/CodeGen/CGRecordLayoutBuilder.cpp
  clang/test/CodeGenCXX/no-unique-address-3.cpp

Index: clang/test/CodeGenCXX/no-unique-address-3.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/no-unique-address-3.cpp
@@ -0,0 +1,209 @@
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -emit-llvm -fdump-record-layouts -std=c++17 %s -o %t | FileCheck %s
+
+// CHECK-LABEL:  0 | class Empty (empty)
+// CHECK-NEXT: | [sizeof=1, dsize=1, align=1,
+// CHECK-NEXT: |  nvsize=1, nvalign=1]
+// CHECK-LABEL:  0 | class Second
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   0:0-0 |   short A
+// CHECK-NEXT: | [sizeof=2, dsize=1, align=2,
+// CHECK-NEXT: |  nvsize=1, nvalign=2]
+// CHECK-LABEL:  0 | class Foo
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   2 |   class Second NZNoUnique
+// CHECK-NEXT:   2 | class Empty (base) (empty)
+// CHECK-NEXT:   2:0-0 | short A
+// CHECK-NEXT:   3 |   char B
+// CHECK-NEXT: | [sizeof=4, dsize=4, align=2,
+// CHECK-NEXT: |  nvsize=4, nvalign=2]
+
+class Empty {};
+
+// CHECK-LABEL: LLVMType:%class.Second = type { i8, i8 }
+// CHECK-NEXT:  NonVirtualBaseLLVMType:%class.Second.base = type { i8 }
+class Second : Empty {
+  short A : 1;
+};
+
+// CHECK-LABEL:   LLVMType:%class.Foo = type { [2 x i8], %class.Second.base, i8 }
+// CHECK-NEXT:NonVirtualBaseLLVMType:%class.Foo = type { [2 x i8], %class.Second.base, i8 }
+class Foo : Empty {
+  [[no_unique_address]] Second NZNoUnique;
+  char B;
+};
+Foo I;
+
+// CHECK-LABEL:  0 | class SecondEmpty (empty)
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT: | [sizeof=1, dsize=0, align=1,
+// CHECK-NEXT: |  nvsize=1, nvalign=1]
+class SecondEmpty: Empty {
+};
+
+// CHECK-LABEL:  0 | class Bar
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   1 |   class SecondEmpty ZNoUnique (empty)
+// CHECK-NEXT:   1 | class Empty (base) (empty)
+// CHECK-NEXT:   0 |   char C
+// CHECK-NEXT: | [sizeof=2, dsize=1, align=1,
+// CHECK-NEXT: |  nvsize=2, nvalign=1]
+
+// CHECK-LABEL:  LLVMType:%class.Bar = type { i8, i8 }
+// CHECK-NEXT:   NonVirtualBaseLLVMType:%class.Bar = type { i8, i8 }
+class Bar : Empty {
+  [[no_unique_address]] SecondEmpty ZNoUnique;
+  char C;
+};
+Bar J;
+
+// CHECK-LABEL:  0 | class IntFieldClass
+// CHECK-NEXT:   0 |   class Empty (base) (empty)
+// CHECK-NEXT:   2 |   class Second Field
+// CHECK-NEXT:   2 | class Empty (base) (empty)
+// CHECK-NEXT:   2:0-0 | short A
+// CHECK-NEXT:   4 |   int C
+// CHECK-NEXT: | [sizeof=8, dsize=8, align=4,
+// CHECK-NEXT: |  nvsize=8, nvalign=4]
+
+// CHECK-LABEL:   LLVMType:%class.IntFieldClass = type { [2 x i8], %class.Second.base, i32 }
+// CHECK-NEXT:NonVirtualBaseLLVMType:%class.IntFieldClass = type { [2 x i8], %class.Second.base, i32 }
+class IntFieldClass : Empty {
+  [[no_unique_address]] Second Field;
+  int C;
+};
+IntFieldClass K;
+
+// CHECK-LABEL: 0 | class UnionClass
+// CHECK-NEXT:  0 |   class Empty (base) (empty)
+// CHECK-NEXT:  0 |   union UnionClass
+// CHECK-NEXT:  0 | int I
+// CHECK-NEXT:  0 | char C
+// CHECK-NEXT:  4 |   int C
+// CHECK-NEXT:| [sizeof=8, dsize=8, align=4,
+// CHECK-NEXT:|  nvsize=8, nvalign=4]
+
+// CHECK-LABEL:  LLVMType:%class.UnionClass = type { %union.anon, i32 }
+// CHECK-NEXT:   NonVirtualBaseLLVMType:%class.UnionClass = type { %union.anon, i32 }
+// CHECK-NEXT:   IsZeroInitializable:1
+// CHECK-NEXT:   BitFields:[
+// CHECK-NEXT: ]>
+class UnionClass : Empty {
+  [[no_unique_address]] union {
+int I;
+char C;
+  } U;
+  int C;
+};
+UnionClass L;
+
+// CHECK-LABEL: 0 | class EnumClass
+// CHECK-NEXT:  0 |   class Empty (base) (empty)
+// CHECK-NEXT:  0 |   enum E A
+// CHECK-NEXT:  4 |   int C
+// CHECK-NEXT:| [sizeof=8, dsize=8, align=4,
+// CHECK-NEXT:|  nvsize=8, nvalign=4]
+
+// CHECK-LABEL:  LLVMType:%class.EnumClass = type { i32, i32 }
+// CHECK-NEXT:   NonVirtualBaseLLVMType:%class.EnumClass = type { i32, i32 }
+// CHECK-NEXT:   IsZeroInitializable:1
+// CHECK-NEXT:   BitFields:[
+// CHECK-NEXT: ]>
+class EnumClass : Empty {
+  [[no_unique_address]] enum class E { X, 

[PATCH] D144147: [Clang][RISCV] Sort test cases into its mnemonics

2023-02-15 Thread Yueh-Ting (eop) Chen via Phabricator via cfe-commits
eopXD created this revision.
eopXD added reviewers: craig.topper, kito-cheng.
Herald added subscribers: luke, VincentWu, vkmr, frasercrmck, evandro, 
luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, psnobl, jocewei, 
PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, jrtc27, 
shiva0217, niosHD, sabuasal, simoncook, johnrusso, rbar, asb, arichardson.
Herald added a project: All.
eopXD requested review of this revision.
Herald added subscribers: cfe-commits, pcwang-thead, MaskRay.
Herald added a project: clang.

Referencing the corresponding change from the source of the test cases:
riscv-non-isa/rvv-intrinsic-doc#196


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144147

Files:
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt_rod.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfncvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vfwcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vlmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vlmul_ext_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vlmul_trunc_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vsext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/non-overloaded/vzext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfncvt_rod.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfncvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vfwcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vlmul.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vlmul_ext_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vlmul_trunc_v.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vsext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext_vf4.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/non-policy/overloaded/vzext_vf8.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfncvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfncvt_rod.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfncvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfwcvt.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vfwcvt_rtz.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext_vf2.c
  
clang/test/CodeGen/RISCV/rvv-intrinsics-autogenerated/policy/non-overloaded/vsext_vf4.c
  

[PATCH] D142867: [Clang] Add machinery to catch overflow in unary minus outside of a constant expression context

2023-02-15 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

In D142867#4108079 , @eaeltsin wrote:

> The warning now fires even if overflow is prevented with `if constexpr`:
>
>   if constexpr (width <= 64) {
> if constexpr (width == 64) {
>   return 1;
> }
> return -static_cast(uint64_t{1} << (width - 1));
>   }
>
> https://godbolt.org/z/M3xdcKd3M

For reference, actually placing the second return into an `else` block (thus 
making it a discarded statement) does suppress the diagnostic:
https://godbolt.org/z/Kb6Md5PrK

I also question the focus on `if constexpr`. Replacing with `if (true) { return 
1; }` should be as effective in the non-`else`-block case in suppressing the 
warning in terms of QoI.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142867

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


[clang] a851d46 - [Clang][Driver] Fix integer normalization with KCFI

2023-02-15 Thread Sami Tolvanen via cfe-commits

Author: Sami Tolvanen
Date: 2023-02-16T00:21:31Z
New Revision: a851d46e07c1234a0763b4630c8475c73208e776

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

LOG: [Clang][Driver] Fix integer normalization with KCFI

Commit 71c7313f42d2b6063fea09854cf4fc46fd0627e1 added integer
normalization for CFI, but doesn't correctly pass the argument
with -fsanitize=kcfi. Set CfiICallNormalizeIntegers also with
SanitizerKind::KCFI to fix the issue.

Added: 


Modified: 
clang/lib/Driver/SanitizerArgs.cpp

Removed: 




diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 7f7ad238c89f4..390faef0dbdf1 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -726,8 +726,11 @@ SanitizerArgs::SanitizerArgs(const ToolChain ,
  options::OPT_fno_sanitize_cfi_canonical_jump_tables, 
true);
   }
 
-  if (AllAddedKinds & SanitizerKind::KCFI && DiagnoseErrors) {
-if (AllAddedKinds & SanitizerKind::CFI)
+  if (AllAddedKinds & SanitizerKind::KCFI) {
+CfiICallNormalizeIntegers =
+Args.hasArg(options::OPT_fsanitize_cfi_icall_normalize_integers);
+
+if (AllAddedKinds & SanitizerKind::CFI && DiagnoseErrors)
   D.Diag(diag::err_drv_argument_not_allowed_with)
   << "-fsanitize=kcfi"
   << lastArgumentForMask(D, Args, SanitizerKind::CFI);



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


[PATCH] D143849: [Clang][OpenCL] Allow pointers in structs as kernel arguments from 2.0

2023-02-15 Thread Ayal Zaks via Phabricator via cfe-commits
Ayal added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:9494
+  // of SVM.
+  if (S.getLangOpts().getOpenCLCompatibleVersion() > 120 &&
+  (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam))

Anastasia wrote:
> Anastasia wrote:
> > Ayal wrote:
> > > Anastasia wrote:
> > > > I think it should be possible to merge this with `if` below to avoid 
> > > > condition duplication.
> > > > 
> > > > 
> > > Sure, but that trades one duplication for another, rather than clearly 
> > > separating the early-continue case early?
> > > 
> > > ```
> > >   if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
> > > if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
> > >   continue;
> > > S.Diag(Param->getLocation(),
> > >diag::err_record_with_pointers_kernel_param)
> > >   << PT->isUnionType()
> > >   << PT;
> > >   } else if (ParamType == InvalidAddrSpacePtrKernelParam) {
> > > S.Diag(Param->getLocation(),
> > >diag::err_record_with_pointers_kernel_param)
> > >   << PT->isUnionType()
> > >   << PT;
> > >   } else {
> > > S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << 
> > > PT;
> > > 
> > > ```
> > I am mainly thinking in terms of maintenance if for example someone fixes 
> > one if and forgets another. Or if ifs will get separated by some other code 
> > and then it is not easy to see that the same thing is handled differently 
> > in OpenCL versions. 
> > 
> > Unfortunately we have a lot of those cases, I know this function has early 
> > exists but it is not a common style.
> > 
> > 
> > I was talking about something like:
> > 
> > 
> > ```
> > if (((S.getLangOpts().getOpenCLCompatibleVersion() <= 120) &&
> > (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam)) ||
> >   ParamType == InvalidAddrSpacePtrKernelParam)
> > ```
> > 
> > It would also be ok to separate `InvalidAddrSpacePtrKernelParam` since it's 
> > handling different feature.
> Sorry I have forgotten that this part of the code is expected to handle the 
> diagnostics only. The decision that the kernel parameter is wrong is done in 
> `getOpenCLKernelParameterType`. I think you should alter the conditions there 
> to check for OpenCL version and avoid classifying cases you care about as 
> `PtrKernelParam` or `PtrPtrKernelParam`. Then here you wouldn't need this 
> extra if/continue block. 
Hmm, would that be better? This part of the code, namely 
`checkIsValidOpenCLKernelParameter()`, does check the validity of arguments 
classified by `getOpenCLKernelParameterType()` in addition to handling 
diagnostics. E.g., the first case above decides that arguments of 
pointer-to-pointer type are wrong along with proper diagnostics for OpenCL 1.x 
while allowing them for other OpenCL versions.

Struct arguments are simply classified as records by 
getOpenCLKernelParameterType(), whereas this part of the code traverses each 
struct and calls getOpenCLKernelParameterType() on each field - the latter 
seems  unaware if it was invoked on a struct field or not? If it is (made) 
aware, it could indeed return a (new kind of?) invalid type instead of pointer 
type for OpenCL 1.x - how would the right err_record_with_pointers_kernel_param 
diagnostics then be handled? If desired, such refactoring should probably be 
done independent of this fix?


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

https://reviews.llvm.org/D143849

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


[PATCH] D144136: Add a "remark" to report on array accesses

2023-02-15 Thread Bill Wendling via Phabricator via cfe-commits
void created this revision.
Herald added a project: All.
void requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This will report a ton of information. It's basically only good for
piping to a file and using Perl to gather any useful information.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144136

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaChecking.cpp


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -16323,6 +16323,10 @@
 else if (size.getBitWidth() < index.getBitWidth())
   size = size.zext(index.getBitWidth());
 
+Context.getDiagnostics().Report(
+BaseExpr->getBeginLoc(), diag::remark_array_access)
+<< 0 << ArrayTy->desugar() << toString(index, 10, true);
+
 // For array subscripting the index must be less than size, but for pointer
 // arithmetic also allow the index (offset) to be equal to size since
 // computing the next address after the end of the array is legal and
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9450,6 +9450,10 @@
 def note_array_declared_here : Note<
   "array %0 declared here">;
 
+def remark_array_access : Remark<
+  "accessing %select{fixed|dynamic}0 sized array %1 by %2">,
+  InGroup;
+
 def warn_inconsistent_array_form : Warning<
   "argument %0 of type %1 with mismatched bound">,
   InGroup, DefaultIgnore;
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -1304,6 +1304,9 @@
 def ProfileInstrUnprofiled : DiagGroup<"profile-instr-unprofiled">;
 def MisExpect : DiagGroup<"misexpect">;
 
+// Array bounds remarks.
+def ArrayBoundsRemarks : DiagGroup<"array-bounds">;
+
 // AddressSanitizer frontend instrumentation remarks.
 def SanitizeAddressRemarks : DiagGroup<"sanitize-address">;
 


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -16323,6 +16323,10 @@
 else if (size.getBitWidth() < index.getBitWidth())
   size = size.zext(index.getBitWidth());
 
+Context.getDiagnostics().Report(
+BaseExpr->getBeginLoc(), diag::remark_array_access)
+<< 0 << ArrayTy->desugar() << toString(index, 10, true);
+
 // For array subscripting the index must be less than size, but for pointer
 // arithmetic also allow the index (offset) to be equal to size since
 // computing the next address after the end of the array is legal and
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9450,6 +9450,10 @@
 def note_array_declared_here : Note<
   "array %0 declared here">;
 
+def remark_array_access : Remark<
+  "accessing %select{fixed|dynamic}0 sized array %1 by %2">,
+  InGroup;
+
 def warn_inconsistent_array_form : Warning<
   "argument %0 of type %1 with mismatched bound">,
   InGroup, DefaultIgnore;
Index: clang/include/clang/Basic/DiagnosticGroups.td
===
--- clang/include/clang/Basic/DiagnosticGroups.td
+++ clang/include/clang/Basic/DiagnosticGroups.td
@@ -1304,6 +1304,9 @@
 def ProfileInstrUnprofiled : DiagGroup<"profile-instr-unprofiled">;
 def MisExpect : DiagGroup<"misexpect">;
 
+// Array bounds remarks.
+def ArrayBoundsRemarks : DiagGroup<"array-bounds">;
+
 // AddressSanitizer frontend instrumentation remarks.
 def SanitizeAddressRemarks : DiagGroup<"sanitize-address">;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f5aa8d1 - [Clang][docs] Update the release notes page to the new skeleton

2023-02-15 Thread Roy Jacobson via cfe-commits

Author: Roy Jacobson
Date: 2023-02-15T23:53:38+02:00
New Revision: f5aa8d191a5b5ea118281bfa410bdb2ee961c704

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

LOG: [Clang][docs] Update the release notes page to the new skeleton

Was discussed at https://reviews.llvm.org/D142578.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ab7518cc2dc6..abb6f0ae8e92 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -13,7 +13,7 @@ Written by the `LLVM Team `_
   .. warning::
  These are in-progress notes for the upcoming Clang |version| release.
  Release notes for previous releases can be found on
- `the Download Page `_.
+ `the Releases Page `_.
 
 Introduction
 
@@ -23,25 +23,30 @@ frontend, part of the LLVM Compiler Infrastructure, release 
|release|. Here we
 describe the status of Clang in some detail, including major
 improvements from the previous release and new feature work. For the
 general LLVM release notes, see `the LLVM
-documentation `_. All LLVM
-releases may be downloaded from the `LLVM releases web
-site `_.
+documentation `_. For the libc++ 
release notes,
+see `this page `_. All LLVM releases
+may be downloaded from the `LLVM releases web site 
`_.
 
 For more information about Clang or LLVM, including information about the
 latest release, please see the `Clang Web Site `_ or 
the
 `LLVM Web Site `_.
 
-Note that if you are reading this file from a Git checkout or the
-main Clang web page, this document applies to the *next* release, not
-the current one. To see the release notes for a specific release, please
-see the `releases page `_.
-
 Potentially Breaking Changes
 
 These changes are ones which we think may surprise users when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+
+C/C++ Language Potentially Breaking Changes
+---
+
+C++ Specific Potentially Breaking Changes
+-
+
+ABI Changes in This Version
+---
+
 What's New in Clang |release|?
 ==
 Some of the major new features and improvements to Clang are listed
@@ -49,33 +54,28 @@ here. Generic improvements to Clang as a whole or to its 
underlying
 infrastructure are described first, followed by language-specific
 sections with improvements to Clang's support for those languages.
 
-Major New Features
---
+C++ Language Changes
+
+- Improved ``-O0`` code generation for calls to ``std::forward_like``. 
Similarly to
+  ``std::move, std::forward`` et al. it is now treated as a compiler builtin 
and implemented
+  directly rather than instantiating the definition from the standard library.
 
-Bug Fixes
--
-- Fix crash on invalid code when looking up a destructor in a templated class
-  inside a namespace. This fixes
-  `Issue 59446 `_.
-- Fix crash when diagnosing incorrect usage of ``_Nullable`` involving alias
-  templates. This fixes
-  `Issue 60344 `_.
-- Fix confusing warning message when ``/clang:-x`` is passed in ``clang-cl``
-  driver mode and emit an error which suggests using ``/TC`` or ``/TP``
-  ``clang-cl`` options instead. This fixes
-  `Issue 59307 `_.
-- Fix crash when evaluating consteval constructor of derived class whose base
-  has more than one field. This fixes
-  `Issue 60166 `_.
+C++20 Feature Support
+^
 
-Improvements to Clang's diagnostics
-^^^
-- We now generate a diagnostic for signed integer overflow due to unary minus
-  in a non-constant expression context. This fixes
-  `Issue 31643 `_
-- Clang now warns by default for C++20 and later about deprecated capture of
-  ``this`` with a capture default of ``=``. This warning can be disabled with
-  ``-Wno-deprecated-this-capture``.
+C++2b Feature Support
+^
+
+Resolutions to C++ Defect Reports
+^
+
+C Language Changes
+--
+
+C2x 

[PATCH] D143919: [Clang] Copy strictfp attribute from pattern to instantiation

2023-02-15 Thread Eli Friedman via Phabricator via cfe-commits
efriedma added a comment.

If the "strictfp" attribute is based on the contents of the function body, 
should we recompute it when the function is instantiated, as opposed to copying 
it?  For example, say you have a pragma inside an "if constexpr"; should that 
set the strictfp attribute if it's discarded?

Otherwise, I guess updateAttrsForLateParsedTemplate makes sense.




Comment at: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp:824
+  continue;
+}
+

Is this necessary?  The non-delayed-parsed case seems to work correctly on 
trunk without any changes, so I suspect the autogenerated 
sema::instantiateTemplateAttribute is doing the right thing.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143919

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


[PATCH] D143109: [Sema] Push a LambdaScopeInfo before calling SubstDefaultArgument

2023-02-15 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann requested changes to this revision.
tahonermann added inline comments.
This revision now requires changes to proceed.



Comment at: clang/lib/Sema/SemaExpr.cpp:19085-19092
+  // If the variable is used in a default argument expression of a lambda call
+  // operator, switch to the enclosing context to sync up with the function
+  // scope.
+  if (isLambdaCallOperator(DC))
+if (auto *PVD = dyn_cast_or_null(
+ExprEvalContexts.back().ManglingContextDecl))
+  if (PVD->getDeclContext() == DC)

I'm struggling to understand the change. If I'm following correctly, it looks 
like we're trying to capture the variable used in the default argument. If so, 
that seems wrong; I think we shouldn't even be trying to capture a variable for 
such usage.

I jumped into a debugger to poke around a bit. Perhaps the right change is to 
detect the use in a default argument in the code below so that the call to 
`getCapturedDeclRefType()` can be skipped for a non-ODR use.
  /localdisk2/thonerma/llvm-project/clang/lib/Sema/SemaExpr.cpp:
   3265 ExprResult Sema::BuildDeclarationNameExpr(
   3266 const CXXScopeSpec , const DeclarationNameInfo , 
NamedDecl *D,
   3267 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
   3268 bool AcceptInvalidDecl) {
  .
   3326   switch (D->getKind()) {
  .
   3389   case Decl::Var:
   3390   case Decl::VarTemplateSpecialization:
   3391   case Decl::VarTemplatePartialSpecialization:
   3392   case Decl::Decomposition:
   3393   case Decl::OMPCapturedExpr:
   3394 // In C, "extern void blah;" is valid and is an r-value.
   3395 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
   3396 type->isVoidType()) {
   3397   valueKind = VK_PRValue;
   3398   break;
   3399 }
   3400 [[fallthrough]];
   3401
   3402   case Decl::ImplicitParam:
   3403   case Decl::ParmVar: {
   3404 // These are always l-values.
   3405 valueKind = VK_LValue;
   3406 type = type.getNonReferenceType();
   3407
   3408 // FIXME: Does the addition of const really only apply in
   3409 // potentially-evaluated contexts? Since the variable isn't actually
   3410 // captured in an unevaluated context, it seems that the answer is 
no.
   3411 if (!isUnevaluatedContext()) {
   3412   QualType CapturedType = getCapturedDeclRefType(cast(VD), 
Loc);
   3413   if (!CapturedType.isNull())
   3414 type = CapturedType;
   3415 }
   3416
   3417 break;
   3418   }
  .
   3516 }



Comment at: clang/test/SemaCXX/lambda-default-arg.cpp:6
+  return [=](float b = a) -> bool {
+return a < 0;
+  }();

Is the use of `a` in the lambda body intentional? It isn't needed to reproduce 
the assertion failure, so its presence here is a bit confusing from a test 
perspective as it implies that variable capture is somehow related. I suggest 
just returning `true`. Likewise for the other two tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143109

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


[PATCH] D144016: [Sema] Relax a failing assertion in TransformBlockExpr

2023-02-15 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 497776.
ahatanak added a comment.

Add triple to the test and add release note for the fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144016

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/TreeTransform.h
  clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp


Index: clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
===
--- clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
+++ clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++1z %s -emit-llvm -o - | FileCheck %s 
--implicit-check-not=should_not_be_used
+// RUN: %clang_cc1 -std=c++1z %s -emit-llvm -fblocks -triple 
x86_64-apple-darwin10 -o - | FileCheck %s 
--implicit-check-not=should_not_be_used
 
 void should_be_used_1();
 void should_be_used_2();
@@ -32,3 +32,20 @@
 // CHECK: should_be_used_1
 // CHECK: should_be_used_2
 // CHECK: should_be_used_3
+
+namespace BlockThisCapture {
+  void foo();
+  struct S {
+template 
+void m() {
+  ^{ if constexpr(b) (void)this; else foo();  }();
+}
+  };
+
+  void test() {
+S().m();
+  }
+}
+
+// CHECK-LABEL: define internal void 
@___ZN16BlockThisCapture1S1mILb0EEEvv_block_invoke(
+// CHECK: call void @_ZN16BlockThisCapture3fooEv(
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14598,7 +14598,12 @@
  oldCapture));
   assert(blockScope->CaptureMap.count(newCapture));
 }
-assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
+
+// The this pointer may not be captured by the instantiated block, even 
when
+// it's captured by the original block, if the expression causing the
+// capture is in the discarded branch of a constexpr if statement.
+assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&
+   "this pointer isn't captured in the old block");
   }
 #endif
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -67,6 +67,9 @@
 - Fix crash when evaluating consteval constructor of derived class whose base
   has more than one field. This fixes
   `Issue 60166 `_.
+- Fix assert that fails when the expression causing the this pointer to be
+  captured by a block is part of a constexpr if statement's branch and
+  instantiation of the enclosing method causes the branch to be discarded.
 
 Improvements to Clang's diagnostics
 ^^^


Index: clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
===
--- clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
+++ clang/test/CodeGenCXX/cxx1z-constexpr-if.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++1z %s -emit-llvm -o - | FileCheck %s --implicit-check-not=should_not_be_used
+// RUN: %clang_cc1 -std=c++1z %s -emit-llvm -fblocks -triple x86_64-apple-darwin10 -o - | FileCheck %s --implicit-check-not=should_not_be_used
 
 void should_be_used_1();
 void should_be_used_2();
@@ -32,3 +32,20 @@
 // CHECK: should_be_used_1
 // CHECK: should_be_used_2
 // CHECK: should_be_used_3
+
+namespace BlockThisCapture {
+  void foo();
+  struct S {
+template 
+void m() {
+  ^{ if constexpr(b) (void)this; else foo();  }();
+}
+  };
+
+  void test() {
+S().m();
+  }
+}
+
+// CHECK-LABEL: define internal void @___ZN16BlockThisCapture1S1mILb0EEEvv_block_invoke(
+// CHECK: call void @_ZN16BlockThisCapture3fooEv(
Index: clang/lib/Sema/TreeTransform.h
===
--- clang/lib/Sema/TreeTransform.h
+++ clang/lib/Sema/TreeTransform.h
@@ -14598,7 +14598,12 @@
  oldCapture));
   assert(blockScope->CaptureMap.count(newCapture));
 }
-assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
+
+// The this pointer may not be captured by the instantiated block, even when
+// it's captured by the original block, if the expression causing the
+// capture is in the discarded branch of a constexpr if statement.
+assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&
+   "this pointer isn't captured in the old block");
   }
 #endif
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -67,6 +67,9 @@
 - Fix crash when evaluating consteval constructor of derived class whose base
   has more than one field. This fixes
   `Issue 60166 

[clang] 8c1f77a - [clang-format] Fix windows build.

2023-02-15 Thread Manuel Klimek via cfe-commits

Author: Manuel Klimek
Date: 2023-02-15T20:59:43Z
New Revision: 8c1f77af7fd14d5a611246aa16b9693d3ebcee22

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

LOG: [clang-format] Fix windows build.

MSVC needs a return after llvm_unreachable.

Added: 


Modified: 
clang/lib/Format/FormatTokenSource.h

Removed: 




diff  --git a/clang/lib/Format/FormatTokenSource.h 
b/clang/lib/Format/FormatTokenSource.h
index 0be46287f6b74..d93efaf676087 100644
--- a/clang/lib/Format/FormatTokenSource.h
+++ b/clang/lib/Format/FormatTokenSource.h
@@ -18,6 +18,7 @@
 #include "FormatToken.h"
 #include "UnwrappedLineParser.h"
 #include "llvm/ADT/DenseMap.h"
+#include 
 
 #define DEBUG_TYPE "format-token-source"
 
@@ -237,6 +238,7 @@ class ScopedMacroState : public FormatTokenSource {
 
   FormatToken *insertTokens(ArrayRef Tokens) override {
 llvm_unreachable("Cannot insert tokens while parsing a macro.");
+return nullptr;
   }
 
 private:



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


[PATCH] D144037: [clang-tidy] allow tests to use --config-file instead of --config

2023-02-15 Thread Alexis Murzeau via Phabricator via cfe-commits
amurzeau updated this revision to Diff 497773.
amurzeau retitled this revision from "[clang-tidy] allow tests to use 
-config-file instead of -config" to "[clang-tidy] allow tests to use 
--config-file instead of --config".
amurzeau added a comment.

Allow use of --config and --config-file (with double dashes)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144037

Files:
  clang-tools-extra/test/clang-tidy/check_clang_tidy.py
  
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
@@ -1,5 +1,4 @@
-// RUN: clang-tidy %s 
--config-file=%S/Inputs/identifier-naming/hungarian-notation2/.clang-tidy 2>&1 \
-// RUN:   | FileCheck -check-prefixes=CHECK-MESSAGES %s
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- 
--config-file=%S/Inputs/identifier-naming/hungarian-notation1/.clang-tidy
 
 // clang-format off
 typedef signed char int8_t; // NOLINT
Index: 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
@@ -1,5 +1,4 @@
-// RUN: clang-tidy %s 
--config-file=%S/Inputs/identifier-naming/hungarian-notation1/.clang-tidy 2>&1 \
-// RUN:   | FileCheck -check-prefixes=CHECK-MESSAGES %s
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- 
--config-file=%S/Inputs/identifier-naming/hungarian-notation2/.clang-tidy
 
 // clang-format off
 typedef signed char int8_t; // NOLINT
Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -107,9 +107,10 @@
 # If the test does not specify a config style, force an empty one; 
otherwise
 # auto-detection logic can discover a ".clang-tidy" file that is not 
related to
 # the test.
-if not any(
-[arg.startswith('-config=') for arg in self.clang_tidy_extra_args]):
-  self.clang_tidy_extra_args.append('-config={}')
+if not any([
+re.match('^-?-config(-file)?=', arg)
+for arg in self.clang_tidy_extra_args]):
+  self.clang_tidy_extra_args.append('--config={}')
 
 if extension in ['.m', '.mm']:
   self.clang_extra_args = ['-fobjc-abi-version=2', '-fobjc-arc', 
'-fblocks'] + \


Index: clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation.cpp
@@ -1,5 +1,4 @@
-// RUN: clang-tidy %s --config-file=%S/Inputs/identifier-naming/hungarian-notation2/.clang-tidy 2>&1 \
-// RUN:   | FileCheck -check-prefixes=CHECK-MESSAGES %s
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- --config-file=%S/Inputs/identifier-naming/hungarian-notation1/.clang-tidy
 
 // clang-format off
 typedef signed char int8_t; // NOLINT
Index: clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-hungarian-notation-cfgfile.cpp
@@ -1,5 +1,4 @@
-// RUN: clang-tidy %s --config-file=%S/Inputs/identifier-naming/hungarian-notation1/.clang-tidy 2>&1 \
-// RUN:   | FileCheck -check-prefixes=CHECK-MESSAGES %s
+// RUN: %check_clang_tidy %s readability-identifier-naming %t -- --config-file=%S/Inputs/identifier-naming/hungarian-notation2/.clang-tidy
 
 // clang-format off
 typedef signed char int8_t; // NOLINT
Index: clang-tools-extra/test/clang-tidy/check_clang_tidy.py
===
--- clang-tools-extra/test/clang-tidy/check_clang_tidy.py
+++ clang-tools-extra/test/clang-tidy/check_clang_tidy.py
@@ -107,9 +107,10 @@
   

[PATCH] D144058: [clang][deps] Split lookupModuleOutput out of DependencyConsumer NFC

2023-02-15 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 accepted this revision.
jansvoboda11 added inline comments.
This revision is now accepted and ready to land.



Comment at: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h:64-66
+/// Dependency scanner callbacks that are used during scanning to influence the
+/// behaviour of the scan - for example, to customize the scanned invocations.
+class DependencyActions {

benlangmuir wrote:
> jansvoboda11 wrote:
> > What do the downstream callbacks do? The class name sounds a bit generic 
> > for something you can call `lookupModuleOutput()` on, but maybe that's the 
> > right name with more context. It's also very similar to the existing 
> > `DependencyScanningAction`.
> They are callbacks that modify the ScanInstance itself, or one of the 
> CompilerInvocations being constructed (either for the TU or for module 
> dependencies).  In practice, we use this to add caching support - modifying 
> invocations to use inputs from a CAS. I chose "actions" based on the fact 
> they are acting on the scanner/invocations, rather than simply consuming the 
> information.  While lookupModuleOutput does not directly modify the 
> invcation, it does indirectly via the ModuleDepCollector incorporating its 
> results into the invocation.  If you're interested, here are our downstream 
> callbacks that I would move into this interface: 
> https://github.com/apple/llvm-project/blob/next/clang/include/clang/Tooling/DependencyScanning/DependencyScanningWorker.h#L49
> 
> RE: DependencyScanningAction: I agree it's not ideal that these names are 
> "close".  On the other hand, they're not too likely to be confused in 
> practice since they have very different roles -- the DependencyScanningAction 
> is not exposed to clients, and it's a tooling action not something you use to 
> control the scan.  We also have other "actions" like the FrontendAction we 
> create, which again have a different role.
> 
> Happy to consider suggestions for a better name!
Thanks, that's helpful. My preference would be slightly towards something more 
specific-sounding, maybe `ScanningAdjuster`, `ScannerAndDependencyAdjuster`, 
but LGTM as-is too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144058

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


[PATCH] D143210: [PowerPC] Include vector bool and pixel when emitting lax warning

2023-02-15 Thread Maryam Moghadas via Phabricator via cfe-commits
maryammo added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:9845
 if (anyAltivecTypes(RHSType, LHSType) &&
-!areSameVectorElemTypes(RHSType, LHSType))
+!Context.areCompatibleVectorTypes(RHSType, LHSType))
   Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)

amyk wrote:
> Might be a silly question, but what does it mean to be a "compatible" vector 
> type?
`areCompatibleVectorTypes` is defined in lib/AST/ASTContext.cpp,  it considers 
all vectors with the same unqualified types to be compatible, also vectors with 
the same number of elements where neither of them is vector bool/pixel or some 
specific SVE types are compatible.  


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143210

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


[PATCH] D144016: [Sema] Relax a failing assertion in TransformBlockExpr

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Precommit CI found an issue on Windows that should be addressed:

  FAIL: Clang :: CodeGenCXX/cxx1z-constexpr-if.cpp (7014 of 17903)
   TEST 'Clang :: CodeGenCXX/cxx1z-constexpr-if.cpp' FAILED 

  Script:
  --
  : 'RUN: at line 1';   
c:\ws\w32-1\llvm-project\premerge-checks\build\bin\clang.exe -cc1 
-internal-isystem 
c:\ws\w32-1\llvm-project\premerge-checks\build\lib\clang\17\include 
-nostdsysteminc -std=c++1z 
C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp
 -emit-llvm -fblocks -o - | 
c:\ws\w32-1\llvm-project\premerge-checks\build\bin\filecheck.exe 
C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp
 --implicit-check-not=should_not_be_used
  --
  Exit Code: 1
  
  Command Output (stdout):
  --
  $ ":" "RUN: at line 1"
  $ "c:\ws\w32-1\llvm-project\premerge-checks\build\bin\clang.exe" "-cc1" 
"-internal-isystem" 
"c:\ws\w32-1\llvm-project\premerge-checks\build\lib\clang\17\include" 
"-nostdsysteminc" "-std=c++1z" 
"C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp"
 "-emit-llvm" "-fblocks" "-o" "-"
  $ "c:\ws\w32-1\llvm-project\premerge-checks\build\bin\filecheck.exe" 
"C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp"
 "--implicit-check-not=should_not_be_used"
  # command stderr:
  
C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp:50:17:
 error: CHECK-LABEL: expected string not found in input
  // CHECK-LABEL: define internal void 
@___ZN16BlockThisCapture1S1mILb0EEEvv_block_invoke(
  ^
  :1:1: note: scanning from here
  ; ModuleID = 
'C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp'
  ^
  :53:1: note: possible intended match here
  define internal void 
@"__??$m@$0A@@S@BlockThisCapture@@QEAAXXZ_block_invoke"(ptr noundef 
%.block_descriptor) #3 {
  ^
  
  Input file: 
  Check file: 
C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp
  
  -dump-input=help explains the following input dump.
  
  Input was:
  <<
  1: ; ModuleID = 
'C:\ws\w32-1\llvm-project\premerge-checks\clang\test\CodeGenCXX\cxx1z-constexpr-if.cpp'
 
  label:50'0 
X
 error: no match found
  2: source_filename = 
"C:\\ws\\w32-1\\llvm-project\\premerge-checks\\clang\\test\\CodeGenCXX\\cxx1z-constexpr-if.cpp"
 
  label:50'0 
~~
  3: target datalayout = 
"e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" 
  label:50'0 
~
  4: target triple = "x86_64-pc-windows-msvc" 
  label:50'0 ~
  5:  
  label:50'0 ~
  6: %"struct.BlockThisCapture::S" = type { i8 } 
  label:50'0 
  .
  .
  .
 48:  call void %0(ptr noundef @__block_literal_global) 
  label:50'0 ~~~
 49:  ret void 
  label:50'0 ~~
 50: } 
  label:50'0 ~~
 51:  
  label:50'0 ~
 52: ; Function Attrs: noinline nounwind optnone 
  label:50'0 
 53: define internal void 
@"__??$m@$0A@@S@BlockThisCapture@@QEAAXXZ_block_invoke"(ptr noundef 
%.block_descriptor) #3 { 
  label:50'0 
~~
  label:50'1 ?  
possible intended match
 54: entry: 
  label:50'0 ~~~
 55:  %.block_descriptor.addr = alloca ptr, align 8 
  label:50'0 ~~~
 56:  %block.addr = alloca ptr, align 8 
  label:50'0 ~~~
 57:  store ptr %.block_descriptor, ptr %.block_descriptor.addr, 
align 8 
  label:50'0 

 58:  store ptr %.block_descriptor, ptr %block.addr, align 8 
  label:50'0 
  .
  .
  .
  >>
  
  error: command failed with exit status: 1

It looks like you may need a target triple to ensure the mangled names are 
consistent.

Also, can you add a release note for the fix?


Repository:
  rG LLVM Github Monorepo

CHANGES 

[PATCH] D143418: [libclang] Add API to set preferred temp dir path

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D143418#4126266 , @vedgy wrote:

> `size_t` indeed makes logical sense for this member as that's the return type 
> of `sizeof`. `size_t` is two times larger than `unsigned` on x86_64, but I 
> don't think the size of this struct has any chance of impacting performance.

Agreed.

> Though it wouldn't hurt to pack the size and the boolean options in a 
> single-pointer-sized region on x86_64. After all, this struct's size will 
> never reach `UINT_MAX`. I slightly prefer `unsigned` due to my efficiency 
> inclinations :). What do you prefer? Is there any benefit in using a 
> fixed-size integer type here?

I've been trying to think of benefits for using a fixed-size integer type and 
the closest I can come is the consistency of the structure size across targets, 
but I don't think we need that consistency. I don't have a strong preference 
for `unsigned` vs `size_t`, so how about we go with your slight preference for 
`unsigned` unless someone finds a reason to use something else?

>>> 2. Should `int excludeDeclarationsFromPCH` and `int displayDiagnostics` 
>>> currently passed to `clang_createIndex()` also be included in the struct? 
>>> Then only a single argument will be passed to 
>>> `clang_createIndexWithOptions()`: `CXIndexOptions`.
>>
>> I think that makes sense to me. It does raise the question of whether we 
>> want to pack these boolean-like fields together, as in:
>>
>>   struct CXIndexOptions {
>> size_t Size;
>>   
>> int ExcludeDeclsFromPCH : 1;
>> int DisplayDiagnostics : 1;
>> int Reserved : 30;
>>   
>> const char *PreambleStoragePath;
>> ...
>>   };
>>
>> This makes it a little less likely to need to grow the structure when adding 
>> new options.
>
> When we add new options, the struct's size must grow in order to distinguish 
> different struct versions and prevent undefined behavior!

Oh gosh you're absolutely right, that was a think-o on my part.

> OK, let's skip the global options member for now. I'll add a `\todo` about 
> this.

SGTM, thank you!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143418

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


[PATCH] D140756: Add clang_CXXMethod_isExplicit to libclang

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D140756#4128729 , @diseraluca 
wrote:

> In D140756#4100387 , @aaron.ballman 
> wrote:
>
>> @diseraluca -- do you need this cherry picked into Clang 16 or are you fine 
>> if this goes into Clang 17 instead?
>
> Sorry for checking in so late, I noticed the notifications only now. We are 
> using a different solution for the time being so it is correct that this is 
> fine being in Clang 17.
>
> Thank you for taking care of this.

Thank you for the info!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D140756

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


[PATCH] D143691: Fix clang-formats IncludeCategory to match the documentation

2023-02-15 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Looks good to me, apart from that one issue.




Comment at: clang/lib/Tooling/Inclusions/IncludeStyle.cpp:23
+
+constexpr int DefaultPriority = std::numeric_limits::max();
+

Please move this into the `mapping` function.



Comment at: clang/unittests/Format/SortIncludesTest.cpp:11
 #include "clang/Format/Format.h"
+#include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/ADT/StringRef.h"

Don't need that, or?



Comment at: clang/unittests/Format/SortIncludesTest.cpp:548
+  EXPECT_EQ("#include \"a.h\"\n"
+"#include \"llvm/a.h\"\n"
+"#include \"b.h\"\n"

While I may accept there are more than one //main// header, this should not 
happen in my opinion.



Comment at: clang/unittests/Format/SortIncludesTest.cpp:557
+
+  // Keep manually splitted groups in place
   EXPECT_EQ("#include \"a.h\"\n"

End comments with full stop.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143691

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


[PATCH] D143430: [C2x] Implement the `unreachable` macro for WG14 N2826

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa9797d7d2d78: [C2x] Implement the `unreachable` macro for 
WG14 N2826 (authored by aaron.ballman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143430

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Headers/stddef.h
  clang/test/C/C2x/n2826.c
  clang/www/c_status.html


Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -1028,7 +1028,7 @@
 
   Add annotations for unreachable control flow v2
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2826.pdf;>N2826
-  No
+  Clang 17
 
 
   Unicode Sequences More Than 21 Bits are a Constraint Violation 
r0
Index: clang/test/C/C2x/n2826.c
===
--- /dev/null
+++ clang/test/C/C2x/n2826.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -ffreestanding -emit-llvm -o - -std=c2x %s | FileCheck %s
+// RUN: %clang_cc1 -ffreestanding -std=c17 -verify %s
+
+/* WG14 N2826: Clang 17
+ * Add annotations for unreachable control flow v2
+ */
+#include 
+
+enum E {
+  Zero,
+  One,
+  Two,
+};
+
+int test(enum E e) {
+  switch (e) {
+  case Zero: return 0;
+  case One: return 1;
+  case Two: return 2;
+  }
+  unreachable(); // expected-error {{call to undeclared function 
'unreachable'}}
+}
+
+// CHECK: switch i32 %0, label %[[EPILOG:.+]] [
+// CHECK: [[EPILOG]]:
+// CHECK-NEXT: unreachable
Index: clang/lib/Headers/stddef.h
===
--- clang/lib/Headers/stddef.h
+++ clang/lib/Headers/stddef.h
@@ -103,6 +103,11 @@
 typedef typeof(nullptr) nullptr_t;
 #endif /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202000L */
 
+#if defined(__need_STDDEF_H_misc) && defined(__STDC_VERSION__) &&  
\
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */
+
 #if defined(__need_STDDEF_H_misc)
 #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) ||  
\
 (defined(__cplusplus) && __cplusplus >= 201103L)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -124,6 +124,8 @@
 
 C2x Feature Support
 ---
+- Implemented the ``unreachable`` macro in freestanding  for
+  `WG14 N2826 `_
 
 C++ Language Changes in Clang
 -


Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -1028,7 +1028,7 @@
 
   Add annotations for unreachable control flow v2
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2826.pdf;>N2826
-  No
+  Clang 17
 
 
   Unicode Sequences More Than 21 Bits are a Constraint Violation r0
Index: clang/test/C/C2x/n2826.c
===
--- /dev/null
+++ clang/test/C/C2x/n2826.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -ffreestanding -emit-llvm -o - -std=c2x %s | FileCheck %s
+// RUN: %clang_cc1 -ffreestanding -std=c17 -verify %s
+
+/* WG14 N2826: Clang 17
+ * Add annotations for unreachable control flow v2
+ */
+#include 
+
+enum E {
+  Zero,
+  One,
+  Two,
+};
+
+int test(enum E e) {
+  switch (e) {
+  case Zero: return 0;
+  case One: return 1;
+  case Two: return 2;
+  }
+  unreachable(); // expected-error {{call to undeclared function 'unreachable'}}
+}
+
+// CHECK: switch i32 %0, label %[[EPILOG:.+]] [
+// CHECK: [[EPILOG]]:
+// CHECK-NEXT: unreachable
Index: clang/lib/Headers/stddef.h
===
--- clang/lib/Headers/stddef.h
+++ clang/lib/Headers/stddef.h
@@ -103,6 +103,11 @@
 typedef typeof(nullptr) nullptr_t;
 #endif /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202000L */
 
+#if defined(__need_STDDEF_H_misc) && defined(__STDC_VERSION__) &&  \
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */
+
 #if defined(__need_STDDEF_H_misc)
 #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) ||  \
 (defined(__cplusplus) && __cplusplus >= 201103L)
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -124,6 +124,8 @@
 
 C2x Feature Support
 ---
+- Implemented the ``unreachable`` macro in freestanding  for
+  `WG14 N2826 `_
 
 C++ Language Changes in Clang
 

[clang] a9797d7 - [C2x] Implement the `unreachable` macro for WG14 N2826

2023-02-15 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-02-15T14:43:01-05:00
New Revision: a9797d7d2d7878464868312e0c147b4e747a31c6

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

LOG: [C2x] Implement the `unreachable` macro for WG14 N2826

This exposes __builtin_unreachable as the expansion for the unreachable
macro in C2x. I added this definition under __need_STDDEF_H_misc on the
assumption there is no need for a separate need macro to control adding
this.

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

Added: 
clang/test/C/C2x/n2826.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Headers/stddef.h
clang/www/c_status.html

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0dcd9b9f04b1d..ab7518cc2dc6b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -124,6 +124,8 @@ C Language Changes in Clang
 
 C2x Feature Support
 ---
+- Implemented the ``unreachable`` macro in freestanding  for
+  `WG14 N2826 `_
 
 C++ Language Changes in Clang
 -

diff  --git a/clang/lib/Headers/stddef.h b/clang/lib/Headers/stddef.h
index 42815176dcd0f..539541f0ed41a 100644
--- a/clang/lib/Headers/stddef.h
+++ b/clang/lib/Headers/stddef.h
@@ -103,6 +103,11 @@ using ::std::nullptr_t;
 typedef typeof(nullptr) nullptr_t;
 #endif /* defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202000L */
 
+#if defined(__need_STDDEF_H_misc) && defined(__STDC_VERSION__) &&  
\
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */
+
 #if defined(__need_STDDEF_H_misc)
 #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L) ||  
\
 (defined(__cplusplus) && __cplusplus >= 201103L)

diff  --git a/clang/test/C/C2x/n2826.c b/clang/test/C/C2x/n2826.c
new file mode 100644
index 0..f108985c13ddd
--- /dev/null
+++ b/clang/test/C/C2x/n2826.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -ffreestanding -emit-llvm -o - -std=c2x %s | FileCheck %s
+// RUN: %clang_cc1 -ffreestanding -std=c17 -verify %s
+
+/* WG14 N2826: Clang 17
+ * Add annotations for unreachable control flow v2
+ */
+#include 
+
+enum E {
+  Zero,
+  One,
+  Two,
+};
+
+int test(enum E e) {
+  switch (e) {
+  case Zero: return 0;
+  case One: return 1;
+  case Two: return 2;
+  }
+  unreachable(); // expected-error {{call to undeclared function 
'unreachable'}}
+}
+
+// CHECK: switch i32 %0, label %[[EPILOG:.+]] [
+// CHECK: [[EPILOG]]:
+// CHECK-NEXT: unreachable

diff  --git a/clang/www/c_status.html b/clang/www/c_status.html
index 741d8c5b1ad9c..ee0f116bc2908 100644
--- a/clang/www/c_status.html
+++ b/clang/www/c_status.html
@@ -1028,7 +1028,7 @@ C2x implementation status
 
   Add annotations for unreachable control flow v2
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2826.pdf;>N2826
-  No
+  Clang 17
 
 
   Unicode Sequences More Than 21 Bits are a Constraint Violation 
r0



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


[PATCH] D142507: [AMDGPU] Split dot7 feature

2023-02-15 Thread Stanislav Mekhanoshin via Phabricator via cfe-commits
rampitec added a comment.

In D142507#4127505 , @b-sumner wrote:

>> My current understanding is the c-p will go into already forked clang-16, 
>> but not to rocm 5.4. So rocm device-libs will be accompanied by the older 
>> clang-16 w/o this and stay compatible. Someone building from scratch will 
>> use latest clang-16 and staging device-libs with this change. Do you think 
>> this will work?
>
> I wouldn't recommend it.  I would patch whatever device libs are being built 
> in association with clang-16, not staging.  Staging device libs is only 
> appropriate for the staging compiler.  A hash of device libs from around the 
> time that clang-16 stable released would probably be safe.

In general the idea is that compiler and device-libs should match. I guess the 
correct answer then users of clang-16 shall use rocm-5.4.x branch of the device 
libs?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142507

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


[PATCH] D109239: Add support for floating-option `-ffp-eval-method` and for new `pragma clang fp eval-method`

2023-02-15 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

In D109239#4129733 , @dmgreen wrote:

> Hi. I created this issue about the use of Ofast and -1:
> https://github.com/llvm/llvm-project/issues/60781

Thanks. Will take a look.


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

https://reviews.llvm.org/D109239

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


[PATCH] D109239: Add support for floating-option `-ffp-eval-method` and for new `pragma clang fp eval-method`

2023-02-15 Thread Dave Green via Phabricator via cfe-commits
dmgreen added a comment.

Hi. I created this issue about the use of Ofast and -1:
https://github.com/llvm/llvm-project/issues/60781


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

https://reviews.llvm.org/D109239

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


[PATCH] D144120: [HLSL] add log library functions This change exposes the log library functions for HLSL, excluding long, int, and long long doubles. The log functions are supported for all scalar, ve

2023-02-15 Thread Joshua Batista via Phabricator via cfe-commits
bob80905 created this revision.
Herald added a subscriber: Anastasia.
Herald added a project: All.
bob80905 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

...missing in this patch because those types
don't exist in HLSL. Int is missing because the log functions only work on 
floating type arguments.

The full documentation of the HLSL log functions are available here:
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log2
https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-log10


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144120

Files:
  clang/lib/Headers/hlsl/hlsl_intrinsics.h
  clang/test/CodeGenHLSL/builtins/log.hlsl
  clang/test/CodeGenHLSL/builtins/log10.hlsl
  clang/test/CodeGenHLSL/builtins/log2.hlsl

Index: clang/test/CodeGenHLSL/builtins/log2.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/builtins/log2.hlsl
@@ -0,0 +1,56 @@
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -fnative-half-type \
+// RUN:   -emit-llvm -disable-llvm-passes -O3 -o - | FileCheck %s
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -emit-llvm -disable-llvm-passes \
+// RUN:   -D__HLSL_ENABLE_16_BIT -o - | FileCheck %s --check-prefix=NO_HALF
+
+// CHECK: define noundef half @
+// CHECK: call half @llvm.log2.f16(
+// NO_HALF: define noundef float @"?test_log2_half@@YA$halff@$halff@@Z"(
+// NO_HALF: call float @llvm.log2.f32(
+half test_log2_half ( half p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <2 x half> @
+// CHECK: call <2 x half> @llvm.log2.v2f16
+// NO_HALF: define noundef <2 x float> @"?test_log2_float2@@YAT?$__vector@M$01@__clang@@T12@@Z"(
+// NO_HALF: call <2 x float> @llvm.log2.v2f32(
+half2 test_log2_half2 ( half2 p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <3 x half> @
+// CHECK: call <3 x half> @llvm.log2.v3f16
+// NO_HALF: define noundef <3 x float> @"?test_log2_float3@@YAT?$__vector@M$02@__clang@@T12@@Z"(
+// NO_HALF: call <3 x float> @llvm.log2.v3f32(
+half3 test_log2_half3 ( half3 p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <4 x half> @
+// CHECK: call <4 x half> @llvm.log2.v4f16
+// NO_HALF: define noundef <4 x float> @"?test_log2_float4@@YAT?$__vector@M$03@__clang@@T12@@Z"(
+// NO_HALF: call <4 x float> @llvm.log2.v4f32(
+half4 test_log2_half4 ( half4 p0 ) {
+  return log2 ( p0 );
+}
+
+// CHECK: define noundef float @
+// CHECK: call float @llvm.log2.f32(
+float test_log2_float ( float p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <2 x float> @
+// CHECK: call <2 x float> @llvm.log2.v2f32
+float2 test_log2_float2 ( float2 p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <3 x float> @
+// CHECK: call <3 x float> @llvm.log2.v3f32
+float3 test_log2_float3 ( float3 p0 ) {
+  return log2 ( p0 );
+}
+// CHECK: define noundef <4 x float> @
+// CHECK: call <4 x float> @llvm.log2.v4f32
+float4 test_log2_float4 ( float4 p0 ) {
+  return log2 ( p0 );
+}
\ No newline at end of file
Index: clang/test/CodeGenHLSL/builtins/log10.hlsl
===
--- /dev/null
+++ clang/test/CodeGenHLSL/builtins/log10.hlsl
@@ -0,0 +1,56 @@
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -fnative-half-type \
+// RUN:   -emit-llvm -disable-llvm-passes -O3 -o - | FileCheck %s
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -emit-llvm -disable-llvm-passes \
+// RUN:   -D__HLSL_ENABLE_16_BIT -o - | FileCheck %s --check-prefix=NO_HALF
+
+// CHECK: define noundef half @
+// CHECK: call half @llvm.log10.f16(
+// NO_HALF: define noundef float @"?test_log10_half@@YA$halff@$halff@@Z"(
+// NO_HALF: call float @llvm.log10.f32(
+half test_log10_half ( half p0 ) {
+  return log10 ( p0 );
+}
+// CHECK: define noundef <2 x half> @
+// CHECK: call <2 x half> @llvm.log10.v2f16
+// NO_HALF: define noundef <2 x float> @"?test_log10_float2@@YAT?$__vector@M$01@__clang@@T12@@Z"(
+// NO_HALF: call <2 x float> @llvm.log10.v2f32(
+half2 test_log10_half2 ( half2 p0 ) {
+  return log10 ( p0 );
+}
+// CHECK: define noundef <3 x half> @
+// CHECK: call <3 x half> @llvm.log10.v3f16
+// NO_HALF: define noundef <3 x float> @"?test_log10_float3@@YAT?$__vector@M$02@__clang@@T12@@Z"(
+// NO_HALF: call <3 x float> @llvm.log10.v3f32(
+half3 test_log10_half3 ( half3 p0 ) {
+  return log10 ( p0 );
+}
+// CHECK: define noundef <4 x half> @
+// CHECK: call <4 x half> @llvm.log10.v4f16
+// NO_HALF: define noundef <4 x float> @"?test_log10_float4@@YAT?$__vector@M$03@__clang@@T12@@Z"(
+// 

[PATCH] D142584: [CodeGen] Add a boolean flag to `Address::getPointer` and `Lvalue::getPointer` that indicates whether the pointer is known not to be null

2023-02-15 Thread Akira Hatanaka via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG57865bc5ad27: [CodeGen] Add a flag to `Address` and `Lvalue` 
that is used to keep (authored by ahatanak).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142584

Files:
  clang/lib/CodeGen/Address.h
  clang/lib/CodeGen/CGBuilder.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGClass.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGException.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/lib/CodeGen/CGNonTrivialStruct.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGValue.h
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h

Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -3164,7 +3164,8 @@
 
 Address getIndirectAddress() const {
   assert(isIndirect());
-  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment));
+  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment),
+ KnownNonNull);
 }
   };
 
@@ -3771,8 +3772,13 @@
   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
   /// variable length type, this is not possible.
   ///
-  LValue EmitLValue(const Expr *E);
+  LValue EmitLValue(const Expr *E,
+KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
 
+private:
+  LValue EmitLValueHelper(const Expr *E, KnownNonNull_t IsKnownNonNull);
+
+public:
   /// Same as EmitLValue but additionally we generate checking code to
   /// guard against undefined behavior.  This is only suitable when we know
   /// that the address will be used to access the object.
@@ -4783,9 +4789,10 @@
   /// into the address of a local variable.  In such a case, it's quite
   /// reasonable to just ignore the returned alignment when it isn't from an
   /// explicit source.
-  Address EmitPointerWithAlignment(const Expr *Addr,
-   LValueBaseInfo *BaseInfo = nullptr,
-   TBAAAccessInfo *TBAAInfo = nullptr);
+  Address
+  EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo = nullptr,
+   TBAAAccessInfo *TBAAInfo = nullptr,
+   KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
 
   /// If \p E references a parameter with pass_object_size info or a constant
   /// array size modifier, emit the object size divided by the size of \p EltTy.
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1104,8 +1104,9 @@
 auto AI = CurFn->arg_begin();
 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
   ++AI;
-ReturnValue = Address(&*AI, ConvertType(RetTy),
-  CurFnInfo->getReturnInfo().getIndirectAlign());
+ReturnValue =
+Address(&*AI, ConvertType(RetTy),
+CurFnInfo->getReturnInfo().getIndirectAlign(), KnownNonNull);
 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
   ReturnValuePointer =
   CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
@@ -1125,8 +1126,8 @@
 cast(Addr)->getResultElementType();
 ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
-ReturnValue =
-Address(Addr, ConvertType(RetTy), CGM.getNaturalTypeAlignment(RetTy));
+ReturnValue = Address(Addr, ConvertType(RetTy),
+  CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
   } else {
 ReturnValue = CreateIRTemp(RetTy, "retval");
 
Index: clang/lib/CodeGen/CGValue.h
===
--- clang/lib/CodeGen/CGValue.h
+++ clang/lib/CodeGen/CGValue.h
@@ -225,6 +225,9 @@
   // this lvalue.
   bool Nontemporal : 1;
 
+  // The pointer is known not to be null.
+  bool IsKnownNonNull : 1;
+
   LValueBaseInfo BaseInfo;
   TBAAAccessInfo TBAAInfo;
 
@@ -333,24 +336,35 @@
   LValueBaseInfo getBaseInfo() const { return BaseInfo; }
   void setBaseInfo(LValueBaseInfo Info) { BaseInfo = Info; }
 
+  KnownNonNull_t isKnownNonNull() const {
+return (KnownNonNull_t)IsKnownNonNull;
+  }
+  LValue setKnownNonNull() {
+IsKnownNonNull = true;
+return *this;
+  }
+
   // simple lvalue
   llvm::Value *getPointer(CodeGenFunction ) const {
 assert(isSimple());
 return V;
   }
   Address getAddress(CodeGenFunction ) const {
-return Address(getPointer(CGF), ElementType, getAlignment());
+return Address(getPointer(CGF), ElementType, getAlignment(),
+  

[clang] 57865bc - [CodeGen] Add a flag to `Address` and `Lvalue` that is used to keep

2023-02-15 Thread Akira Hatanaka via cfe-commits

Author: Akira Hatanaka
Date: 2023-02-15T10:15:13-08:00
New Revision: 57865bc5ad277166507d9e9fbb5205be86caa73a

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

LOG: [CodeGen] Add a flag to `Address` and `Lvalue` that is used to keep
track of whether the pointer is known not to be null

The flag will be used for the arm64e work we plan to upstream in the
future (see https://lists.llvm.org/pipermail/llvm-dev/2019-October/136091.html).
Currently the flag has no effect on code generation.

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

Added: 


Modified: 
clang/lib/CodeGen/Address.h
clang/lib/CodeGen/CGBuilder.h
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGClass.cpp
clang/lib/CodeGen/CGDecl.cpp
clang/lib/CodeGen/CGException.cpp
clang/lib/CodeGen/CGExpr.cpp
clang/lib/CodeGen/CGExprCXX.cpp
clang/lib/CodeGen/CGNonTrivialStruct.cpp
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGValue.h
clang/lib/CodeGen/CodeGenFunction.cpp
clang/lib/CodeGen/CodeGenFunction.h

Removed: 




diff  --git a/clang/lib/CodeGen/Address.h b/clang/lib/CodeGen/Address.h
index bddeac1d6dcbd..9f7cd17752121 100644
--- a/clang/lib/CodeGen/Address.h
+++ b/clang/lib/CodeGen/Address.h
@@ -22,52 +22,69 @@
 namespace clang {
 namespace CodeGen {
 
+// Indicates whether a pointer is known not to be null.
+enum KnownNonNull_t { NotKnownNonNull, KnownNonNull };
+
 // We try to save some space by using 6 bits over two PointerIntPairs to store
 // the alignment. However, some arches don't support 3 bits in a PointerIntPair
 // so we fallback to storing the alignment separately.
 template = 8> class AddressImpl {};
 
 template  class AddressImpl {
-  llvm::Value *Pointer;
+  llvm::PointerIntPair PointerAndKnownNonNull;
   llvm::Type *ElementType;
   CharUnits Alignment;
 
 public:
   AddressImpl(llvm::Value *Pointer, llvm::Type *ElementType,
-  CharUnits Alignment)
-  : Pointer(Pointer), ElementType(ElementType), Alignment(Alignment) {}
-  llvm::Value *getPointer() const { return Pointer; }
+  CharUnits Alignment, KnownNonNull_t IsKnownNonNull)
+  : PointerAndKnownNonNull(Pointer, IsKnownNonNull),
+ElementType(ElementType), Alignment(Alignment) {}
+  llvm::Value *getPointer() const {
+return PointerAndKnownNonNull.getPointer();
+  }
   llvm::Type *getElementType() const { return ElementType; }
   CharUnits getAlignment() const { return Alignment; }
+  KnownNonNull_t isKnownNonNull() const {
+return (KnownNonNull_t)PointerAndKnownNonNull.getInt();
+  }
+  void setKnownNonNull() { PointerAndKnownNonNull.setInt(true); }
 };
 
 template  class AddressImpl {
-  // Int portion stores upper 3 bits of the log of the alignment.
+  // Int portion stores the non-null bit and the upper 2 bits of the log of the
+  // alignment.
   llvm::PointerIntPair Pointer;
   // Int portion stores lower 3 bits of the log of the alignment.
   llvm::PointerIntPair ElementType;
 
 public:
   AddressImpl(llvm::Value *Pointer, llvm::Type *ElementType,
-  CharUnits Alignment)
+  CharUnits Alignment, KnownNonNull_t IsKnownNonNull)
   : Pointer(Pointer), ElementType(ElementType) {
-if (Alignment.isZero())
+if (Alignment.isZero()) {
+  this->Pointer.setInt(IsKnownNonNull << 2);
   return;
-// Currently the max supported alignment is much less than 1 << 63 and is
+}
+// Currently the max supported alignment is exactly 1 << 32 and is
 // guaranteed to be a power of 2, so we can store the log of the alignment
-// into 6 bits.
+// into 5 bits.
 assert(Alignment.isPowerOfTwo() && "Alignment cannot be zero");
 auto AlignLog = llvm::Log2_64(Alignment.getQuantity());
-assert(AlignLog < (1 << 6) && "cannot fit alignment into 6 bits");
-this->Pointer.setInt(AlignLog >> 3);
+assert(AlignLog < (1 << 5) && "cannot fit alignment into 5 bits");
+this->Pointer.setInt(IsKnownNonNull << 2 | AlignLog >> 3);
 this->ElementType.setInt(AlignLog & 7);
   }
   llvm::Value *getPointer() const { return Pointer.getPointer(); }
   llvm::Type *getElementType() const { return ElementType.getPointer(); }
   CharUnits getAlignment() const {
-unsigned AlignLog = (Pointer.getInt() << 3) | ElementType.getInt();
+unsigned AlignLog = ((Pointer.getInt() & 0x3) << 3) | ElementType.getInt();
 return CharUnits::fromQuantity(CharUnits::QuantityType(1) << AlignLog);
   }
+  KnownNonNull_t isKnownNonNull() const {
+return (KnownNonNull_t)(!!(Pointer.getInt() & 0x4));
+  }
+  void setKnownNonNull() { Pointer.setInt(Pointer.getInt() | 0x4); }
 };
 
 /// An aligned address.
@@ -75,11 +92,13 @@ class Address {
   AddressImpl A;
 
 protected:
-  Address(std::nullptr_t) : 

[PATCH] D144036: [clang-tidy] Add bugprone-enum-to-bool-conversion check

2023-02-15 Thread Piotr Zegar via Phabricator via cfe-commits
ClockMan added a comment.

Fixed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144036

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


[PATCH] D144036: [clang-tidy] Add bugprone-enum-to-bool-conversion check

2023-02-15 Thread Piotr Zegar via Phabricator via cfe-commits
ClockMan updated this revision to Diff 497727.
ClockMan marked 3 inline comments as done.
ClockMan added a comment.

Corrected issues mentioned in review


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144036

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-bool-conversion.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion-cpp11.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp
@@ -0,0 +1,119 @@
+// RUN: %check_clang_tidy -std=c++98-or-later %s bugprone-enum-to-bool-conversion %t -- \
+// RUN:   -config="{CheckOptions: [{key: bugprone-enum-to-bool-conversion.EnumIgnoreRegexp, value: '^::without::issue::IgnoredEnum$'}]}"
+
+namespace with::issue
+{
+
+typedef enum EStatus
+{
+SUCCESS   = 1,
+FAILURE   = 2,
+INVALID_PARAM = 3,
+UNKNOWN   = 4
+} Status;
+
+bool testEnumConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+bool testTypedefConversion(Status value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+bool testExplicitConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:30: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return static_cast(value);
+}
+
+bool testInIfConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:9: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+if (value)
+{
+return false;
+}
+
+return true;
+}
+
+bool testWithNegation(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:16: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return not value;
+}
+
+}
+
+namespace without::issue
+{
+
+enum StatusWithZero
+{
+UNK  = 0,
+OK   = 1,
+NOT_OK = 2
+};
+
+bool testEnumConversion(StatusWithZero value)
+{
+return value;
+}
+
+enum WithDefault
+{
+Value0,
+Value1
+};
+
+bool testEnumConversion(WithDefault value)
+{
+return value;
+}
+
+enum WithNegative : int
+{
+Nen2 = -2,
+Nen1,
+Nen0
+};
+
+bool testEnumConversion(WithNegative value)
+{
+return value;
+}
+
+enum EStatus
+{
+SUCCESS = 1,
+FAILURE,
+INVALID_PARAM,
+UNKNOWN
+};
+
+bool explicitCompare(EStatus value)
+{
+return value == SUCCESS;
+}
+
+bool testEnumeratorCompare()
+{
+return SUCCESS;
+}
+
+enum IgnoredEnum
+{
+IGNORED_VALUE_1 = 1,
+IGNORED_VALUE_2
+};
+
+bool testIgnored(IgnoredEnum value)
+{
+return value;
+}
+
+}
Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion-cpp11.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion-cpp11.cpp
@@ -0,0 +1,32 @@
+// RUN: %check_clang_tidy -std=c++11-or-later %s bugprone-enum-to-bool-conversion %t
+
+namespace with::issue
+{
+
+enum class EStatus : char
+{
+SUCCESS   = 1,
+FAILURE   = 2,
+INVALID_PARAM = 3,
+UNKNOWN   = 4
+};
+
+bool testEnumConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return static_cast(value);
+}
+
+enum EResult : short
+{
+OK = 1,
+NOT_OK
+};
+
+bool testEnumConversion(const EResult& value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EResult' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+}
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===
--- 

[PATCH] D142584: [CodeGen] Add a boolean flag to `Address::getPointer` and `Lvalue::getPointer` that indicates whether the pointer is known not to be null

2023-02-15 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak updated this revision to Diff 497719.
ahatanak added a comment.

Fix type and add comment. Remove unnecessary cast.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142584

Files:
  clang/lib/CodeGen/Address.h
  clang/lib/CodeGen/CGBuilder.h
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGClass.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CGException.cpp
  clang/lib/CodeGen/CGExpr.cpp
  clang/lib/CodeGen/CGExprCXX.cpp
  clang/lib/CodeGen/CGNonTrivialStruct.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGValue.h
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h

Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -3164,7 +3164,8 @@
 
 Address getIndirectAddress() const {
   assert(isIndirect());
-  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment));
+  return Address(Value, ElementType, CharUnits::fromQuantity(Alignment),
+ KnownNonNull);
 }
   };
 
@@ -3771,8 +3772,13 @@
   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
   /// variable length type, this is not possible.
   ///
-  LValue EmitLValue(const Expr *E);
+  LValue EmitLValue(const Expr *E,
+KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
 
+private:
+  LValue EmitLValueHelper(const Expr *E, KnownNonNull_t IsKnownNonNull);
+
+public:
   /// Same as EmitLValue but additionally we generate checking code to
   /// guard against undefined behavior.  This is only suitable when we know
   /// that the address will be used to access the object.
@@ -4783,9 +4789,10 @@
   /// into the address of a local variable.  In such a case, it's quite
   /// reasonable to just ignore the returned alignment when it isn't from an
   /// explicit source.
-  Address EmitPointerWithAlignment(const Expr *Addr,
-   LValueBaseInfo *BaseInfo = nullptr,
-   TBAAAccessInfo *TBAAInfo = nullptr);
+  Address
+  EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo = nullptr,
+   TBAAAccessInfo *TBAAInfo = nullptr,
+   KnownNonNull_t IsKnownNonNull = NotKnownNonNull);
 
   /// If \p E references a parameter with pass_object_size info or a constant
   /// array size modifier, emit the object size divided by the size of \p EltTy.
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1104,8 +1104,9 @@
 auto AI = CurFn->arg_begin();
 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
   ++AI;
-ReturnValue = Address(&*AI, ConvertType(RetTy),
-  CurFnInfo->getReturnInfo().getIndirectAlign());
+ReturnValue =
+Address(&*AI, ConvertType(RetTy),
+CurFnInfo->getReturnInfo().getIndirectAlign(), KnownNonNull);
 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
   ReturnValuePointer =
   CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
@@ -1125,8 +1126,8 @@
 cast(Addr)->getResultElementType();
 ReturnValuePointer = Address(Addr, Ty, getPointerAlign());
 Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
-ReturnValue =
-Address(Addr, ConvertType(RetTy), CGM.getNaturalTypeAlignment(RetTy));
+ReturnValue = Address(Addr, ConvertType(RetTy),
+  CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
   } else {
 ReturnValue = CreateIRTemp(RetTy, "retval");
 
Index: clang/lib/CodeGen/CGValue.h
===
--- clang/lib/CodeGen/CGValue.h
+++ clang/lib/CodeGen/CGValue.h
@@ -225,6 +225,9 @@
   // this lvalue.
   bool Nontemporal : 1;
 
+  // The pointer is known not to be null.
+  bool IsKnownNonNull : 1;
+
   LValueBaseInfo BaseInfo;
   TBAAAccessInfo TBAAInfo;
 
@@ -333,24 +336,35 @@
   LValueBaseInfo getBaseInfo() const { return BaseInfo; }
   void setBaseInfo(LValueBaseInfo Info) { BaseInfo = Info; }
 
+  KnownNonNull_t isKnownNonNull() const {
+return (KnownNonNull_t)IsKnownNonNull;
+  }
+  LValue setKnownNonNull() {
+IsKnownNonNull = true;
+return *this;
+  }
+
   // simple lvalue
   llvm::Value *getPointer(CodeGenFunction ) const {
 assert(isSimple());
 return V;
   }
   Address getAddress(CodeGenFunction ) const {
-return Address(getPointer(CGF), ElementType, getAlignment());
+return Address(getPointer(CGF), ElementType, getAlignment(),
+   isKnownNonNull());
   }
   void setAddress(Address address) {
 assert(isSimple());
 V = address.getPointer();
   

[PATCH] D143849: [Clang][OpenCL] Allow pointers in structs as kernel arguments from 2.0

2023-02-15 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:9494
+  // of SVM.
+  if (S.getLangOpts().getOpenCLCompatibleVersion() > 120 &&
+  (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam))

Anastasia wrote:
> Ayal wrote:
> > Anastasia wrote:
> > > I think it should be possible to merge this with `if` below to avoid 
> > > condition duplication.
> > > 
> > > 
> > Sure, but that trades one duplication for another, rather than clearly 
> > separating the early-continue case early?
> > 
> > ```
> >   if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
> > if (S.getLangOpts().getOpenCLCompatibleVersion() > 120)
> >   continue;
> > S.Diag(Param->getLocation(),
> >diag::err_record_with_pointers_kernel_param)
> >   << PT->isUnionType()
> >   << PT;
> >   } else if (ParamType == InvalidAddrSpacePtrKernelParam) {
> > S.Diag(Param->getLocation(),
> >diag::err_record_with_pointers_kernel_param)
> >   << PT->isUnionType()
> >   << PT;
> >   } else {
> > S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
> > 
> > ```
> I am mainly thinking in terms of maintenance if for example someone fixes one 
> if and forgets another. Or if ifs will get separated by some other code and 
> then it is not easy to see that the same thing is handled differently in 
> OpenCL versions. 
> 
> Unfortunately we have a lot of those cases, I know this function has early 
> exists but it is not a common style.
> 
> 
> I was talking about something like:
> 
> 
> ```
> if (((S.getLangOpts().getOpenCLCompatibleVersion() <= 120) &&
> (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam)) ||
>   ParamType == InvalidAddrSpacePtrKernelParam)
> ```
> 
> It would also be ok to separate `InvalidAddrSpacePtrKernelParam` since it's 
> handling different feature.
Sorry I have forgotten that this part of the code is expected to handle the 
diagnostics only. The decision that the kernel parameter is wrong is done in 
`getOpenCLKernelParameterType`. I think you should alter the conditions there 
to check for OpenCL version and avoid classifying cases you care about as 
`PtrKernelParam` or `PtrPtrKernelParam`. Then here you wouldn't need this extra 
if/continue block. 


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

https://reviews.llvm.org/D143849

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


[PATCH] D144115: [clang] Extend pragma dump to support expressions

2023-02-15 Thread Vlad Serebrennikov via Phabricator via cfe-commits
Endill created this revision.
Endill added reviewers: clang-language-wg, aaron.ballman.
Herald added a project: All.
Endill requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Extend `#pragma clang __debug dump` to support not only single identifier, but 
an expression as well. This makes it possible to test ADL and overload 
resolution directly, without being creative to make them observable via 
diagnostics (e.g. when over.match.best  
is involved). This implementation has a known limitation of not supporting 
dependent expressions properly, but it's quite useful even without such support.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144115

Files:
  clang/lib/Lex/Pragma.cpp
  clang/lib/Parse/ParsePragma.cpp


Index: clang/lib/Parse/ParsePragma.cpp
===
--- clang/lib/Parse/ParsePragma.cpp
+++ clang/lib/Parse/ParsePragma.cpp
@@ -13,6 +13,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/PragmaKinds.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Lex/LexDiagnostic.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/Token.h"
 #include "clang/Parse/LoopHint.h"
@@ -706,10 +707,27 @@
 
 void Parser::HandlePragmaDump() {
   assert(Tok.is(tok::annot_pragma_dump));
-  IdentifierInfo *II =
-  reinterpret_cast(Tok.getAnnotationValue());
-  Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
   ConsumeAnnotationToken();
+  if (Tok.is(tok::eod)) {
+PP.Diag(Tok, diag::warn_pragma_debug_missing_argument) << "dump";
+  } else if (NextToken().is(tok::eod)) {
+if (Tok.isNot(tok::identifier)) {
+  PP.Diag(Tok, diag::warn_pragma_debug_unexpected_argument);
+  ConsumeAnyToken();
+  ExpectAndConsume(tok::eod);
+  return;
+}
+IdentifierInfo *II = Tok.getIdentifierInfo();
+Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
+ConsumeToken();
+  } else {
+ExprResult E = ParseExpression();
+if (!E.isInvalid()) {
+  E.get()->dump();
+}
+SkipUntil(tok::eod, StopBeforeMatch);
+  }
+  ExpectAndConsume(tok::eod);
 }
 
 void Parser::HandlePragmaWeak() {
Index: clang/lib/Lex/Pragma.cpp
===
--- clang/lib/Lex/Pragma.cpp
+++ clang/lib/Lex/Pragma.cpp
@@ -1066,21 +1066,11 @@
 PP.EnterToken(Crasher, /*IsReinject*/ false);
   }
 } else if (II->isStr("dump")) {
-  Token Identifier;
-  PP.LexUnexpandedToken(Identifier);
-  if (auto *DumpII = Identifier.getIdentifierInfo()) {
-Token DumpAnnot;
-DumpAnnot.startToken();
-DumpAnnot.setKind(tok::annot_pragma_dump);
-DumpAnnot.setAnnotationRange(
-SourceRange(Tok.getLocation(), Identifier.getLocation()));
-DumpAnnot.setAnnotationValue(DumpII);
-PP.DiscardUntilEndOfDirective();
-PP.EnterToken(DumpAnnot, /*IsReinject*/false);
-  } else {
-PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
-<< II->getName();
-  }
+  Token DumpAnnot;
+  DumpAnnot.startToken();
+  DumpAnnot.setKind(tok::annot_pragma_dump);
+  DumpAnnot.setAnnotationRange(SourceRange(Tok.getLocation()));
+  PP.EnterToken(DumpAnnot, /*IsReinject*/false);
 } else if (II->isStr("diag_mapping")) {
   Token DiagName;
   PP.LexUnexpandedToken(DiagName);


Index: clang/lib/Parse/ParsePragma.cpp
===
--- clang/lib/Parse/ParsePragma.cpp
+++ clang/lib/Parse/ParsePragma.cpp
@@ -13,6 +13,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/Basic/PragmaKinds.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Lex/LexDiagnostic.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/Token.h"
 #include "clang/Parse/LoopHint.h"
@@ -706,10 +707,27 @@
 
 void Parser::HandlePragmaDump() {
   assert(Tok.is(tok::annot_pragma_dump));
-  IdentifierInfo *II =
-  reinterpret_cast(Tok.getAnnotationValue());
-  Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
   ConsumeAnnotationToken();
+  if (Tok.is(tok::eod)) {
+PP.Diag(Tok, diag::warn_pragma_debug_missing_argument) << "dump";
+  } else if (NextToken().is(tok::eod)) {
+if (Tok.isNot(tok::identifier)) {
+  PP.Diag(Tok, diag::warn_pragma_debug_unexpected_argument);
+  ConsumeAnyToken();
+  ExpectAndConsume(tok::eod);
+  return;
+}
+IdentifierInfo *II = Tok.getIdentifierInfo();
+Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
+ConsumeToken();
+  } else {
+ExprResult E = ParseExpression();
+if (!E.isInvalid()) {
+  E.get()->dump();
+}
+SkipUntil(tok::eod, StopBeforeMatch);
+  }
+  ExpectAndConsume(tok::eod);
 }
 
 void Parser::HandlePragmaWeak() {
Index: clang/lib/Lex/Pragma.cpp

[PATCH] D143921: [debug-info][codegen] Prevent creation of self-referential SP node

2023-02-15 Thread Felipe de Azevedo Piovezan via Phabricator via cfe-commits
fdeazeve updated this revision to Diff 497713.
fdeazeve added a comment.

Fixed clang format issue


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143921

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  llvm/docs/LangRef.rst
  llvm/lib/IR/Verifier.cpp
  llvm/test/Verifier/disubprogram_declaration.ll


Index: llvm/test/Verifier/disubprogram_declaration.ll
===
--- /dev/null
+++ llvm/test/Verifier/disubprogram_declaration.ll
@@ -0,0 +1,17 @@
+; RUN: llvm-as -disable-output <%s 2>&1| FileCheck %s
+
+declare !dbg !12 i32 @declared_only()
+
+!llvm.module.flags = !{!2}
+!llvm.dbg.cu = !{!5}
+
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !6, 
producer: "clang", emissionKind: FullDebug)
+!6 = !DIFile(filename: "a.cpp", directory: "/")
+!7 = !{}
+!11 = !DISubroutineType(types: !7)
+
+!12 = !DISubprogram(name: "declared_only", scope: !6, file: !6, line: 2, type: 
!11, spFlags: DISPFlagOptimized, retainedNodes: !7, declaration: !13)
+!13 = !DISubprogram(name: "declared_only", scope: !6, file: !6, line: 2, type: 
!11, spFlags: DISPFlagOptimized, retainedNodes: !7)
+; CHECK: subprogram declaration must not have a declaration field
+; CHECK: warning: ignoring invalid debug info
Index: llvm/lib/IR/Verifier.cpp
===
--- llvm/lib/IR/Verifier.cpp
+++ llvm/lib/IR/Verifier.cpp
@@ -1400,6 +1400,8 @@
   } else {
 // Subprogram declarations (part of the type hierarchy).
 CheckDI(!Unit, "subprogram declarations must not have a compile unit", );
+CheckDI(!N.getRawDeclaration(),
+"subprogram declaration must not have a declaration field");
   }
 
   if (auto *RawThrownTypes = N.getRawThrownTypes()) {
Index: llvm/docs/LangRef.rst
===
--- llvm/docs/LangRef.rst
+++ llvm/docs/LangRef.rst
@@ -5776,11 +5776,12 @@
 
 .. _DISubprogramDeclaration:
 
-When ``isDefinition: false``, subprograms describe a declaration in the type
-tree as opposed to a definition of a function.  If the scope is a composite
-type with an ODR ``identifier:`` and that does not set ``flags: DIFwdDecl``,
-then the subprogram declaration is uniqued based only on its ``linkageName:``
-and ``scope:``.
+When ``spFlags: DISPFlagDefinition`` is not present, subprograms describe a
+declaration in the type tree as opposed to a definition of a function. In this
+case, the ``declaration`` field must be empty. If the scope is a composite type
+with an ODR ``identifier:`` and that does not set ``flags: DIFwdDecl``, then
+the subprogram declaration is uniqued based only on its ``linkageName:`` and
+``scope:``.
 
 .. code-block:: text
 
@@ -5789,9 +5790,9 @@
 }
 
 !0 = distinct !DISubprogram(name: "foo", linkageName: "_Zfoov", scope: !1,
-file: !2, line: 7, type: !3, isLocal: true,
-isDefinition: true, scopeLine: 8,
-containingType: !4,
+file: !2, line: 7, type: !3,
+spFlags: DISPFlagDefinition | 
DISPFlagLocalToUnit,
+scopeLine: 8, containingType: !4,
 virtuality: DW_VIRTUALITY_pure_virtual,
 virtualIndex: 10, flags: DIFlagPrototyped,
 isOptimized: true, unit: !5, templateParams: 
!6,
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -4214,10 +4214,9 @@
 
   llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
   llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
-  llvm::DISubprogram *SP =
-  DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo, STy,
-  ScopeLine, Flags, SPFlags, TParamsArray.get(),
-  getFunctionDeclaration(D), nullptr, Annotations);
+  llvm::DISubprogram *SP = DBuilder.createFunction(
+  FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
+  SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations);
 
   // Preserve btf_decl_tag attributes for parameters of extern functions
   // for BPF target. The parameters created in this loop are attached as


Index: llvm/test/Verifier/disubprogram_declaration.ll
===
--- /dev/null
+++ llvm/test/Verifier/disubprogram_declaration.ll
@@ -0,0 +1,17 @@
+; RUN: llvm-as -disable-output <%s 2>&1| FileCheck %s
+
+declare !dbg !12 i32 @declared_only()
+
+!llvm.module.flags = !{!2}
+!llvm.dbg.cu = !{!5}
+
+!2 = !{i32 2, !"Debug Info Version", i32 3}
+!5 

[PATCH] D143109: [Sema] Push a LambdaScopeInfo before calling SubstDefaultArgument

2023-02-15 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added a comment.

@tahonermann @cor3ntin have you had a chance to take a look at the updated 
patch?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143109

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


[PATCH] D142499: [Clang][AMDGPU] Set LTO CG opt level based on Clang option

2023-02-15 Thread Scott Linder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG97ba3c2bec48: [Clang][AMDGPU] Set LTO CG opt level based on 
Clang option (authored by scott.linder).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142499

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/test/Driver/hip-toolchain-opt.hip


Index: clang/test/Driver/hip-toolchain-opt.hip
===
--- clang/test/Driver/hip-toolchain-opt.hip
+++ clang/test/Driver/hip-toolchain-opt.hip
@@ -57,6 +57,14 @@
 // RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
 // RUN: 2>&1 | FileCheck --check-prefixes=ALL,Og %s
 
+// RUN: %clang -### -O0 \
+// RUN:   -Xoffload-linker --lto-CGO2 \
+// RUN:   --target=x86_64-unknown-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx900 \
+// RUN:   -c -nogpulib \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck --check-prefixes=ALL,O0-CGO2 %s
+
 // ALL: "-cc1" "-triple" "amdgcn-amd-amdhsa"
 // DEFAULT-NOT: "-O{{.}}"
 // O0-SAME: "-O0"
@@ -66,6 +74,8 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"
 
 // ALL-NOT: "{{.*}}opt"
 
@@ -74,12 +84,22 @@
 // ALL: "{{.*}}lld{{.*}}" {{.*}} "-plugin-opt=mcpu=gfx900"
 // DEFAULT-NOT: "-plugin-opt=O{{.*}}"
 // O0-SAME: "-plugin-opt=O0"
+// O0-SAME: "--lto-CGO0"
 // O1-SAME: "-plugin-opt=O1"
+// O1-SAME: "--lto-CGO1"
 // O2-SAME: "-plugin-opt=O2"
+// O2-SAME: "--lto-CGO2"
 // O3-SAME: "-plugin-opt=O3"
+// O3-SAME: "--lto-CGO3"
 // Os-SAME: "-plugin-opt=O2"
+// Os-SAME: "--lto-CGO2"
 // Oz-SAME: "-plugin-opt=O2"
+// Oz-SAME: "--lto-CGO2"
 // Og-SAME: "-plugin-opt=O1"
+// Og-SAME: "--lto-CGO1"
+// O0-CGO2-SAME: "-plugin-opt=O0"
+// O0-CGO2-SAME: "--lto-CGO0"
+// O0-CGO2-SAME: "--lto-CGO2"
 
 // ALL: "-cc1" "-triple" "x86_64-unknown-linux-gnu"
 // DEFAULT-NOT: "-O{{.}}"
@@ -90,3 +110,5 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"
Index: clang/lib/Driver/ToolChains/HIPAMD.cpp
===
--- clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -152,8 +152,10 @@
 
   addLinkerCompressDebugSectionsOption(TC, Args, LldArgs);
 
-  for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker))
+  for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker)) {
 LldArgs.push_back(Arg->getValue(1));
+Arg->claim();
+  }
 
   LldArgs.append({"-o", Output.getFilename()});
   for (auto Input : Inputs)
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -567,6 +567,7 @@
   ArgStringList , const InputInfo ,
   const InputInfo , bool IsThinLTO) {
   const bool IsOSAIX = ToolChain.getTriple().isOSAIX();
+  const bool IsAMDGCN = ToolChain.getTriple().isAMDGCN();
   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
   const Driver  = ToolChain.getDriver();
   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
@@ -631,9 +632,12 @@
 OOpt = "2";
 } else if (A->getOption().matches(options::OPT_O0))
   OOpt = "0";
-if (!OOpt.empty())
+if (!OOpt.empty()) {
   CmdArgs.push_back(
   Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt));
+  if (IsAMDGCN)
+CmdArgs.push_back(Args.MakeArgString(Twine("--lto-CGO") + OOpt));
+}
   }
 
   if (Args.hasArg(options::OPT_gsplit_dwarf))


Index: clang/test/Driver/hip-toolchain-opt.hip
===
--- clang/test/Driver/hip-toolchain-opt.hip
+++ clang/test/Driver/hip-toolchain-opt.hip
@@ -57,6 +57,14 @@
 // RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
 // RUN: 2>&1 | FileCheck --check-prefixes=ALL,Og %s
 
+// RUN: %clang -### -O0 \
+// RUN:   -Xoffload-linker --lto-CGO2 \
+// RUN:   --target=x86_64-unknown-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx900 \
+// RUN:   -c -nogpulib \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck --check-prefixes=ALL,O0-CGO2 %s
+
 // ALL: "-cc1" "-triple" "amdgcn-amd-amdhsa"
 // DEFAULT-NOT: "-O{{.}}"
 // O0-SAME: "-O0"
@@ -66,6 +74,8 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"
 
 // ALL-NOT: "{{.*}}opt"
 
@@ -74,12 +84,22 @@
 // ALL: "{{.*}}lld{{.*}}" {{.*}} "-plugin-opt=mcpu=gfx900"
 // DEFAULT-NOT: "-plugin-opt=O{{.*}}"
 // O0-SAME: "-plugin-opt=O0"
+// O0-SAME: "--lto-CGO0"
 // O1-SAME: "-plugin-opt=O1"
+// O1-SAME: "--lto-CGO1"
 // O2-SAME: "-plugin-opt=O2"
+// O2-SAME: "--lto-CGO2"
 // O3-SAME: "-plugin-opt=O3"
+// O3-SAME: "--lto-CGO3"
 

[clang] 97ba3c2 - [Clang][AMDGPU] Set LTO CG opt level based on Clang option

2023-02-15 Thread Scott Linder via cfe-commits

Author: Scott Linder
Date: 2023-02-15T17:34:35Z
New Revision: 97ba3c2bec48ca55cc842c6499b19b0b8a271951

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

LOG: [Clang][AMDGPU] Set LTO CG opt level based on Clang option

For AMDGCN default to mapping --lto-O# to --lto-CGO# in a 1:1 manner
(i.e. clang -O implies --lto-O and --lto-CGO).

Ensure there is a means to override this via -Xoffload-linker and begin
to claim these arguments to avoid incorrect warnings that they are not
used.

Reviewed By: yaxunl, MaskRay

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Driver/ToolChains/HIPAMD.cpp
clang/test/Driver/hip-toolchain-opt.hip

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index e6360fd8edc13..c179c4152cee4 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -567,6 +567,7 @@ void tools::addLTOOptions(const ToolChain , const 
ArgList ,
   ArgStringList , const InputInfo ,
   const InputInfo , bool IsThinLTO) {
   const bool IsOSAIX = ToolChain.getTriple().isOSAIX();
+  const bool IsAMDGCN = ToolChain.getTriple().isAMDGCN();
   const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
   const Driver  = ToolChain.getDriver();
   if (llvm::sys::path::filename(Linker) != "ld.lld" &&
@@ -631,9 +632,12 @@ void tools::addLTOOptions(const ToolChain , 
const ArgList ,
 OOpt = "2";
 } else if (A->getOption().matches(options::OPT_O0))
   OOpt = "0";
-if (!OOpt.empty())
+if (!OOpt.empty()) {
   CmdArgs.push_back(
   Args.MakeArgString(Twine(PluginOptPrefix) + ExtraDash + "O" + OOpt));
+  if (IsAMDGCN)
+CmdArgs.push_back(Args.MakeArgString(Twine("--lto-CGO") + OOpt));
+}
   }
 
   if (Args.hasArg(options::OPT_gsplit_dwarf))

diff  --git a/clang/lib/Driver/ToolChains/HIPAMD.cpp 
b/clang/lib/Driver/ToolChains/HIPAMD.cpp
index ff797e5959a49..3131c8ed24639 100644
--- a/clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ b/clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -152,8 +152,10 @@ void AMDGCN::Linker::constructLldCommand(Compilation , 
const JobAction ,
 
   addLinkerCompressDebugSectionsOption(TC, Args, LldArgs);
 
-  for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker))
+  for (auto *Arg : Args.filtered(options::OPT_Xoffload_linker)) {
 LldArgs.push_back(Arg->getValue(1));
+Arg->claim();
+  }
 
   LldArgs.append({"-o", Output.getFilename()});
   for (auto Input : Inputs)

diff  --git a/clang/test/Driver/hip-toolchain-opt.hip 
b/clang/test/Driver/hip-toolchain-opt.hip
index a82323d3da966..501f9654a2580 100644
--- a/clang/test/Driver/hip-toolchain-opt.hip
+++ b/clang/test/Driver/hip-toolchain-opt.hip
@@ -57,6 +57,14 @@
 // RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
 // RUN: 2>&1 | FileCheck --check-prefixes=ALL,Og %s
 
+// RUN: %clang -### -O0 \
+// RUN:   -Xoffload-linker --lto-CGO2 \
+// RUN:   --target=x86_64-unknown-linux-gnu \
+// RUN:   --cuda-gpu-arch=gfx900 \
+// RUN:   -c -nogpulib \
+// RUN:   %S/Inputs/hip_multiple_inputs/b.hip \
+// RUN: 2>&1 | FileCheck --check-prefixes=ALL,O0-CGO2 %s
+
 // ALL: "-cc1" "-triple" "amdgcn-amd-amdhsa"
 // DEFAULT-NOT: "-O{{.}}"
 // O0-SAME: "-O0"
@@ -66,6 +74,8 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"
 
 // ALL-NOT: "{{.*}}opt"
 
@@ -74,12 +84,22 @@
 // ALL: "{{.*}}lld{{.*}}" {{.*}} "-plugin-opt=mcpu=gfx900"
 // DEFAULT-NOT: "-plugin-opt=O{{.*}}"
 // O0-SAME: "-plugin-opt=O0"
+// O0-SAME: "--lto-CGO0"
 // O1-SAME: "-plugin-opt=O1"
+// O1-SAME: "--lto-CGO1"
 // O2-SAME: "-plugin-opt=O2"
+// O2-SAME: "--lto-CGO2"
 // O3-SAME: "-plugin-opt=O3"
+// O3-SAME: "--lto-CGO3"
 // Os-SAME: "-plugin-opt=O2"
+// Os-SAME: "--lto-CGO2"
 // Oz-SAME: "-plugin-opt=O2"
+// Oz-SAME: "--lto-CGO2"
 // Og-SAME: "-plugin-opt=O1"
+// Og-SAME: "--lto-CGO1"
+// O0-CGO2-SAME: "-plugin-opt=O0"
+// O0-CGO2-SAME: "--lto-CGO0"
+// O0-CGO2-SAME: "--lto-CGO2"
 
 // ALL: "-cc1" "-triple" "x86_64-unknown-linux-gnu"
 // DEFAULT-NOT: "-O{{.}}"
@@ -90,3 +110,5 @@
 // Os-SAME: "-Os"
 // Oz-SAME: "-Oz"
 // Og-SAME: "-Og"
+// O0-CGO2-SAME: "-O0"
+// O0-CGO2-NOT: "--lto-CGO2"



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


[PATCH] D143691: Fix clang-formats IncludeCategory to match the documentation

2023-02-15 Thread Fabian Keßler via Phabricator via cfe-commits
Febbe marked 2 inline comments as done.
Febbe added inline comments.



Comment at: clang/lib/Format/Format.cpp:1379
   LLVMStyle.IncludeStyle.IncludeCategories = {
-  {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0, false},
-  {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0, false},
-  {".*", 1, 0, false}};
+  {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 2, false},
+  {"^(<|\"(gtest|gmock|isl|json)/)", 3, 3, false},

HazardyKnusperkeks wrote:
> Febbe wrote:
> > HazardyKnusperkeks wrote:
> > > I don't follow why this is necessary. And I don't feel comfortable with 
> > > it.
> > This **was** required, but is not required necessarily, my last update of 
> > the patch made this change most likely obsolete.
> > 
> > But the actual reason is, that `SortPriority` is described in the 
> > documentation as "optional value which is defaulted to `Priority`, if 
> > absent", but it is neither a (std::)optional value nor it was defaulted to 
> > Priority if absent.
> > It was indirectly updated from **0** to `Priority` in the algorithm.
> > 
> > Since I moved the buggy, re-initialization of `SortPriority` to the first 
> > initialization:
> > clang/lib/Tooling/Inclusions/IncludeStyle.cpp:L20 this change must also be 
> > covered by the tests: All zero initializations must now be default to 
> > `Priority` to not change the test behavior, which is what you want.
> > 
> > Either by creating a Constructor without `SortPriority`, which defaults to 
> > Priority,
> > creating a factory function, or by doing this for all tests manually.
> > 
> > 
> > Imagine the tests would also test the interpretation of the JSON input. 
> > Then the tests would not require an adjustment to be semantically equal.
> > 
> > But since I added Priority to the sorting after **this** change, this is 
> > kind of irrelevant.
> My main question is, does this change behavior? In either case, please add 
> some tests to show the difference, or the lack thereof.
I removed all changes to the tests, which do not change the behavior.

One test required a change. It assumed, that only one file can be a main 
include, which is, in my opinion, not correct. I've made the change, that all 
files, which are matched as main include are ordered with priority 0 (this 
especially means includes introduced by `IncludeIsMainRegex` and 
`IncludeIsMainSourceRegex`). The previous implementation ignored those, if 
another main file was found earlier. It could also result in unpredictable 
resorting.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143691

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


[PATCH] D144011: [clang]Fix warning for signed conversion

2023-02-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 497703.
yaxunl added a comment.

revised by Fanrui's comments


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

https://reviews.llvm.org/D144011

Files:
  clang/lib/Sema/SemaChecking.cpp
  clang/test/Sema/sign-conversion.c


Index: clang/test/Sema/sign-conversion.c
===
--- clang/test/Sema/sign-conversion.c
+++ clang/test/Sema/sign-conversion.c
@@ -5,4 +5,8 @@
 void test(int x) {
   unsigned t0 = x; // expected-warning {{implicit conversion changes 
signedness}}
   unsigned t1 = (t0 == 5 ? x : 0); // expected-warning {{operand of ? changes 
signedness}}
+
+  // Clang has special treatment for left shift of literal '1'.
+  // Make sure there is no diagnostics.
+  long t2 = 1LL << x;
 }
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -14293,6 +14293,12 @@
 if (S.SourceMgr.isInSystemMacro(CC))
   return;
 
+if (SourceBT && SourceBT->isInteger() && TargetBT &&
+TargetBT->isInteger() &&
+Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
+  return;
+}
+
 unsigned DiagID = diag::warn_impcast_integer_sign;
 
 // Traditionally, gcc has warned about this under -Wsign-compare.


Index: clang/test/Sema/sign-conversion.c
===
--- clang/test/Sema/sign-conversion.c
+++ clang/test/Sema/sign-conversion.c
@@ -5,4 +5,8 @@
 void test(int x) {
   unsigned t0 = x; // expected-warning {{implicit conversion changes signedness}}
   unsigned t1 = (t0 == 5 ? x : 0); // expected-warning {{operand of ? changes signedness}}
+
+  // Clang has special treatment for left shift of literal '1'.
+  // Make sure there is no diagnostics.
+  long t2 = 1LL << x;
 }
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -14293,6 +14293,12 @@
 if (S.SourceMgr.isInSystemMacro(CC))
   return;
 
+if (SourceBT && SourceBT->isInteger() && TargetBT &&
+TargetBT->isInteger() &&
+Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
+  return;
+}
+
 unsigned DiagID = diag::warn_impcast_integer_sign;
 
 // Traditionally, gcc has warned about this under -Wsign-compare.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D144011: [clang]Fix warning for signed conversion

2023-02-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D144011#4126853 , @MaskRay wrote:

> I think it makes sense for `-Wsign-conversion` to not warn for this LP64 
> case, like we don't emit a warning for `-m32`. I do not know whether we need 
> another diagnostic like `-Wshorten-64-to-32` for this case, but am inclined 
> to no.
>
> I wonder whether the newly added condition can be merged with the following 
> condition:
>
>   if ((!isa(Target) || !isa(Source)) &&
>   ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
>(!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
> LikelySourceRange.Width == TargetRange.Width))) {
> if (S.SourceMgr.isInSystemMacro(CC))

Yes. Will do.


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

https://reviews.llvm.org/D144011

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


[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Shangwu Yao via Phabricator via cfe-commits
shangwuyao added a comment.

In D144047#4129247 , @yaxunl wrote:

> In D144047#4129182 , @shangwuyao 
> wrote:
>
>> In D144047#4129154 , @yaxunl wrote:
>>
>>> Making the builtin types consistent is necessary to keep struct layout 
>>> consistent across host and device, but why do we need to make  
>>> __GCC_ATOMIC_XXX_LOCK_FREE macros the same between the host and device? Is 
>>> there any concrete issue if they are not the same?
>>
>> The reason is the same as NVPTX, see 
>> https://github.com/llvm/llvm-project/blob/22882c39df71397cc6f9774d18e87d06e016c55f/clang/lib/Basic/Targets/NVPTX.cpp#L137-L141.
>>  Without it, we won't be able to use libraries that statically check the 
>> __atomic_always_lock_free. I could add the comments in the code if that 
>> makes things more clear.
>
> I see. Better add some comments about that.
>
> This also means backend needs to handle atomic operations not supported by 
> hardware.

Yeah. It is probably the application developer's responsibility to not request 
atomics that are not supported by the hardware?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

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


[PATCH] D143691: Fix clang-formats IncludeCategory to match the documentation

2023-02-15 Thread Fabian Keßler via Phabricator via cfe-commits
Febbe updated this revision to Diff 497701.
Febbe added a comment.

Added requested tests:

- since we now support priorities, equal to 0 (the main include priority) 
sorting should work now for those.
- multiple files can be main-includes now, the tests expects that now.
- negative priorities do not override the main include priority anymore, which 
is also tested


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143691

Files:
  clang/lib/Format/Format.cpp
  clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
  clang/lib/Tooling/Inclusions/IncludeStyle.cpp
  clang/unittests/Format/SortIncludesTest.cpp

Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -8,6 +8,7 @@
 
 #include "FormatTestUtils.h"
 #include "clang/Format/Format.h"
+#include "clang/Tooling/Inclusions/IncludeStyle.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Debug.h"
 #include "gtest/gtest.h"
@@ -535,16 +536,48 @@
  "#include \"b.h\"\n",
  "a.cc"));
 
-  // Only recognize the first #include with a matching basename as main include.
+  // Todo (remove-before-merge): I consider the assumption, that there is only
+  // one main include as wrong.
+  // E.g. a.cpp -> a.priv.h && a.h
+  // E.g. a_test.cpp -> a_test.h && a.h
+  // Maybe add a "//clang-format pragma: not_main" to remove false positives
+
+  // Recognize all possible main #include's with a matching basename as main
+  // include.
+  EXPECT_EQ("#include \"a.h\"\n"
+"#include \"llvm/a.h\"\n"
+"#include \"b.h\"\n"
+"#include \"c.h\"\n",
+sort("#include \"b.h\"\n"
+ "#include \"a.h\"\n"
+ "#include \"c.h\"\n"
+ "#include \"llvm/a.h\"\n",
+ "a.cc"));
+
+  // Keep manually splitted groups in place
   EXPECT_EQ("#include \"a.h\"\n"
 "#include \"b.h\"\n"
 "#include \"c.h\"\n"
+"// no main:\n"
 "#include \"llvm/a.h\"\n",
 sort("#include \"b.h\"\n"
  "#include \"a.h\"\n"
  "#include \"c.h\"\n"
+ "// no main:\n"
  "#include \"llvm/a.h\"\n",
  "a.cc"));
+
+  // Keep both main files together (with priority 0)
+  Style.IncludeIsMainRegex = "([-_](test|unittest))?$";
+  EXPECT_EQ("#include \"a.h\"\n"
+"#include \"a_test.h\"\n"
+"#include \"b.h\"\n"
+"#include \"c.h\"\n",
+sort("#include \"b.h\"\n"
+ "#include \"a.h\"\n"
+ "#include \"c.h\"\n"
+ "#include \"a_test.h\"\n",
+ "a_test.cc"));
 }
 
 TEST_F(SortIncludesTest, LeavesMainHeaderFirstInAdditionalExtensions) {
@@ -762,6 +795,64 @@
  "#include \"c_main.h\"\n"
  "#include \"a_other.h\"\n",
  "c_main.cc", 0));
+  // All negative
+  Style.IncludeCategories = {{".*important_os_header.*", -3, 0, false},
+ {".*", -2, 0, false}};
+
+  EXPECT_EQ("#include \"important_os_header.h\"\n"
+"#include \"a_other.h\"\n"
+"#include \"c_main.h\"\n",
+sort("#include \"c_main.h\"\n"
+ "#include \"a_other.h\"\n"
+ "#include \"important_os_header.h\"\n",
+ "c_main.cc"));
+}
+
+TEST_F(SortIncludesTest, ZeroPriorities) {
+  Style.IncludeCategories = {{".*important_os_header.*", 0, -1, false},
+ {".*", 1, 0, false}};
+  EXPECT_EQ("#include \"important_os_header.h\"\n"
+"#include \"c_main.h\"\n"
+"#include \"a_other.h\"\n",
+sort("#include \"c_main.h\"\n"
+ "#include \"a_other.h\"\n"
+ "#include \"important_os_header.h\"\n",
+ "c_main.cc"));
+
+  // check stable when re-run
+  EXPECT_EQ("#include \"important_os_header.h\"\n"
+"#include \"c_main.h\"\n"
+"#include \"a_other.h\"\n",
+sort("#include \"important_os_header.h\"\n"
+ "#include \"c_main.h\"\n"
+ "#include \"a_other.h\"\n",
+ "c_main.cc", 0));
+
+  // All zero, sorted after name
+  Style.IncludeCategories = {{".*important_os_header.*", 0, 0, false},
+ {".*", 0, 0, false}};
+
+  EXPECT_EQ("#include \"a_other.h\"\n"
+"#include \"c_main.h\"\n"
+"#include \"important_os_header.h\"\n",
+sort("#include \"important_os_header.h\"\n"
+ "#include \"c_main.h\"\n"
+ "#include \"a_other.h\"\n",
+ "c_main.cc"));
+
+  // Grouped:
+  Style.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
+  Style.IncludeCategories = 

[PATCH] D143891: [Clang] Adjust triviality computation in QualType::isTrivialType to C++20 cases.

2023-02-15 Thread Roy Jacobson via Phabricator via cfe-commits
royjacobson added a comment.

It's an interesting discussion, I just want to remind that this change is for 
triviality rules from P0848 (conditionally trivial member functions) which is 
only going to ship in Clang 16 anyway.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143891

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


[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Shangwu Yao via Phabricator via cfe-commits
shangwuyao updated this revision to Diff 497700.
shangwuyao added a comment.

Amend with comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

Files:
  clang/lib/Basic/Targets/SPIR.h
  clang/test/CodeGenCUDASPIRV/cuda-types.cu

Index: clang/test/CodeGenCUDASPIRV/cuda-types.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDASPIRV/cuda-types.cu
@@ -0,0 +1,56 @@
+// Check that types, widths, __CLANG_ATOMIC* macros, etc. match on the host and
+// device sides of CUDA compilations. Note that we filter out long double and
+// maxwidth of _BitInt(), as this is intentionally different on host and device.
+//
+// Also ignore __CLANG_ATOMIC_LLONG_LOCK_FREE on i386. The default host CPU for
+// an i386 triple is typically at least an i586, which has cmpxchg8b (Clang
+// feature, "cx8"). Therefore, __CLANG_ATOMIC_LLONG_LOCK_FREE is 2 on the host,
+// but the value should be 1 for the device.
+//
+// Unlike CUDA, the width of SPIR-V POINTER type could differ between host and
+// device, because SPIR-V explicitly sets POINTER type width. So it is the
+// user's responsibility to choose the offload with the right POINTER size,
+// otherwise the values for __CLANG_ATOMIC_POINTER_LOCK_FREE could be different.
+
+// RUN: mkdir -p %t
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv32 -target i386-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv32 -target i386-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-device-defines-filtered
+// RUN: diff %t/i386-host-defines-filtered %t/i386-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv32 -target i386-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-msvc-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv32 -target i386-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/i386-msvc-device-defines-filtered
+// RUN: diff %t/i386-msvc-host-defines-filtered %t/i386-msvc-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-device-defines-filtered
+// RUN: diff %t/x86_64-host-defines-filtered %t/x86_64-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv64 -target powerpc64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/powerpc64-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv64 -target powerpc64-unknown-linux-gnu -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/powerpc64-device-defines-filtered
+// RUN: diff %t/powerpc64-host-defines-filtered %t/powerpc64-device-defines-filtered
+
+// RUN: %clang --cuda-host-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-msvc-host-defines-filtered
+// RUN: %clang --cuda-device-only -nocudainc -nocudalib --offload=spirv64 -target x86_64-windows-msvc -x cuda -emit-llvm -E -dM -o - /dev/null \
+// RUN:   | grep -E '__CLANG_ATOMIC' \
+// RUN:   | grep -Ev '_ATOMIC_LLONG_LOCK_FREE' > %t/x86_64-msvc-device-defines-filtered
+// RUN: diff %t/x86_64-msvc-host-defines-filtered %t/x86_64-msvc-device-defines-filtered
+
Index: clang/lib/Basic/Targets/SPIR.h
===
--- clang/lib/Basic/Targets/SPIR.h
+++ clang/lib/Basic/Targets/SPIR.h
@@ -13,6 +13,7 @@
 #ifndef LLVM_CLANG_LIB_BASIC_TARGETS_SPIR_H
 #define LLVM_CLANG_LIB_BASIC_TARGETS_SPIR_H
 
+#include "Targets.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TargetOptions.h"
 #include "llvm/Support/Compiler.h"
@@ -79,8 +80,10 @@
 
 // Base 

[PATCH] D143342: [clang-tidy] Support std::format and std::print in readability-redundant-string-cstr

2023-02-15 Thread Mike Crowe via Phabricator via cfe-commits
mikecrowe added a comment.

Thanks for the review and further suggestions.

Mike.




Comment at: 
clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp:181-190
+
+  // Detect redundant 'c_str()' calls in parameters passed to std::print and
+  // std::format.
+  Finder->addMatcher(
+  traverse(
+  TK_AsIs,
+  callExpr(

njames93 wrote:
> Can this be wrapped in a check to make sure it only runs in c++20
> 
> Likewise `::std::print` is only c++23, so maybe:
> ```lang=c++
> getLangOpts().CPlusPlus2B ? hasAnyName("::std::print", "::std::format") : 
> hasAnyName("::std::format")
> ```
I can do that. I had (presumably incorrectly) assumed that since and use of 
`std::print` and `std::format` in any previous version would be UB then it was 
safe to apply the check regardless of the C++ version.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability/redundant-string-cstr.cpp:1
-// RUN: %check_clang_tidy %s readability-redundant-string-cstr %t
+// RUN: %check_clang_tidy -std=c++20 %s readability-redundant-string-cstr %t
 

njames93 wrote:
> We shouldn't be removing tests from older language standards
> Can all the changes made to the file be moved into a new file 
> `redundant-string-cstr-cpp20.cpp`
> Would likely either need to create a second file for c++23 or make use of the 
> check-suffix to run the tests for std::print
My brief reading up on check-suffix implies that it could be used to keep 
everything in `redundant-string-cstr.cpp`, but that file is getting rather 
large anyway. Having `redundant-string-cstr-cpp20.cpp` also containing C++23 
tests might be a bit confusing. Having `redundant-string-cstr-cpp23.cpp` too 
would mean moving the format_args stuff to a header (which might be beneficial 
regardless.)

Anyway, I shall have a play and see what I can make work.

Do I need to add tests to ensure that the checks don't trigger when running 
against earlier standard versions?


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

https://reviews.llvm.org/D143342

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


[PATCH] D144036: [clang-tidy] Add bugprone-enum-to-bool-conversion check

2023-02-15 Thread Piotr Zegar via Phabricator via cfe-commits
ClockMan created this revision.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a reviewer: njames93.
Herald added a project: All.
ClockMan updated this revision to Diff 497408.
ClockMan added a comment.
Eugene.Zelenko added reviewers: aaron.ballman, carlosgalvezp.
ClockMan updated this revision to Diff 497692.
ClockMan published this revision for review.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Removed "Offers fixes" from list.rst


ClockMan added a comment.

Correct copyrights and commit author


ClockMan added a comment.

Ready for review




Comment at: clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.h:28
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
+

Should language be checked for C++?



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-bool-conversion.rst:6
+
+Detect implicit and explicit casts of `enum` type into `bool` where `enum` type
+doesn't have a zero-value enumerator. If `enum` is used only to hold values

Please synchronize first statement with statement in Release Notes. Please use 
double back-ticks for language constructs.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-bool-conversion.rst:49
+
+Default value: '^$'.
+Regexp used to ignore usages of enum declarations that match regexp.

Please use single back-ticks for option values. Default value is usually placed 
after option description.


Detect implicit and explicit conversions of enum to bool,
when enum doesn't have a enumerator with value equal to 0.
In theory such conversion should always return TRUE.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144036

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/EnumToBoolConversionCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/bugprone/enum-to-bool-conversion.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion-cpp11.cpp
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/enum-to-bool-conversion.cpp
@@ -0,0 +1,119 @@
+// RUN: %check_clang_tidy -std=c++98-or-later %s bugprone-enum-to-bool-conversion %t -- \
+// RUN:   -config="{CheckOptions: [{key: bugprone-enum-to-bool-conversion.EnumIgnoreRegexp, value: '^::without::issue::IgnoredEnum$'}]}"
+
+namespace with::issue
+{
+
+typedef enum EStatus
+{
+SUCCESS   = 1,
+FAILURE   = 2,
+INVALID_PARAM = 3,
+UNKNOWN   = 4
+} Status;
+
+bool testEnumConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+bool testTypedefConversion(Status value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:12: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return value;
+}
+
+bool testExplicitConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:30: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return static_cast(value);
+}
+
+bool testInIfConversion(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:9: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+if (value)
+{
+return false;
+}
+
+return true;
+}
+
+bool testWithNegation(EStatus value)
+{
+// CHECK-MESSAGES: :[[@LINE+1]]:16: warning: conversion of 'EStatus' into 'bool' will always return 'true', enum doesn't have a zero-value enumerator [bugprone-enum-to-bool-conversion]
+return not value;
+}
+
+}
+
+namespace without::issue
+{
+
+enum StatusWithZero
+{
+UNK  = 0,
+OK   = 1,
+NOT_OK = 2
+};
+
+bool testEnumConversion(StatusWithZero value)
+{
+return value;
+}
+
+enum WithDefault
+{
+Value0,
+Value1
+};
+
+bool testEnumConversion(WithDefault value)
+{
+return value;
+}
+
+enum WithNegative : int
+{
+Nen2 = -2,
+Nen1,
+Nen0
+};
+
+bool testEnumConversion(WithNegative value)
+{
+return value;
+}
+
+enum EStatus
+{
+SUCCESS = 1,
+

[PATCH] D143891: [Clang] Adjust triviality computation in QualType::isTrivialType to C++20 cases.

2023-02-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added a subscriber: rsmith.
erichkeane added a comment.

In D143891#4129214 , 
@hubert.reinterpretcast wrote:

> In D143891#4122660 , @aaron.ballman 
> wrote:
>
>> This is an ABI breaking change, isn't it? (The type trait now returns 
>> something different than it did before, which could change instantiations or 
>> object layout.)
>
> In my opinion, this is an argument for not fixing in a fix release of a 
> specific version of Clang--not an argument for additional option control in 
> new versions.
> Instantiations change all the time from changes to constant expression 
> evaluation, overload resolution, partial ordering rules for templates, etc.
> As for object layout, I believe the language and the ABI rules for triviality 
> diverged quite some time ago.
>
> I know that the evaluation for this specific case was that we don't need to 
> apply ABI versioning control for this because it only affects code using 
> Concepts, but I think we will eventually need to (re)discover when ABI 
> versioning control is the appropriate tool.
>
> I propose an action item: Someone needed to review past application of the 
> ABI versioning options to see if we can extract and document workable 
> criteria (perhaps in https://clang.llvm.org/docs/InternalsManual.html).

Before doing that amount of work, I'd see if we could convince @rsmith to just 
share what his rule for this was, I think it was quite reasonable the few times 
he enforced it, and he can likely better state it at least.  Even if he were to 
share here, I'm sure one of us would be willing to clean up his statement and 
put it in the Internals Manual.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143891

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


[PATCH] D143342: [clang-tidy] Support std::format and std::print in readability-redundant-string-cstr

2023-02-15 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

Just a few more points then it should be good to land




Comment at: 
clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp:181-190
+
+  // Detect redundant 'c_str()' calls in parameters passed to std::print and
+  // std::format.
+  Finder->addMatcher(
+  traverse(
+  TK_AsIs,
+  callExpr(

Can this be wrapped in a check to make sure it only runs in c++20

Likewise `::std::print` is only c++23, so maybe:
```lang=c++
getLangOpts().CPlusPlus2B ? hasAnyName("::std::print", "::std::format") : 
hasAnyName("::std::format")
```



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/readability/redundant-string-cstr.cpp:1
-// RUN: %check_clang_tidy %s readability-redundant-string-cstr %t
+// RUN: %check_clang_tidy -std=c++20 %s readability-redundant-string-cstr %t
 

We shouldn't be removing tests from older language standards
Can all the changes made to the file be moved into a new file 
`redundant-string-cstr-cpp20.cpp`
Would likely either need to create a second file for c++23 or make use of the 
check-suffix to run the tests for std::print


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

https://reviews.llvm.org/D143342

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


[PATCH] D143691: Fix clang-formats IncludeCategory to match the documentation

2023-02-15 Thread Fabian Keßler via Phabricator via cfe-commits
Febbe updated this revision to Diff 497687.
Febbe marked 3 inline comments as done.
Febbe added a comment.

- Removed some, not required changes.
- Reverted mapOptional -> mapRequired change, since it might break existing 
configs


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143691

Files:
  clang/lib/Format/Format.cpp
  clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
  clang/lib/Tooling/Inclusions/IncludeStyle.cpp
  clang/unittests/Format/SortIncludesTest.cpp

Index: clang/unittests/Format/SortIncludesTest.cpp
===
--- clang/unittests/Format/SortIncludesTest.cpp
+++ clang/unittests/Format/SortIncludesTest.cpp
@@ -535,11 +535,18 @@
  "#include \"b.h\"\n",
  "a.cc"));
 
-  // Only recognize the first #include with a matching basename as main include.
+  // Todo (remove-before-merge): I consider the assumption, that there is only
+  // one main include as wrong.
+  // E.g. a.cpp -> a.priv.h && a.h
+  // E.g. a_test.cpp -> a_test.h && a.h
+  // Maybe add a "//clang-format pragma: not_main" to remove false positives
+
+  // Recognize all possible main #include's with a matching basename as main
+  // include.
   EXPECT_EQ("#include \"a.h\"\n"
+"#include \"llvm/a.h\"\n"
 "#include \"b.h\"\n"
-"#include \"c.h\"\n"
-"#include \"llvm/a.h\"\n",
+"#include \"c.h\"\n",
 sort("#include \"b.h\"\n"
  "#include \"a.h\"\n"
  "#include \"c.h\"\n"
Index: clang/lib/Tooling/Inclusions/IncludeStyle.cpp
===
--- clang/lib/Tooling/Inclusions/IncludeStyle.cpp
+++ clang/lib/Tooling/Inclusions/IncludeStyle.cpp
@@ -7,17 +7,26 @@
 //===--===//
 
 #include "clang/Tooling/Inclusions/IncludeStyle.h"
+#include 
 
 using clang::tooling::IncludeStyle;
 
 namespace llvm {
 namespace yaml {
 
+// Todo (remove before merge): changes here are required,
+// because the explicit override for the default values of 0 are moved from
+// the algorithm to this place
+// Since we can't make those values required, we must set the previously
+// intended default values here, to prevent behaviour changes.
+
+constexpr int DefaultPriority = std::numeric_limits::max();
+
 void MappingTraits::mapping(
 IO , IncludeStyle::IncludeCategory ) {
   IO.mapOptional("Regex", Category.Regex);
-  IO.mapOptional("Priority", Category.Priority);
-  IO.mapOptional("SortPriority", Category.SortPriority);
+  IO.mapOptional("Priority", Category.Priority, DefaultPriority);
+  IO.mapOptional("SortPriority", Category.SortPriority, Category.Priority);
   IO.mapOptional("CaseSensitive", Category.RegexIsCaseSensitive);
 }
 
Index: clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
===
--- clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
+++ clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
@@ -12,6 +12,7 @@
 #include "clang/Lex/Lexer.h"
 #include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/Path.h"
+#include 
 #include 
 
 namespace clang {
@@ -206,33 +207,33 @@
   }
 }
 
+constexpr int DefaultMainIncludePriority = 0;
+constexpr int DefaultMainIncludeSortPriority = 0;
+
 int IncludeCategoryManager::getIncludePriority(StringRef IncludeName,
bool CheckMainHeader) const {
-  int Ret = INT_MAX;
+  if (CheckMainHeader && IsMainFile && isMainHeader(IncludeName))
+return DefaultMainIncludePriority;
+
   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
-if (CategoryRegexs[i].match(IncludeName)) {
-  Ret = Style.IncludeCategories[i].Priority;
-  break;
-}
-  if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
-Ret = 0;
-  return Ret;
+if (CategoryRegexs[i].match(IncludeName))
+  return Style.IncludeCategories[i].Priority;
+
+  return std::numeric_limits::max();
 }
 
 int IncludeCategoryManager::getSortIncludePriority(StringRef IncludeName,
bool CheckMainHeader) const {
-  int Ret = INT_MAX;
+  if (CheckMainHeader && IsMainFile && isMainHeader(IncludeName))
+return DefaultMainIncludeSortPriority;
+
   for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
-if (CategoryRegexs[i].match(IncludeName)) {
-  Ret = Style.IncludeCategories[i].SortPriority;
-  if (Ret == 0)
-Ret = Style.IncludeCategories[i].Priority;
-  break;
-}
-  if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
-Ret = 0;
-  return Ret;
+if (CategoryRegexs[i].match(IncludeName))
+  return Style.IncludeCategories[i].SortPriority;
+
+  return std::numeric_limits::max();
 }
+
 bool 

[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D144047#4129182 , @shangwuyao 
wrote:

> In D144047#4129154 , @yaxunl wrote:
>
>> Making the builtin types consistent is necessary to keep struct layout 
>> consistent across host and device, but why do we need to make  
>> __GCC_ATOMIC_XXX_LOCK_FREE macros the same between the host and device? Is 
>> there any concrete issue if they are not the same?
>
> The reason is the same as NVPTX, see 
> https://github.com/llvm/llvm-project/blob/22882c39df71397cc6f9774d18e87d06e016c55f/clang/lib/Basic/Targets/NVPTX.cpp#L137-L141.
>  Without it, we won't be able to use libraries that statically check the 
> __atomic_always_lock_free. I could add the comments in the code if that makes 
> things more clear.

I see. Better add some comments about that.

This also means backend needs to handle atomic operations not supported by 
hardware.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

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


[PATCH] D143891: [Clang] Adjust triviality computation in QualType::isTrivialType to C++20 cases.

2023-02-15 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

In D143891#4122660 , @aaron.ballman 
wrote:

> This is an ABI breaking change, isn't it? (The type trait now returns 
> something different than it did before, which could change instantiations or 
> object layout.)

In my opinion, this is an argument for not fixing in a fix release of a 
specific version of Clang--not an argument for additional option control in new 
versions.
Instantiations change all the time from changes to constant expression 
evaluation, overload resolution, partial ordering rules for templates, etc.
As for object layout, I believe the language and the ABI rules for triviality 
diverged quite some time ago.

I know that the evaluation for this specific case was that we don't need to 
apply ABI versioning control for this because it only affects code using 
Concepts, but I think we will eventually need to (re)discover when ABI 
versioning control is the appropriate tool.

I propose an action item: Someone needed to review past application of the ABI 
versioning options to see if we can extract and document workable criteria 
(perhaps in https://clang.llvm.org/docs/InternalsManual.html).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143891

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


[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Shangwu Yao via Phabricator via cfe-commits
shangwuyao added a comment.

In D144047#4129154 , @yaxunl wrote:

> Making the builtin types consistent is necessary to keep struct layout 
> consistent across host and device, but why do we need to make  
> __GCC_ATOMIC_XXX_LOCK_FREE macros the same between the host and device? Is 
> there any concrete issue if they are not the same?

The reason is the same as NVPTX, see 
https://github.com/llvm/llvm-project/blob/22882c39df71397cc6f9774d18e87d06e016c55f/clang/lib/Basic/Targets/NVPTX.cpp#L137-L141.
 Without it, we won't be able to use libraries that statically check the 
__atomic_always_lock_free. I could add the comments in the code if that makes 
things more clear.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

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


[PATCH] D143920: [clang][dataflow] Change `transfer` API to take a reference.

2023-02-15 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6b991ba486b6: [clang][dataflow] Change `transfer` API to 
take a reference. (authored by ymandel).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143920

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h
  
clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
  clang/include/clang/Analysis/FlowSensitive/NoopAnalysis.h
  clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
  clang/lib/Analysis/FlowSensitive/Models/ChromiumCheckModel.cpp
  clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
  clang/unittests/Analysis/FlowSensitive/ChromiumCheckModelTest.cpp
  clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
  clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
  clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
  clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -112,7 +112,7 @@
 
   static NonConvergingLattice initialElement() { return {0}; }
 
-  void transfer(const CFGElement *, NonConvergingLattice , Environment &) {
+  void transfer(const CFGElement &, NonConvergingLattice , Environment &) {
 ++E.State;
   }
 };
@@ -194,8 +194,8 @@
 
   static FunctionCallLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, FunctionCallLattice , Environment &) {
-auto CS = Elt->getAs();
+  void transfer(const CFGElement , FunctionCallLattice , Environment &) {
+auto CS = Elt.getAs();
 if (!CS)
   return;
 const auto *S = CS->getStmt();
@@ -350,8 +350,8 @@
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, NoopLattice &, Environment ) {
-auto CS = Elt->getAs();
+  void transfer(const CFGElement , NoopLattice &, Environment ) {
+auto CS = Elt.getAs();
 if (!CS)
   return;
 const auto *S = CS->getStmt();
@@ -508,8 +508,8 @@
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, NoopLattice &, Environment ) {
-auto CS = Elt->getAs();
+  void transfer(const CFGElement , NoopLattice &, Environment ) {
+auto CS = Elt.getAs();
 if (!CS)
   return;
 const Stmt *S = CS->getStmt();
@@ -1202,8 +1202,8 @@
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, NoopLattice &, Environment ) {
-auto CS = Elt->getAs();
+  void transfer(const CFGElement , NoopLattice &, Environment ) {
+auto CS = Elt.getAs();
 if (!CS)
   return;
 const Stmt *S = CS->getStmt();
Index: clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
@@ -44,7 +44,7 @@
   explicit TestPropagationAnalysis(ASTContext )
   : DataflowAnalysis(Context) {}
   static TestLattice initialElement() { return TestLattice::bottom(); }
-  void transfer(const CFGElement *, TestLattice &, Environment &) {}
+  void transfer(const CFGElement &, TestLattice &, Environment &) {}
   void transferBranch(bool Branch, const Stmt *S, TestLattice ,
   Environment ) {
 L.Branch = Branch;
Index: clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
@@ -124,9 +124,9 @@
 return ConstantPropagationLattice::bottom();
   }
 
-  void transfer(const CFGElement *E, ConstantPropagationLattice ,
+  void transfer(const CFGElement , ConstantPropagationLattice ,
 Environment ) {
-auto CS = E->getAs();
+auto CS = E.getAs();
 if (!CS)
   return;
 auto S = CS->getStmt();
Index: clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
@@ -330,9 +330,9 @@
 
   static NoopLattice initialElement() { return {}; }
 
-  void 

[clang] 6b991ba - [clang][dataflow] Change `transfer` API to take a reference.

2023-02-15 Thread Yitzhak Mandelbaum via cfe-commits

Author: Yitzhak Mandelbaum
Date: 2023-02-15T15:37:21Z
New Revision: 6b991ba486b64f09e7d90ebc1fc2118ab48c8bff

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

LOG: [clang][dataflow] Change `transfer` API to take a reference.

The provided `CFGElement` is never null, so a reference is a more precise type.

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

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h

clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
clang/include/clang/Analysis/FlowSensitive/NoopAnalysis.h
clang/include/clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h
clang/lib/Analysis/FlowSensitive/Models/ChromiumCheckModel.cpp
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
clang/unittests/Analysis/FlowSensitive/ChromiumCheckModelTest.cpp
clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
clang/unittests/Analysis/FlowSensitive/SignAnalysisTest.cpp
clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
clang/unittests/Analysis/FlowSensitive/TransferBranchTest.cpp
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
index d7ca721246757..3be29cfed0a9c 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowAnalysis.h
@@ -41,7 +41,7 @@ namespace dataflow {
 ///  must provide the following public members:
 ///   * `LatticeT initialElement()` - returns a lattice element that models the
 /// initial state of a basic block;
-///   * `void transfer(const CFGElement *, LatticeT &, Environment &)` - 
applies
+///   * `void transfer(const CFGElement &, LatticeT &, Environment &)` - 
applies
 /// the analysis transfer function for a given CFG element and lattice
 /// element.
 ///
@@ -122,8 +122,7 @@ class DataflowAnalysis : public TypeErasedDataflowAnalysis {
   void transferTypeErased(const CFGElement , TypeErasedLattice ,
   Environment ) final {
 Lattice  = llvm::any_cast(E.Value);
-// FIXME: change the contract of `transfer` to take a reference.
-static_cast(this)->transfer(, L, Env);
+static_cast(this)->transfer(Element, L, Env);
   }
 
   void transferBranchTypeErased(bool Branch, const Stmt *Stmt,
@@ -239,7 +238,7 @@ runDataflowAnalysis(
 class DataflowModel : public Environment::ValueModel {
 public:
   /// Return value indicates whether the model processed the `Element`.
-  virtual bool transfer(const CFGElement *Element, Environment ) = 0;
+  virtual bool transfer(const CFGElement , Environment ) = 0;
 };
 
 } // namespace dataflow

diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h 
b/clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h
index e65f40b0b726e..b4315e41d79fa 100644
--- a/clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h
+++ b/clang/include/clang/Analysis/FlowSensitive/Models/ChromiumCheckModel.h
@@ -13,7 +13,6 @@
 #define CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_CHROMIUMCHECKMODEL_H
 
 #include "clang/AST/DeclCXX.h"
-#include "clang/AST/Stmt.h"
 #include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "llvm/ADT/DenseSet.h"
@@ -26,7 +25,7 @@ namespace dataflow {
 class ChromiumCheckModel : public DataflowModel {
 public:
   ChromiumCheckModel() = default;
-  bool transfer(const CFGElement *Element, Environment ) override;
+  bool transfer(const CFGElement , Environment ) override;
 
 private:
   /// Declarations for `::logging::CheckError::.*Check`, lazily initialized.

diff  --git 
a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
 
b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
index 2d52ee5fc846d..23dfdd49e94d9 100644
--- 
a/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
+++ 
b/clang/include/clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h
@@ -52,7 +52,7 @@ class UncheckedOptionalAccessModel
 
   static NoopLattice initialElement() { return {}; }
 
-  void transfer(const CFGElement *Elt, NoopLattice , Environment );
+  void transfer(const CFGElement , NoopLattice , Environment );
 
   ComparisonResult compare(QualType Type, const Value ,
const Environment , const Value ,

diff  --git 

[PATCH] D138037: [analyzer] Remove unjustified assertion from EQClass::simplify

2023-02-15 Thread Gábor Horváth via Phabricator via cfe-commits
xazax.hun added a comment.

I am ok with committing this to unblock people hitting this assert, but at the 
same time I wonder if we want to open a ticket on GitHub that we might want to 
rethink how some of this works.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138037

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


[PATCH] D142822: [clang] ASTImporter: Fix importing of va_list types and declarations

2023-02-15 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

But there should be a way to make the namespace "invisible" like it is done 
with `std::bad_alloc`, the linked commit seems to contain the code to "hide" 
the first std definition and this may not work any more. Another question is 
why this architecture has a probably not standard requirement. This may be a 
question for the discourse forum to reach the developers that can make a 
working fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142822

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


[PATCH] D144041: [clang-tidy] add primitive types for hungarian identifier-naming (unsigned char and void)

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

LGTM!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144041

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


[PATCH] D144047: [CUDA][SPIRV] Match builtin types and __GCC_ATOMIC_XXX_LOCK_FREE macros on host/device

2023-02-15 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

Making the builtin types consistent is necessary to keep struct layout 
consistent across host and device, but why do we need to make  
__GCC_ATOMIC_XXX_LOCK_FREE macros the same between the host and device? Is 
there any concrete issue if they are not the same?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144047

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


[PATCH] D144037: [clang-tidy] allow tests to use -config-file instead of -config

2023-02-15 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp requested changes to this revision.
carlosgalvezp added a comment.
This revision now requires changes to proceed.

LGTM except the comments left by other reviewers! Marking it as "Request 
Changes" for visibility.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144037

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


[PATCH] D142822: [clang] ASTImporter: Fix importing of va_list types and declarations

2023-02-15 Thread Whisperity via Phabricator via cfe-commits
whisperity added subscribers: rsmith, whisperity.
whisperity added a comment.

In D142822#4095896 , @DavidSpickett 
wrote:

>   
> /home/david.spickett/llvm-project/clang/test/CodeGenCXX/cxx20-module-std-subst-2b.cpp:14:18:
>  error: reference to 'std' is ambiguous
>   void f(str> ) {
>^
>   
> /home/david.spickett/llvm-project/clang/test/CodeGenCXX/cxx20-module-std-subst-2b.cpp:7:11:
>  note: candidate found by name lookup is 'std'
>   namespace std {
> ^

This looks like an ouchie of the highest order. I've been looking into 
Modules... 5-ish years ago, when it was still under design. There are two major 
concerns here, one is that we've been having a feature called //"Modules"// 
which was very Clang-specific (but a good proof-of-concept spiritual 
predecessor of what became the Standard Modules), and there are the standard 
modules. Now the file name explicitly mentions `cxx20` so this is likely about 
Standard Modules stuff. But to be fair, I'd take this implementation with a 
pinch of salt. Due to the lack of build-system support for Modules (there are 
some murmurs these days on the CMake GitLab about very soon adding meaningful 
support for this...) we do not really seem to have large-scale real-world 
experience as to how the standard really could be made working, **especially** 
in such a weird case like touching `namespace std` which //might// not be 
standards-compliant in the first place. (But yeah, we are test code here in a 
compiler; we can cut ourselves some slack.)

The code itself in these test files is really weird; it seems the test is 
centred around the idea that there are:

  // TU "A"
  module; // Code in the *global module fragment*
  namespace std { /* ... */ class basic_string; }
  
  export module Whatever; // Code in the public module interface unit of module 
Whatever.
  export /* ... */ using str = std::basic_string<...>;

So we have a symbol called `str`, which is publicly visible (to TUs importing 
`Whatever`), and the `namespace std` preceding `Whatever` in `TU "A"` is 
**not** visible but **reachable**? (The standard's way of expressing 
reachability is a kind of a mess , so I'd 
**definitely** try finding the people who worked in developing the actual 
solution that makes Standard Modules //work// in Clang... call the help of 
someone who's really expert on the Standard...) Perhaps @rsmith could help us 
clarify this situation.

You can't name `std::basic_string<...>` in the client code (because it is not 
//visible//), but you can depend on the symbol (e.g., `decltype` it to an 
alias!) because it is //reachable//!

And then you have

  // TU "B"
  import Whatever;
  
  namespace std { /* ... */ struct char_traits {}; }
  
  // use Sb mangling, not Ss, as this is not global-module std::char_traits
  /* ... */
  void f(str<..., std::char_traits<...>>)

In which there is "another" (?) `namespace std`, which should(??) also be part 
of the global module :

> The //global module// is the collection of all //global-module-fragments// 
> and all translation units that are not module units. Declarations appearing 
> in such a context are said to be in the //purview// of the global module.

I believe that `TU "B"` is **not** a module unit... But the comment (which is 
somehow misformatted?) in it would like to say that this `std` is, in fact, 
//not// part of the global module.

So somehow, the changes in this patch are making //both// `std`s part of the 
same //purview// (whatever that means, really...), thus resulting in ambiguity.

- Does this only happen on non-X86? @vabridgers, you could try adding a 
`--target=` flag locally in the test file to the compiler invocation and 
re-running the tests to verify. (Might need an LLVM build that is capable of 
generating code of other architectures.)
- My other suggestion would be putting some `->dump()` calls in your change, 
running the code and observing how the ASTs are looking in the states when 
execution is within the functions you're trying to change.




Comment at: clang/test/AST/ast-dump-traits.cpp:55
 // CHECK-NEXT: | `-ExpressionTraitExpr {{.*}}  'bool' 
__is_lvalue_expr
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:30:6{{( 
imported)?}} test_unary_expr_or_type_trait 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:30:6{{( 
imported)?}} test_unary_expr_or_type_trait 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

How is this change legit? Is this `FunctionDecl` node just "floating"? If so, 
why is there a `-` preceding in the textual dump? Usually top-level nodes do 
not have such a prefix.



Comment at: clang/test/AST/fixed_point.c:405
 
-//CHECK-NEXT: `-VarDecl {{.*}} literallast '_Accum' cinit
+//CHECK-NEXT:  -VarDecl {{.*}} literallast '_Accum' cinit
 //CHECK-NEXT:   `-FixedPointLiteral {{.*}} '_Accum' 1.0

[PATCH] D144037: [clang-tidy] allow tests to use -config-file instead of -config

2023-02-15 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: clang-tools-extra/test/clang-tidy/check_clang_tidy.py:111
 if not any(
-[arg.startswith('-config=') for arg in self.clang_tidy_extra_args]):
+[arg.startswith('-config=') or arg.startswith('-config-file=') for arg 
in self.clang_tidy_extra_args]):
   self.clang_tidy_extra_args.append('-config={}')

ClockMan wrote:
> clang-tidy works with -config and with --config.
> But in documentation there is --config.
> 
> This python script should be updated to accept both single and double dash 
> arguments for config.
Please follow 80 characters limit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144037

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


[PATCH] D142604: [Clang] Fix __VA_OPT__ implementation so that it treats the concatenation of a non-placemaker token and placemaker token as a non-placemaker token

2023-02-15 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

I suspect the libc++ failure is because the patch is not rebased onto `main`. I 
remember seeing those issues a while back. I think it's unlikely to be this 
patch.


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

https://reviews.llvm.org/D142604

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


[PATCH] D142822: [clang] ASTImporter: Fix importing of va_list types and declarations

2023-02-15 Thread Donát Nagy via Phabricator via cfe-commits
donat.nagy added a comment.

In D142822#4102795 , @balazske wrote:

> I looked at some of the failing tests but can not decide how to fix the 
> problems. The problem seems to be with the extra `namespace std` that was not 
> there before. I do not know what the tests are exactly testing. A part of the 
> tests can be fixed by adding new expect lines but these must be platform 
> specific.

It seems that your change in `Sema.cpp` creates the `std` namespace (or makes 
it visible?) in some situations where it's not declared by the code and should 
not be visible. I suspect that this behavior of your commit is not compliant 
with the standard, and there is precedent that Clang code pays attention to 
avoiding this sort of thing. For example commit 87f54060 

  introduces the simple testcase

  int *use_new(int N) {
return new int [N];
  }
  
  int std = 17;

which ensures that the `std` namespace is not visible even if a reference to 
`operator new` (whose full type references `std:bad_alloc`) is present.

I think the commit needs to be updated to avoid "leaking" the `std` namespace 
into code that do not declare it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D142822

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


[PATCH] D143210: PowerPC] Include vector bool and pixel when emitting lax warning

2023-02-15 Thread Amy Kwan via Phabricator via cfe-commits
amyk added inline comments.



Comment at: clang/lib/Sema/SemaExpr.cpp:9845
 if (anyAltivecTypes(RHSType, LHSType) &&
-!areSameVectorElemTypes(RHSType, LHSType))
+!Context.areCompatibleVectorTypes(RHSType, LHSType))
   Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)

Might be a silly question, but what does it mean to be a "compatible" vector 
type?



Comment at: clang/test/CodeGen/SystemZ/zvector.c:1
-// RUN: %clang_cc1 -triple s390x-linux-gnu -target-cpu z13 -fzvector 
-emit-llvm -o - -W -Wall -Werror %s | opt -S -passes=mem2reg | FileCheck %s
+// RUN: %clang_cc1 -triple s390x-linux-gnu -target-cpu z13 -fzvector 
-emit-llvm -o - -W -Wall -Werror -Wno-error=deprecate-lax-vec-conv-all \
+// RUN: %s | opt -S -passes=mem2reg | FileCheck %s

Nit: I think this line is still over 80 characters.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143210

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


[PATCH] D143430: [C2x] Implement the `unreachable` macro for WG14 N2826

2023-02-15 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Headers/stddef.h:108
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */

aaron.ballman wrote:
> erichkeane wrote:
> > Is this REALLY required to be a macro by standard?  Is it so they don't 
> > have to steal the word/can do #undef?  This is going to result in a worse 
> > diagnostic here any time we diagnose on this line.
> Yes, it's required to be a macro by the C standard.  According to my personal 
> notes:
> 
> This led us up to a preference poll, does WG14 prefer the syntax variant over 
> the macro variant in N2826? 3/12/5 (no consensus). Does WG14 prefer to put 
> the macro into  as in N2826 in C23? 11/2/7 (consensus). Does WG14 
> want to adopt the unreachable feature Change 5 & 6 with stddef.h in place of 
> HEADER.h into C23? 13/2/6 (consensus).
> 
> I don't think the diagnostic behavior here will be any different than for 
> `offsetof` (defined a few lines below), right?
`offsetof` is what made me ask this question :D I guess we do the whole 
'macro-like' escape in other places, but everything here is already crap, so I 
guess this is no different.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143430

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


[PATCH] D143430: [C2x] Implement the `unreachable` macro for WG14 N2826

2023-02-15 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Headers/stddef.h:108
+__STDC_VERSION__ >= 202000L
+#define unreachable() __builtin_unreachable()
+#endif /* defined(__need_STDDEF_H_misc) && >= C23 */

erichkeane wrote:
> Is this REALLY required to be a macro by standard?  Is it so they don't have 
> to steal the word/can do #undef?  This is going to result in a worse 
> diagnostic here any time we diagnose on this line.
Yes, it's required to be a macro by the C standard.  According to my personal 
notes:

This led us up to a preference poll, does WG14 prefer the syntax variant over 
the macro variant in N2826? 3/12/5 (no consensus). Does WG14 prefer to put the 
macro into  as in N2826 in C23? 11/2/7 (consensus). Does WG14 want to 
adopt the unreachable feature Change 5 & 6 with stddef.h in place of HEADER.h 
into C23? 13/2/6 (consensus).

I don't think the diagnostic behavior here will be any different than for 
`offsetof` (defined a few lines below), right?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143430

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


[PATCH] D143142: [clang][lex] Enable Lexer to grow its buffer

2023-02-15 Thread David Rector via Phabricator via cfe-commits
davrec added a comment.

Only had a chance to give it a once over, I will look through more closely 
later, def by this weekend.  Main thing is I think we shouldn't be exposing the 
buffer pointers after this change, i.e. no public function should return `const 
char *`, unless I'm missing something.  If that box is checked and performance 
cost is negligible I'd give this the thumbs up.




Comment at: clang/include/clang/Lex/Lexer.h:307
   /// Return the current location in the buffer.
-  const char *getBufferLocation() const { return BufferPtr; }
+  const char *getBufferLocation() const {
+assert(BufferOffset <= BufferSize && "Invalid buffer state");

I think I'd like this to return `unsigned`; i.e. I think after this patch we 
should not even be publicly exposing buffer locations as pointers, IIUC.  A 
brief search for uses of `getBufferLocation()` (there aren't many) suggests 
this would be probably be fine and indeed would get rid of some unnecessary 
pointer arithmetic.  And indeed if anything really needs that `const char *` 
that might be a red flag to investigate further.



Comment at: clang/include/clang/Lex/Lexer.h:609
 
-  bool CheckUnicodeWhitespace(Token , uint32_t C, const char *CurPtr);
+  bool CheckUnicodeWhitespace(Token , uint32_t C, unsigned CurOffset);
 

FWIW it sucks that `uint32_t` is already sprinkled throughout the interface 
alongside `unsigned`, wish just one was used consistently, but that does not 
need to be addressed in this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143142

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


[PATCH] D144100: [clang] Fix a bug that allowed some overflowing octal escape sequences

2023-02-15 Thread Sergei Barannikov via Phabricator via cfe-commits
barannikov88 created this revision.
Herald added a project: All.
barannikov88 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144100

Files:
  clang/lib/Lex/LiteralSupport.cpp
  clang/test/Lexer/char-escapes-delimited.c


Index: clang/test/Lexer/char-escapes-delimited.c
===
--- clang/test/Lexer/char-escapes-delimited.c
+++ clang/test/Lexer/char-escapes-delimited.c
@@ -58,6 +58,8 @@
 #if __WCHAR_MAX__ > 0x
   unsigned d = L'\o{377}'; // ext-warning {{extension}} cxx2b-warning 
{{C++2b}}
   unsigned e = L'\o{400}'; // expected-error {{octal escape sequence 
out of range}}
+  unsigned f = L'\o{1000}'; // expected-error {{octal escape sequence 
out of range}}
+  unsigned g = L'\o{2000}'; // expected-error {{octal escape sequence 
out of range}}
 #else
   unsigned d = L'\o{17}'; // ext-warning {{extension}} cxx2b-warning 
{{C++2b}}
   unsigned e = L'\o{20}'; // expected-error {{octal escape sequence out of 
range}}
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -263,7 +263,8 @@
 ThisTokBuf++;
 continue;
   }
-  if (ResultChar & 0x02000)
+  // About to shift out a digit?
+  if (ResultChar & 0xE000)
 Overflow = true;
 
   ResultChar <<= 3;


Index: clang/test/Lexer/char-escapes-delimited.c
===
--- clang/test/Lexer/char-escapes-delimited.c
+++ clang/test/Lexer/char-escapes-delimited.c
@@ -58,6 +58,8 @@
 #if __WCHAR_MAX__ > 0x
   unsigned d = L'\o{377}'; // ext-warning {{extension}} cxx2b-warning {{C++2b}}
   unsigned e = L'\o{400}'; // expected-error {{octal escape sequence out of range}}
+  unsigned f = L'\o{1000}'; // expected-error {{octal escape sequence out of range}}
+  unsigned g = L'\o{2000}'; // expected-error {{octal escape sequence out of range}}
 #else
   unsigned d = L'\o{17}'; // ext-warning {{extension}} cxx2b-warning {{C++2b}}
   unsigned e = L'\o{20}'; // expected-error {{octal escape sequence out of range}}
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -263,7 +263,8 @@
 ThisTokBuf++;
 continue;
   }
-  if (ResultChar & 0x02000)
+  // About to shift out a digit?
+  if (ResultChar & 0xE000)
 Overflow = true;
 
   ResultChar <<= 3;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D138777: [clang-tidy] Add check bugprone-multiple-new-in-one-expression.

2023-02-15 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 497654.
balazske added a comment.

make check available in all C++ versions, add compound operator related test 
and code


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138777

Files:
  clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
  clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
  clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp
  clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/multiple-new-in-one-expression.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/multiple-new-in-one-expression.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/multiple-new-in-one-expression.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/multiple-new-in-one-expression.cpp
@@ -0,0 +1,183 @@
+// RUN: %check_clang_tidy -std=c++11 -check-suffixes=ALL,CPP11 %s bugprone-multiple-new-in-one-expression %t
+// RUN: %check_clang_tidy -std=c++17 -check-suffixes=ALL,CPP17 %s bugprone-multiple-new-in-one-expression %t
+
+namespace std {
+typedef __typeof__(sizeof(0)) size_t;
+enum class align_val_t : std::size_t {};
+class exception {};
+class bad_alloc : public exception {};
+struct nothrow_t {};
+extern const nothrow_t nothrow;
+} // namespace std
+
+void *operator new(std::size_t, const std::nothrow_t &) noexcept;
+void *operator new(std::size_t, std::align_val_t, const std::nothrow_t &) noexcept;
+void *operator new(std::size_t, void *) noexcept;
+void *operator new(std::size_t, char);
+
+struct B;
+
+struct A { int VarI; int *PtrI; B *PtrB; };
+
+struct B { int VarI; };
+
+struct G {
+  G(A*, B*) {}
+  int operator+=(A *) { return 3; };
+};
+
+int f(int);
+int f(A*);
+int f(A*, B*);
+int f(int, B*);
+int f(G, G);
+int f(B*);
+void f1(void *, void *);
+A *g(A *);
+
+G operator+(const G&, const G&);
+
+void test_function_parameter(A *XA, B *XB) {
+  (void)f(new A, new B);
+  try {
+(void)f(new A, new B);
+  }
+  catch (A) {};
+  try {
+(void)f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:13: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception; order of these allocations is undefined [
+(void)f(f(new A, new B));
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+int X = f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:11: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = 1 + f(new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+
+(void)f(g(new A), new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+
+(void)f(1 + f(new A), new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:19: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+(void)f(XA = new A, new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:18: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+(void)f(1 + f(new A), XB = new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:19: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+  }
+  catch (std::exception) {}
+}
+
+void test_operator(G *G1) {
+  (void)(f(new A) + f(new B));
+  try {
+(void)(f(new A) + f(new B));
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:14: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+(void)f(f(new A) + f(new B));
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+int X = f(new A) + f(new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = f(new A) + f(new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:11: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+X = 1 + f(new A) + 1 + f(new B);
+ // CHECK-MESSAGES-ALL: :[[@LINE-1]]:15: warning: memory allocation may leak if an other allocation is sequenced after it and throws an exception;
+
+

[PATCH] D144074: [clangd] Hide inlay hints when using a macro as a calling argument that with a param comment

2023-02-15 Thread Younan Zhang via Phabricator via cfe-commits
zyounan created this revision.
Herald added subscribers: kadircet, arphaman.
Herald added a project: All.
zyounan added reviewers: kadircet, nridge.
zyounan added a comment.
zyounan retitled this revision from "[clangd] Hide extra inlay hints for macro 
as argument" to "[clangd] Hide inlay hints when using a macro as a calling 
argument that with a param comment".
zyounan published this revision for review.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Note that we still have some issues on inlay hints with macro expansion even 
after D133982 .

  void func(int a, int b)
  #define CALL(a, b) func(int(a), b)
  
  CALL(3, 4)  // CALL(3, b: 4)

This is because `spelledForExpanded` doesn't return counterpart spelling ( 
`int(3)` -> `3` ). (I guess it is due to patch D134618 
.)

  void func(int a, int b)
  void work(int a, int )
  #define CALL(a, b) { func(int(a), b); work(a, b); }
  
  int z = 42;
  CALL(3, z)  // CALL(a: 3, :b: 4)

This is because call expression handling logic (i.e. 
`InlayHintVisitor::processCall`) doesn't know the macro expansion context of 
expression, resulting producing two inlay hints at the same spelled position.




Comment at: clang-tools-extra/clangd/InlayHints.cpp:521
+auto Decomposed = SM.getDecomposedExpansionLoc(ExprStartLoc);
 if (Decomposed.first != MainFileID)
   return false;

stupid question: I was suspicious with this check that when would 
`Decomposed.first` not being the same as MainFileID? Should the "top-caller" of 
the macro always be in main file? I didn't find a case that differs, except 
when `getDecomposedLoc` provides wrong FileID.


We don't want to produce inlay hints for arguments for which
user has left param name comments. But we're not decomposing
location of the parameter correctly at the moment because the
location we've passed into `SM.getDecomposedLoc` is not always
FileID.

Fixes clangd/clangd#1495


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D144074

Files:
  clang-tools-extra/clangd/InlayHints.cpp
  clang-tools-extra/clangd/unittests/InlayHintTests.cpp


Index: clang-tools-extra/clangd/unittests/InlayHintTests.cpp
===
--- clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -1050,9 +1050,15 @@
 void bar() {
   foo(/*param*/42);
   foo( /* param = */ 42);
+#define X 42
+#define Y X
+#define Z(...) Y
+  foo(/*param=*/Z(a));
+  foo($macro[[Z(a)]]);
   foo(/* the answer */$param[[42]]);
 }
   )cpp",
+   ExpectedHint{"param: ", "macro"},
ExpectedHint{"param: ", "param"});
 }
 
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -517,7 +517,7 @@
   bool isPrecededByParamNameComment(const Expr *E, StringRef ParamName) {
 auto  = AST.getSourceManager();
 auto ExprStartLoc = SM.getTopMacroCallerLoc(E->getBeginLoc());
-auto Decomposed = SM.getDecomposedLoc(ExprStartLoc);
+auto Decomposed = SM.getDecomposedExpansionLoc(ExprStartLoc);
 if (Decomposed.first != MainFileID)
   return false;
 


Index: clang-tools-extra/clangd/unittests/InlayHintTests.cpp
===
--- clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -1050,9 +1050,15 @@
 void bar() {
   foo(/*param*/42);
   foo( /* param = */ 42);
+#define X 42
+#define Y X
+#define Z(...) Y
+  foo(/*param=*/Z(a));
+  foo($macro[[Z(a)]]);
   foo(/* the answer */$param[[42]]);
 }
   )cpp",
+   ExpectedHint{"param: ", "macro"},
ExpectedHint{"param: ", "param"});
 }
 
Index: clang-tools-extra/clangd/InlayHints.cpp
===
--- clang-tools-extra/clangd/InlayHints.cpp
+++ clang-tools-extra/clangd/InlayHints.cpp
@@ -517,7 +517,7 @@
   bool isPrecededByParamNameComment(const Expr *E, StringRef ParamName) {
 auto  = AST.getSourceManager();
 auto ExprStartLoc = SM.getTopMacroCallerLoc(E->getBeginLoc());
-auto Decomposed = SM.getDecomposedLoc(ExprStartLoc);
+auto Decomposed = SM.getDecomposedExpansionLoc(ExprStartLoc);
 if (Decomposed.first != MainFileID)
   return false;
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 861764b - [NVPTX] Fix NVPTX output name in the driver with `-save-temps`

2023-02-15 Thread Joseph Huber via cfe-commits

Author: Joseph Huber
Date: 2023-02-15T07:39:59-06:00
New Revision: 861764b1c5f7fc31601655f01d84407d42013c30

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

LOG: [NVPTX] Fix NVPTX output name in the driver with `-save-temps`

Summary:
Currently, OpenMP and direct compilation uses an NVPTX toolchain to
directly invoke the CUDA tools from Clang to do the assembling and
linking of NVPTX codes. This breaks under `-save-temps` because of a
workaround. The `nvlink` linker does not accept `.o` files, so we need
to be selective when we output these. The previous logic keyed off of
presense in the temp files and wasn't a great solution. Change this to
just query the input args for `-c` to see if we stop at the assembler.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Cuda.cpp
clang/test/Driver/cuda-cross-compiling.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 6d710fd4275e0..95d932e1eb9b7 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -446,13 +446,8 @@ void NVPTX::Assembler::ConstructJob(Compilation , const 
JobAction ,
   std::string OutputFileName = TC.getInputFilename(Output);
 
   // If we are invoking `nvlink` internally we need to output a `.cubin` file.
-  // Checking if the output is a temporary is the cleanest way to determine
-  // this. Putting this logic in `getInputFilename` isn't an option because it
-  // relies on the compilation.
   // FIXME: This should hopefully be removed if NVIDIA updates their tooling.
-  if (Output.isFilename() &&
-  llvm::find(C.getTempFiles(), Output.getFilename()) !=
-  C.getTempFiles().end()) {
+  if (!C.getInputArgs().getLastArg(options::OPT_c)) {
 SmallString<256> Filename(Output.getFilename());
 llvm::sys::path::replace_extension(Filename, "cubin");
 OutputFileName = Filename.str();

diff  --git a/clang/test/Driver/cuda-cross-compiling.c 
b/clang/test/Driver/cuda-cross-compiling.c
index 992fda8deb33e..9750f09508010 100644
--- a/clang/test/Driver/cuda-cross-compiling.c
+++ b/clang/test/Driver/cuda-cross-compiling.c
@@ -43,6 +43,8 @@
 //
 // RUN: %clang -target nvptx64-nvidia-cuda -march=sm_61 -c -### %s 2>&1 \
 // RUN:   | FileCheck -check-prefix=OBJECT %s
+// RUN: %clang -target nvptx64-nvidia-cuda -save-temps -march=sm_61 -c -### %s 
2>&1 \
+// RUN:   | FileCheck -check-prefix=OBJECT %s
 
 //  OBJECT: -cc1" "-triple" "nvptx64-nvidia-cuda" "-S" {{.*}} 
"-target-cpu" "sm_61" "-target-feature" "+ptx{{[0-9]+}}" {{.*}} "-o" 
"[[PTX:.+]].s"
 // OBJECT-NEXT: ptxas{{.*}}"-m64" "-O0" "--gpu-name" "sm_61" "--output-file" 
"[[OBJ:.+]].o" "[[PTX]].s" "-c"



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


[clang] 1f818f6 - [clang-format] assert(false) -> llvm_unreachable

2023-02-15 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2023-02-15T14:10:09+01:00
New Revision: 1f818f63b829f3038a9fd605bf90348ba58cd981

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

LOG: [clang-format] assert(false) -> llvm_unreachable

Avoids warnings in -asserts builds.

FormatTokenSource.h:240:3: error: non-void function does not return a value 
[-Werror,-Wreturn-type]
  }
  ^

Added: 


Modified: 
clang/lib/Format/FormatTokenSource.h

Removed: 




diff  --git a/clang/lib/Format/FormatTokenSource.h 
b/clang/lib/Format/FormatTokenSource.h
index 8bf7e6932c89..0be46287f6b7 100644
--- a/clang/lib/Format/FormatTokenSource.h
+++ b/clang/lib/Format/FormatTokenSource.h
@@ -236,7 +236,7 @@ class ScopedMacroState : public FormatTokenSource {
   }
 
   FormatToken *insertTokens(ArrayRef Tokens) override {
-assert(false && "Cannot insert tokens while parsing a macro.");
+llvm_unreachable("Cannot insert tokens while parsing a macro.");
   }
 
 private:



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


[PATCH] D143496: [clangd] Add support for missing includes analysis.

2023-02-15 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

Thanks! Details mostly looks good, but i think we had different ideas about how 
the final diagnostics should look like. Let's try to clear that up a bit. My 
suggested proposal is:

- Having a main diagnostic for each symbol that doesn't have a satisfying 
include in the main file, attached to the first use of the symbol, with message 
` providing 'ns::Foo' is not directly included`, with severity warning
- Having notes attached to this main diagnostic, on rest of the references of 
the same symbol inside the main file, with message `Also used here`, with 
severity info
- Having a single fix attached to main diagnostic inserting the first provider.

I believe in the future the main diagnostic message should change to `No header 
providing 'ns::Foo' is directly included`, and we should have multiple fixes 
attached. But there's value in explicitly spelling the header name when there's 
only one fix to get rid of indirections.

This means:

  + we'll emit different diagnostics for each unsatisfied symbol even if 
they're satisfied by the same provider.
  + the user will be able to see usage sites for each symbol as a whole (as 
we're attaching them as notes), and if need be can make a decision around 
dropping the dependency or introducing a forward decl.
  + we won't "butcher" the diagnostic panel with 100 duplicated diagnostics all 
talking about the same thing.
  - in certain editors, like vscode, related information doesn't show up as 
extra decorations in code. so if the user ignores diagnostic panel and the 
first usage of a symbol is not visible. they'll likely miss the finding.

WDYT about this approach? any other alternatives you've in mind? I think it 
might make sense to get others opinion's here as well. Especially around the 
diagnostic message, as usually whatever is convenient to a single person isn't 
necessarily clear/obvious for every one :D




Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:516
+
+  std::vector Macros =
+  collectMacroReferences(AST);

VitaNuo wrote:
> kadircet wrote:
> > 
> Why would you use `auto` here? The return type is not obvious from the 
> function call.
> 
> The style guide says: "types that you and your reviewer experience as 
> unnecessary clutter will very often provide useful information to others. For 
> example, you can assume that the return type of `make_unique()` is 
> obvious, but the return type of `MyWidgetFactory()` probably isn't." 
> (http://go/cstyle#Type_deduction)
well, feel free to keep it. but at least, inside clangd codebase, we use auto 
frequently (maybe more than we should). especially in cases like this where a 
declaration would otherwise fit a single line and because the name of the 
initializer implies this will be a container of macro references and any extra 
details about the container is probably irrelevant.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:547
+convertIncludes(const SourceManager ,
+std::vector MainFileIncludes) {
+  include_cleaner::Includes Includes;

VitaNuo wrote:
> kadircet wrote:
> > you can just pass an `llvm::ArrayRef` to prevent a copy
> By preventing a copy, do you mean that the construction of 
> `llvm::ArrayRef` will only copy a pointer to the data rather than 
> the whole vector? AFAIU `const std::vector&` should be even better 
> then, no copies involved. CMIIW.
well from performance-wise they're pretty close, passing by const ref doesn't 
mean you don't do any copies, it'll still require address of the entity to be 
signalled somehow, which is a pointer copy. passing an arrayref implies copying 
a pointer to data and the size (so it's slightly worse in that regard). but it 
can represent any chunk of contiguous memory, the data source doesn't need to 
be a vector. moreover you can easily pass a slice of a vector rather than the 
whole vector etc.

the performance implications rarely matters in practice, and the abstraction it 
provides on the interfaces is usually a benefit, e.g. if we were to change 
underlying type from vector to llvm::SmallVector, the APIs would still work and 
you don't need to think about any concrete types. hence we tend to prefer 
having ArrayRef on API boundaries whenever possible.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:512
+include_cleaner::Includes
+convertIncludes(const SourceManager ,
+const std::vector ) {

since this is a local symbol, either mark it as `static` or move it to 
anonymous namespace above so that it won't be visible to other translation 
units.



Comment at: clang-tools-extra/clangd/IncludeCleaner.cpp:513
+convertIncludes(const SourceManager ,
+const std::vector ) {
+  include_cleaner::Includes Includes;

nit: you can use `llvm::ArrayRef` instead of a `const std::vector &`. 
`ArrayRef` is a trivially 

[PATCH] D143070: [clang-format] Enable FormatTokenSource to insert tokens.

2023-02-15 Thread Manuel Klimek via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1995d4424505: [clang-format] Enable FormatTokenSource to 
insert tokens. (authored by klimek).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D143070

Files:
  clang/lib/Format/FormatTokenSource.h
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTokenSourceTest.cpp

Index: clang/unittests/Format/FormatTokenSourceTest.cpp
===
--- clang/unittests/Format/FormatTokenSourceTest.cpp
+++ clang/unittests/Format/FormatTokenSourceTest.cpp
@@ -28,12 +28,17 @@
 #define EXPECT_TOKEN_KIND(FormatTok, Kind) \
   do { \
 FormatToken *Tok = FormatTok;  \
-EXPECT_EQ((Tok)->Tok.getKind(), Kind) << *(Tok);   \
+EXPECT_EQ(Tok->Tok.getKind(), Kind) << *Tok;   \
+  } while (false);
+#define EXPECT_TOKEN_ID(FormatTok, Name)   \
+  do { \
+FormatToken *Tok = FormatTok;  \
+EXPECT_EQ(Tok->Tok.getKind(), tok::identifier) << *Tok;\
+EXPECT_EQ(Tok->TokenText, Name) << *Tok;   \
   } while (false);
 
 TEST_F(IndexedTokenSourceTest, EmptyInput) {
-  TokenList Tokens = lex("");
-  IndexedTokenSource Source(Tokens);
+  IndexedTokenSource Source(lex(""));
   EXPECT_FALSE(Source.isEOF());
   EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
   EXPECT_TRUE(Source.isEOF());
@@ -46,8 +51,7 @@
 }
 
 TEST_F(IndexedTokenSourceTest, NavigateTokenStream) {
-  TokenList Tokens = lex("int a;");
-  IndexedTokenSource Source(Tokens);
+  IndexedTokenSource Source(lex("int a;"));
   EXPECT_TOKEN_KIND(Source.peekNextToken(), tok::kw_int);
   EXPECT_TOKEN_KIND(Source.getNextToken(), tok::kw_int);
   EXPECT_EQ(Source.getPreviousToken(), nullptr);
@@ -60,11 +64,12 @@
   EXPECT_TOKEN_KIND(Source.peekNextToken(), tok::eof);
   EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
   EXPECT_TOKEN_KIND(Source.getPreviousToken(), tok::semi);
+  EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
+  EXPECT_TOKEN_KIND(Source.getPreviousToken(), tok::semi);
 }
 
 TEST_F(IndexedTokenSourceTest, ResetPosition) {
-  TokenList Tokens = lex("int a;");
-  IndexedTokenSource Source(Tokens);
+  IndexedTokenSource Source(lex("int a;"));
   Source.getNextToken();
   unsigned Position = Source.getPosition();
   Source.getNextToken();
@@ -73,6 +78,50 @@
   EXPECT_TOKEN_KIND(Source.setPosition(Position), tok::kw_int);
 }
 
+TEST_F(IndexedTokenSourceTest, InsertTokens) {
+  IndexedTokenSource Source(lex("A1 A2"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1 B2")), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "B2");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A2");
+}
+
+TEST_F(IndexedTokenSourceTest, InsertTokensAtEOF) {
+  IndexedTokenSource Source(lex("A1"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1 B2")), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "B2");
+  EXPECT_TOKEN_KIND(Source.getNextToken(), tok::eof);
+}
+
+TEST_F(IndexedTokenSourceTest, InsertTokensRecursive) {
+  IndexedTokenSource Source(lex("A1"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  // A1
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1")), "B1");
+  // B1 A1
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("C1")), "C1");
+  // C1 B1 A1
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("D1")), "D1");
+  // D1 C1 B1 A1
+  EXPECT_TOKEN_ID(Source.getNextToken(), "C1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+}
+
+TEST_F(IndexedTokenSourceTest, InsertTokensRecursiveAtEndOfSequence) {
+  IndexedTokenSource Source(lex("A1"));
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("B1")), "B1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("C1")), "C1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+  EXPECT_TOKEN_ID(Source.insertTokens(lex("D1")), "D1");
+  EXPECT_TOKEN_ID(Source.getNextToken(), "A1");
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -280,9 +280,6 @@
   FormatTokenSource *Tokens;
   

[clang] 1995d44 - [clang-format] Enable FormatTokenSource to insert tokens.

2023-02-15 Thread Manuel Klimek via cfe-commits

Author: Manuel Klimek
Date: 2023-02-15T12:39:24Z
New Revision: 1995d4424505cb5a1c3f0e5f851a660ec32d7af1

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

LOG: [clang-format] Enable FormatTokenSource to insert tokens.

In preparation for configured macro replacements in formatting,
add the ability to insert tokens to FormatTokenSource, and implement
token insertion in IndexedTokenSource.

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

Added: 


Modified: 
clang/lib/Format/FormatTokenSource.h
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTokenSourceTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatTokenSource.h 
b/clang/lib/Format/FormatTokenSource.h
index 0bef45a7ff980..8bf7e6932c895 100644
--- a/clang/lib/Format/FormatTokenSource.h
+++ b/clang/lib/Format/FormatTokenSource.h
@@ -1,4 +1,3 @@
-
 //===--- FormatTokenSource.h - Format C++ code --*- C++ 
-*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
@@ -8,7 +7,7 @@
 
//===--===//
 ///
 /// \file
-/// This file defines the \c TokenSource interface, which provides a token
+/// This file defines the \c FormatTokenSource interface, which provides a 
token
 /// stream as well as the ability to manipulate the token stream.
 ///
 
//===--===//
@@ -18,12 +17,17 @@
 
 #include "FormatToken.h"
 #include "UnwrappedLineParser.h"
+#include "llvm/ADT/DenseMap.h"
 
 #define DEBUG_TYPE "format-token-source"
 
 namespace clang {
 namespace format {
 
+// Navigate a token stream.
+//
+// Enables traversal of a token stream, resetting the position in a token
+// stream, as well as inserting new tokens.
 class FormatTokenSource {
 public:
   virtual ~FormatTokenSource() {}
@@ -33,6 +37,9 @@ class FormatTokenSource {
 
   // Returns the token preceding the token returned by the last call to
   // getNextToken() in the token stream, or nullptr if no such token exists.
+  //
+  // Must not be called directly at the position directly after insertTokens()
+  // is called.
   virtual FormatToken *getPreviousToken() = 0;
 
   // Returns the token that would be returned by the next call to
@@ -45,14 +52,31 @@ class FormatTokenSource {
   virtual bool isEOF() = 0;
 
   // Gets the current position in the token stream, to be used by 
setPosition().
+  //
+  // Note that the value of the position is not meaningful, and specifically
+  // should not be used to get relative token positions.
   virtual unsigned getPosition() = 0;
 
   // Resets the token stream to the state it was in when getPosition() returned
   // Position, and return the token at that position in the stream.
   virtual FormatToken *setPosition(unsigned Position) = 0;
+
+  // Insert the given tokens before the current position.
+  // Returns the first token in \c Tokens.
+  // The next returned token will be the second token in \c Tokens.
+  // Requires the last token in Tokens to be EOF; once the EOF token is 
reached,
+  // the next token will be the last token returned by getNextToken();
+  //
+  // For example, given the token sequence 'a1 a2':
+  // getNextToken() -> a1
+  // insertTokens('b1 b2') -> b1
+  // getNextToken() -> b2
+  // getNextToken() -> a1
+  // getNextToken() -> a2
+  virtual FormatToken *insertTokens(ArrayRef Tokens) = 0;
 };
 
-class LLVM_GSL_POINTER IndexedTokenSource : public FormatTokenSource {
+class IndexedTokenSource : public FormatTokenSource {
 public:
   IndexedTokenSource(ArrayRef Tokens)
   : Tokens(Tokens), Position(-1) {}
@@ -65,7 +89,7 @@ class LLVM_GSL_POINTER IndexedTokenSource : public 
FormatTokenSource {
   });
   return Tokens[Position];
 }
-++Position;
+Position = successor(Position);
 LLVM_DEBUG({
   llvm::dbgs() << "Next ";
   dbgToken(Position);
@@ -74,16 +98,17 @@ class LLVM_GSL_POINTER IndexedTokenSource : public 
FormatTokenSource {
   }
 
   FormatToken *getPreviousToken() override {
+assert(Position <= 0 || !Tokens[Position - 1]->is(tok::eof));
 return Position > 0 ? Tokens[Position - 1] : nullptr;
   }
 
   FormatToken *peekNextToken(bool SkipComment = false) override {
 if (isEOF())
   return Tokens[Position];
-int Next = Position + 1;
+int Next = successor(Position);
 if (SkipComment)
   while (Tokens[Next]->is(tok::comment))
-++Next;
+Next = successor(Next);
 LLVM_DEBUG({
   llvm::dbgs() << "Peeking ";
   dbgToken(Next);
@@ -107,9 +132,40 @@ class LLVM_GSL_POINTER IndexedTokenSource : public 
FormatTokenSource {
 return Tokens[Position];
   }
 
+  FormatToken *insertTokens(ArrayRef New) 

  1   2   >